File: syntax.py

package info (click to toggle)
twextpy 1%3A0.1~git20161216.0.b90293c-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,724 kB
  • sloc: python: 20,458; sh: 742; makefile: 5
file content (2142 lines) | stat: -rw-r--r-- 67,128 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
# -*- test-case-name: twext.enterprise.dal.test.test_sqlsyntax -*-
##
# Copyright (c) 2010-2016 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

"""
Syntax wrappers and generators for SQL.
"""

__all__ = [
    "DALError",
    "QueryPlaceholder",
    "FixedPlaceholder",
    "NumericPlaceholder",
    "defaultPlaceholder",
    "QueryGenerator",
    "TableMismatch",
    "NotEnoughValues",
    "Syntax",
    "comparison",
    "ExpressionSyntax",
    "FunctionInvocation",
    "Constant",
    "NamedValue",
    "Function",
    "SchemaSyntax",
    "SequenceSyntax",
    "TableSyntax",
    "TableAlias",
    "Join",
    "ColumnSyntax",
    "ResultAliasSyntax",
    "AliasReferenceSyntax",
    "AliasedColumnSyntax",
    "Comparison",
    "Not",
    "NullComparison",
    "CompoundComparison",
    "ColumnComparison",
    "Column",
    "Tuple",
    "SetExpression",
    "Union",
    "Intersect",
    "Except",
    "Select",
    "Insert",
    "Update",
    "Delete",
    "Lock",
    "DatabaseLock",
    "DatabaseUnlock",
    "RollbackToSavepoint",
    "ReleaseSavepoint",
    "SavepointAction",
    "NoOp",
    "SQLFragment",
    "Parameter",
]

from itertools import count, repeat
from functools import partial
from operator import eq, ne

from zope.interface import implements

from twisted.internet.defer import succeed

from twext.enterprise.dal.model import Schema, Table, Column, Sequence, SQLType
from twext.enterprise.ienterprise import (
    POSTGRES_DIALECT, ORACLE_DIALECT, SQLITE_DIALECT, DatabaseType, IDerivedParameter
)
from twext.enterprise.util import mapOracleOutputType

from twisted.internet.defer import inlineCallbacks, returnValue

try:
    import cx_Oracle
    cx_Oracle
except ImportError:
    cx_Oracle = None


class DALError(Exception):
    """
    Base class for exceptions raised by this module.  This can be raised
    directly for API violations.  This exception represents a serious
    programming error and should normally never be caught or ignored.
    """


class QueryPlaceholder(object):
    """
    Representation of the placeholders required to generate some SQL, for a
    single statement.  Contains information necessary to generate place holder
    strings based on the database dialect.
    """

    def placeholder(self):
        raise NotImplementedError("See subclasses.")


class FixedPlaceholder(QueryPlaceholder):
    """
    Fixed string used as the place holder.
    """

    def __init__(self, placeholder):
        self._placeholder = placeholder

    def placeholder(self):
        return self._placeholder


class NumericPlaceholder(QueryPlaceholder):
    """
    Numeric counter used as the place holder.
    """

    def __init__(self):
        self._next = count(1).next

    def placeholder(self):
        return ":" + str(self._next())


def defaultPlaceholder():
    """
    Generate a default L{QueryPlaceholder}
    """
    return FixedPlaceholder("?")


class QueryGenerator(object):
    """
    Maintains various pieces of transient information needed when building a
    query. This includes the SQL dialect, the format of the place holder and
    and automated id generator.
    """

    def __init__(self, dbtype=None, placeholder=None):
        self.dbtype = dbtype if dbtype else DatabaseType(POSTGRES_DIALECT, "qmark")
        if placeholder is None:
            placeholder = defaultPlaceholder()
        self.placeholder = placeholder

        self.generatedID = count(1).next

    def nextGeneratedID(self):
        return "genid_%d" % (self.generatedID(),)

    def shouldQuote(self, name):
        return (self.dbtype.dialect == ORACLE_DIALECT and name.lower() in _KEYWORDS)


class TableMismatch(Exception):
    """
    A table in a statement did not match with a column.
    """


class NotEnoughValues(DALError):
    """
    Not enough values were supplied for an L{Insert}.
    """


class _Statement(object):
    """
    An SQL statement that may be executed.  (An abstract base class, must
    implement several methods.)
    """

    _paramstyles = {
        "pyformat": partial(FixedPlaceholder, "%s"),
        "numeric": NumericPlaceholder,
        "qmark": defaultPlaceholder,
    }

    def toSQL(self, queryGenerator=None):
        if queryGenerator is None:
            queryGenerator = QueryGenerator()
        return self._toSQL(queryGenerator)

    def _extraVars(self, txn, queryGenerator):
        """
        A hook for subclasses to provide additional keyword arguments to the
        C{bind} call when L{_Statement.on} is executed.  Currently this is used
        only for "out" parameters to capture results when executing statements
        that do not normally have a result (L{Insert}, L{Delete}, L{Update}).
        """
        return {}

    def _extraResult(self, result, outvars, queryGenerator):
        """
        A hook for subclasses to manipulate the results of "on", after they've
        been retrieved by the database but before they've been given to
        application code.

        @param result: a L{Deferred} that will fire with the rows as returned
            by the database.
        @type result: C{list} of rows, which are C{list}s or C{tuple}s.

        @param outvars: a dictionary of extra variables returned by
            C{self._extraVars}.

        @param queryGenerator: information about the connection where the
            statement was executed.

        @type queryGenerator: L{QueryGenerator} (a subclass thereof)

        @return: the result to be returned from L{_Statement.on}.
        @rtype: L{Deferred} firing result rows
        """
        return result

    def on(self, txn, raiseOnZeroRowCount=None, **kw):
        """
        Execute this statement on a given L{IAsyncTransaction} and return the
        resulting L{Deferred}.

        @param txn: the L{IAsyncTransaction} to execute this on.

        @param raiseOnZeroRowCount: a 0-argument callable which returns an
            exception to raise if the executed SQL does not affect any rows.

        @param kw: keyword arguments, mapping names of L{Parameter} objects
            located somewhere in C{self}

        @return: results from the database.
        @rtype: a L{Deferred} firing a C{list} of records (C{tuple}s or
            C{list}s)
        """
        queryGenerator = QueryGenerator(
            txn.dbtype, self._paramstyles[txn.dbtype.paramstyle]()
        )
        outvars = self._extraVars(txn, queryGenerator)
        kw.update(outvars)
        fragment = self.toSQL(queryGenerator).bind(**kw)
        result = txn.execSQL(
            fragment.text, fragment.parameters, raiseOnZeroRowCount
        )
        result = self._extraResult(result, outvars, queryGenerator)
        if queryGenerator.dbtype.dialect == ORACLE_DIALECT and result:
            result.addCallback(self._fixOracleNulls)
        return result

    def _resultColumns(self):
        """
        Subclasses must implement this to return a description of the columns
        expected to be returned.  This is a list of L{ColumnSyntax} objects,
        and possibly other expression syntaxes which will be converted to
        C{None}.
        """
        raise NotImplementedError(
            "Each statement subclass must describe its result"
        )

    def _resultShape(self):
        """
        Process the result of the subclass's C{_resultColumns}, as described in
        the docstring above.
        """
        for expectation in self._resultColumns():
            if isinstance(expectation, ColumnSyntax):
                yield expectation.model
            else:
                yield None

    def _fixOracleNulls(self, rows):
        """
        Oracle treats empty strings as C{NULL}.  Fix this by looking at the
        columns we expect to have returned, and replacing any C{None}s with
        empty strings in the appropriate position.
        """
        if rows is None:
            return None

        newRows = []

        for row in rows:
            newRow = []

            for column, description in zip(row, self._resultShape()):
                if (
                    description is not None and
                    # FIXME: "is the python type str" is what I mean; this list
                    # should be more centrally maintained
                    description.type.name in ("varchar", "text", "char") and
                    column is None
                ):
                    column = ""
                newRow.append(column)

            newRows.append(newRow)

        return newRows


