-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathcol.py
More file actions
2187 lines (1785 loc) · 71.5 KB
/
col.py
File metadata and controls
2187 lines (1785 loc) · 71.5 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
"""
Col -- SQLObject columns
Note that each column object is named BlahBlahCol, and these are used
in class definitions. But there's also a corresponding SOBlahBlahCol
object, which is used in SQLObject *classes*.
An explanation: when a SQLObject subclass is created, the metaclass
looks through your class definition for any subclasses of Col. It
collects them together, and indexes them to do all the database stuff
you like, like the magic attributes and whatnot. It then asks the Col
object to create an SOCol object (usually a subclass, actually). The
SOCol object contains all the interesting logic, as well as a record
of the attribute name you used and the class it is bound to (set by
the metaclass).
So, in summary: Col objects are what you define, but SOCol objects
are what gets used.
"""
from array import array
from decimal import Decimal
from itertools import count
import json
try:
import cPickle as pickle
except ImportError:
import pickle
import time
from uuid import UUID
import weakref
from formencode import compound, validators
from .classregistry import findClass
# Sadly the name "constraints" conflicts with many of the function
# arguments in this module, so we rename it:
from . import constraints as constrs
from . import converters
from . import sqlbuilder
from .styles import capword
from .compat import PY2, string_type, unicode_type, buffer_type
import datetime
datetime_available = True
try:
from mx import DateTime as mxDateTime
except ImportError:
mxdatetime_available = False
else:
mxdatetime_available = True
try:
# DateTime from Zope
import DateTime as zopeDateTime
except ImportError:
zope_datetime_available = False
else:
zope_datetime_available = True
DATETIME_IMPLEMENTATION = "datetime"
MXDATETIME_IMPLEMENTATION = "mxDateTime"
ZOPE_DATETIME_IMPLEMENTATION = "zopeDateTime"
if mxdatetime_available and hasattr(mxDateTime, "Time"):
mxDateTimeType = type(mxDateTime.now())
mxTimeType = type(mxDateTime.Time())
if zope_datetime_available:
zopeDateTimeType = type(zopeDateTime.DateTime())
__all__ = ["datetime_available", "mxdatetime_available",
"default_datetime_implementation", "DATETIME_IMPLEMENTATION"]
if mxdatetime_available:
__all__.append("MXDATETIME_IMPLEMENTATION")
if zope_datetime_available:
__all__.append("ZOPE_DATETIME_IMPLEMENTATION")
default_datetime_implementation = DATETIME_IMPLEMENTATION
if not PY2:
# alias for python 3 compatibility
long = int
# This is to satisfy flake8 under python 3
unicode = str
NoDefault = sqlbuilder.NoDefault
def use_microseconds(use=True):
if use:
SODateTimeCol.datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
SOTimeCol.timeFormat = '%H:%M:%S.%f'
dt_types = [(datetime.datetime, converters.DateTimeConverterMS),
(datetime.time, converters.TimeConverterMS)]
else:
SODateTimeCol.datetimeFormat = '%Y-%m-%d %H:%M:%S'
SOTimeCol.timeFormat = '%H:%M:%S'
dt_types = [(datetime.datetime, converters.DateTimeConverter),
(datetime.time, converters.TimeConverter)]
for dt_type, converter in dt_types:
converters.registerConverter(dt_type, converter)
__all__.append("use_microseconds")
creationOrder = count()
########################################
# Columns
########################################
# Col is essentially a column definition, it doesn't have much logic to it.
class SOCol(object):
def __init__(self,
name,
soClass,
creationOrder,
dbName=None,
default=NoDefault,
defaultSQL=None,
foreignKey=None,
alternateID=False,
alternateMethodName=None,
constraints=None,
notNull=NoDefault,
notNone=NoDefault,
unique=NoDefault,
sqlType=None,
columnDef=None,
validator=None,
validator2=None,
immutable=False,
cascade=None,
lazy=False,
noCache=False,
forceDBName=False,
title=None,
tags=[],
origName=None,
dbEncoding=None,
extra_vars=None):
super(SOCol, self).__init__()
# This isn't strictly true, since we *could* use backquotes or
# " or something (database-specific) around column names, but
# why would anyone *want* to use a name like that?
# @@: I suppose we could actually add backquotes to the
# dbName if we needed to...
if not forceDBName:
assert sqlbuilder.sqlIdentifier(name), (
'Name must be SQL-safe '
'(letters, numbers, underscores): %s (or use forceDBName=True)'
% repr(name))
assert name != 'id', (
'The column name "id" is reserved for SQLObject use '
'(and is implicitly created).')
assert name, "You must provide a name for all columns"
self.columnDef = columnDef
self.creationOrder = creationOrder
self.immutable = immutable
# cascade can be one of:
# None: no constraint is generated
# True: a CASCADE constraint is generated
# False: a RESTRICT constraint is generated
# 'null': a SET NULL trigger is generated
if not isinstance(cascade, (bool, string_type, type(None))):
raise TypeError(
'Expected cascade to be True, False, None or "null", '
"(you gave: %r %r)" % (type(cascade), cascade)
)
if isinstance(cascade, str) and (cascade != 'null'):
raise ValueError(
"The only string value allowed for cascade is 'null' "
"(you gave: %r)" % cascade)
self.cascade = cascade
if not isinstance(constraints, (list, tuple)):
constraints = [constraints]
self.constraints = self.autoConstraints() + constraints
self.notNone = False
if notNull is not NoDefault:
self.notNone = notNull
assert notNone is NoDefault or (not notNone) == (not notNull), (
"The notNull and notNone arguments are aliases, "
"and must not conflict. "
"You gave notNull=%r, notNone=%r" % (notNull, notNone))
elif notNone is not NoDefault:
self.notNone = notNone
if self.notNone:
self.constraints = [constrs.notNull] + self.constraints
self.name = name
self.soClass = soClass
self._default = default
self.defaultSQL = defaultSQL
self.customSQLType = sqlType
# deal with foreign keys
self.foreignKey = foreignKey
if self.foreignKey:
if origName is not None:
idname = soClass.sqlmeta.style.instanceAttrToIDAttr(origName)
else:
idname = soClass.sqlmeta.style.instanceAttrToIDAttr(name)
if self.name != idname:
self.foreignName = self.name
self.name = idname
else:
self.foreignName = soClass.sqlmeta.style.\
instanceIDAttrToAttr(self.name)
else:
self.foreignName = None
# if they don't give us a specific database name for
# the column, we separate the mixedCase into mixed_case
# and assume that.
if dbName is None:
self.dbName = soClass.sqlmeta.style.pythonAttrToDBColumn(self.name)
else:
self.dbName = dbName
# alternateID means that this is a unique column that
# can be used to identify rows
self.alternateID = alternateID
if unique is NoDefault:
self.unique = alternateID
else:
self.unique = unique
if self.unique and alternateMethodName is None:
self.alternateMethodName = 'by' + capword(self.name)
else:
self.alternateMethodName = alternateMethodName
_validators = self.createValidators()
if validator:
_validators.append(validator)
if validator2:
_validators.insert(0, validator2)
_vlen = len(_validators)
if _vlen:
for _validator in _validators:
_validator.soCol = weakref.proxy(self)
if _vlen == 0:
self.validator = None # Set sef.{from,to}_python
elif _vlen == 1:
self.validator = _validators[0]
elif _vlen > 1:
self.validator = compound.All.join(
_validators[0], *_validators[1:])
self.noCache = noCache
self.lazy = lazy
# this is in case of ForeignKey, where we rename the column
# and append an ID
self.origName = origName or name
self.title = title
self.tags = tags
self.dbEncoding = dbEncoding
if extra_vars:
for name, value in extra_vars.items():
setattr(self, name, value)
def _set_validator(self, value):
self._validator = value
if self._validator:
self.to_python = self._validator.to_python
self.from_python = self._validator.from_python
else:
self.to_python = None
self.from_python = None
def _get_validator(self):
return self._validator
validator = property(_get_validator, _set_validator)
def createValidators(self):
"""Create a list of validators for the column."""
return []
def autoConstraints(self):
return []
def _get_default(self):
# A default can be a callback or a plain value,
# here we resolve the callback
if self._default is NoDefault:
return NoDefault
elif hasattr(self._default, '__sqlrepr__'):
return self._default
elif callable(self._default):
return self._default()
else:
return self._default
default = property(_get_default, None, None)
def _get_joinName(self):
return self.soClass.sqlmeta.style.instanceIDAttrToAttr(self.name)
joinName = property(_get_joinName, None, None)
def __repr__(self):
r = '<%s %s' % (self.__class__.__name__, self.name)
if self.default is not NoDefault:
r += ' default=%s' % repr(self.default)
if self.foreignKey:
r += ' connected to %s' % self.foreignKey
if self.alternateID:
r += ' alternate ID'
if self.notNone:
r += ' not null'
return r + '>'
def createSQL(self):
return ' '.join([self._sqlType()] + self._extraSQL())
def _extraSQL(self):
result = []
if self.notNone or self.alternateID:
result.append('NOT NULL')
if self.unique or self.alternateID:
result.append('UNIQUE')
if self.defaultSQL is not None:
result.append("DEFAULT %s" % self.defaultSQL)
return result
def _sqlType(self):
if self.customSQLType is None:
raise ValueError("Col %s (%s) cannot be used for automatic "
"schema creation (too abstract)" %
(self.name, self.__class__))
else:
return self.customSQLType
def _mysqlType(self):
return self._sqlType()
def _postgresType(self):
return self._sqlType()
def _sqliteType(self):
# SQLite is naturally typeless, so as a fallback it uses
# no type.
try:
return self._sqlType()
except ValueError:
return ''
def _sybaseType(self):
return self._sqlType()
def _mssqlType(self):
return self._sqlType()
def _firebirdType(self):
return self._sqlType()
def _maxdbType(self):
return self._sqlType()
def mysqlCreateSQL(self, connection=None):
self.connection = connection
return ' '.join([self.dbName, self._mysqlType()] + self._extraSQL())
def postgresCreateSQL(self):
return ' '.join([self.dbName, self._postgresType()] + self._extraSQL())
def sqliteCreateSQL(self):
return ' '.join([self.dbName, self._sqliteType()] + self._extraSQL())
def sybaseCreateSQL(self):
return ' '.join([self.dbName, self._sybaseType()] + self._extraSQL())
def mssqlCreateSQL(self, connection=None):
self.connection = connection
return ' '.join([self.dbName, self._mssqlType()] + self._extraSQL())
def firebirdCreateSQL(self):
# Ian Sparks pointed out that fb is picky about the order
# of the NOT NULL clause in a create statement. So, we handle
# them differently for Enum columns.
if not isinstance(self, SOEnumCol):
return ' '.join(
[self.dbName, self._firebirdType()] + self._extraSQL())
else:
return ' '.join(
[self.dbName] + [self._firebirdType()[0]]
+ self._extraSQL() + [self._firebirdType()[1]])
def maxdbCreateSQL(self):
return ' '.join([self.dbName, self._maxdbType()] + self._extraSQL())
def __get__(self, obj, type=None):
if obj is None:
# class attribute, return the descriptor itself
return self
if obj.sqlmeta._obsolete:
raise RuntimeError('The object <%s %s> is obsolete' % (
obj.__class__.__name__, obj.id))
if obj.sqlmeta.cacheColumns:
columns = obj.sqlmeta._columnCache
if columns is None:
obj.sqlmeta.loadValues()
try:
return columns[name] # noqa
except KeyError:
return obj.sqlmeta.loadColumn(self)
else:
return obj.sqlmeta.loadColumn(self)
def __set__(self, obj, value):
if self.immutable:
raise AttributeError("The column %s.%s is immutable" %
(obj.__class__.__name__,
self.name))
obj.sqlmeta.setColumn(self, value)
def __delete__(self, obj):
raise AttributeError("I can't be deleted from %r" % obj)
def getDbEncoding(self, state, default='utf-8'):
if self.dbEncoding:
return self.dbEncoding
dbEncoding = state.soObject.sqlmeta.dbEncoding
if dbEncoding:
return dbEncoding
try:
connection = state.connection or state.soObject._connection
except AttributeError:
dbEncoding = None
else:
dbEncoding = getattr(connection, "dbEncoding", None)
if not dbEncoding:
dbEncoding = default
return dbEncoding
class Col(object):
baseClass = SOCol
def __init__(self, name=None, **kw):
super(Col, self).__init__()
self.__dict__['_name'] = name
self.__dict__['_kw'] = kw
self.__dict__['creationOrder'] = next(creationOrder)
self.__dict__['_extra_vars'] = {}
def _set_name(self, value):
assert self._name is None or self._name == value, (
"You cannot change a name after it has already been set "
"(from %s to %s)" % (self.name, value))
self.__dict__['_name'] = value
def _get_name(self):
return self._name
name = property(_get_name, _set_name)
def withClass(self, soClass):
return self.baseClass(soClass=soClass, name=self._name,
creationOrder=self.creationOrder,
columnDef=self,
extra_vars=self._extra_vars,
**self._kw)
def __setattr__(self, var, value):
if var == 'name':
super(Col, self).__setattr__(var, value)
return
self._extra_vars[var] = value
def __repr__(self):
return '<%s %s %s>' % (
self.__class__.__name__, hex(abs(id(self)))[2:],
self._name or '(unnamed)')
class SOValidator(validators.Validator):
def getDbEncoding(self, state, default='utf-8'):
try:
return self.dbEncoding
except AttributeError:
return self.soCol.getDbEncoding(state, default=default)
class SOStringLikeCol(SOCol):
"""A common ancestor for SOStringCol and SOUnicodeCol"""
def __init__(self, **kw):
self.length = kw.pop('length', None)
self.varchar = kw.pop('varchar', 'auto')
self.char_binary = kw.pop('char_binary', None) # A hack for MySQL
if not self.length:
assert self.varchar == 'auto' or not self.varchar, \
"Without a length strings are treated as TEXT, not varchar"
self.varchar = False
elif self.varchar == 'auto':
self.varchar = True
super(SOStringLikeCol, self).__init__(**kw)
def autoConstraints(self):
constraints = [constrs.isString]
if self.length is not None:
constraints += [constrs.MaxLength(self.length)]
return constraints
def _sqlType(self):
if self.customSQLType is not None:
return self.customSQLType
if not self.length:
return 'TEXT'
elif self.varchar:
return 'VARCHAR(%i)' % self.length
else:
return 'CHAR(%i)' % self.length
def _check_case_sensitive(self, db):
if self.char_binary:
raise ValueError("%s does not support "
"binary character columns" % db)
def _mysqlType(self):
type = self._sqlType()
if self.char_binary:
type += " BINARY"
return type
def _postgresType(self):
self._check_case_sensitive("PostgreSQL")
return super(SOStringLikeCol, self)._postgresType()
def _sqliteType(self):
self._check_case_sensitive("SQLite")
return super(SOStringLikeCol, self)._sqliteType()
def _sybaseType(self):
self._check_case_sensitive("SYBASE")
type = self._sqlType()
return type
def _mssqlType(self):
if self.customSQLType is not None:
return self.customSQLType
if not self.length:
if self.connection and self.connection.can_use_max_types():
type = 'VARCHAR(MAX)'
else:
type = 'VARCHAR(4000)'
elif self.varchar:
type = 'VARCHAR(%i)' % self.length
else:
type = 'CHAR(%i)' % self.length
return type
def _firebirdType(self):
self._check_case_sensitive("FireBird")
if not self.length:
return 'BLOB SUB_TYPE TEXT'
else:
return self._sqlType()
def _maxdbType(self):
self._check_case_sensitive("SAP DB/MaxDB")
if not self.length:
return 'LONG ASCII'
else:
return self._sqlType()
class StringValidator(SOValidator):
def to_python(self, value, state):
if value is None:
return None
try:
connection = state.connection or state.soObject._connection
binaryType = connection._binaryType
dbName = connection.dbName
except AttributeError:
binaryType = type(None) # Just a simple workaround
dbEncoding = self.getDbEncoding(state, default='ascii')
if isinstance(value, unicode_type):
if PY2:
return value.encode(dbEncoding)
return value
if self.dataType and isinstance(value, self.dataType):
return value
if isinstance(value,
(str, bytes, buffer_type, binaryType,
sqlbuilder.SQLExpression)):
return value
if hasattr(value, '__unicode__'):
return unicode(value).encode(dbEncoding)
if dbName == 'mysql':
if isinstance(value, bytearray):
if PY2:
return bytes(value)
else:
return value.decode(dbEncoding, errors='surrogateescape')
if not PY2 and isinstance(value, bytes):
return value.decode('ascii', errors='surrogateescape')
raise validators.Invalid(
"expected a str in the StringCol '%s', got %s %r instead" % (
self.name, type(value), value), value, state)
from_python = to_python
class SOStringCol(SOStringLikeCol):
def createValidators(self, dataType=None):
return [StringValidator(name=self.name, dataType=dataType)] + \
super(SOStringCol, self).createValidators()
class StringCol(Col):
baseClass = SOStringCol
class NQuoted(sqlbuilder.SQLExpression):
def __init__(self, value):
self.value = value
def __hash__(self):
return hash(self.value)
def __sqlrepr__(self, db):
assert db == 'mssql'
return "N" + sqlbuilder.sqlrepr(self.value, db)
class UnicodeStringValidator(SOValidator):
def to_python(self, value, state):
if value is None:
return None
if isinstance(value, (unicode_type, sqlbuilder.SQLExpression)):
return value
if isinstance(value, str):
return value.decode(self.getDbEncoding(state))
if isinstance(value, array): # MySQL
return value.tostring().decode(self.getDbEncoding(state))
if hasattr(value, '__unicode__'):
return unicode(value)
raise validators.Invalid(
"expected a str or a unicode in the UnicodeCol '%s', "
"got %s %r instead" % (
self.name, type(value), value), value, state)
def from_python(self, value, state):
if value is None:
return None
if isinstance(value, (str, sqlbuilder.SQLExpression)):
return value
if isinstance(value, unicode_type):
try:
connection = state.connection or state.soObject._connection
except AttributeError:
pass
else:
if connection.dbName == 'mssql':
if PY2:
value = value.encode(self.getDbEncoding(state))
return NQuoted(value)
return value.encode(self.getDbEncoding(state))
if hasattr(value, '__unicode__'):
return unicode(value).encode(self.getDbEncoding(state))
raise validators.Invalid(
"expected a str or a unicode in the UnicodeCol '%s', "
"got %s %r instead" % (
self.name, type(value), value), value, state)
class SOUnicodeCol(SOStringLikeCol):
def _mssqlType(self):
if self.customSQLType is not None:
return self.customSQLType
return 'N' + super(SOUnicodeCol, self)._mssqlType()
def createValidators(self):
return [UnicodeStringValidator(name=self.name)] + \
super(SOUnicodeCol, self).createValidators()
class UnicodeCol(Col):
baseClass = SOUnicodeCol
class IntValidator(SOValidator):
def to_python(self, value, state):
if value is None:
return None
if isinstance(value, (int, long, sqlbuilder.SQLExpression)):
return value
for converter, attr_name in (int, '__int__'), (long, '__long__'):
if hasattr(value, attr_name):
try:
return converter(value)
except Exception:
break
raise validators.Invalid(
"expected an int in the IntCol '%s', got %s %r instead" % (
self.name, type(value), value), value, state)
from_python = to_python
class SOIntCol(SOCol):
# 3-03 @@: support precision, maybe max and min directly
def __init__(self, **kw):
self.length = kw.pop('length', None)
self.unsigned = bool(kw.pop('unsigned', None))
self.zerofill = bool(kw.pop('zerofill', None))
SOCol.__init__(self, **kw)
def autoConstraints(self):
return [constrs.isInt]
def createValidators(self):
return [IntValidator(name=self.name)] + \
super(SOIntCol, self).createValidators()
def addSQLAttrs(self, str):
_ret = str
if str is None or len(str) < 1:
return None
if self.length and self.length >= 1:
_ret = "%s(%d)" % (_ret, self.length)
if self.unsigned:
_ret += " UNSIGNED"
if self.zerofill:
_ret += " ZEROFILL"
return _ret
def _sqlType(self):
return self.addSQLAttrs("INT")
class IntCol(Col):
baseClass = SOIntCol
class SOTinyIntCol(SOIntCol):
def _sqlType(self):
return self.addSQLAttrs("TINYINT")
class TinyIntCol(Col):
baseClass = SOTinyIntCol
class SOSmallIntCol(SOIntCol):
def _sqlType(self):
return self.addSQLAttrs("SMALLINT")
class SmallIntCol(Col):
baseClass = SOSmallIntCol
class SOMediumIntCol(SOIntCol):
def _sqlType(self):
return self.addSQLAttrs("MEDIUMINT")
class MediumIntCol(Col):
baseClass = SOMediumIntCol
class SOBigIntCol(SOIntCol):
def _sqlType(self):
return self.addSQLAttrs("BIGINT")
class BigIntCol(Col):
baseClass = SOBigIntCol
class BoolValidator(SOValidator):
def to_python(self, value, state):
if value is None:
return None
if isinstance(value, (bool, sqlbuilder.SQLExpression)):
return value
if PY2 and hasattr(value, '__nonzero__') \
or not PY2 and hasattr(value, '__bool__'):
return bool(value)
try:
connection = state.connection or state.soObject._connection
except AttributeError:
pass
else:
if connection.dbName == 'postgres' and \
connection.driver in ('odbc', 'pyodbc', 'pypyodbc') and \
isinstance(value, string_type):
return bool(int(value))
raise validators.Invalid(
"expected a bool or an int in the BoolCol '%s', "
"got %s %r instead" % (
self.name, type(value), value), value, state)
from_python = to_python
class SOBoolCol(SOCol):
def autoConstraints(self):
return [constrs.isBool]
def createValidators(self):
return [BoolValidator(name=self.name)] + \
super(SOBoolCol, self).createValidators()
def _postgresType(self):
return 'BOOL'
def _mysqlType(self):
return "BOOL"
def _sybaseType(self):
return "BIT"
def _mssqlType(self):
return "BIT"
def _firebirdType(self):
return 'INT'
def _maxdbType(self):
return "BOOLEAN"
def _sqliteType(self):
return "BOOLEAN"
class BoolCol(Col):
baseClass = SOBoolCol
class FloatValidator(SOValidator):
def to_python(self, value, state):
if value is None:
return None
if isinstance(value, (float, int, long, sqlbuilder.SQLExpression)):
return value
for converter, attr_name in (
(float, '__float__'), (int, '__int__'), (long, '__long__')):
if hasattr(value, attr_name):
try:
return converter(value)
except Exception:
break
raise validators.Invalid(
"expected a float in the FloatCol '%s', got %s %r instead" % (
self.name, type(value), value), value, state)
from_python = to_python
class SOFloatCol(SOCol):
# 3-03 @@: support precision (e.g., DECIMAL)
def autoConstraints(self):
return [constrs.isFloat]
def createValidators(self):
return [FloatValidator(name=self.name)] + \
super(SOFloatCol, self).createValidators()
def _sqlType(self):
return 'FLOAT'
def _mysqlType(self):
return "DOUBLE PRECISION"
class FloatCol(Col):
baseClass = SOFloatCol
class SOKeyCol(SOCol):
key_type = {int: "INT", str: "TEXT"}
# 3-03 @@: this should have a simplified constructor
# Should provide foreign key information for other DBs.
def __init__(self, **kw):
self.refColumn = kw.pop('refColumn', None)
super(SOKeyCol, self).__init__(**kw)
def _idType(self):
return self.soClass.sqlmeta.idType
def _sqlType(self):
return self.key_type[self._idType()]
def _sybaseType(self):
key_type = {int: "NUMERIC(18,0)", str: "TEXT"}
return key_type[self._idType()]
def _mssqlType(self):
key_type = {int: "INT", str: "TEXT"}
return key_type[self._idType()]
def _firebirdType(self):
key_type = {int: "INT", str: "VARCHAR(255)"}
return key_type[self._idType()]
class KeyCol(Col):
baseClass = SOKeyCol
class ForeignKeyValidator(SOValidator):
def __init__(self, *args, **kw):
super(ForeignKeyValidator, self).__init__(*args, **kw)
self.fkIDType = None
def from_python(self, value, state):
if value is None:
return None
# Avoid importing the main module
# to get the SQLObject class for isinstance
if hasattr(value, 'sqlmeta'):
return value
if self.fkIDType is None:
otherTable = findClass(self.soCol.foreignKey,
self.soCol.soClass.sqlmeta.registry)
self.fkIDType = otherTable.sqlmeta.idType
try:
value = self.fkIDType(value)
return value
except (ValueError, TypeError):
pass
raise validators.Invalid("expected a %r for the ForeignKey '%s', "
"got %s %r instead" %
(self.fkIDType, self.name,
type(value), value), value, state)
class SOForeignKey(SOKeyCol):
def __init__(self, **kw):
foreignKey = kw['foreignKey']
style = kw['soClass'].sqlmeta.style
if kw.get('name'):
kw['origName'] = kw['name']
kw['name'] = style.instanceAttrToIDAttr(kw['name'])
else:
kw['name'] = style.instanceAttrToIDAttr(
style.pythonClassToAttr(foreignKey))
super(SOForeignKey, self).__init__(**kw)
def createValidators(self):
return [ForeignKeyValidator(name=self.name)] + \
super(SOForeignKey, self).createValidators()
def _idType(self):
other = findClass(self.foreignKey, self.soClass.sqlmeta.registry)
return other.sqlmeta.idType
def sqliteCreateSQL(self):
sql = SOKeyCol.sqliteCreateSQL(self)
other = findClass(self.foreignKey, self.soClass.sqlmeta.registry)
tName = other.sqlmeta.table
idName = self.refColumn or other.sqlmeta.idName
if self.cascade is not None:
if self.cascade == 'null':
action = 'ON DELETE SET NULL'
elif self.cascade:
action = 'ON DELETE CASCADE'
else:
action = 'ON DELETE RESTRICT'
else:
action = ''
constraint = ('CONSTRAINT %(colName)s_exists '
# 'FOREIGN KEY(%(colName)s) '
'REFERENCES %(tName)s(%(idName)s) '
'%(action)s' %
{'tName': tName,
'colName': self.dbName,
'idName': idName,