forked from clips/pattern
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy path__init__.py
More file actions
3050 lines (2509 loc) · 106 KB
/
__init__.py
File metadata and controls
3050 lines (2509 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#### PATTERN | DB ########################################################
# -*- coding: utf-8 -*-
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
##########################################################################
from __future__ import print_function
import os
import sys
import inspect
import warnings
import re
import urllib
import base64
import csv as csvlib
from codecs import BOM_UTF8
from itertools import islice
from datetime import datetime, timedelta
from calendar import monthrange
from time import mktime, strftime
from math import sqrt
from types import GeneratorType
from functools import cmp_to_key
try: # Python 2.x vs 3.x
from cStringIO import StringIO
except:
from io import BytesIO as StringIO
try: # Python 2.x vs 3.x
import htmlentitydefs
except:
from html import entities as htmlentitydefs
try: # Python 2.4 vs 2.5+
from email.Utils import parsedate_tz, mktime_tz
except:
from email.utils import parsedate_tz, mktime_tz
try:
MODULE = os.path.dirname(os.path.realpath(__file__))
except:
MODULE = ""
if sys.version > "3":
long = int
basestring = str
unicode = str
xrange = range
unichr = chr
MYSQL = "mysql"
SQLITE = "sqlite"
def _import_db(engine=SQLITE):
"""Lazy import called from Database() or Database.new().
Depending on the type of database we either import MySQLdb or SQLite.
Note: 64-bit Python needs 64-bit MySQL, 32-bit the 32-bit version.
"""
global MySQLdb
global sqlite
if engine == MYSQL:
import MySQLdb
warnings.simplefilter("ignore", MySQLdb.Warning)
if engine == SQLITE:
try:
# Python 2.5+
import sqlite3.dbapi2 as sqlite
except:
# Python 2.4 with pysqlite2
import pysqlite2.dbapi2 as sqlite
def pd(*args):
"""Returns the path to the parent directory of the script that calls pd() +
given relative path.
For example, in this script: pd("..") => /usr/local/lib/python2.x/site-packages/pattern/db/..
"""
f = inspect.currentframe()
f = inspect.getouterframes(f)[1][1]
f = f != "<stdin>" and f or os.getcwd()
return os.path.join(os.path.dirname(os.path.realpath(f)), *args)
_sum = sum # pattern.db.sum() is also a column aggregate function.
#### DATE FUNCTIONS ######################################################
NOW, YEAR = "now", datetime.now().year
# Date formats can be found in the Python documentation:
# http://docs.python.org/library/time.html#time.strftime
DEFAULT_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
date_formats = [
DEFAULT_DATE_FORMAT, # 2010-09-21 09:27:01 => SQLite + MySQL
"%Y-%m-%dT%H:%M:%SZ", # 2010-09-20T09:27:01Z => Bing
"%a, %d %b %Y %H:%M:%S +0000", # Fri, 21 Sep 2010 09:27:01 +000 => Twitter
"%a %b %d %H:%M:%S +0000 %Y", # Fri Sep 21 09:21:01 +0000 2010 => Twitter
"%Y-%m-%dT%H:%M:%S+0000", # 2010-09-20T09:27:01+0000 => Facebook
"%Y-%m-%d %H:%M", # 2010-09-21 09:27
"%Y-%m-%d", # 2010-09-21
"%d/%m/%Y", # 21/09/2010
"%d %B %Y", # 21 September 2010
"%B %d %Y", # September 21 2010
"%B %d, %Y", # September 21, 2010
]
def _yyyywwd2yyyymmdd(year, week, weekday):
"""Returns (year, month, day) for given (year, week, weekday)."""
d = datetime(year, month=1, day=4) # 1st week contains January 4th.
d = d - timedelta(d.isoweekday() - 1) + \
timedelta(days=weekday - 1, weeks=week - 1)
return (d.year, d.month, d.day)
def _strftime1900(d, format):
"""Returns the given date formatted as a string."""
if d.year < 1900: # Python's strftime() doesn't handle year < 1900.
return strftime(format, (1900,) + d.timetuple()[1:]).replace("1900", str(d.year), 1)
return datetime.strftime(d, format)
class DateError(Exception):
pass
class Date(datetime):
"""A convenience wrapper for datetime.datetime with a default string
format."""
format = DEFAULT_DATE_FORMAT
# Date.year
# Date.month
# Date.day
# Date.minute
# Date.second
@property
def minutes(self):
return self.minute
@property
def seconds(self):
return self.second
@property
def microseconds(self):
return self.microsecond
@property
def week(self):
return self.isocalendar()[1]
@property
def weekday(self):
return self.isocalendar()[2]
@property
def timestamp(self):
return int(mktime(self.timetuple())) # Seconds elapsed since 1/1/1970.
def strftime(self, format):
return _strftime1900(self, format)
def copy(self):
return date(self.timestamp)
def __str__(self):
return self.strftime(self.format)
def __repr__(self):
return "Date(%s)" % repr(self.__str__())
def __iadd__(self, t):
return self.__add__(t)
def __isub__(self, t):
return self.__sub__(t)
def __add__(self, t):
d = self
if getattr(t, "years" , 0) \
or getattr(t, "months", 0):
# January 31 + 1 month = February 28.
y = (d.month + t.months - 1) // 12 + d.year + t.years
m = (d.month + t.months + 0) % 12 or 12
r = monthrange(y, m)
d = date(
y, m, min(d.day, r[1]), d.hour, d.minute, d.second, d.microsecond)
d = datetime.__add__(d, t)
return date(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, self.format)
def __sub__(self, t):
if isinstance(t, (Date, datetime)):
# Subtracting two dates returns a Time.
t = datetime.__sub__(self, t)
return Time(+t.days, +t.seconds,
microseconds=+t.microseconds)
if isinstance(t, (Time, timedelta)):
return self + Time(-t.days, -t.seconds,
microseconds=-t.microseconds,
months=-getattr(t, "months", 0),
years=-getattr(t, "years", 0))
def date(*args, **kwargs):
""" Returns a Date from the given parameters:
- date(format=Date.format) => now
- date(int)
- date(string)
- date(string, format=Date.format)
- date(string, inputformat, format=Date.format)
- date(year, month, day, format=Date.format)
- date(year, month, day, hours, minutes, seconds, format=Date.format)
If a string is given without an explicit input format, all known formats will be tried.
"""
d = None
f = None
if len(args) == 0 \
and kwargs.get("year") is not None \
and kwargs.get("month") \
and kwargs.get("day"):
# Year, month, day.
d = Date(**kwargs)
elif kwargs.get("week"):
# Year, week, weekday.
f = kwargs.pop("format", None)
d = Date(*_yyyywwd2yyyymmdd(
kwargs.pop("year", args and args[0] or Date.now().year),
kwargs.pop("week"),
kwargs.pop("weekday", kwargs.pop("day", 1))), **kwargs)
elif len(args) == 0 or args[0] == NOW:
# No parameters or one parameter NOW.
d = Date.now()
elif len(args) == 1 \
and isinstance(args[0], (Date, datetime)):
# One parameter, a Date or datetime object.
d = Date.fromtimestamp(int(mktime(args[0].timetuple())))
d += time(microseconds=args[0].microsecond)
elif len(args) == 1 \
and (isinstance(args[0], int)
or isinstance(args[0], basestring) and args[0].isdigit()):
# One parameter, an int or string timestamp.
d = Date.fromtimestamp(int(args[0]))
elif len(args) == 1 \
and isinstance(args[0], basestring):
# One parameter, a date string for which we guess the input format
# (RFC2822 or known formats).
try:
d = Date.fromtimestamp(mktime_tz(parsedate_tz(args[0])))
except:
for format in ("format" in kwargs and [kwargs["format"]] or []) + date_formats:
try:
d = Date.strptime(args[0], format)
break
except:
pass
if d is None:
raise DateError("unknown date format for %s" % repr(args[0]))
elif len(args) == 2 \
and isinstance(args[0], basestring):
# Two parameters, a date string and an explicit input format.
d = Date.strptime(args[0], args[1])
elif len(args) >= 3:
# 3-6 parameters: year, month, day, hours, minutes, seconds.
f = kwargs.pop("format", None)
d = Date(*args[:7], **kwargs)
else:
raise DateError("unknown date format")
d.format = kwargs.get("format") or len(
args) > 7 and args[7] or f or Date.format
return d
class Time(timedelta):
def __new__(cls, *args, **kwargs):
"""A convenience wrapper for datetime.timedelta that handles months and
years."""
# Time.years
# Time.months
# Time.days
# Time.seconds
# Time.microseconds
y = kwargs.pop("years", 0)
m = kwargs.pop("months", 0)
t = timedelta.__new__(cls, *args, **kwargs)
setattr(t, "years", y)
setattr(t, "months", m)
return t
def time(days=0, seconds=0, minutes=0, hours=0, **kwargs):
"""Returns a Time that can be added to a Date object.
Other parameters: microseconds, milliseconds, weeks, months, years.
"""
return Time(days=days, seconds=seconds, minutes=minutes, hours=hours, **kwargs)
#### STRING FUNCTIONS ####################################################
# Latin-1 (ISO-8859-1) encoding is identical to Windows-1252 except for the code points 128-159:
# Latin-1 assigns control codes in this range, Windows-1252 has characters, punctuation, symbols
# assigned to these code points.
def decode_string(v, encoding="utf-8"):
"""Returns the given value as a Unicode string (if possible)."""
if isinstance(encoding, basestring):
encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
if isinstance(v, str):
for e in encoding:
try:
return v.decode(*e)
except:
pass
return v
return unicode(v)
def encode_string(v, encoding="utf-8"):
"""Returns the given value as a Python byte string (if possible)."""
if isinstance(encoding, basestring):
encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
if isinstance(v, unicode):
for e in encoding:
try:
return v.encode(*e)
except:
pass
return v
return str(v)
decode_utf8 = decode_string
encode_utf8 = encode_string
def string(value, default=""):
"""Returns the value cast to unicode, or default if it is None/empty."""
# Useful for HTML interfaces.
# Don't do value != None because this includes 0.
if value is None or value == "":
return default
return decode_utf8(value)
class EncryptionError(Exception):
pass
class DecryptionError(Exception):
pass
def encrypt_string(s, key=""):
"""Returns the given string as an encrypted bytestring."""
key += " "
s = encode_utf8(s)
a = []
for i in xrange(len(s)):
try:
a.append(chr(ord(s[i]) + ord(key[i % len(key)]) % 256))
except:
raise EncryptionError()
s = "".join(a)
s = base64.urlsafe_b64encode(s)
return s
def decrypt_string(s, key=""):
"""Returns the given string as a decrypted Unicode string."""
key += " "
s = base64.urlsafe_b64decode(s)
a = []
for i in xrange(len(s)):
try:
a.append(chr(ord(s[i]) - ord(key[i % len(key)]) % 256))
except:
raise DecryptionError()
s = "".join(a)
s = decode_utf8(s)
return s
RE_AMPERSAND = re.compile("\&(?!\#)") # & not followed by #
RE_UNICODE = re.compile(r'&(#?)(x|X?)(\w+);') # É
def encode_entities(string):
""" Encodes HTML entities in the given string ("<" => "<").
For example, to display "<em>hello</em>" in a browser,
we need to pass "<em>hello</em>" (otherwise "hello" in italic is displayed).
"""
if isinstance(string, (str, unicode)):
string = RE_AMPERSAND.sub("&", string)
string = string.replace("<", "<")
string = string.replace(">", ">")
string = string.replace('"', """)
string = string.replace("'", "'")
return string
def decode_entities(string):
""" Decodes HTML entities in the given string ("<" => "<").
"""
# http://snippets.dzone.com/posts/show/4569
def replace_entity(match):
hash, hex, name = match.group(1), match.group(2), match.group(3)
if hash == "#" or name.isdigit():
if hex == '':
return unichr(int(name)) # "&" => "&"
if hex in ("x", "X"):
return unichr(int('0x' + name, 16)) # "&" = > "&"
else:
cp = htmlentitydefs.name2codepoint.get(name) # "&" => "&"
return cp and unichr(cp) or match.group() # "&foo;" => "&foo;"
if isinstance(string, (str, unicode)):
return RE_UNICODE.subn(replace_entity, string)[0]
return string
class _Binary:
""" A wrapper for BLOB data with engine-specific encoding.
See also: Database.binary().
"""
def __init__(self, data, type=SQLITE):
self.data, self.type = str(
hasattr(data, "read") and data.read() or data), type
def escape(self):
if self.type == SQLITE:
return str(self.data.encode("string-escape")).replace("'", "''")
if self.type == MYSQL:
return MySQLdb.escape_string(self.data)
def _escape(value, quote=lambda string: "'%s'" % string.replace("'", "\\'")):
"""Returns the quoted, escaped string (e.g., "'a bird\'s feathers'") for
database entry.
Anything that is not a string (e.g., an integer) is converted to string.
Booleans are converted to "0" and "1", None is converted to "null".
See also: Database.escape()
"""
# Note: use Database.escape() for MySQL/SQLITE-specific escape.
if isinstance(value, str):
# Strings are encoded as UTF-8.
try:
value = value.encode("utf-8")
except:
pass
if value in ("current_timestamp",):
# Don't quote constants such as current_timestamp.
return value
if isinstance(value, basestring):
# Strings are quoted, single quotes are escaped according to the
# database engine.
return quote(value)
if isinstance(value, bool):
# Booleans are converted to "0" or "1".
return str(int(value))
if isinstance(value, (int, long, float)):
# Numbers are converted to string.
return str(value)
if isinstance(value, datetime):
# Dates are formatted as string.
return quote(value.strftime(DEFAULT_DATE_FORMAT))
if isinstance(value, type(None)):
# None is converted to NULL.
return "null"
if isinstance(value, Query):
# A Query is converted to "("+Query.SQL()+")" (=subquery).
return "(%s)" % value.SQL().rstrip(";")
if isinstance(value, _Binary):
# Binary data is escaped with attention to null bytes.
return "'%s'" % value.escape()
return value
def cast(x, f, default=None):
"""Returns f(x) or default."""
if f is str and isinstance(x, unicode):
return decode_utf8(x)
if f is bool and x in ("1", "True", "true"):
return True
if f is bool and x in ("0", "False", "false"):
return False
if f is int:
f = lambda x: int(round(float(x)))
try:
return f(x)
except:
return default
#### LIST FUNCTIONS ######################################################
def find(match=lambda item: False, list=[]):
"""Returns the first item in the list for which match(item) is True."""
for item in list:
if match(item) is True:
return item
def order(list, cmp=None, key=None, reverse=False):
"""Returns a list of indices in the order as when the given list is sorted.
For example: ["c","a","b"] => [1, 2, 0]
This means that in the sorted list, "a" (index 1) comes first and "c" (index 0) last.
"""
if cmp and key:
f = lambda i, j: cmp(key(list[i]), key(list[j]))
elif cmp:
f = lambda i, j: cmp(list[i], list[j])
elif key:
f = lambda i, j: int(key(list[i]) >= key(list[j])) * 2 - 1
else:
f = lambda i, j: int(list[i] >= list[j]) * 2 - 1
return sorted(range(len(list)), key=cmp_to_key(f), reverse=reverse)
_order = order
def avg(list):
"""Returns the arithmetic mean of the given list of values.
For example: mean([1,2,3,4]) = 10/4 = 2.5.
"""
return float(_sum(list)) / (len(list) or 1)
def variance(list):
"""Returns the variance of the given list of values.
The variance is the average of squared deviations from the mean.
"""
a = avg(list)
return _sum([(x - a) ** 2 for x in list]) / (len(list) - 1 or 1)
def stdev(list):
"""Returns the standard deviation of the given list of values.
Low standard deviation => values are close to the mean.
High standard deviation => values are spread out over a large range.
"""
return sqrt(variance(list))
#### SQLITE FUNCTIONS ####################################################
# Convenient MySQL functions not in in pysqlite2. These are created at
# each Database.connect().
class sqlite_first(list):
def step(self, value):
self.append(value)
def finalize(self):
return self[0]
class sqlite_last(list):
def step(self, value):
self.append(value)
def finalize(self):
return self[-1]
class sqlite_group_concat(list):
def step(self, value):
self.append(value)
def finalize(self):
return ",".join(string(v) for v in self if v is not None)
# SQLite (and MySQL) date string format:
# yyyy-mm-dd hh:mm:ss
def sqlite_year(datestring):
return int(datestring.split(" ")[0].split("-")[0])
def sqlite_month(datestring):
return int(datestring.split(" ")[0].split("-")[1])
def sqlite_day(datestring):
return int(datestring.split(" ")[0].split("-")[2])
def sqlite_hour(datestring):
return int(datestring.split(" ")[1].split(":")[0])
def sqlite_minute(datestring):
return int(datestring.split(" ")[1].split(":")[1])
def sqlite_second(datestring):
return int(datestring.split(" ")[1].split(":")[2])
#### DATABASE ############################################################
class DatabaseConnectionError(Exception):
pass
class Database(object):
class Tables(dict):
# Table objects are lazily constructed when retrieved.
# This saves time because each table executes a metadata query when
# constructed.
def __init__(self, db, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.db = db
def __getitem__(self, k):
if dict.__getitem__(self, k) is None:
dict.__setitem__(self, k, Table(name=k, database=self.db))
return dict.__getitem__(self, k)
def __init__(self, name, host="localhost", port=3306, username="root", password="", type=SQLITE, unicode=True, **kwargs):
"""A collection of tables stored in an SQLite or MySQL database.
If the database does not exist, creates it. If the host, user or
password is wrong, raises DatabaseConnectionError.
"""
_import_db(type)
self.type = type
self.name = name
self.host = host
self.port = port
self.username = kwargs.get("user", username)
self.password = password
self._connection = None
self.connect(unicode)
# Table names are available in the Database.tables dictionary,
# table objects as attributes (e.g. Database.table_name).
q = self.type == SQLITE and "select name from sqlite_master where type='table';" or "show tables;"
self.tables = Database.Tables(self)
for name, in self.execute(q):
if not name.startswith(("sqlite_",)):
self.tables[name] = None
# The SQL syntax of the last query is kept in cache.
self._query = None
# Persistent relations between tables, stored as (table1, table2, key1,
# key2, join) tuples.
self.relations = []
def connect(self, unicode=True):
# Connections for threaded applications work differently,
# see http://tools.cherrypy.org/wiki/Databases
# (have one Database object for each thread).
if self._connection is not None:
return
# MySQL
if self.type == MYSQL:
try:
self._connection = MySQLdb.connect(
self.host, self.username, self.password, self.name, port=self.port, use_unicode=unicode)
self._connection.autocommit(False)
except Exception as e:
# Create the database if it doesn't exist yet.
if "unknown database" not in str(e).lower():
# Wrong host, username and/or password.
raise DatabaseConnectionError(e[1])
connection = MySQLdb.connect(
self.host, self.username, self.password)
cursor = connection.cursor()
cursor.execute(
"create database if not exists `%s`;" % self.name)
cursor.close()
connection.close()
self._connection = MySQLdb.connect(
self.host, self.username, self.password, self.name, port=self.port, use_unicode=unicode)
self._connection.autocommit(False)
if unicode:
self._connection.set_character_set("utf8")
# SQLite
if self.type == SQLITE:
self._connection = sqlite.connect(
self.name, detect_types=sqlite.PARSE_DECLTYPES)
# Create functions that are not natively supported by the engine.
# Aggregate functions (for grouping rows) + date functions.
self._connection.create_aggregate("first", 1, sqlite_first)
self._connection.create_aggregate("last", 1, sqlite_last)
self._connection.create_aggregate(
"group_concat", 1, sqlite_group_concat)
self._connection.create_function("year", 1, sqlite_year)
self._connection.create_function("month", 1, sqlite_month)
self._connection.create_function("day", 1, sqlite_day)
self._connection.create_function("hour", 1, sqlite_hour)
self._connection.create_function("minute", 1, sqlite_minute)
self._connection.create_function("second", 1, sqlite_second)
# Map field type INTEGER to int (not long(), e.g., 1L).
# Map field type BOOLEAN to bool.
# Map field type DATE to str, yyyy-mm-dd hh:mm:ss.
if self.type == MYSQL:
type = MySQLdb.constants.FIELD_TYPE
self._connection.converter[type.LONG] = int
self._connection.converter[type.LONGLONG] = int
self._connection.converter[type.DECIMAL] = float
self._connection.converter[type.NEWDECIMAL] = float
self._connection.converter[type.TINY] = bool
self._connection.converter[type.TIMESTAMP] = date
if self.type == SQLITE:
sqlite.converters["TINYINT(1)"] = lambda v: bool(int(v))
sqlite.converters["BLOB"] = lambda v: str(
v).decode("string-escape")
sqlite.converters["TIMESTAMP"] = date
def disconnect(self):
if self._connection is not None:
self._connection.commit()
self._connection.close()
self._connection = None
@property
def connection(self):
return self._connection
@property
def connected(self):
return self._connection is not None
def __getattr__(self, k):
"""Tables are available as attributes by name, e.g.,
Database.persons."""
if k in self.__dict__["tables"]:
return self.__dict__["tables"][k]
if k in self.__dict__:
return self.__dict__[k]
raise AttributeError("'Database' object has no attribute '%s'" % k)
def __len__(self):
return len(self.tables)
def __iter__(self):
return iter(self.tables.keys())
def __getitem__(self, table):
return self.tables[table]
def __setitem__(self, table, fields):
self.create(table, fields)
def __delitem__(self, table):
self.drop(table)
def __nonzero__(self):
return True
# Backwards compatibility.
def _get_user(self):
return self.username
def _set_user(self, v):
self.username = v
user = property(_get_user, _set_user)
@property
def query(self):
"""Yields the last executed SQL query as a string."""
return self._query
def execute(self, SQL, commit=False):
"""Executes the given SQL query and return an iterator over the rows.
With commit=True, automatically commits insert/update/delete changes.
"""
self._query = SQL
if not SQL:
return # MySQL doesn't like empty queries.
# print(SQL)
cursor = self._connection.cursor()
cursor.execute(SQL)
if commit is not False:
self._connection.commit()
return self.RowsIterator(cursor)
class RowsIterator:
"""Iterator over the rows returned from Database.execute()."""
def __init__(self, cursor):
self._cursor = cursor
def next(self):
return next(self.__iter__())
def __iter__(self):
for row in (hasattr(self._cursor, "__iter__") and self._cursor or self._cursor.fetchall()):
yield row
self._cursor.close()
def __del__(self):
self._cursor.close()
def commit(self):
"""Commit all pending insert/update/delete changes."""
self._connection.commit()
def rollback(self):
"""Discard changes since the last commit."""
self._connection.rollback()
def escape(self, value):
"""Returns the quoted, escaped string (e.g., "'a bird\'s feathers'")
for database entry.
Anything that is not a string (e.g., an integer) is converted to
string. Booleans are converted to "0" and "1", None is converted
to "null".
"""
def quote(string):
# How to escape strings differs between database engines.
if self.type == MYSQL:
# return "'%s'" % self._connection.escape_string(string) #
# Doesn't like Unicode.
return "'%s'" % string.replace("'", "\\'")
if self.type == SQLITE:
return "'%s'" % string.replace("'", "''")
return _escape(value, quote)
def binary(self, data):
"""Returns the string of binary data as a value that can be inserted in
a BLOB field."""
return _Binary(data, self.type)
blob = binary
def _field_SQL(self, table, field):
# Returns a (field, index)-tuple with SQL strings for the given field().
# The field string can be used in a CREATE TABLE or ALTER TABLE statement.
# The index string is an optional CREATE INDEX statement (or None).
auto = " auto%sincrement" % (self.type == MYSQL and "_" or "")
field = isinstance(field, basestring) and [field, STRING(255)] or field
field = list(field) + [STRING, None, False, True][len(field) - 1:]
field = list(
_field(field[0], field[1], default=field[2], index=field[3], optional=field[4]))
if field[1] == "timestamp" and field[2] == "now":
field[2] = "current_timestamp"
a = b = None
a = "`%s` %s%s%s%s" % (
# '`id` integer not null primary key auto_increment'
field[0],
field[1] == STRING and field[1]() or field[1],
field[4] is False and " not null" or " null",
field[2] is not None and " default %s" % self.escape(
field[2]) or "",
field[3] == PRIMARY and " primary key%s" % ("", auto)[field[1] == INTEGER] or "")
if field[3] in (UNIQUE, True):
b = "create %sindex `%s_%s` on `%s` (`%s`);" % (
field[3] == UNIQUE and "unique " or "", table, field[0], table, field[0])
return a, b
def create(self, table, fields=[], encoding="utf-8", **kwargs):
"""Creates a new table with the given fields.
The given list of fields must contain values returned from the
field() function.
"""
if table in self.tables:
raise TableError("table '%s' already exists" %
(self.name + "." + table))
if table.startswith(XML_HEADER):
# From an XML-string generated with Table.xml.
return parse_xml(self, table,
table=kwargs.get("name"),
field=kwargs.get("field", lambda s: s.replace(".", "_")))
encoding = self.type == MYSQL and " default charset=" + \
encoding.replace("utf-8", "utf8") or ""
fields, indices = zip(*[self._field_SQL(table, f) for f in fields])
self.execute("create table `%s` (%s)%s;" %
(table, ", ".join(fields), encoding))
for index in indices:
if index is not None:
self.execute(index, commit=True)
self.tables[table] = None # lazy loading
return self.tables[table]
def drop(self, table):
"""Removes the table with the given name."""
if isinstance(table, Table) and table.db == self:
table = table.name
if table in self.tables:
self.tables[table].database = None
self.tables.pop(table)
self.execute("drop table `%s`;" % table, commit=True)
# The SQLite version in Python 2.5 has a drop/recreate table bug.
# Reconnect. This means that any reference to Database.connection
# is no longer valid after Database.drop().
if self.type == SQLITE and sys.version < "2.6":
self.disconnect()
self.connect()
remove = drop
def link(self, table1, field1, table2, field2, join="left"):
"""Defines a relation between two tables in the database.
When executing a table query, fields from the linked table will
also be available (to disambiguate between field names, use
table.field_name).
"""
if isinstance(table1, Table):
table1 = table1.name
if isinstance(table2, Table):
table2 = table2.name
self.relations.append((table1, field1, table2, field2, join))
def __repr__(self):
return "Database(name=%s, host=%s, tables=%s)" % (
repr(self.name),
repr(self.host),
repr(self.tables.keys()))
def _delete(self):
# No warning is issued, seems a bad idea to document the method.
# Anyone wanting to delete an entire database should use an editor.
if self.type == MYSQL:
self.execute("drop database `%s`" % self.name, commit=True)
self.disconnect()
if self.type == SQLITE:
self.disconnect()
os.unlink(self.name)
def __delete__(self):
try:
self.disconnect()
except:
pass
#### FIELD ###############################################################
class _String(str):
# The STRING constant can be called with a length when passed to field(),
# for example field("language", type=STRING(2), default="en", index=True).
def __new__(self):
return str.__new__(self, "string")
def __call__(self, length=100):
return "varchar(%s)" % (length > 255 and 255 or (length < 1 and 1 or length))
# Field type.
# Note: SQLite string fields do not impose a string limit.
# Unicode strings have more characters than actually displayed (e.g. "♥").
# Boolean fields are stored as tinyint(1), int 0 or 1.
STRING, INTEGER, FLOAT, TEXT, BLOB, BOOLEAN, DATE = \
_String(), "integer", "float", "text", "blob", "boolean", "date"
STR, INT, BOOL = STRING, INTEGER, BOOLEAN
# Field index.
PRIMARY = "primary"
UNIQUE = "unique"
# DATE default.
NOW = "now"
#--- FIELD- --------------------------------------------------------------
# def field(name, type=STRING, default=None, index=False, optional=True)
def field(name, type=STRING, **kwargs):
"""Returns a table field definition that can be passed to
Database.create().
The column can be indexed by setting index to True, PRIMARY or UNIQUE.
Primary key number columns are always auto-incremented.