class Syntax(object):
    """
    Base class for syntactic convenience.

    This class will define dynamic attribute access to represent its underlying
    model as a Python namespace.

    You can access the underlying model as ".model".
    """

    modelType = None
    model = None

    def __init__(self, model):
        if not isinstance(model, self.modelType):
            # make sure we don't get a misleading repr()
            raise DALError("type mismatch: %r %r", type(self), model)
        self.model = model

    def __repr__(self):
        if self.model is not None:
            return "<Syntax for: %r>" % (self.model,)
        return super(Syntax, self).__repr__()


def comparison(comparator):
    def __(self, other):
        if other is None:
            return NullComparison(self, comparator)
        if isinstance(other, Select):
            return NotImplemented
        if isinstance(other, ColumnSyntax):
            return ColumnComparison(self, comparator, other)
        if isinstance(other, ExpressionSyntax):
            return CompoundComparison(self, comparator, other)
        else:
            return CompoundComparison(self, comparator, Constant(other))
    return __


class ExpressionSyntax(Syntax):
    __eq__ = comparison("=")
    __ne__ = comparison("!=")

    # NB: these operators "cannot be used with lists" (see ORA-01796)
    __gt__ = comparison(">")
    __ge__ = comparison(">=")
    __lt__ = comparison("<")
    __le__ = comparison("<=")

    # TODO: operators aren't really comparisons; these should behave slightly
    # differently.  (For example; in Oracle, C{select 3 = 4 from dual} doesn't
    # work, but C{select 3 + 4 from dual} does; similarly, you can't do
    # C{select * from foo where 3 + 4}, but you can do C{select * from foo
    # where 3 + 4 > 0}.)
    __add__ = comparison("+")
    __sub__ = comparison("-")
    __div__ = comparison("/")
    __mul__ = comparison("*")

    def __nonzero__(self):
        raise DALError(
            "SQL expressions should not be tested for truth value in Python.")

    def In(self, other):
        """
        We support two forms of the SQL "IN" syntax: one where a list of values
        is supplied, the other where a sub-select is used to provide a set of
        values.

        @param other: a constant parameter or sub-select
        @type other: L{Parameter} or L{Select}
        """
        return self._commonIn('in', other)

    def NotIn(self, other):
        """
        We support two forms of the SQL "NOT IN" syntax: one where a list of values
        is supplied, the other where a sub-select is used to provide a set of
        values.

        @param other: a constant parameter or sub-select
        @type other: L{Parameter} or L{Select}
        """
        return self._commonIn('not in', other)

    def _commonIn(self, op, other):
        """
        We support two forms of the SQL "IN" and "NOT IN" syntax: one where a list
        of values is supplied, the other where a sub-select is used to provide a set
        of values.

        @param other: a constant parameter or sub-select
        @type other: L{Parameter} or L{Select}
        """

        if isinstance(other, Parameter):
            if other.count is None:
                raise DALError(
                    "{} expression needs an explicit count of parameters".format(op.upper())
                )
            return CompoundComparison(self, op, Constant(other))
        elif isinstance(other, set) or isinstance(other, frozenset) or isinstance(other, list) or isinstance(other, tuple):
            return CompoundComparison(self, op, Constant(other))
        else:
            # Can't be Select.__contains__ because __contains__ gets
            # __nonzero__ called on its result by the "in" syntax.
            return CompoundComparison(self, op, other)

    def StartsWith(self, other):
        return CompoundComparison(
            self, "like",
            CompoundComparison(Constant(other), "||", Constant("%"))
        )

    def NotStartsWith(self, other):
        return CompoundComparison(
            self, "not like",
            CompoundComparison(Constant(other), "||", Constant("%"))
        )

    def EndsWith(self, other):
        return CompoundComparison(
            self, "like",
            CompoundComparison(Constant("%"), "||", Constant(other))
        )

    def NotEndsWith(self, other):
        return CompoundComparison(
            self, "not like",
            CompoundComparison(Constant("%"), "||", Constant(other))
        )

    def Contains(self, other):
        return CompoundComparison(
            self, "like",
            CompoundComparison(
                Constant("%"), "||",
                CompoundComparison(Constant(other), "||", Constant("%"))
            )
        )

    def NotContains(self, other):
        return CompoundComparison(
            self, "not like",
            CompoundComparison(
                Constant("%"), "||",
                CompoundComparison(Constant(other), "||", Constant("%"))
            )
        )


class FunctionInvocation(ExpressionSyntax):

    def __init__(self, function, *args):
        self.function = function
        self.args = args

    def allColumns(self):
        """
        All of the columns in all of the arguments' columns.
        """
        def ac():
            for arg in self.args:
                for column in arg.allColumns():
                    yield column
        return list(ac())

    def subSQL(self, queryGenerator, allTables):
        result = SQLFragment(self.function.nameFor(queryGenerator))
        result.append(_inParens(
            _commaJoined(
                _convert(arg).subSQL(queryGenerator, allTables)
                for arg in self.args
            )
        ))
        return result


class Constant(ExpressionSyntax):
    """
    Generates an expression for a place holder where a value will be bound to
    the query. If the constant is a Parameter with count > 1 then a
    parenthesized, comma-separated list of place holders will be generated.
    """

    def __init__(self, value):
        self.value = value

    def allColumns(self):
        return []

    def subSQL(self, queryGenerator, allTables):
        if isinstance(self.value, Parameter) and self.value.count is not None:
            return _inParens(
                _CommaList([
                    SQLFragment(
                        queryGenerator.placeholder.placeholder(),
                        [self.value] if counter == 0 else []
                    )
                    for counter in range(self.value.count)
                ]).subSQL(queryGenerator, allTables)
            )
        elif isinstance(self.value, set) or isinstance(self.value, frozenset) or isinstance(self.value, list) or isinstance(self.value, tuple):
            return _inParens(
                _CommaList([
                    SQLFragment(queryGenerator.placeholder.placeholder(), [value])
                    for value in self.value
                ]).subSQL(queryGenerator, allTables)
            )
        else:
            return SQLFragment(
                queryGenerator.placeholder.placeholder(), [self.value]
            )


class NamedValue(ExpressionSyntax):
    """
    A constant within the database; something predefined, such as
    CURRENT_TIMESTAMP.
    """

    def __init__(self, name):
        self.name = name

    def subSQL(self, queryGenerator, allTables):
        return SQLFragment(self.name)


class Function(object):
    """
    An L{Function} is a representation of an SQL Function function.
    """

    def __init__(self, name, oracleName=None):
        self.name = name
        self.oracleName = oracleName

    def nameFor(self, queryGenerator):
        if (
            queryGenerator.dbtype.dialect == ORACLE_DIALECT and
            self.oracleName is not None
        ):
            return self.oracleName

        return self.name

    def __call__(self, *args):
        """
        Produce an L{FunctionInvocation}
        """
        return FunctionInvocation(self, *args)


