forked from sqlobject/sqlobject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlbuilder.py
More file actions
1610 lines (1200 loc) · 46.8 KB
/
sqlbuilder.py
File metadata and controls
1610 lines (1200 loc) · 46.8 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
"""
sqlobject.sqlbuilder
--------------------
:author: Ian Bicking <ianb@colorstudy.com>
Builds SQL expressions from normal Python expressions.
Disclaimer
----------
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
USA.
Instructions
------------
To begin a SQL expression, you must use some sort of SQL object -- a
field, table, or SQL statement (``SELECT``, ``INSERT``, etc.) You can
then use normal operators, with the exception of: `and`, `or`, `not`,
and `in`. You can use the `AND`, `OR`, `NOT`, and `IN` functions
instead, or you can also use `&`, `|`, and `~` for `and`, `or`, and
`not` respectively (however -- the precidence for these operators
doesn't work as you would want, so you must use many parenthesis).
To create a sql field, table, or constant/function, use the namespaces
`table`, `const`, and `func`. For instance, ``table.address`` refers
to the ``address`` table, and ``table.address.state`` refers to the
``state`` field in the address table. ``const.NULL`` is the ``NULL``
SQL constant, and ``func.NOW()`` is the ``NOW()`` function call
(`const` and `func` are actually identicle, but the two names are
provided for clarity). Once you create this object, expressions
formed with it will produce SQL statements.
The ``sqlrepr(obj)`` function gets the SQL representation of these
objects, as well as the proper SQL representation of basic Python
types (None==NULL).
There are a number of DB-specific SQL features that this does not
implement. There are a bunch of normal ANSI features also not present.
See the bottom of this module for some examples, and run it (i.e.
``python sql.py``) to see the results of those examples.
"""
########################################
# Constants
########################################
import fnmatch
import operator
import re
import threading
import types
import weakref
from . import classregistry
from .converters import registerConverter, sqlrepr, quote_str, unquote_str
from .compat import PY2, string_type
class VersionError(Exception):
pass
class NoDefault:
pass
class SQLObjectState(object):
def __init__(self, soObject, connection=None):
self.soObject = weakref.proxy(soObject)
self.connection = connection
safeSQLRE = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_\.]*$')
def sqlIdentifier(obj):
# some db drivers return unicode column names
return isinstance(obj, string_type) and bool(safeSQLRE.search(obj.strip()))
def execute(expr, executor):
if hasattr(expr, 'execute'):
return expr.execute(executor)
else:
return expr
def _str_or_sqlrepr(expr, db):
if isinstance(expr, string_type):
return expr
return sqlrepr(expr, db)
########################################
# Expression generation
########################################
class SQLExpression:
def __add__(self, other):
return SQLOp("+", self, other)
def __radd__(self, other):
return SQLOp("+", other, self)
def __sub__(self, other):
return SQLOp("-", self, other)
def __rsub__(self, other):
return SQLOp("-", other, self)
def __mul__(self, other):
return SQLOp("*", self, other)
def __rmul__(self, other):
return SQLOp("*", other, self)
def __div__(self, other):
return SQLOp("/", self, other)
def __rdiv__(self, other):
return SQLOp("/", other, self)
def __truediv__(self, other):
return SQLOp("/", self, other)
def __rtruediv__(self, other):
return SQLOp("/", other, self)
def __floordiv__(self, other):
return SQLConstant("FLOOR")(SQLOp("/", self, other))
def __rfloordiv__(self, other):
return SQLConstant("FLOOR")(SQLOp("/", other, self))
def __pos__(self):
return SQLPrefix("+", self)
def __neg__(self):
return SQLPrefix("-", self)
def __pow__(self, other):
return SQLConstant("POW")(self, other)
def __rpow__(self, other):
return SQLConstant("POW")(other, self)
def __abs__(self):
return SQLConstant("ABS")(self)
def __mod__(self, other):
return SQLModulo(self, other)
def __rmod__(self, other):
return SQLConstant("MOD")(other, self)
def __lt__(self, other):
return SQLOp("<", self, other)
def __le__(self, other):
return SQLOp("<=", self, other)
def __gt__(self, other):
return SQLOp(">", self, other)
def __ge__(self, other):
return SQLOp(">=", self, other)
def __eq__(self, other):
if other is None:
return ISNULL(self)
else:
return SQLOp("=", self, other)
def __ne__(self, other):
if other is None:
return ISNOTNULL(self)
else:
return SQLOp("<>", self, other)
def __and__(self, other):
return SQLOp("AND", self, other)
def __rand__(self, other):
return SQLOp("AND", other, self)
def __or__(self, other):
return SQLOp("OR", self, other)
def __ror__(self, other):
return SQLOp("OR", other, self)
def __invert__(self):
return SQLPrefix("NOT", self)
def __call__(self, *args):
return SQLCall(self, args)
def __repr__(self):
try:
return self.__sqlrepr__(None)
except AssertionError:
return '<%s %s>' % (
self.__class__.__name__, hex(id(self))[2:])
def __str__(self):
return repr(self)
def __cmp__(self, other):
raise VersionError("Python 2.1+ required")
def __rcmp__(self, other):
raise VersionError("Python 2.1+ required")
def startswith(self, s):
return STARTSWITH(self, s)
def endswith(self, s):
return ENDSWITH(self, s)
def contains(self, s):
return CONTAINSSTRING(self, s)
def components(self):
return []
def tablesUsed(self, db):
return self.tablesUsedSet(db)
def tablesUsedSet(self, db):
tables = set()
for table in self.tablesUsedImmediate():
if hasattr(table, '__sqlrepr__'):
table = sqlrepr(table, db)
tables.add(table)
for component in self.components():
tables.update(tablesUsedSet(component, db))
return tables
def tablesUsedImmediate(self):
return []
#######################################
# Converter for SQLExpression instances
#######################################
def SQLExprConverter(value, db):
return value.__sqlrepr__()
registerConverter(SQLExpression, SQLExprConverter)
def tablesUsedSet(obj, db):
if hasattr(obj, "tablesUsedSet"):
return obj.tablesUsedSet(db)
else:
return {}
if PY2:
div = operator.div
else:
div = operator.truediv
operatorMap = {
"+": operator.add,
"/": div,
"-": operator.sub,
"*": operator.mul,
"<": operator.lt,
"<=": operator.le,
"=": operator.eq,
"!=": operator.ne,
">=": operator.ge,
">": operator.gt,
"IN": operator.contains,
"IS": operator.eq,
}
class SQLOp(SQLExpression):
def __init__(self, op, expr1, expr2):
self.op = op.upper()
if isinstance(expr1, Subquery):
expr1, expr2 = expr2, expr1
self.expr1 = expr1
self.expr2 = expr2
def __sqlrepr__(self, db):
s1 = sqlrepr(self.expr1, db)
s2 = sqlrepr(self.expr2, db)
if s1[0] != '(' and s1 != 'NULL':
s1 = '(' + s1 + ')'
if s2[0] != '(' and s2 != 'NULL' and \
not isinstance(self.expr2, Subquery):
s2 = '(' + s2 + ')'
return "(%s %s %s)" % (s1, self.op, s2)
def components(self):
return [self.expr1, self.expr2]
def execute(self, executor):
if self.op == "AND":
return execute(self.expr1, executor) \
and execute(self.expr2, executor)
elif self.op == "OR":
return execute(self.expr1, executor) \
or execute(self.expr2, executor)
else:
return operatorMap[self.op.upper()](execute(self.expr1, executor),
execute(self.expr2, executor))
registerConverter(SQLOp, SQLExprConverter)
class SQLModulo(SQLOp):
def __init__(self, expr1, expr2):
SQLOp.__init__(self, '%', expr1, expr2)
def __sqlrepr__(self, db):
if db == 'sqlite':
return SQLOp.__sqlrepr__(self, db)
s1 = sqlrepr(self.expr1, db)
s2 = sqlrepr(self.expr2, db)
return "MOD(%s, %s)" % (s1, s2)
registerConverter(SQLModulo, SQLExprConverter)
class SQLCall(SQLExpression):
def __init__(self, expr, args):
self.expr = expr
self.args = args
def __sqlrepr__(self, db):
return "%s%s" % (sqlrepr(self.expr, db), sqlrepr(self.args, db))
def components(self):
return [self.expr] + list(self.args)
def execute(self, executor):
raise ValueError("I don't yet know how to locally execute functions")
registerConverter(SQLCall, SQLExprConverter)
class SQLPrefix(SQLExpression):
def __init__(self, prefix, expr):
self.prefix = prefix
self.expr = expr
def __sqlrepr__(self, db):
return "%s %s" % (self.prefix, sqlrepr(self.expr, db))
def components(self):
return [self.expr]
def execute(self, executor):
prefix = self.prefix
expr = execute(self.expr, executor)
if prefix == "+":
return expr
elif prefix == "-":
return -expr
elif prefix.upper() == "NOT":
return not expr
registerConverter(SQLPrefix, SQLExprConverter)
class SQLConstant(SQLExpression):
def __init__(self, const):
self.const = const
def __sqlrepr__(self, db):
return self.const
def execute(self, executor):
raise ValueError("I don't yet know how to execute SQL constants")
registerConverter(SQLConstant, SQLExprConverter)
class SQLTrueClauseClass(SQLExpression):
def __sqlrepr__(self, db):
return "1 = 1"
def execute(self, executor):
return 1
SQLTrueClause = SQLTrueClauseClass()
registerConverter(SQLTrueClauseClass, SQLExprConverter)
########################################
# Namespaces
########################################
class Field(SQLExpression):
def __init__(self, tableName, fieldName):
self.tableName = tableName
self.fieldName = fieldName
def __sqlrepr__(self, db):
return self.tableName + "." + self.fieldName
def tablesUsedImmediate(self):
return [self.tableName]
def execute(self, executor):
return executor.field(self.tableName, self.fieldName)
class SQLObjectField(Field):
def __init__(self, tableName, fieldName, original, soClass, column):
Field.__init__(self, tableName, fieldName)
self.original = original
self.soClass = soClass
self.column = column
def _from_python(self, value):
column = self.column
if not isinstance(value, SQLExpression) and \
column and column.from_python:
value = column.from_python(value, SQLObjectState(self.soClass))
return value
def __eq__(self, other):
if other is None:
return ISNULL(self)
other = self._from_python(other)
return SQLOp('=', self, other)
def __ne__(self, other):
if other is None:
return ISNOTNULL(self)
other = self._from_python(other)
return SQLOp('<>', self, other)
def startswith(self, s):
s = self._from_python(s)
return STARTSWITH(self, s)
def endswith(self, s):
s = self._from_python(s)
return ENDSWITH(self, s)
def contains(self, s):
s = self._from_python(s)
return CONTAINSSTRING(self, s)
registerConverter(SQLObjectField, SQLExprConverter)
class Table(SQLExpression):
FieldClass = Field
def __init__(self, tableName):
self.tableName = tableName
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return self.FieldClass(self.tableName, attr)
def __sqlrepr__(self, db):
return _str_or_sqlrepr(self.tableName, db)
def execute(self, executor):
raise ValueError("Tables don't have values")
class SQLObjectTable(Table):
FieldClass = SQLObjectField
def __init__(self, soClass):
self.soClass = soClass
assert soClass.sqlmeta.table, (
"Bad table name in class %r: %r"
% (soClass, soClass.sqlmeta.table))
Table.__init__(self, soClass.sqlmeta.table)
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
if attr == 'id':
return self._getattrFromID(attr)
elif attr in self.soClass.sqlmeta.columns:
column = self.soClass.sqlmeta.columns[attr]
return self._getattrFromColumn(column, attr)
elif attr + 'ID' in \
[k for (k, v) in self.soClass.sqlmeta.columns.items()
if v.foreignKey]:
attr += 'ID'
column = self.soClass.sqlmeta.columns[attr]
return self._getattrFromColumn(column, attr)
else:
raise AttributeError(
"%s instance has no attribute '%s'" % (self.soClass.__name__,
attr))
def _getattrFromID(self, attr):
return self.FieldClass(self.tableName, self.soClass.sqlmeta.idName,
attr, self.soClass, None)
def _getattrFromColumn(self, column, attr):
return self.FieldClass(self.tableName, column.dbName, attr,
self.soClass, column)
class SQLObjectTableWithJoins(SQLObjectTable):
def __getattr__(self, attr):
if attr + 'ID' in \
[k for (k, v) in self.soClass.sqlmeta.columns.items()
if v.foreignKey]:
column = self.soClass.sqlmeta.columns[attr + 'ID']
return self._getattrFromForeignKey(column, attr)
elif attr in [x.joinMethodName for x in self.soClass.sqlmeta.joins]:
join = [x for x in self.soClass.sqlmeta.joins
if x.joinMethodName == attr][0]
return self._getattrFromJoin(join, attr)
else:
return SQLObjectTable.__getattr__(self, attr)
def _getattrFromForeignKey(self, column, attr):
ret = getattr(self, column.name) == \
getattr(self.soClass, '_SO_class_' + column.foreignKey).q.id
return ret
def _getattrFromJoin(self, join, attr):
if hasattr(join, 'otherColumn'):
return AND(
join.otherClass.q.id == Field(join.intermediateTable,
join.otherColumn),
Field(join.intermediateTable,
join.joinColumn) == self.soClass.q.id)
else:
return getattr(join.otherClass.q, join.joinColumn) == \
self.soClass.q.id
class TableSpace:
TableClass = Table
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return self.TableClass(attr)
class ConstantSpace:
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return SQLConstant(attr)
########################################
# Table aliases
########################################
class AliasField(Field):
def __init__(self, tableName, fieldName, alias, aliasTable):
Field.__init__(self, tableName, fieldName)
self.alias = alias
self.aliasTable = aliasTable
def __sqlrepr__(self, db):
fieldName = self.fieldName
if isinstance(fieldName, SQLExpression):
fieldName = sqlrepr(fieldName, db)
return self.alias + "." + fieldName
def tablesUsedImmediate(self):
return [self.aliasTable]
class AliasTable(Table):
as_string = '' # set it to "AS" if your database requires it
FieldClass = AliasField
_alias_lock = threading.Lock()
_alias_counter = 0
def __init__(self, table, alias=None):
if hasattr(table, "sqlmeta"):
tableName = SQLConstant(table.sqlmeta.table)
elif isinstance(table, (Select, Union)):
assert alias is not None, \
"Alias name cannot be constructed from Select instances, " \
"please provide an 'alias' keyword."
tableName = Subquery('', table)
table = None
else:
tableName = SQLConstant(table)
table = None
Table.__init__(self, tableName)
self.table = table
if alias is None:
self._alias_lock.acquire()
try:
AliasTable._alias_counter += 1
alias = "%s_alias%d" % (tableName, AliasTable._alias_counter)
finally:
self._alias_lock.release()
self.alias = alias
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
if self.table:
attr = getattr(self.table.q, attr).fieldName
return self.FieldClass(self.tableName, attr, self.alias, self)
def __sqlrepr__(self, db):
return "%s %s %s" % (sqlrepr(self.tableName, db), self.as_string,
self.alias)
class Alias(SQLExpression):
def __init__(self, table, alias=None):
self.q = AliasTable(table, alias)
def __sqlrepr__(self, db):
return sqlrepr(self.q, db)
def components(self):
return [self.q]
class Union(SQLExpression):
def __init__(self, *tables):
tabs = []
for t in tables:
if not isinstance(t, SQLExpression) and hasattr(t, 'sqlmeta'):
t = t.sqlmeta.table
if isinstance(t, Alias):
t = t.q
if isinstance(t, Table):
t = t.tableName
if not isinstance(t, SQLExpression):
t = SQLConstant(t)
tabs.append(t)
self.tables = tabs
def __sqlrepr__(self, db):
return " UNION ".join([str(sqlrepr(t, db)) for t in self.tables])
########################################
# SQL Statements
########################################
class Select(SQLExpression):
def __init__(self, items=NoDefault, where=NoDefault, groupBy=NoDefault,
having=NoDefault, orderBy=NoDefault, limit=NoDefault,
join=NoDefault, lazyColumns=False, distinct=False,
start=0, end=None, reversed=False, forUpdate=False,
clause=NoDefault, staticTables=NoDefault,
distinctOn=NoDefault):
self.ops = {}
if not isinstance(items, (list, tuple, types.GeneratorType)):
items = [items]
if clause is NoDefault and where is not NoDefault:
clause = where
if staticTables is NoDefault:
staticTables = []
self.ops['items'] = items
self.ops['clause'] = clause
self.ops['groupBy'] = groupBy
self.ops['having'] = having
self.ops['orderBy'] = orderBy
self.ops['limit'] = limit
self.ops['join'] = join
self.ops['lazyColumns'] = lazyColumns
self.ops['distinct'] = distinct
self.ops['distinctOn'] = distinctOn
self.ops['start'] = start
self.ops['end'] = end
self.ops['reversed'] = reversed
self.ops['forUpdate'] = forUpdate
self.ops['staticTables'] = staticTables
def clone(self, **newOps):
ops = self.ops.copy()
ops.update(newOps)
return self.__class__(**ops)
def newItems(self, items):
return self.clone(items=items)
def newClause(self, new_clause):
return self.clone(clause=new_clause)
def orderBy(self, orderBy):
return self.clone(orderBy=orderBy)
def unlimited(self):
return self.clone(limit=NoDefault, start=0, end=None)
def limit(self, limit):
self.clone(limit=limit)
def lazyColumns(self, value):
return self.clone(lazyColumns=value)
def reversed(self):
return self.clone(reversed=not self.ops.get('reversed', False))
def distinct(self):
return self.clone(distinct=True)
def filter(self, filter_clause):
if filter_clause is None:
# None doesn't filter anything, it's just a no-op:
return self
clause = self.ops['clause']
if isinstance(clause, string_type):
clause = SQLConstant('(%s)' % clause)
return self.newClause(AND(clause, filter_clause))
def __sqlrepr__(self, db):
select = "SELECT"
if self.ops['distinct']:
select += " DISTINCT"
if self.ops['distinctOn'] is not NoDefault:
select += " ON(%s)" % _str_or_sqlrepr(
self.ops['distinctOn'], db)
if not self.ops['lazyColumns']:
select += " %s" % ", ".join(
[str(_str_or_sqlrepr(v, db)) for v in self.ops['items']])
else:
select += " %s" % _str_or_sqlrepr(self.ops['items'][0], db)
join = []
join_str = ''
if self.ops['join'] is not NoDefault and self.ops['join'] is not None:
_join = self.ops['join']
if isinstance(_join, str):
join_str = " " + _join
elif isinstance(_join, SQLJoin):
join.append(_join)
else:
join.extend(_join)
tables = set()
for x in self.ops['staticTables']:
if isinstance(x, SQLExpression):
x = sqlrepr(x, db)
tables.add(x)
things = list(self.ops['items']) + join
if self.ops['clause'] is not NoDefault:
things.append(self.ops['clause'])
for thing in things:
if isinstance(thing, SQLExpression):
tables.update(tablesUsedSet(thing, db))
for j in join:
t1 = _str_or_sqlrepr(j.table1, db)
if t1 in tables:
tables.remove(t1)
t2 = _str_or_sqlrepr(j.table2, db)
if t2 in tables:
tables.remove(t2)
if tables:
select += " FROM %s" % ", ".join(sorted(tables))
elif join:
select += " FROM"
tablesYet = tables
for j in join:
if tablesYet and j.table1:
sep = ", "
else:
sep = " "
select += sep + sqlrepr(j, db)
tablesYet = True
if join_str:
select += join_str
if self.ops['clause'] is not NoDefault:
select += " WHERE %s" % _str_or_sqlrepr(self.ops['clause'], db)
if self.ops['groupBy'] is not NoDefault:
groupBy = _str_or_sqlrepr(self.ops['groupBy'], db)
if isinstance(self.ops['groupBy'], (list, tuple)):
groupBy = groupBy[1:-1] # Remove parens
select += " GROUP BY %s" % groupBy
if self.ops['having'] is not NoDefault:
select += " HAVING %s" % _str_or_sqlrepr(self.ops['having'], db)
if self.ops['orderBy'] is not NoDefault and \
self.ops['orderBy'] is not None:
orderBy = self.ops['orderBy']
if self.ops['reversed']:
reverser = DESC
else:
def reverser(x):
return x
if isinstance(orderBy, (list, tuple)):
select += " ORDER BY %s" % ", ".join(
[_str_or_sqlrepr(reverser(_x), db) for _x in orderBy])
else:
select += " ORDER BY %s" % _str_or_sqlrepr(
reverser(orderBy), db)
start, end = self.ops['start'], self.ops['end']
if self.ops['limit'] is not NoDefault:
end = start + self.ops['limit']
if start or end:
from .dbconnection import dbConnectionForScheme
select = dbConnectionForScheme(db)._queryAddLimitOffset(select,
start, end)
if self.ops['forUpdate']:
select += " FOR UPDATE"
return select
registerConverter(Select, SQLExprConverter)
class Insert(SQLExpression):
def __init__(self, table, valueList=None, values=None, template=NoDefault):
self.template = template
self.table = table
if valueList:
if values:
raise TypeError("You may only give valueList *or* values")
self.valueList = valueList
else:
self.valueList = [values]
def __sqlrepr__(self, db):
if not self.valueList:
return ''
insert = "INSERT INTO %s" % self.table
allowNonDict = True
template = self.template
if (template is NoDefault) and isinstance(self.valueList[0], dict):
template = list(sorted(self.valueList[0].keys()))
allowNonDict = False
if template is not NoDefault:
insert += " (%s)" % ", ".join(template)
insert += " VALUES "
listToJoin = []
listToJoin_app = listToJoin.append
for value in self.valueList:
if isinstance(value, dict):
if template is NoDefault:
raise TypeError(
"You can't mix non-dictionaries with dictionaries "
"in an INSERT if you don't provide a template (%s)" %
repr(value))
value = dictToList(template, value)
elif not allowNonDict:
raise TypeError(
"You can't mix non-dictionaries with dictionaries "
"in an INSERT if you don't provide a template (%s)" %
repr(value))
listToJoin_app("(%s)" % ", ".join([sqlrepr(v, db) for v in value]))
insert = "%s%s" % (insert, ", ".join(listToJoin))
return insert
registerConverter(Insert, SQLExprConverter)
def dictToList(template, dict):
list = []
for key in template:
list.append(dict[key])
if len(dict.keys()) > len(template):
raise TypeError(
"Extra entries in dictionary that aren't asked for in template "
"(template=%s, dict=%s)" % (repr(template), repr(dict)))
return list
class Update(SQLExpression):
def __init__(self, table, values, template=NoDefault, where=NoDefault):
self.table = table
self.values = values
self.template = template
self.whereClause = where
def __sqlrepr__(self, db):
update = "%s %s" % (self.sqlName(), self.table)
update += " SET"
first = True
if self.template is not NoDefault:
for i in range(len(self.template)):
if first:
first = False
else:
update += ","
update += " %s=%s" % (self.template[i],
sqlrepr(self.values[i], db))
else:
for key, value in sorted(self.values.items()):
if first:
first = False
else:
update += ","
update += " %s=%s" % (key, sqlrepr(value, db))
if self.whereClause is not NoDefault:
update += " WHERE %s" % _str_or_sqlrepr(self.whereClause, db)
return update
def sqlName(self):
return "UPDATE"
registerConverter(Update, SQLExprConverter)
class Delete(SQLExpression):
"""To be safe, this will signal an error if there is no where clause,
unless you pass in where=None to the constructor."""
def __init__(self, table, where=NoDefault):
self.table = table
if where is NoDefault:
raise TypeError(
"You must give a where clause or pass in None "
"to indicate no where clause")
self.whereClause = where
def __sqlrepr__(self, db):
whereClause = self.whereClause
if whereClause is None:
return "DELETE FROM %s" % self.table
whereClause = _str_or_sqlrepr(whereClause, db)
return "DELETE FROM %s WHERE %s" % (self.table, whereClause)
registerConverter(Delete, SQLExprConverter)
class Replace(Update):
def sqlName(self):
return "REPLACE"
registerConverter(Replace, SQLExprConverter)
########################################
# SQL Builtins
########################################
class DESC(SQLExpression):
def __init__(self, expr):
self.expr = expr
def __sqlrepr__(self, db):
if isinstance(self.expr, DESC):
return sqlrepr(self.expr.expr, db)
return '%s DESC' % sqlrepr(self.expr, db)
def AND(*ops):
if not ops:
return None
op1 = ops[0]
ops = ops[1:]
if ops:
return SQLOp("AND", op1, AND(*ops))
else:
return op1
def OR(*ops):
if not ops:
return None
op1 = ops[0]
ops = ops[1:]
if ops:
return SQLOp("OR", op1, OR(*ops))
else:
return op1
def NOT(op):
return SQLPrefix("NOT", op)
def _IN(item, list):
return SQLOp("IN", item, list)