Count = Function("count")
Sum = Function("sum")
Max = Function("max")
Min = Function("min")
Len = Function("character_length", "length")
Upper = Function("upper")
Lower = Function("lower")
Coalesce = Function("coalesce")
NullIf = Function("nullif")

_sqliteLastInsertRowID = Function("last_insert_rowid")

# Use a specific value here for "the convention for case-insensitive values in
# the database" so we don't need to keep remembering whether it's upper or
# lowercase.
CaseFold = Lower


class SchemaSyntax(Syntax):
    """
    Syntactic convenience for L{Schema}.
    """

    modelType = Schema

    def __getattr__(self, attr):
        try:
            tableModel = self.model.tableNamed(attr)
        except KeyError:
            try:
                seqModel = self.model.sequenceNamed(attr)
            except KeyError:
                raise AttributeError(
                    "schema has no table or sequence %r" % (attr,)
                )
            else:
                return SequenceSyntax(seqModel)
        else:
            syntax = TableSyntax(tableModel)
            # Needs to be preserved here so that aliasing will work.
            setattr(self, attr, syntax)
            return syntax

    def __iter__(self):
        for table in self.model.tables:
            yield TableSyntax(table)


class SequenceSyntax(ExpressionSyntax):
    """
    Syntactic convenience for L{Sequence}.
    """

    modelType = Sequence

    def subSQL(self, queryGenerator, allTables):
        """
        Convert to an SQL fragment.
        """
        if queryGenerator.dbtype.dialect == ORACLE_DIALECT:
            fmt = "%s.nextval"
        else:
            fmt = "nextval('%s')"
        return SQLFragment(fmt % (self.model.name,))


def _nameForDialect(name, dialect):
    """
    If the given name is being computed in the oracle dialect, truncate it to
    30 characters.
    """
    if dialect == ORACLE_DIALECT:
        name = name[:30]
    return name


class TableSyntax(Syntax):
    """
    Syntactic convenience for L{Table}.
    """

    modelType = Table

    def alias(self):
        """
        Return an alias for this L{TableSyntax} so that it might be joined
        against itself.

        As in SQL, C{someTable.join(someTable)} is an error; you can't join a
        table against itself.  However, C{t = someTable.alias();
        someTable.join(t)} is usable as a C{from} clause.
        """
        return TableAlias(self.model)

    def join(self, otherTableSyntax, on=None, type=""):
        """
        Create a L{Join}, representing a join between two tables.
        """
        if on is None and not type:
            type = "cross"
        return Join(self, type, otherTableSyntax, on)

    def subSQL(self, queryGenerator, allTables):
        """
        Generate the L{SQLFragment} for this table's identification; this is
        for use in a C{from} clause.
        """
        # XXX maybe there should be a specific method which is only invoked
        # from the FROM clause, that only tables and joins would implement?
        return SQLFragment(
            _nameForDialect(self.model.name, queryGenerator.dbtype.dialect)
        )

    def __getattr__(self, attr):
        """
        Attributes named after columns on a L{TableSyntax} are returned by
        accessing their names as attributes.  For example, if there is a schema
        syntax object created from SQL equivalent to C{create table foo (bar
        integer, baz integer)}, C{schemaSyntax.foo.bar} and
        C{schemaSyntax.foo.baz}
        """
        try:
            column = self.model.columnNamed(attr)
        except KeyError:
            raise AttributeError(
                "table {0} has no column {1}".format(self.model.name, attr)
            )
        else:
            return ColumnSyntax(column)

    def __iter__(self):
        """
        Yield a L{ColumnSyntax} for each L{Column} in this L{TableSyntax}'s
        model's table.
        """
        for column in self.model.columns:
            yield ColumnSyntax(column)

    def tables(self):
        """
        Return a C{list} of tables involved in the query by this table.  (This
        method is expected by anything that can act as the C{From} clause: see
        L{Join.tables})
        """
        return [self]

    def columnAliases(self):
        """
        Inspect the Python aliases for this table in the given schema.  Python
        aliases for a table are created by setting an attribute on the schema.
        For example, in a schema which had "schema.MYTABLE.ID =
        schema.MYTABLE.MYTABLE_ID" applied to it,
        schema.MYTABLE.columnAliases() would return C{[("ID",
        schema.MYTABLE.MYTABLE_ID)]}.

        @return: a list of 2-tuples of (alias (C{str}), column
            (C{ColumnSyntax})), enumerating all of the Python aliases provided.
        """
        result = {}
        for k, v in self.__dict__.items():
            if isinstance(v, ColumnSyntax):
                result[k] = v
        return result

    def __contains__(self, columnSyntax):
        if isinstance(columnSyntax, FunctionInvocation):
            columnSyntax = columnSyntax.arg
        return (columnSyntax.model.table is self.model)


class TableAlias(TableSyntax):
    """
    An alias for a table, under a different name, for the purpose of doing a
    self-join.
    """

    def subSQL(self, queryGenerator, allTables):
        """
        Return an L{SQLFragment} with a string of the form C{"mytable myalias"}
        suitable for use in a FROM clause.
        """
        result = super(TableAlias, self).subSQL(queryGenerator, allTables)
        result.append(SQLFragment(" " + self._aliasName(allTables)))
        return result

    def _aliasName(self, allTables):
        """
        The alias under which this table will be known in the query.

        @param allTables: a C{list}, as passed to a C{subSQL} method during SQL
            generation.

        @return: a string naming this alias, a unique identifier, albeit one
            which is only stable within the query which populated C{allTables}.
        @rtype: C{str}
        """
        anum = [
            t for t in allTables
            if isinstance(t, TableAlias)
        ].index(self) + 1
        return "alias%d" % (anum,)

    def __getattr__(self, attr):
        return AliasedColumnSyntax(self, self.model.columnNamed(attr))


class Join(object):
    """
    A DAL object representing an SQL C{join} statement.

    @ivar leftSide: a L{Join} or L{TableSyntax} representing the left side of
        this join.

    @ivar rightSide: a L{TableSyntax} representing the right side of this join.

    @ivar type: the type of join this is.  For example, for a left outer join,
        this would be C{"left outer"}.
    @type type: C{str}

    @ivar on: the "on" clause of this table.
    @type on: L{ExpressionSyntax}
    """

    def __init__(self, leftSide, type, rightSide, on):
        self.leftSide = leftSide
        self.type = type
        self.rightSide = rightSide
        self.on = on

    def subSQL(self, queryGenerator, allTables):
        stmt = SQLFragment()
        stmt.append(self.leftSide.subSQL(queryGenerator, allTables))
        if self.type == ",":
            stmt.text += ", "
        else:
            stmt.text += " "
            if self.type:
                stmt.text += self.type
                stmt.text += " "
            stmt.text += "join "
        stmt.append(self.rightSide.subSQL(queryGenerator, allTables))
        if self.type not in ("cross", ","):
            stmt.text += " on "
            stmt.append(self.on.subSQL(queryGenerator, allTables))
        return stmt

    def tables(self):
        """
        Return a C{list} of tables which this L{Join} will involve in a query:
        all those present on the left side, as well as all those present on the
        right side.
        """
        return self.leftSide.tables() + self.rightSide.tables()

    def join(self, otherTable, on=None, type=None):
        if on is None:
            type = "cross"
        return Join(self, type, otherTable, on)


_KEYWORDS = frozenset([
    # SQL keyword, but we have a column with this name
    "access",

    # Not actually a standard keyword, but a function in oracle, and we have a
    # column with this name.
    "path",

    # not actually sure what this is; only experimentally determined that not
    # quoting it causes an issue.
    "size",

    # Oracle docs: UID returns an integer that uniquely identifies the session
    # user (the user who logged on).
    "uid",
])


class ColumnSyntax(ExpressionSyntax):
    """
    Syntactic convenience for L{Column}.

    @ivar _alwaysQualified: a boolean indicating whether to always qualify the
        column name in generated SQL, regardless of whether the column name is
        specific enough even when unqualified.
    @type _alwaysQualified: C{bool}
    """

    modelType = Column

    _alwaysQualified = False

    def allColumns(self):
        return [self]

    def subSQL(self, queryGenerator, allTables):
        # XXX This, and "model", could in principle conflict with column names.
        # Maybe do something about that.
        name = self.model.name
        if queryGenerator.shouldQuote(name):
            name = '"%s"' % (name,)

        if self._alwaysQualified:
            qualified = True
        else:
            qualified = False
            for tableSyntax in allTables:
                if self.model.table is not tableSyntax.model:
                    if (
                        self.model.name in (
                            c.name for c in
                            tableSyntax.model.columns
                        )
                    ):
                        qualified = True
                        break
        if qualified:
            return SQLFragment(self._qualify(name, allTables))
        else:
            return SQLFragment(name)

    def __hash__(self):
        return hash(self.model) + 10

    def _qualify(self, name, allTables):
        return self.model.table.name + "." + name


class ResultAliasSyntax(ExpressionSyntax):

    def __init__(self, expression, alias=None):
        self.expression = expression
        self.alias = alias

    def aliasName(self, queryGenerator):
        if self.alias is None:
            self.alias = queryGenerator.nextGeneratedID()
        return self.alias

    def columnReference(self):
        return AliasReferenceSyntax(self)

    def allColumns(self):
        return self.expression.allColumns()

    def subSQL(self, queryGenerator, allTables):
        result = SQLFragment()
        result.append(self.expression.subSQL(queryGenerator, allTables))
        result.append(SQLFragment(" %s" % (self.aliasName(queryGenerator),)))
        return result


class AliasReferenceSyntax(ExpressionSyntax):

    def __init__(self, resultAlias):
        self.resultAlias = resultAlias

    def allColumns(self):
        return self.resultAlias.allColumns()

    def subSQL(self, queryGenerator, allTables):
        return SQLFragment(self.resultAlias.aliasName(queryGenerator))


class AliasedColumnSyntax(ColumnSyntax):
    """
    An L{AliasedColumnSyntax} is like a L{ColumnSyntax}, but it generates SQL
    for a column of a table under an alias, rather than directly.  i.e. this is
    used for C{"something.col"} in C{"select something.col from tablename
    something"} rather than the "col" in C{"select col from tablename"}.

    @see: L{TableSyntax.alias}
    """

    _alwaysQualified = True

    def __init__(self, tableAlias, model):
        super(AliasedColumnSyntax, self).__init__(model)
        self._tableAlias = tableAlias

    def _qualify(self, name, allTables):
        return self._tableAlias._aliasName(allTables) + "." + name


class Comparison(ExpressionSyntax):

    def __init__(self, a, op, b):
        self.a = a
        self.op = op
        self.b = b

    def _subexpression(self, expr, queryGenerator, allTables):
        result = expr.subSQL(queryGenerator, allTables)
        if self.op not in ("and", "or") and isinstance(expr, Comparison):
            result = _inParens(result)
        return result

    def booleanOp(self, operand, other):
        return CompoundComparison(self, operand, other)

    def And(self, other):
        return self.booleanOp("and", other)

    def Or(self, other):
        return self.booleanOp("or", other)


class Not(Comparison):
    """
    A L{NotColumn} is a logical NOT of an expression.
    """

    def __init__(self, a):
        # "op" and "b" are always None for this comparison type
        super(Not, self).__init__(a, None, None)

    def subSQL(self, queryGenerator, allTables):
        sqls = SQLFragment()
        sqls.text += "not "
        result = self.a.subSQL(queryGenerator, allTables)
        if isinstance(self.a, CompoundComparison) and self.a.op in ("or", "and"):
            result = _inParens(result)
        sqls.append(result)
        return sqls


class NullComparison(Comparison):
    """
    A L{NullComparison} is a comparison of a column or expression with None.
    """

    def __init__(self, a, op):
        # "b" is always None for this comparison type
        super(NullComparison, self).__init__(a, op, None)

    def allColumns(self):
        return self.a.allColumns()

    def subSQL(self, queryGenerator, allTables):
        sqls = SQLFragment()
        sqls.append(self.a.subSQL(queryGenerator, allTables))
        sqls.text += " is "
        if self.op != "=":
            sqls.text += "not "
        sqls.text += "null"
        return sqls


class CompoundComparison(Comparison):
    """
    A compound comparison; two or more constraints, joined by an operation
    (currently only AND or OR).
    """

    def allColumns(self):
        return self.a.allColumns() + self.b.allColumns()

    def subSQL(self, queryGenerator, allTables):
        if (
            queryGenerator.dbtype.dialect == ORACLE_DIALECT and
            isinstance(self.b, Constant) and
            self.b.value == "" and self.op in ("=", "!=")
        ):
            return NullComparison(self.a, self.op).subSQL(
                queryGenerator, allTables
            )

        stmt = SQLFragment()
        result = self._subexpression(self.a, queryGenerator, allTables)
        if (
            isinstance(self.a, CompoundComparison) and
            self.a.op == "or" and self.op == "and"
        ):
            result = _inParens(result)
        stmt.append(result)

        stmt.text += " %s " % (self.op,)

        result = self._subexpression(self.b, queryGenerator, allTables)
        if (
            isinstance(self.b, CompoundComparison) and
            self.b.op == "or" and self.op == "and"
        ):
            result = _inParens(result)

        if isinstance(self.b, Tuple):
            # If the right-hand side of the comparison is a Tuple, it needs to
            # be double-parenthesized in Oracle, as per
            # http://docs.oracle.com/cd/B28359_01/server.111/b28286/expressions015.htm#i1033664
            # because it is an expression list.
            result = _inParens(result)

        stmt.append(result)

        return stmt


_operators = {"=": eq, "!=": ne}


class ColumnComparison(CompoundComparison):
    """
    Comparing two columns is the same as comparing any other two expressions,
    except that Python can retrieve a truth value, so that columns may be
    compared for value equality in scripts that want to interrogate schemas.
    """

    def __nonzero__(self):
        thunk = _operators.get(self.op)
        if thunk is None:
            return super(ColumnComparison, self).__nonzero__()
        return thunk(self.a.model, self.b.model)


class _AllColumns(NamedValue):

    def __init__(self):
        self.name = "*"

    def allColumns(self):
        return []


ALL_COLUMNS = _AllColumns()


class _SomeColumns(object):

    def __init__(self, columns):
        self.columns = columns

    def subSQL(self, queryGenerator, allTables):
        first = True
        cstatement = SQLFragment()
        for column in self.columns:
            if first:
                first = False
            else:
                cstatement.append(SQLFragment(", "))
            cstatement.append(column.subSQL(queryGenerator, allTables))
        return cstatement


def _checkColumnsMatchTables(columns, tables):
    """
    Verify that the given C{columns} match the given C{tables}; that is, that
    every L{TableSyntax} referenced by every L{ColumnSyntax} referenced by
    every L{ExpressionSyntax} in the given C{columns} list is present in the
    given C{tables} list.

    @param columns: a L{list} of L{ExpressionSyntax}, each of which references
        some set of L{ColumnSyntax}es via its C{allColumns} method.

    @param tables: a L{list} of L{TableSyntax}

    @return: L{None}
    @rtype: L{NoneType}

    @raise TableMismatch: if any table referenced by a column is I{not} found
        in C{tables}
    """
    for expression in columns:
        for column in expression.allColumns():
            for table in tables:
                if column in table:
                    break
            else:
                raise TableMismatch(
                    "{} not found in {}".format(column, tables)
                )
    return None


class Case(ExpressionSyntax):
    """
    Implementation of a simple CASE statement:

    CASE ... WHEN ... THEN ... ELSE ... END

    Note that SQL actually allows multiple WHEN ... THEN ... clauses, but
    this implementation only supports one.
    """

    def __init__(self, when, true_result, false_result):
        """
        @param when: WHEN clause - typically a L{Comparison}
        @type when: L{Expression}
        @param true_result: result when WHEN clause is true
        @type true_result: L{Constant} or L{None}
        @param false_result: result when WHEN clause is false
        @type false_result: L{Constant} or L{None}
        """
        self.when = when
        self.true_result = true_result
        self.false_result = false_result

    def subSQL(self, queryGenerator, allTables):
        result = SQLFragment("case when ")
        result.append(self.when.subSQL(queryGenerator, allTables))
        result.append(SQLFragment(" then "))
        if self.true_result is None:
            result.append(SQLFragment("null"))
        else:
            result.append(self.true_result.subSQL(queryGenerator, allTables))
        result.append(SQLFragment(" else "))
        if self.false_result is None:
            result.append(SQLFragment("null"))
        else:
            result.append(self.false_result.subSQL(queryGenerator, allTables))
        result.append(SQLFragment(" end"))

        return result

    def allColumns(self):
        """
        Return all columns referenced by any sub-clauses.
        """
        return self.when.allColumns() + \
            (self.true_result.allColumns() if self.true_result is not None else []) + \
            (self.false_result.allColumns() if self.false_result is not None else [])


class Tuple(ExpressionSyntax):

    def __init__(self, columns):
        self.columns = columns

    def __iter__(self):
        return iter(self.columns)

    def subSQL(self, queryGenerator, allTables):
        return _inParens(_commaJoined(
            c.subSQL(queryGenerator, allTables)
            for c in self.columns
        ))

    def allColumns(self):
        return self.columns


class SetExpression(object):
    """
    A UNION, INTERSECT, or EXCEPT construct used inside a SELECT.
    """

    OPTYPE_ALL = "all"
    OPTYPE_DISTINCT = "distinct"

    def __init__(self, selects, optype=None):
        """
        @param selects: a single Select or a list of Selects
        @type selects: C{list} or L{Select}

        @param optype: whether to use the ALL, DISTINCT constructs: C{None} use
            neither, OPTYPE_ALL, or OPTYPE_DISTINCT
        @type optype: C{str}
        """

        if isinstance(selects, Select):
            selects = (selects,)
        self.selects = selects
        self.optype = optype

        for select in self.selects:
            if not isinstance(select, Select):
                raise DALError(
                    "Must have SELECT statements in a set expression"
                )
        if self.optype not in (
            None, SetExpression.OPTYPE_ALL, SetExpression.OPTYPE_DISTINCT,
        ):
            raise DALError(
                "Must have either 'all' or 'distinct' in a set expression"
            )

    def subSQL(self, queryGenerator, allTables):
        result = SQLFragment()
        for select in self.selects:
            result.append(self.setOpSQL(queryGenerator))
            if self.optype == SetExpression.OPTYPE_ALL:
                result.append(SQLFragment("ALL "))
            elif self.optype == SetExpression.OPTYPE_DISTINCT:
                result.append(SQLFragment("DISTINCT "))
            result.append(select.subSQL(queryGenerator, allTables))
        return result

    def allColumns(self):
        return []


class Union(SetExpression):
    """
    A UNION construct used inside a SELECT.
    """

    def setOpSQL(self, queryGenerator):
        return SQLFragment(" UNION ")


class Intersect(SetExpression):
    """
    An INTERSECT construct used inside a SELECT.
    """

    def setOpSQL(self, queryGenerator):
        return SQLFragment(" INTERSECT ")


class Except(SetExpression):
    """
    An EXCEPT construct used inside a SELECT.
    """

    def setOpSQL(self, queryGenerator):
        if queryGenerator.dbtype.dialect == POSTGRES_DIALECT:
            return SQLFragment(" EXCEPT ")
        elif queryGenerator.dbtype.dialect == ORACLE_DIALECT:
            return SQLFragment(" MINUS ")
        else:
            raise NotImplementedError("Unsupported dialect")


class Select(_Statement):
    """
    C{select} statement.
    """

    def __init__(
        self,
        columns=None, Where=None, From=None,
        OrderBy=None, GroupBy=None,
        Limit=None, ForUpdate=False, NoWait=False, SkipLocked=False, Ascending=None,
        Having=None, Distinct=False, As=None, SetExpression=None
    ):
        self.From = From
        self.Where = Where
        self.Distinct = Distinct
        if not isinstance(OrderBy, (Tuple, list, tuple, type(None))):
            OrderBy = [OrderBy]
        self.OrderBy = OrderBy
        if not isinstance(GroupBy, (list, tuple, type(None))):
            GroupBy = [GroupBy]
        self.GroupBy = GroupBy
        self.Limit = Limit
        self.Having = Having
        self.SetExpression = SetExpression

        if columns is None:
            columns = ALL_COLUMNS
        else:
            _checkColumnsMatchTables(columns, From.tables())
            columns = _SomeColumns(columns)
        self.columns = columns

        self.ForUpdate = ForUpdate
        self.NoWait = NoWait
        self.SkipLocked = SkipLocked
        self.Ascending = Ascending
        self.As = As

        # A FROM that uses a sub-select will need the AS alias name
        if isinstance(self.From, Select):
            if self.From.As is None:
                self.From.As = ""

    def __eq__(self, other):
        """
        Create a comparison.
        """
        if isinstance(other, (list, tuple)):
            other = Tuple(other)
        return CompoundComparison(other, "=", self)

    def _toSQL(self, queryGenerator):
        """
        @return: a C{select} statement with placeholders and arguments
        @rtype: L{SQLFragment}
        """
        if self.SetExpression is not None:
            stmt = SQLFragment("(")
        else:
            stmt = SQLFragment()

        stmt.append(SQLFragment("select "))
        if self.Distinct:
            stmt.text += "distinct "

        allTables = self.From.tables()
        stmt.append(self.columns.subSQL(queryGenerator, allTables))
        stmt.text += " from "
        stmt.append(self.From.subSQL(queryGenerator, allTables))

        if self.Where is not None:
            wherestmt = self.Where.subSQL(queryGenerator, allTables)
            stmt.text += " where "
            stmt.append(wherestmt)

        if self.GroupBy is not None:
            stmt.text += " group by "
            fst = True
            for subthing in self.GroupBy:
                if fst:
                    fst = False
                else:
                    stmt.text += ", "
                stmt.append(subthing.subSQL(queryGenerator, allTables))

        if self.Having is not None:
            havingstmt = self.Having.subSQL(queryGenerator, allTables)
            stmt.text += " having "
            stmt.append(havingstmt)

        if self.SetExpression is not None:
            stmt.append(SQLFragment(")"))
            stmt.append(self.SetExpression.subSQL(queryGenerator, allTables))

        if self.OrderBy is not None:
            stmt.text += " order by "
            fst = True
            for subthing in self.OrderBy:
                if fst:
                    fst = False
                else:
                    stmt.text += ", "
                stmt.append(subthing.subSQL(queryGenerator, allTables))
            if self.Ascending is not None:
                if self.Ascending:
                    kw = " asc"
                else:
                    kw = " desc"
                stmt.append(SQLFragment(kw))

        if self.ForUpdate:
            # FOR UPDATE not supported with sqlite - but that is probably not relevant
            # given that sqlite does file level locking of the DB
            if queryGenerator.dbtype.dialect != SQLITE_DIALECT:
                # Oracle turns this statement into a sub-select if Limit is non-zero, but we can't have
                # the "for update" in the sub-select. So suppress it here and add it in the outer limit
                # select later.
                if self.Limit is None or queryGenerator.dbtype.dialect != ORACLE_DIALECT:
                    stmt.text += " for update"
                    if self.NoWait:
                        stmt.text += " nowait"
                    if self.SkipLocked:
                        stmt.text += " skip locked"

        if self.Limit is not None:
            limitConst = Constant(self.Limit).subSQL(queryGenerator, allTables)
            if queryGenerator.dbtype.dialect == ORACLE_DIALECT:
                wrapper = SQLFragment("select * from (")
                wrapper.append(stmt)
                wrapper.append(SQLFragment(") where ROWNUM <= "))
                stmt = wrapper
            else:
                stmt.text += " limit "
            stmt.append(limitConst)

            # Add in any Oracle "for update"
            if self.ForUpdate and queryGenerator.dbtype.dialect == ORACLE_DIALECT:
                stmt.text += " for update"
                if self.NoWait:
                    stmt.text += " nowait"

        return stmt

    def subSQL(self, queryGenerator, allTables):
        result = SQLFragment("(")
        result.append(self.toSQL(queryGenerator))
        result.append(SQLFragment(")"))

        if self.As is not None:
            if self.As == "":
                self.As = queryGenerator.nextGeneratedID()
            result.append(SQLFragment(" %s" % (self.As,)))

        return result

    def _resultColumns(self):
        """
        Determine the list of L{ColumnSyntax} objects that will represent the
        result.  Normally just the list of selected columns; if wildcard syntax
        is used though, determine the ordering from the database.
        """
        if self.columns is ALL_COLUMNS:
            # TODO: Possibly this rewriting should always be done, before even
            # executing the query, so that if we develop a schema mismatch with
            # the database (additional columns), the application will still see
            # the right rows.
            for table in self.From.tables():
                for column in table:
                    yield column
        else:
            for column in self.columns.columns:
                yield column

    def tables(self):
        """
        Determine the tables used by the result columns.
        """
        if self.columns is ALL_COLUMNS:
            # TODO: Possibly this rewriting should always be done, before even
            # executing the query, so that if we develop a schema mismatch with
            # the database (additional columns), the application will still see
            # the right rows.
            return self.From.tables()
        else:
            tables = set([
                column.model.table for column in self.columns.columns
                if isinstance(column, ColumnSyntax)
            ])
            for table in self.From.tables():
                tables.add(table.model)
            return [TableSyntax(table) for table in tables]


class Call(_Statement):
    """
    CALL statement. Only supported by Oracle.
    """

    def __init__(self, name, *args, **kwargs):
        """
        @param name: name of procedure or function to call
        @type name: L{str}
        @param *args: arguments for the procedure or functions
        @type *args: L{list}
        @param returnType: kwarg: the Python type of the return value for
            a function
        @type returnType: L{Type}
        """
        self.Name = name
        self.Args = args
        self.ReturnType = kwargs.get("returnType")

    def _toSQL(self, queryGenerator):
        """
        Generate an SQL statement of the form "call <name>()" with a list of
        args, where the first arg is always the return type (which is C{None}
        for a procedure, rather than a function, call).

        @return: a C{call} statement with arguments
        @rtype: L{SQLFragment}
        """

        if queryGenerator.dbtype.dialect != ORACLE_DIALECT:
            raise NotImplementedError("CALL statement only available with Oracle DB")
        args = (self.ReturnType,) + self.Args
        stmt = SQLFragment("call ", args)
        stmt.text += self.Name
        stmt.text += "()"

        return stmt

    def _fixOracleNulls(self, rows):
        """
        Suppress the super class behavior because we are getting result values
        directly, not from columns.
        """
        return rows[0][0]


def _commaJoined(stmts):
    first = True
    cstatement = SQLFragment()
    for stmt in stmts:
        if first:
            first = False
        else:
            cstatement.append(SQLFragment(", "))
        cstatement.append(stmt)
    return cstatement


def _inParens(stmt):
    result = SQLFragment("(")
    result.append(stmt)
    result.append(SQLFragment(")"))
    return result


def _fromSameTable(columns):
    """
    Extract the common table used by a list of L{Column} objects, raising
    L{TableMismatch}.
    """
    table = columns[0].table
    for column in columns:
        if table is not column.table:
            raise TableMismatch("Columns must all be from the same table.")
    return table


def _modelsFromMap(columnMap):
    """
    Get the L{Column} objects from a mapping of L{ColumnSyntax} to values.
    """
    return [c.model for c in columnMap.keys()]


class _CommaList(object):

    def __init__(self, subfragments):
        self.subfragments = subfragments

    def subSQL(self, queryGenerator, allTables):
        return _commaJoined(
            f.subSQL(queryGenerator, allTables)
            for f in self.subfragments
        )


class _DMLStatement(_Statement):
    """
    Common functionality of Insert/Update/Delete statements.
    """

    def _returningClause(self, queryGenerator, stmt, allTables):
        """
        Add a dialect-appropriate C{returning} clause to the end of the given
        SQL statement.

        @param queryGenerator: describes the database we are generating the
            statement for.
        @type queryGenerator: L{QueryGenerator}

        @param stmt: the SQL fragment generated without the C{returning} clause
        @type stmt: L{SQLFragment}

        @param allTables: all tables involved in the query; see any C{subSQL}
            method.

        @return: the C{stmt} parameter.
        """
        retclause = self.Return

        if retclause is None:
            return stmt

        if isinstance(retclause, (tuple, list)):
            retclause = _CommaList(retclause)

        if queryGenerator.dbtype.dialect == SQLITE_DIALECT:
            # sqlite does this another way.
            return stmt

        if retclause is not None:
            stmt.text += " returning "
            stmt.append(retclause.subSQL(queryGenerator, allTables))
            if queryGenerator.dbtype.dialect == ORACLE_DIALECT:
                stmt.text += " into "
                params = []
                retvals = self._returnAsList()
                for n, _ignore_v in enumerate(retvals):
                    params.append(
                        Constant(Parameter("oracle_out_" + str(n)))
                        .subSQL(queryGenerator, allTables)
                    )
                stmt.append(_commaJoined(params))

        return stmt

    def _returnAsList(self):
        if not isinstance(self.Return, (tuple, list)):
            return [self.Return]
        else:
            return self.Return

    def _extraVars(self, txn, queryGenerator):
        if self.Return is None:
            return []
        result = []
        rvars = self._returnAsList()
        if queryGenerator.dbtype.dialect == ORACLE_DIALECT:
            for n, v in enumerate(rvars):
                result.append(("oracle_out_" + str(n), _OracleOutParam(v)))
        return result

    def _extraResult(self, result, outvars, queryGenerator):
        if (
            queryGenerator.dbtype.dialect == ORACLE_DIALECT and
            self.Return is not None
        ):
            def processIt(emptyListResult):
                # See comment in L{adbapi2._ConnectedTxn._reallyExecSQL}. If the
                # result is an empty list, just return that. If the result is a
                # L{list} of empty L{list} then there are return into rows to return.
                if len(emptyListResult) > 0:
                    emptyListResult = [[v.value for _ignore_k, v in outvars]]
                return emptyListResult
            return result.addCallback(processIt)
        else:
            return result

    def _resultColumns(self):
        return self._returnAsList()


class _OracleOutParam(object):
    """
    A parameter that will be populated using the cx_Oracle API for host
    variables.
    """
    implements(IDerivedParameter)

    def __init__(self, columnSyntax):
        self.typeID = columnSyntax.model.type.name.lower()

    def preQuery(self, cursor):
        typeMap = {"integer": cx_Oracle.NUMBER,
                   "text": cx_Oracle.NCLOB,
                   "varchar": cx_Oracle.STRING,
                   "timestamp": cx_Oracle.TIMESTAMP}
        self.var = cursor.var(typeMap[self.typeID])
        return self.var

    def postQuery(self, cursor):
        self.value = mapOracleOutputType(self.var.getvalue())
        self.var = None


class Insert(_DMLStatement):
    """
    C{insert} statement.
    """

    def __init__(self, columnMap, Return=None):
        self.columnMap = columnMap
        self.Return = Return
        columns = _modelsFromMap(columnMap)
        table = _fromSameTable(columns)
        required = [column for column in table.columns if column.needsValue()]
        unspecified = [column for column in required
                       if column not in columns]
        if unspecified:
            raise NotEnoughValues(
                "Columns [%s] required."
                % (", ".join([c.name for c in unspecified]))
            )

    def _toSQL(self, queryGenerator):
        """
        @return: a C{insert} statement with placeholders and arguments

        @rtype: L{SQLFragment}
        """
        columnsAndValues = self.columnMap.items()
        tableModel = columnsAndValues[0][0].model.table
        specifiedColumnModels = [x.model for x in self.columnMap.keys()]

        if queryGenerator.dbtype.dialect == ORACLE_DIALECT:
            # See test_nextSequenceDefaultImplicitExplicitOracle.
            for column in tableModel.columns:
                if isinstance(column.default, Sequence):
                    columnSyntax = ColumnSyntax(column)
                    if column not in specifiedColumnModels:
                        columnsAndValues.append(
                            (columnSyntax, SequenceSyntax(column.default))
                        )

        sortedColumns = sorted(
            columnsAndValues,
            key=lambda (c, v): c.model.name
        )
        allTables = []

        stmt = SQLFragment("insert into ")
        stmt.append(TableSyntax(tableModel).subSQL(queryGenerator, allTables))
        stmt.append(SQLFragment(" "))
        stmt.append(_inParens(_commaJoined([
            c.subSQL(queryGenerator, allTables)
            for (c, _ignore_v) in sortedColumns
        ])))
        stmt.append(SQLFragment(" values "))
        stmt.append(_inParens(_commaJoined([
            _convert(v).subSQL(queryGenerator, allTables)
            for (c, v) in sortedColumns
        ])))

        return self._returningClause(queryGenerator, stmt, allTables)

    @inlineCallbacks
    def on(self, txn, *a, **kw):
        """
        Override to provide extra logic for L{Insert}s that return values on
        databases that don't provide return values as part of their C{INSERT}
        behavior.
        """
        result = yield super(_DMLStatement, self).on(txn, *a, **kw)
        if self.Return is not None and txn.dbtype.dialect == SQLITE_DIALECT:
            table = self._returnAsList()[0].model.table
            result = yield Select(
                self._returnAsList(),
                # TODO: error reporting when "return" includes columns
                # foreign to the primary table.
                From=TableSyntax(table),
                Where=(
                    ColumnSyntax(
                        Column(table, "rowid", SQLType("integer", None))
                    ) == _sqliteLastInsertRowID()
                )
            ).on(txn, *a, **kw)
        returnValue(result)


def _convert(x):
    """
    Convert a value to an appropriate SQL AST node.  (Currently a simple
    isinstance, could be promoted to use adaptation if we want to get fancy.)
    """
    if isinstance(x, ExpressionSyntax):
        return x
    else:
        return Constant(x)


class Update(_DMLStatement):
    """
    C{update} statement

    @ivar columnMap: A L{dict} mapping L{ColumnSyntax} objects to values to
        change; values may be simple database values (such as L{str},
        L{unicode}, L{datetime.datetime}, L{float}, L{int} etc) or L{Parameter}
        instances.
    @type columnMap: L{dict}
    """

    def __init__(self, columnMap, Where, Return=None):
        super(Update, self).__init__()
        _fromSameTable(_modelsFromMap(columnMap))
        self.columnMap = columnMap
        self.Where = Where
        self.Return = Return

    @inlineCallbacks
    def on(self, txn, *a, **kw):
        """
        Override to provide extra logic for L{Update}s that return values on
        databases that don't provide return values as part of their C{UPDATE}
        behavior.
        """
        doExtra = self.Return is not None and txn.dbtype.dialect == SQLITE_DIALECT
        upcall = lambda: super(_DMLStatement, self).on(txn, *a, **kw)

        if doExtra:
            table = self._returnAsList()[0].model.table
            rowidcol = ColumnSyntax(Column(table, "rowid",
                                           SQLType("integer", None)))
            prequery = Select([rowidcol], From=TableSyntax(table),
                              Where=self.Where)
            preresult = prequery.on(txn, *a, **kw)
            before = yield preresult
            yield upcall()
            result = yield Select(
                self._returnAsList(),
                # TODO: error reporting when "return" includes
                # columns foreign to the primary table.
                From=TableSyntax(table),
                Where=reduce(
                    lambda left, right: left.Or(right),
                    ((rowidcol == x) for [x] in before)
                )
            ).on(txn, *a, **kw)
            returnValue(result)
        else:
            returnValue((yield upcall()))

    def _toSQL(self, queryGenerator):
        """
        @return: an C{insert} statement with placeholders and arguments
        @rtype: L{SQLFragment}
        """
        sortedColumns = sorted(
            self.columnMap.items(), key=lambda (c, v): c.model.name
        )
        allTables = []
        result = SQLFragment("update ")
        result.append(
            TableSyntax(sortedColumns[0][0].model.table).subSQL(
                queryGenerator, allTables
            )
        )
        result.text += " set "
        result.append(_commaJoined([
            c.subSQL(queryGenerator, allTables).append(
                SQLFragment(" = ").subSQL(queryGenerator, allTables)
            ).append(
                _convert(v).subSQL(queryGenerator, allTables)
            )
            for (c, v) in sortedColumns
        ]))

        if self.Where is not None:
            result.append(SQLFragment(" where "))
            result.append(self.Where.subSQL(queryGenerator, allTables))

        return self._returningClause(queryGenerator, result, allTables)


class Delete(_DMLStatement):
    """
    C{delete} statement.
    """

    def __init__(self, From, Where, Return=None):
        """
        If Where is None then all rows will be deleted.
        """
        self.From = From
        self.Where = Where
        self.Return = Return

    def _toSQL(self, queryGenerator):
        result = SQLFragment()
        allTables = self.From.tables()
        result.text += "delete from "
        result.append(self.From.subSQL(queryGenerator, allTables))
        if self.Where is not None:
            result.text += " where "
            result.append(self.Where.subSQL(queryGenerator, allTables))
        return self._returningClause(queryGenerator, result, allTables)

    @inlineCallbacks
    def on(self, txn, *a, **kw):
        upcall = lambda: super(Delete, self).on(txn, *a, **kw)
        if txn.dbtype.dialect == SQLITE_DIALECT and self.Return is not None:
            result = yield Select(
                self._returnAsList(),
                From=self.From, Where=self.Where
            ).on(txn, *a, **kw)
            yield upcall()
        else:
            result = yield upcall()
        returnValue(result)


class _LockingStatement(_Statement):
    """
    A statement related to lock management, which implicitly has no results.
    """

    def _resultColumns(self):
        """
        No columns should be expected, so return an infinite iterator of None.
        """
        return repeat(None)


class Lock(_LockingStatement):
    """
    An SQL "lock" statement.
    """

    def __init__(self, table, mode):
        self.table = table
        self.mode = mode

    @classmethod
    def exclusive(cls, table):
        return cls(table, "exclusive")

    def _toSQL(self, queryGenerator):
        if queryGenerator.dbtype.dialect == SQLITE_DIALECT:
            # FIXME - this is only stubbed out for testing right now, actual
            # concurrency would require some kind of locking statement here.
            # BEGIN IMMEDIATE maybe, if that's okay in the middle of a
            # transaction or repeatedly?
            return SQLFragment("select null")

        return SQLFragment("lock table ").append(
            self.table.subSQL(queryGenerator, [self.table])
        ).append(
            SQLFragment(" in %s mode" % (self.mode,))
        )


class DatabaseLock(_LockingStatement):
    """
    An SQL exclusive session level advisory lock
    """

    def _toSQL(self, queryGenerator):
        assert(queryGenerator.dbtype.dialect == POSTGRES_DIALECT)
        return SQLFragment("select pg_advisory_lock(1)")

    def on(self, txn, *a, **kw):
        """
        Override on() to only execute on Postgres
        """
        if txn.dbtype.dialect == POSTGRES_DIALECT:
            return super(DatabaseLock, self).on(txn, *a, **kw)

        return succeed(None)


class DatabaseUnlock(_LockingStatement):
    """
    An SQL exclusive session level advisory lock
    """

    def _toSQL(self, queryGenerator):
        assert(queryGenerator.dbtype.dialect == POSTGRES_DIALECT)
        return SQLFragment("select pg_advisory_unlock(1)")

    def on(self, txn, *a, **kw):
        """
        Override on() to only execute on Postgres
        """
        if txn.dbtype.dialect == POSTGRES_DIALECT:
            return super(DatabaseUnlock, self).on(txn, *a, **kw)

        return succeed(None)


class Savepoint(_LockingStatement):
    """
    An SQL C{savepoint} statement.
    """

    def __init__(self, name):
        self.name = name

    def _toSQL(self, queryGenerator):
        return SQLFragment("savepoint %s" % (self.name,))


class RollbackToSavepoint(_LockingStatement):
    """
    An SQL C{rollback to savepoint} statement.
    """

    def __init__(self, name):
        self.name = name

    def _toSQL(self, queryGenerator):
        return SQLFragment("rollback to savepoint %s" % (self.name,))


class ReleaseSavepoint(_LockingStatement):
    """
    An SQL C{release savepoint} statement.
    """

    def __init__(self, name):
        self.name = name

    def _toSQL(self, queryGenerator):
        return SQLFragment("release savepoint %s" % (self.name,))


class SavepointAction(object):

    def __init__(self, name):
        self._name = name

    def _safeName(self, txn):
        if txn.dbtype.dialect == ORACLE_DIALECT:
            # Oracle limits the length of identifiers
            return self._name[:30]
        else:
            return self._name

    def acquire(self, txn):
        return Savepoint(self._safeName(txn)).on(txn)

    def rollback(self, txn):
        return RollbackToSavepoint(self._safeName(txn)).on(txn)

    def release(self, txn):
        if txn.dbtype.dialect == ORACLE_DIALECT:
            # There is no "release savepoint" statement in oracle, but then, we
            # don't need it because there's no resource to manage.  Just don't
            # do anything.
            return NoOp()
        else:
            return ReleaseSavepoint(self._safeName(txn)).on(txn)


class NoOp(object):

    def on(self, *a, **kw):
        return succeed(None)


class SQLFragment(object):
    """
    Combination of SQL text and arguments; a statement which may be executed
    against a database.
    """

    def __init__(self, text="", parameters=None):
        self.text = text
        if parameters is None:
            parameters = []
        self.parameters = parameters

    def bind(self, **kw):
        params = []
        for parameter in self.parameters:
            if isinstance(parameter, Parameter):
                if parameter.count is not None:
                    if parameter.count != len(kw[parameter.name]):
                        raise DALError(
                            "Number of place holders does not match "
                            "number of items to bind"
                        )
                    for item in kw[parameter.name]:
                        params.append(item)
                else:
                    params.append(kw[parameter.name])
            else:
                params.append(parameter)

        return SQLFragment(self.text, params)

    def append(self, anotherStatement):
        self.text += anotherStatement.text
        self.parameters += anotherStatement.parameters
        return self

    def __eq__(self, stmt):
        if not isinstance(stmt, SQLFragment):
            return NotImplemented
        return (self.text, self.parameters) == (stmt.text, stmt.parameters)

    def __ne__(self, stmt):
        if not isinstance(stmt, SQLFragment):
            return NotImplemented
        return not self.__eq__(stmt)

    def __repr__(self):
        return self.__class__.__name__ + repr((self.text, self.parameters))

    def subSQL(self, queryGenerator, allTables):
        return self


class Parameter(object):
    """
    Used to represent a place holder for a value to be bound to the query
    at a later date. If count > 1, then a "set" of parenthesized,
    comma separate place holders will be generated.
    """

    def __init__(self, name, count=None):
        self.name = name
        self.count = count
        if self.count is not None and self.count < 1:
            raise DALError("Must have Parameter.count > 0")

    def __eq__(self, param):
        if not isinstance(param, Parameter):
            return NotImplemented
        return self.name == param.name and self.count == param.count

    def __ne__(self, param):
        if not isinstance(param, Parameter):
            return NotImplemented
        return not self.__eq__(param)

    def __repr__(self):
        return "Parameter(%r)" % (self.name,)


# Common helpers:

# current timestamp in UTC format.  Hack to support standard syntax for this,
# rather than the compatibility procedure found in various databases.
utcNowSQL = NamedValue("CURRENT_TIMESTAMP at time zone 'UTC'")

# You can't insert a column with no rows.  In SQL that just isn't valid syntax,
# and in this DAL you need at least one key or we can't tell what table you're
# talking about.  Luckily there's the C{default} keyword to the rescue, which,
# in the context of an INSERT statement means "use the default value
# explicitly".
# (Although this is a special keyword in a CREATE statement, in an INSERT it
# behaves like an expression to the best of my knowledge.)
default = NamedValue("default")