Source

htsql / src / htsql / core / tr / dump.py

Full commit
   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
#
# Copyright (c) 2006-2013, Prometheus Research, LLC
#


"""
:mod:`htsql.core.tr.dump`
=========================

This module implements the SQL serialization process.
"""


from ..util import listof, maybe
from ..adapter import Adapter, Protocol, adapt, call
from ..domain import (Domain, BooleanDomain, IntegerDomain, DecimalDomain,
                      FloatDomain, TextDomain, EnumDomain, DateDomain,
                      TimeDomain, DateTimeDomain, ListDomain, RecordDomain)
from ..error import Error, translate_guard
from ..syn.syntax import IdentifierSyntax, ApplySyntax, LiteralSyntax
from .frame import (Clause, Frame, TableFrame, BranchFrame, NestedFrame,
                    SegmentFrame, QueryFrame,
                    Phrase, NullPhrase, CastPhrase, LiteralPhrase,
                    ColumnPhrase, ReferencePhrase, EmbeddingPhrase,
                    FormulaPhrase, Anchor, LeadingAnchor)
from .signature import (Signature, isformula, IsEqualSig, IsTotallyEqualSig,
                        IsInSig, IsNullSig, IfNullSig, NullIfSig, CompareSig,
                        AndSig, OrSig, NotSig, SortDirectionSig, RowNumberSig,
                        ToPredicateSig, FromPredicateSig, PlaceholderSig)
from .plan import Plan, Statement
import StringIO
import re
import math


class Stream(StringIO.StringIO, object):
    """
    Implements a writable file-like object.

    Use :meth:`write` to write a string to the stream.  The data is
    accumulated in an internal buffer of the stream.

    Use :meth:`flush` to get the accumulated content and truncate
    the stream.

    :class:`Stream` also provides means for automatic indentation.
    Use :meth:`indent` to set a new indentation level, :meth:`dedent`
    to revert to the previous indentation level, :meth:`newline`
    to set the position to the current indentation level.
    """
    # Note: we inherit from `object` to be able to use `super()`.

    def __init__(self):
        # Initialize the `StringIO` object.
        super(Stream, self).__init__()
        # The current cursor position.
        self.column = 0
        # The current indentation level.
        self.indentation = 0
        # The stack of previous indentation levels.
        self.indentation_stack = []

    def write(self, data):
        """
        Writes a string to the stream.
        """
        # Expect a Unicode string.
        assert isinstance(data, unicode)
        # Call `StringIO.write`, which performs the action.
        super(Stream, self).write(data)
        # Update the cursor position.  Note that we count
        # Unicode codepoints rather than bytes.
        if u"\n" in data:
            self.column = len(data)-data.rindex(u"\n")-1
        else:
            self.column += len(data)

    def newline(self):
        """
        Sets the cursor to the current indentation level.
        """
        if self.column <= self.indentation:
            self.write(u" "*(self.indentation-self.column))
        else:
            self.write(u"\n"+u" "*self.indentation)

    def indent(self):
        """
        Sets the indentation level to the current cursor position.
        """
        self.indentation_stack.append(self.indentation)
        self.indentation = self.column

    def dedent(self):
        """
        Reverts to the previous indentation level.
        """
        self.indentation = self.indentation_stack.pop()

    def flush(self):
        """
        Returns the accumulated content and truncates the stream.
        """
        # FIXME: we override the builtin `StringIO.flush()`
        # (which is no-op though)

        # Make sure the indentation level is at zero position.
        assert self.indentation == 0 and not self.indentation_stack
        # The accumulated content of the stream.
        output = self.getvalue()
        # Blank the stream and return the content.
        self.truncate(0)
        self.column = 0
        return output


class Hook(object):
    """
    Encapsulates serializing hints and instructions.

    `with_aliases` (Boolean)
        If set, indicates that the generated ``SELECT`` clause
        must contain aliases.
    """

    def __init__(self, with_aliases):
        assert isinstance(with_aliases, bool)
        self.with_aliases = with_aliases


class SerializingState(object):
    """
    Encapsulates the state of the serializing process.

    State attributes:

    `stream` (:class:`Stream`)
        A file-like object accumulating the generated SQL statement.

    `frame_by_tag` (a mapping: integer -> :class:`htsql.core.tr.frame.Frame`)
        Maps the frame tag to the respective frame.

    `select_aliases_by_tag` (a mapping: integer -> a list of aliases)
        Maps the frame tag to the list of aliases for the frame
        ``SELECT`` clause.

    `frame_alias_by_tag` (a mapping: integer -> an alias)
        Maps the frame tag to the alias of the frame.

    `hook` (:class:`Hook`)
        Encapsulates serializing hints and directives.
    """

    def __init__(self):
        # The stream that accumulates the generated SQL.
        self.stream = Stream()
        # A mapping: tag -> frame.
        self.frame_by_tag = {}
        # A mapping: tag -> a list of `SELECT` aliases.
        self.select_aliases_by_tag = {}
        # A mapping: tag -> the frame alias.
        self.frame_alias_by_tag = {}
        # The stack of previous values of serializing directives.
        self.hook_stack = []
        # The active serializing hints and directives.
        self.hook = None
        self.placeholders = {}

    def set_tree(self, frame):
        """
        Initializes the serializing state.

        This method must be called before dumping any clauses.

        `frame` (:class:`htsql.core.tr.frame.SegmentFrame`)
            The term corresponding to the top-level ``SELECT`` statement.
        """
        assert isinstance(frame, SegmentFrame)
        # Initialize serializing directives.
        self.hook = Hook(with_aliases=False)
        # Populate `frame_by_tag` mapping: use BFS over the frame tree.
        queue = [frame]
        while queue:
            frame = queue.pop(0)
            self.frame_by_tag[frame.tag] = frame
            queue.extend(frame.kids)

    def push_hook(self, with_aliases):
        """
        Updates serializing directives.

        `with_aliases` (Boolean)
            If set, indicates that the ``SELECT`` clause must have aliases.
        """
        assert isinstance(with_aliases, bool)
        self.hook_stack.append(self.hook)
        self.hook = Hook(with_aliases=with_aliases)

    def pop_hook(self):
        """
        Restores the previous serializing directives.
        """
        self.hook = self.hook_stack.pop()

    def add_placeholder(self, index, domain):
        if index not in self.placeholders:
            self.placeholders[index] = domain

    def flush(self):
        """
        Clears the serializing state and returns the generated SQL.
        """
        # Revert all attributes to their pristine state.  We assume
        # that the `hook_stack` must be already empty.
        self.frame_by_tag = {}
        self.select_aliases_by_tag = {}
        self.frame_alias_by_tag = {}
        assert not self.hook_stack
        self.hook = None
        self.placeholders = {}
        # Truncate the stream and return the accumulated data.
        return self.stream.flush()

    def serialize(self, clause):
        """
        Serializes the given clause.

        `clause` (:class:`htsql.core.tr.frame.Clause`)
            The clause to serialize.
        """
        # Realize and call the `Serialize` adapter.
        with translate_guard(clause):
            return serialize(clause, self)

    def dump(self, clause):
        """
        Writes SQL for the given clause.

        `clause` (:class:`htsql.core.tr.frame.Clause`)
            The clause to dump.
        """
        # Realize and call the `Dump` adapter.
        # Note: returns `None`.
        with translate_guard(clause):
            return Dump.__invoke__(clause, self)

    def dub(self, clause):
        """
        Generates a preform alias for the given clause.

        `clause` (:class:`htsql.core.tr.frame.Clause`)
            The clause to generate an alias for.
        """
        # Realize and call the `Dub` adapter.
        with translate_guard(clause):
            return Dub.__invoke__(clause, self)


class Serialize(Adapter):
    """
    Translates a clause to SQL.

    This is an interface adapter; see subclasses for implementations.

    The :class:`Serialize` has the following signature::

        Serialize: (Clause, SerializingState) -> SQL

    The adapter is polymorphic on the `Clause` argument.

    `clause` (:class:`htsql.core.tr.frame.Clause`)
        The clause to serialize.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.
    """

    adapt(Clause)

    def __init__(self, clause, state):
        assert isinstance(clause, Clause)
        assert isinstance(state, SerializingState)
        self.clause = clause
        self.state = state

    def __call__(self):
        # Must be implemented in subclasses.
        raise NotImplementedError("the serialize adapter is not implemented"
                                  " for a %r node" % self.clause)


class SerializeQuery(Serialize):
    """
    Serializes an HTSQL query to an execution plan.
    """

    adapt(QueryFrame)

    def __call__(self):
        # When exists, serialize the query segment.
        profile = self.clause.binding.profile
        compose = self.clause.compose
        statement = None
        if self.clause.segment is not None:
            statement = self.state.serialize(self.clause.segment)

        # Produce an execution plan.
        return Plan(profile, statement, compose)


class SerializeSegment(Serialize):
    """
    Serializes an HTSQL segment to SQL.

    Class attributes:

    `max_alias_length` (an integer)
        The maximum length of an alias.
    """

    adapt(SegmentFrame)

    # The maximum length of an alias.  We could choose an arbitrary
    # value and let the backends override it.  Here we have chosen
    # the PostgreSQL limit `NAMEDATALEN-1`.
    max_alias_length = 63

    def __call__(self):
        # Populate the `frame_by_tag` mapping.
        self.state.set_tree(self.clause)
        # Generate `SELECT` and `FROM` aliases.
        self.aliasing()
        # Dump the `SELECT` statement.
        self.state.dump(self.clause)
        # Retrieve and return the generated SQL.
        placeholders = self.state.placeholders
        sql = self.state.flush()
        domains = [phrase.domain for phrase in self.clause.select]
        substatements = [self.state.serialize(subframe)
                         for subframe in self.clause.subtrees]
        return Statement(sql, domains, substatements, placeholders)

    def aliasing(self, frame=None,
                 taken_select_aliases=None,
                 taken_include_aliases=None):
        """
        Generates ``SELECT`` and ``FROM`` aliases.

        `frame` (:class:`htsql.core.tr.frame.BranchFrame` or ``None``)
            The frame to generate aliases for.

        `taken_select_aliases` (a set or ``None``)
            The ``SELECT`` aliases to avoid.  Note that :meth:`aliasing`
            may update the collection.

        `taken_include_aliases` (a set of ``None``)
            The ``FROM`` aliases to avoid.  Note that :meth:`aliasing`
            may update the collection.
        """
        # Initialize default values for the arguments.
        if frame is None:
            frame = self.clause
        if taken_select_aliases is None:
            taken_select_aliases = set()
        if taken_include_aliases is None:
            taken_include_aliases = set()
        # Get preform aliases for the `SELECT` phrases.
        select_names = [self.state.dub(phrase)
                        for phrase in frame.select]
        # Complete and assign the `SELECT` aliases.
        select_aliases = self.names_to_aliases(select_names,
                                               taken_select_aliases)
        self.state.select_aliases_by_tag[frame.tag] = select_aliases
        # Get preform aliases for the `FROM` subframes.
        include_names = [self.state.dub(anchor.frame)
                         for anchor in frame.include]
        # Complete and assign the `FROM` aliases.
        include_aliases = self.names_to_aliases(include_names,
                                                taken_include_aliases)
        for alias, anchor in zip(include_aliases, frame.include):
            self.state.frame_alias_by_tag[anchor.frame.tag] = alias
        # Generate aliases for each sub-`SELECT` in the `FROM` clause.
        for anchor in frame.include:
            if anchor.frame.is_branch:
                self.aliasing(anchor.frame)
        # Generate aliases for the embedded subframes.  Since embedded
        # subframes may refer to its parent frame's subframes, we need
        # to pass the aliases reserved by the parent frame.
        # FIXME: only need to pass `FROM` aliases since `SELECT` aliases
        # are not referrable from an embedded subframe?  It's a moot
        # point since embedded subframes do not use `SELECT` aliases anyway.
        for subframe in frame.embed:
            self.aliasing(subframe,
                          taken_select_aliases.copy(),
                          taken_include_aliases.copy())

    def names_to_aliases(self, names, taken_aliases):
        # Converts a list of preform aliases to actual aliases.

        # We got a list of proposed aliases, now we need to amend it
        # to make sure that:
        # - all aliases are unique among themselves and do not clash
        #   with any reserved aliases;
        # - the length of an alias does not exceed `max_alias_length`.
        # We generate aliases of the form `preform_N`, where `N`
        # is a sequiental numeric index; however, when possible, we try
        # to avoid adding the `_N` suffix.

        # A mapping: preform alias -> the next suffix to try.
        next_number_by_name = {}
        # Initialize the mapping with `1` for duplicate preforms.
        duplicates = set()
        for name in names:
            if name in duplicates:
                next_number_by_name[name] = 1
            duplicates.add(name)

        # The generated aliases.
        aliases = []
        # For each preform, generate an alias.
        for name in names:
            # The generated alias.
            alias = None
            # Try it until the alias is generated.
            while alias is None:
                # Generate an alias of the form `preform` or `preform_N`,
                # where `N` are consecutive numbers.  Note that we may need
                # to cut the preform to fit the allowed alias length limit.
                number = next_number_by_name.get(name)
                if number is None:
                    alias = name[:self.max_alias_length]
                    number = 1
                else:
                    cut = self.max_alias_length - len(unicode(number)) - 1
                    alias = u"%s_%s" % (name[:cut], number)
                    number += 1
                next_number_by_name[name] = number
                # Check if the alias is already reserved.
                if alias in taken_aliases:
                    alias = None
            # A unique alias is generated; save and reserve it.
            aliases.append(alias)
            taken_aliases.add(alias)

        return aliases


class DumpBase(Adapter):
    """
    Translates a clause node to SQL.

    This is a base class for the family of `Dump` adapters; it encapsulates
    methods and attributes shared between these adapters.

    A `Dump` adapter generates a SQL expression for the given frame or
    phrase clause node and writes it to the stream that accumulates a SQL
    statement.

    `clause` (:class:`htsql.core.tr.frame.Clause`)
        A clause to serialize.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.
    """

    # A pattern to match expressions of the forms:
    #   {name}
    #   {name:kind}
    #   {name:kind{modifier}}
    #   ...a chunk of text without {}...
    template_pattern = r"""
        \{
            (?P<name> \w+ )
            (?:
                :
                (?P<kind> \w+ )
                (?:
                    \{
                        (?P<modifier> [^{}]* )
                    \}
                )?
            )?
        \}
        |
        (?P<chunk> (?: [^{}] | \{\{ | \}\} )+ )
    """
    template_regexp = re.compile(template_pattern, re.X)

    def __init__(self, clause, state):
        assert isinstance(clause, Clause)
        assert isinstance(state, SerializingState)
        self.clause = clause
        self.state = state
        self.stream = state.stream

    def __call__(self):
        # By default, generate an error.
        raise Error("Unable to serialize an expression")

    def format(self, template, *namespaces, **keywords):
        """
        Serializes a set of variables according to a template.

        The :meth:`format` method expects a template string containing
        variable fields denoted by ``{}``.  The method writes the string
        to the SQL stream replacing variables with respective values.

        The format of the variable fields is::

            {name}
            {name:kind}
            {name:kind{modifier}}

        Here,

        * `name` is the name of the variable;
        * `kind` indicates how the variable is converted to a string;
        * `modifier` is an optional conversion parameter.

        The :class:`Format` protocol defines various conversion methods.

        `template` (a (Unicode) string)
            A template string.

        `namespaces`, `keywords` (dictionaries)
            Dictionaries containing substitution variables.
        """
        assert isinstance(template, (str, unicode))
        if isinstance(template, str):
            template = template.decode()
        # Aggregate variables from the given namespaces.  A namespace is
        # either a dictionary or an object with variables as attributes.
        variables = {}
        for namespace in namespaces:
            if isinstance(namespace, dict):
                variables.update(namespace)
            else:
                assert hasattr(namespace, '__dict__')
                variables.update(namespace.__dict__)
        variables.update(keywords)
        # Parse the template string till the end.
        start = 0
        while start < len(template):
            # Extract the next part from the template string.  It is
            # either a chunk of regular text or a variable field.
            match = self.template_regexp.match(template, start)
            assert match is not None, (template, start)
            start = match.end()
            # Is it a regular text?  Write it to the stream then.
            # Note that we have escaping rules:
            #   {{ -> {
            #   }} -> }
            chunk = match.group('chunk')
            if chunk is not None:
                chunk = chunk.replace(u"{{", u"{").replace(u"}}", u"}")
                self.stream.write(chunk)
            # It must be variable substitution then.  Extract the value
            # of the variable and realize a `Format` instance to perform
            # the substitution.
            else:
                name = match.group('name').encode()
                kind = match.group('kind')
                if kind is None:
                    kind = 'default'
                else:
                    kind = kind.encode()
                modifier = match.group('modifier')
                assert name in variables, name
                value = variables[name]
                Format.__invoke__(kind, value, modifier, self.state)

    def write(self, data):
        """
        Writes a string to the SQL stream.
        """
        self.stream.write(data)

    def indent(self):
        """
        Sets the indentation level to the current cursor position.
        """
        self.stream.indent()

    def dedent(self):
        """
        Reverts to the previous indentation level.
        """
        self.stream.dedent()

    def newline(self):
        """
        Sets the cursor to the current indentation level.
        """
        self.stream.newline()


class Format(Protocol):
    """
    Serializes a substitution variable.

    This is an auxiliary protocol used by :meth:`DumpBase.format`.  It is
    called to serialize a substitution variable of the form::

        {variable:kind{modifier}}

    `kind` (a string)
        The name of the conversion operation.  The protocol is polymorphic
        on this argument.

    `value` (an object)
        The value of the variable to be serialized.

    `modifier` (an object or ``None``)
        An optional conversion parameter.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.
    """

    def __init__(self, kind, value, modifier, state):
        assert isinstance(kind, str)
        assert isinstance(state, SerializingState)
        self.kind = kind
        self.value = value
        self.modifier = modifier
        self.state = state
        self.stream = state.stream

    def __call__(self):
        # Must be overridden in subclasses.
        raise NotImplementedError("the format %r is not implemented"
                                  % self.kind)


class FormatDefault(Format):
    """
    Dumps a clause node.

    This is the default conversion, used when the conversion kind is
    not specified explicitly::

        {clause}

    Here, the value of `clause` is a :class:`htsql.core.tr.frame.Clause`
    instance to serialize.
    """

    call('default')

    def __init__(self, kind, value, modifier, state):
        assert isinstance(value, Clause)
        assert modifier is None
        super(FormatDefault, self).__init__(kind, value, modifier, state)

    def __call__(self):
        # Delegate serialization to the `Dump` adapter.
        self.state.dump(self.value)


class FormatUnion(Format):
    """
    Dumps a list of clause nodes.

    Usage::

        {clauses:union}
        {clauses:union{ separator }}

    Here,

    * the value of the `clauses` variable is a list of
      :class:`htsql.core.tr.frame.Clause` nodes;
    * `separator` is a separator between clauses (``', '``, by default).
    """

    call('union')

    def __init__(self, kind, value, modifier, state):
        assert isinstance(value, listof(Clause)) and len(value) > 0
        assert isinstance(modifier, maybe(unicode))
        # The default separator is `', '`.
        if modifier is None:
            modifier = u", "
        super(FormatUnion, self).__init__(kind, value, modifier, state)

    def __call__(self):
        # Dump:
        #   <clause><separator><clause><separator>...
        for index, phrase in enumerate(self.value):
            if index > 0:
                self.stream.write(self.modifier)
            self.state.dump(phrase)


class FormatName(Format):
    """
    Dumps a SQL identifier.

    Usage::

        {identifier:name}

    The value of `identifier` is a string, which is serialized
    as a quoted SQL identifier.
    """

    call('name')

    def __init__(self, kind, value, modifier, state):
        assert isinstance(value, unicode)
        assert modifier is None
        # This is the last place where we could prevent an injection attack,
        # so check that the string is well-formed.
        assert u"\0" not in value
        assert len(value) > 0
        super(FormatName, self).__init__(kind, value, modifier, state)

    def __call__(self):
        # Assume standard SQL quoting rules for identifiers:
        # - an identifier is enclosed by `"`;
        # - any `"` character must be replaced with `""`.
        # A backend with non-standard quoting rules must override this method.
        self.stream.write(u"\"%s\"" % self.value.replace(u"\"", u"\"\""))


class FormatLiteral(Format):
    """
    Dumps a SQL literal.

    Usage::

        {value:literal}

    The value of the `value` variable is serialized as a quoted SQL literal.
    """

    call('literal')

    def __init__(self, kind, value, modifier, state):
        assert isinstance(value, unicode)
        assert modifier is None
        # This is the last place where we could prevent an injection attack,
        # so check that the string is well-formed.
        assert u"\0" not in value
        super(FormatLiteral, self).__init__(kind, value, modifier, state)

    def __call__(self):
        # Assume standard SQL quoting rules for literals:
        # - a value is enclosed by `'`;
        # - any `'` character must be replaced with `''`.
        # We also assume the backend accepts UTF-8 encoded strings.
        # A backend with non-standard quoting rules must override this method.
        self.stream.write(u"'%s'" % self.value.replace(u"'", u"''"))


class FormatNot(Format):
    """
    Dumps a ``NOT`` clause.

    Usage::

        {polarity:not}

    The action depends on the value of the `polarity` variable:

    * writes nothing when `polarity` is equal to ``+1``;
    * writes ``NOT`` followed by a space when `polarity` is equal to ``-1``.
    """

    call('not')

    def __init__(self, kind, value, modifier, state):
        assert value in [+1, -1]
        assert modifier is None
        super(FormatNot, self).__init__(kind, value, modifier, state)

    def __call__(self):
        # For `{polarity:not}`, dump:
        #   polarity=+1 => ""
        #   polarity=-1 => "NOT "
        if self.value < 0:
            self.stream.write(u"NOT ")


class FormatSwitch(Format):
    """
    Dumps one of two given clauses.

    Usage::

        {polarity:switch{P|N}}

    The action depends on the value of the `polarity` variable:

    * writes the ``P`` clause when `polarity` is equal to ``+1``;
    * writes the ``N`` clause when `polarity` is equal to ``-1``.
    """

    call('switch')

    def __init__(self, kind, value, modifier, state):
        assert value in [+1, -1]
        assert isinstance(modifier, unicode) and modifier.count(u"|")
        super(FormatSwitch, self).__init__(kind, value, modifier, state)

    def __call__(self):
        # For `{polarity:switch{P|N}}`, dump
        #   polarity=+1 => P
        #   polarity=-1 => N
        positive, negative = self.modifier.split(u"|")
        if self.value > 0:
            self.stream.write(positive)
        else:
            self.stream.write(negative)


class FormatPlaceholder(Format):
    """
    Dumps a placeholder indicator.

    Usage::

        {field:placeholder}

    Field is an index or a name of the placeholder.
    """

    call('placeholder')

    def __init__(self, kind, value, modifier, state):
        assert isinstance(value, maybe(unicode))
        assert modifier is None
        super(FormatPlaceholder, self).__init__(kind, value, modifier, state)

    def __call__(self):
        if self.value is None:
            self.stream.write(u"?")
        else:
            self.stream.write(u":"+self.value)


class FormatPass(Format):
    """
    Dumps the given string.

    Usage::

        {string:pass}

    The value of the `string` variable is written directly to the SQL stream.
    """

    call('pass')

    def __init__(self, kind, value, modifier, state):
        assert isinstance(value, unicode)
        assert modifier is None
        super(FormatPass, self).__init__(kind, value, modifier, state)

    def __call__(self):
        self.stream.write(self.value)


class Dub(Adapter):
    """
    Generates a preform alias name for a clause node.

    This is an auxiliary adapter used to generate aliases for
    ``SELECT`` and ``FROM`` clauses.

    `clause` (:class:`htsql.core.tr.frame.Clause`)
        A clause node to make an alias for.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.
    """

    adapt(Clause)

    def __init__(self, clause, state):
        self.clause = clause
        self.state = state

    def __call__(self):
        # The adapter must never fail, so the default implementation
        # provides a valid, though meaningless, alias name.
        return u"!"


class Dump(DumpBase):
    """
    Translates a clause node to SQL.

    This is an interface adapter; see subclasses for implementations.

    The :class:`Dump` adapter has the following signature::

        Dump: (Clause, SerializingState) -> writes to SQL stream

    The adapter is polymorphic on the `Clause` argument.

    The adapter generates a SQL clause for the given node and
    writes it to the stream that accumulates a SQL statement.

    `clause` (:class:`htsql.core.tr.frame.Clause`)
        A clause to serialize.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.
    """

    adapt(Clause)


class DubFrame(Dub):
    """
    Generates a preform alias for a frame node.
    """

    adapt(Frame)

    def __call__(self):
        # For a frame, a good alias is the name of the table
        # represented by the frame.
        space = self.clause.space
        while space.family.is_quotient:
            space = space.family.seed
        if space.family.is_table:
            return space.family.table.name
        # Use the default alias when the frame does not represent
        # any table.
        return super(DubFrame, self).__call__()


class DumpFrame(Dump):
    """
    Translates a frame node to SQL.

    `frame` (:class:`htsql.core.tr.frame.Frame`)
        A frame node to serialize.
    """

    adapt(Frame)

    def __init__(self, frame, state):
        super(DumpFrame, self).__init__(frame, state)
        self.frame = frame


class DubPhrase(Dub):
    """
    Generates a preform alias for a phrase node.
    """

    adapt(Phrase)

    def __call__(self):
        # Generate a useful alias for a phrase node.  We base the alias
        # on the underlying syntax node.
        syntax = self.clause.syntax
        # For an identifier node, take the identifier name.
        if isinstance(syntax, IdentifierSyntax):
            return syntax.name
        # For a function call node, take the function name.
        if isinstance(syntax, ApplySyntax):
            return syntax.name
        # For a literal node, take the value of the literal.
        if isinstance(syntax, LiteralSyntax) and syntax.text:
            return syntax.text
        # Otherwise, use the default alias.
        return super(DubPhrase, self).__call__()


class DumpPhrase(Dump):
    """
    Translates a phrase node to SQL.

    `phrase` (:class:`htsql.core.tr.frame.Phrase`)
        A phrase node to serialize.
    """

    adapt(Phrase)

    def __init__(self, phrase, state):
        super(DumpPhrase, self).__init__(phrase, state)
        self.phrase = phrase


class DumpTable(Dump):
    """
    Serializes a table frame.
    """

    adapt(TableFrame)

    def __call__(self):
        # Serialize a table reference in a `FROM` clause.
        # If the schema name is set, dump:
        #   <schema>.<table>
        # otherwise, dump:
        #   <table>
        table = self.frame.table
        # Check if we need to serialize the schema name.
        need_schema = False
        # Missing schema name means schemas are not supported by the backend
        # or the default schema.
        if table.schema.name:
            need_schema = True
            # Check if the table schema is the first in the search path,
            # in which case, we could omit the schema name.
            if table.schema.priority > 0:
                need_schema = False
                if any(schema.priority > table.schema.priority
                       for schema in table.schema.catalog):
                    need_schema = True
        # Serialize the table name.
        if need_schema:
            self.format("{schema:name}.{table:name}",
                        schema=table.schema.name,
                        table=table.name)
        else:
            self.format("{table:name}", table=table.name)


class DumpBranch(Dump):
    """
    Serializes a ``SELECT`` frame.
    """

    adapt(BranchFrame)

    def __call__(self):
        # Sequentially serialize the clauses of the `SELECT` frame.
        self.dump_select()
        self.dump_include()
        self.dump_where()
        self.dump_group()
        self.dump_having()
        self.dump_order()
        self.dump_limit()

    def dump_select(self):
        # Serialize a `SELECT` clause.  Dump:
        #   SELECT <phrase> AS <alias>,
        #          <phrase> AS <alias>,
        #          ...

        # The `SELECT` aliases for the current frame.
        aliases = self.state.select_aliases_by_tag[self.frame.tag]
        # Write `SELECT` and set the indentation level to the position
        # after `SELECT`.
        self.write(u"SELECT ")
        self.indent()
        # Serialize the selection phrases.
        for index, phrase in enumerate(self.frame.select):
            # Check if we need to provide an alias, and if so, fetch it.
            alias = None
            if self.state.hook.with_aliases:
                alias = aliases[index]
                # Now even if we are required to provide an alias, we may
                # still be able to omit it if it coincides with an implicit
                # alias generated by the SQL engine.  It may happen in two
                # cases.
                # (1) The selection refers to a column, and the alias
                #     coincides with the column name.
                if isinstance(phrase, ColumnPhrase):
                    if alias == phrase.column.name:
                        alias = None
                # (2) The selection exports a value from a nested `SELECT`,
                #     and the alias coincides with the alias of the nested
                #     selection.
                if isinstance(phrase, ReferencePhrase):
                    target_alias = (self.state.select_aliases_by_tag
                                            [phrase.tag][phrase.index])
                    if alias == target_alias:
                        alias = None
            # Write the selection and, if needed, its alias.
            if alias is not None:
                self.format("{selection} AS {alias:name}",
                            selection=phrase, alias=alias)
            else:
                self.format("{selection}",
                            selection=phrase)
            # Write the trailing comma.
            if index < len(self.frame.select)-1:
                self.write(u",")
                self.newline()
        # Restore the original indentation level.
        self.dedent()

    def dump_include(self):
        # Serialize a `FROM` clause.  Dump:
        #   FROM <leading_anchor>
        #        <anchor>
        #        ...

        # Nothing two write if there are no nested subframes.
        if not self.frame.include:
            return
        # Write `FROM` and set the indentation level to the next position.
        self.newline()
        self.write(u"FROM ")
        self.indent()
        # Serialize the subframes.
        for index, anchor in enumerate(self.frame.include):
            self.format("{anchor}", anchor=anchor)
        # Restore the original indentation level.
        self.dedent()

    def dump_where(self):
        # Serialize a `WHERE` clause.  Dump:
        #   WHERE <phrase>
        # or, if the top-level phrase is an `AND` operator,
        #   WHERE <op>
        #         AND <op>
        #         ...

        # Nothing to write if there is no `WHERE` condition.
        if self.frame.where is None:
            return
        self.newline()
        # Handle the case when the condition is an `AND` operator.
        if isformula(self.frame.where, AndSig):
            self.write(u"WHERE ")
            self.indent()
            for index, op in enumerate(self.frame.where.ops):
                self.format("{op}", op=op)
                if index < len(self.frame.where.ops)-1:
                    self.newline()
                    self.write(u"AND ")
            self.dedent()
        # Handle the regular case.
        else:
            self.format("WHERE {condition}",
                        condition=self.frame.where)

    def dump_group(self):
        # Serialize a `GROUP BY` clause.  Dump:
        #   GROUP BY <phrase>, ...

        # Nothing to write if there is no `GROUP BY` items.
        if not self.frame.group:
            return
        self.newline()
        self.write(u"GROUP BY ")
        # Write the `GROUP BY` items.
        for index, phrase in enumerate(self.frame.group):
            self.format(u"{kernel}", kernel=phrase)
            # Dump the trailing comma.
            if index < len(self.frame.group)-1:
                self.write(u", ")

    def dump_having(self):
        # Serialize a `HAVING` clause.  Dump:
        #   HAVING <phrase>
        # or, if the top-level phrase is an `AND` operator,
        #   HAVING <op>
        #          AND <op>
        #          ...

        # Note: currently unused as the assembler never generates a `HAVING`
        # clause.

        # Nothing to write if there is no `HAVING` condition.
        if self.frame.having is None:
            return
        self.newline()
        # Handle the case when the condition is an `AND` operator.
        if isformula(self.frame.having, AndSig):
            self.write(u"HAVING ")
            self.indent()
            for index, op in enumerate(self.frame.having.ops):
                self.format("{op}", op=op)
                if index < len(self.frame.having.ops)-1:
                    self.newline()
                    self.write(u"AND ")
            self.dedent()
        # Handle the regular case.
        else:
            self.format("HAVING {condition}",
                        condition=self.frame.having)

    def dump_order(self):
        # Serialize an `ORDER BY` clause.  Dump:
        #   ORDER BY <phrase> (ASC|DESC), ...

        # Nothing to write if there is no `ORDER BY` items.
        if not self.frame.order:
            return
        self.newline()
        self.write(u"ORDER BY ")
        # Write the `GROUP BY` items.
        for index, phrase in enumerate(self.frame.order):
            self.format("{kernel}", kernel=phrase)
            # Write the trailing comma.
            if index < len(self.frame.order)-1:
                self.write(u", ")

    def dump_limit(self):
        # Serialize `LIMIT` and `OFFSET` clauses.  Dump:
        #   LIMIT <limit>
        #   OFFSET <offset>
        # Note: this syntax is commonly used, but not standard.  A backend
        # with a different syntax for `LIMIT` and `SELECT` clauses must
        # override this method.

        # Nothing to write if there is no `LIMIT` or `OFFSET` clause.
        if self.frame.limit is None and self.frame.offset is None:
            return
        # Dump a `LIMIT` clause.
        if self.frame.limit is not None:
            self.newline()
            self.write(u"LIMIT "+unicode(self.frame.limit))
        # Dump an `OFFSET` clause.
        if self.frame.offset is not None:
            self.newline()
            self.write(u"OFFSET "+unicode(self.frame.offset))


class DumpNested(Dump):
    """
    Serializes a nested ``SELECT`` frame.
    """

    adapt(NestedFrame)

    def __call__(self):
        # Dump:
        #   (SELECT ...
        #    ...)
        self.write(u"(")
        self.indent()
        super(DumpNested, self).__call__()
        self.dedent()
        self.write(u")")


class DumpSegment(Dump):
    """
    Serializes a top-level ``SELECT`` frame.
    """

    adapt(SegmentFrame)

    def __call__(self):
        super(DumpSegment, self).__call__()
        # FIXME: add a semicolon?
        # Make sure the statement ends with a new line.
        self.newline()


class DumpLeadingAnchor(Dump):
    """
    Serializes the leading subframe in a ``FROM`` clause.
    """

    adapt(LeadingAnchor)

    def __call__(self):
        # Dump:
        #   <frame> AS <alias>
        alias = self.state.frame_alias_by_tag[self.clause.frame.tag]
        # Omit the alias if it coincides with the table name.
        if isinstance(self.clause.frame, TableFrame):
            table = self.clause.frame.table
            if alias == table.name:
                alias = None
        # Dump the frame clause.
        self.state.push_hook(with_aliases=True)
        if alias is not None:
            self.format("{frame} AS {alias:name}",
                        frame=self.clause.frame, alias=alias)
        else:
            self.format("{frame}", frame=self.clause.frame)
        self.state.pop_hook()


class DumpAnchor(Dump):
    """
    Serializes a successive subframe in a ``FROM`` clause.
    """

    adapt(Anchor)

    def __call__(self):
        # Dump:
        #   (CROSS|INNER|...) JOIN <frame> AS <alias>
        #                          ON <condition>
        alias = self.state.frame_alias_by_tag[self.clause.frame.tag]
        # Omit the alias if it coincides with the table name.
        if isinstance(self.clause.frame, TableFrame):
            table = self.clause.frame.table
            if alias == table.name:
                alias = None
        # Dump the `JOIN` clause.
        self.newline()
        if self.clause.is_cross:
            self.write(u"CROSS JOIN ")
        elif self.clause.is_inner:
            self.write(u"INNER JOIN ")
        elif self.clause.is_left and not self.clause.is_right:
            self.write(u"LEFT OUTER JOIN ")
        elif self.clause.is_right and not self.clause.is_left:
            self.write(u"RIGHT OUTER JOIN ")
        else:
            self.write(u"FULL OUTER JOIN ")
        self.indent()
        self.state.push_hook(with_aliases=True)
        if alias is not None:
            self.format("{frame} AS {alias:name}",
                        frame=self.clause.frame, alias=alias)
        else:
            self.format("{frame}", frame=self.clause.frame)
        self.state.pop_hook()
        if self.clause.condition is not None:
            self.newline()
            self.format("ON {condition}",
                        condition=self.clause.condition)
        self.dedent()


class DubColumn(Dub):
    """
    Generates a preform alias for a column reference.
    """

    adapt(ColumnPhrase)

    def __call__(self):
        # Use the name of the column as an alias.
        return self.clause.column.name


class DumpColumn(Dump):
    """
    Serializes a reference to a table frame.
    """

    adapt(ColumnPhrase)

    def __call__(self):
        # Dump:
        #   <alias>.<column>
        parent = self.state.frame_alias_by_tag[self.phrase.tag]
        child = self.phrase.column.name
        self.format("{parent:name}.{child:name}",
                    parent=parent, child=child)


class DubReference(Dub):
    """
    Generates a preform alias for a reference to a nested ``SELECT``.
    """

    adapt(ReferencePhrase)

    def __call__(self):
        # Use the same alias as the target phrase.
        frame = self.state.frame_by_tag[self.clause.tag]
        phrase = frame.select[self.clause.index]
        return self.state.dub(phrase)


class DumpReference(Dump):
    """
    Serializes a reference to a nested subframe.
    """

    adapt(ReferencePhrase)

    def __call__(self):
        # Dump:
        #   <frame>.<column>
        parent = self.state.frame_alias_by_tag[self.phrase.tag]
        select_aliases = self.state.select_aliases_by_tag[self.phrase.tag]
        child = select_aliases[self.phrase.index]
        self.format("{parent:name}.{child:name}",
                    parent=parent, child=child)


class DubEmbedding(Dub):
    """
    Generates a preform alias for a correlated subquery.
    """

    adapt(EmbeddingPhrase)

    def __call__(self):
        # Use the same alias as the (only) output column of the subquery.
        frame = self.state.frame_by_tag[self.clause.tag]
        [phrase] = frame.select
        return self.state.dub(phrase)


class DumpEmbedding(Dump):
    """
    Serializes an embedded subquery.
    """

    adapt(EmbeddingPhrase)

    def __call__(self):
        # Fetch and serialize the suframe.
        frame = self.state.frame_by_tag[self.phrase.tag]
        self.state.push_hook(with_aliases=False)
        self.format("{frame}", frame=frame)
        self.state.pop_hook()


class DumpLiteral(Dump):
    """
    Serializes a literal node.

    Serialiation is delegated to the :class:`DumpByDomain` adapter.
    """

    adapt(LiteralPhrase)

    def __call__(self):
        # Delegate serialization to `DumpByDomain`.
        return DumpByDomain.__invoke__(self.phrase, self.state)


class DumpNull(Dump):
    """
    Serializes a ``NULL`` value.
    """

    adapt(NullPhrase)

    def __call__(self):
        # We serialize a `NULL` value here to avoid checking for
        # `NULL` in every implementation of `DumpByDomain`.
        # FIXME: This assumes that we never need to add an explicit type
        # specifier to a `NULL` value.
        self.write(u"NULL")


class DumpByDomain(DumpBase):
    """
    Serializes a literal node.

    This is an auxiliary adapter used for serialization of literal nodes.
    The adapter is polymorphic on the domain of the literal.

    `phrase` (:class:`htsql.core.tr.frame.LiteralPhrase`)
        A literal node to serialize.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.

    Other attributes:

    `value` (depends on the domain or ``None``)
        The value of the literal.

    `domain` (:class:`htsql.core.domain.Domain`)
        The domain of the literal.
    """

    adapt(Domain)

    @classmethod
    def __dispatch__(interface, phrase, *args, **kwds):
        # Dispatch the adapter on the domain of the literal node.
        assert isinstance(phrase, LiteralPhrase)
        return (type(phrase.domain),)

    def __init__(self, phrase, state):
        assert isinstance(phrase, LiteralPhrase)
        assert phrase.value is not None
        super(DumpByDomain, self).__init__(phrase, state)
        self.phrase = phrase
        # Extract commonly used attributes of the literal node.
        self.value = phrase.value
        self.domain = phrase.domain


class DumpBoolean(DumpByDomain):
    """
    Serializes a Boolean literal.
    """

    adapt(BooleanDomain)

    def __call__(self):
        # Use the SQL standard constants: `TRUE` and `FALSE`.
        # Backends not supporting those must override this implementation.
        if self.value is True:
            self.write(u"TRUE")
        if self.value is False:
            self.write(u"FALSE")


class DumpInteger(DumpByDomain):
    """
    Serializes an integer literal.
    """

    adapt(IntegerDomain)

    def __call__(self):
        # Dump an integer number.  A backend may override this implementation
        # to support a different range of integer values.

        # We assume that the database supports 8-byte signed integer values
        # natively and complain if the value is out of this range.
        if not (-2**63 <= self.value < 2**63):
            raise Error("Found integer value is out of range")
        # Write the number; use `(...)` around a negative number.
        if self.value >= 0:
            self.write(unicode(self.value))
        else:
            self.write(u"(%s)" % self.value)


class DumpFloat(DumpByDomain):
    """
    Serializes a float literal.
    """

    adapt(FloatDomain)

    def __call__(self):
        # Dump a floating-point number.  A backend may override this method
        # to support a different range of floating-point values or to
        # provide an exact type specifier.

        # Last check that we didn't get a non-number.
        assert not math.isinf(self.value) and not math.isnan(self.value)
        # Write the standard representation of the number assuming that
        # the database could figure out its type from the context; use `(...)`
        # around a negative number.
        if self.value >= 0.0:
            self.write(u"%r" % self.value)
        else:
            self.write(u"(%r)" % self.value)


class DumpDecimal(DumpByDomain):
    """
    Serializes a decimal literal.
    """

    adapt(DecimalDomain)

    def __call__(self):
        # Dump a decimal number.  A backend may override this method
        # to support a different range of values or to add an exact
        # type specifier.

        # Last check that we didn't get a non-number.
        assert self.value.is_finite()
        # Write the standard representation of the number assuming that
        # the database could figure out its type from the context; use `(...)`
        # around a negative number.
        if not self.value.is_signed():
            self.write(unicode(self.value))
        else:
            self.write(u"(%s)" % self.value)


class DumpText(DumpByDomain):
    """
    Serializes a string literal.
    """

    adapt(TextDomain)

    def __call__(self):
        # Dump the value as a quoted literal.
        self.format("{value:literal}", value=self.value)


class DumpEnum(DumpByDomain):
    """
    Serializes a value of an enumerated type.
    """

    adapt(EnumDomain)

    def __call__(self):
        # There is no an enumerated type in the SQL standard, but most
        # backends which support enumerated types accept quoted literals.
        self.format("{value:literal}", value=self.value)


class DumpDate(DumpByDomain):
    """
    Serializes a date literal.
    """

    adapt(DateDomain)

    def __call__(self):
        # Dump:
        #   DATE 'YYYY-MM-DD'
        # A backend with a different (or no) date represetation may need
        # to override this implementation.
        self.format("DATE {value:literal}", value=unicode(self.value))


class DumpTime(DumpByDomain):
    """
    Serializes a time literal.
    """

    adapt(TimeDomain)

    def __call__(self):
        self.format("TIME {value:literal}", value=unicode(self.value))


class DumpDateTime(DumpByDomain):
    """
    Serializes a datetime literal.
    """

    adapt(DateTimeDomain)

    def __call__(self):
        if self.value.tzinfo is None:
            self.format("TIMESTAMP {value:literal}", value=unicode(self.value))
        else:
            self.format("TIMESTAMP WITH TIME ZONE {value:literal}",
                        value=unicode(self.value))


class DumpCast(Dump):
    """
    Serializes a ``CAST`` clause.

    Serialiation is delegated to the :class:`DumpByDomain` adapter.
    """

    adapt(CastPhrase)

    def __call__(self):
        # Delegate serialization to `DumpToDomain`.
        return DumpToDomain.__invoke__(self.phrase, self.state)


class DumpToDomain(DumpBase):
    """
    Serializes a ``CAST`` clause.

    This is an auxiliary adapter used for serialization of cast phrase nodes.
    The adapter is polymorphic on the pair of the origin and the target
    domains.

    `phrase` (:class:`htsql.core.tr.frame.CastPhrase`)
        A cast node to serialize.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.

    Other attributes:

    `base` (:class:`htsql.core.tr.frame.Phrase`)
        The operand of the ``CAST`` expression.

    `domain` (:class:`htsql.core.domain.Domain`)
        The target domain.
    """

    adapt(Domain, Domain)

    @classmethod
    def __dispatch__(interface, phrase, *args, **kwds):
        # Dispatch the adapter on the origin and the target domains
        # of the cast.
        assert isinstance(phrase, CastPhrase)
        return (type(phrase.base.domain), type(phrase.domain))

    def __init__(self, phrase, state):
        assert isinstance(phrase, CastPhrase)
        super(DumpToDomain, self).__init__(phrase, state)
        self.phrase = phrase
        # Extract commonly used attributes.
        self.base = phrase.base
        self.domain = phrase.domain


class DumpToInteger(DumpToDomain):
    """
    Serializes conversion to an integer value.

    Handles conversion from a string and other numeric data types.
    """

    adapt(Domain, IntegerDomain)

    def __call__(self):
        # Dump:
        #   CAST(<base> AS INTEGER)
        # A backend with no integer data type or an integer data type
        # with a different name needs to override this implementation.
        self.format("CAST({base} AS INTEGER)", base=self.base)


class DumpToFloat(DumpToDomain):
    """
    Serializes conversion to a floating-point number.

    Handles conversion from a string and other numeric data types.
    """

    adapt(Domain, FloatDomain)

    def __call__(self):
        # Dump:
        #   CAST(<base> AS DOUBLE PRECISION)
        # A backend with no floating-point data type or a floating-point
        # data type with a different name needs to override this
        # implementation.
        self.format("CAST({base} AS DOUBLE PRECISION)", base=self.base)


class DumpToDecimal(DumpToDomain):
    """
    Serializes conversion to a decimal number.

    Handles conversion from a string and other numeric data types.
    """

    adapt(Domain, DecimalDomain)

    def __call__(self):
        # Dump:
        #   CAST(<base> AS DECIMAL)
        # A backend with no decimal data type or a decimal data type
        # with a different name needs to override this implementation.
        self.format("CAST({base} AS DECIMAL)", base=self.base)


class DumpToText(DumpToDomain):
    """
    Serializes conversion to a string.

    Handles conversion from other data types to a string.
    """

    adapt(Domain, TextDomain)

    def __call__(self):
        # Dump:
        #   CAST(<base> AS CHARACTER VARYING)
        # A backend that supports many character types may choose a different
        # target data type.
        self.format("CAST({base} AS CHARACTER VARYING)", base=self.base)


class DumpToDate(DumpToDomain):
    """
    Serializes conversion to a date value.

    Handles conversion from a string and a datetime.
    """

    adapt(Domain, DateDomain)

    def __call__(self):
        self.format("CAST({base} AS DATE)", base=self.base)


class DumpToTime(DumpToDomain):
    """
    Serializes conversion to a time value.

    Handles conversion from a string and a datetime.
    """

    adapt(Domain, TimeDomain)

    def __call__(self):
        self.format("CAST({base} AS TIME)", base=self.base)


class DumpToDateTime(DumpToDomain):
    """
    Serializes conversion to a datetime value.

    Handles conversion from a string.
    """

    adapt(Domain, DateTimeDomain)

    def __call__(self):
        self.format("CAST({base} AS TIMESTAMP)", base=self.base)


class DumpFormula(Dump):
    """
    Serializes a formula node.

    Serialiation is delegated to the :class:`DumpBySignature` adapter.
    """

    adapt(FormulaPhrase)

    def __call__(self):
        # Delegate serialization to `DumpBySignature`.
        return DumpBySignature.__invoke__(self.phrase, self.state)


class DumpBySignature(DumpBase):
    """
    Serializes a formula node.

    This is an auxiliary adapter used for serialization of formula nodes.
    The adapter is polymorphic on the formula signature.

    `phrase` (:class:`htsql.core.tr.frame.FormulaPhrase`)
        A formula node to serialize.

    `state` (:class:`SerializingState`)
        The current state of the serializing process.

    Other attributes:

    `signature` (:class:`htsql.core.tr.signature.Signature`)
        The signature of the formula.

    `domain` (:class:`htsql.core.tr.domain.Domain`)
        The co-domain of the formula.

    `arguments` (:class:`htsql.core.tr.signature.Bag`)
        The arguments of the formula.
    """

    adapt(Signature)

    @classmethod
    def __dispatch__(interface, phrase, *args, **kwds):
        # Dispatch the adapter on the signature of the formula.
        assert isinstance(phrase, FormulaPhrase)
        return (type(phrase.signature),)

    def __init__(self, phrase, state):
        assert isinstance(phrase, FormulaPhrase)
        super(DumpBySignature, self).__init__(phrase, state)
        self.phrase = phrase
        # Extract commonly used attributes of the formula.
        self.signature = phrase.signature
        self.domain = phrase.domain
        self.arguments = phrase.arguments


class DumpIsEqual(DumpBySignature):
    """
    Serializes an (in)equality (``=`` or ``!=``) operator
    """

    adapt(IsEqualSig)

    def __call__(self):
        # Dump:
        #   (<lop> (=|<>) <rop>)
        self.format("({lop} {polarity:switch{=|<>}} {rop})",
                    self.arguments, self.signature)


class DumpIsTotallyEqual(DumpBySignature):
    """
    Serializes a total (in)equality (``==`` or ``!==``) operator.
    """

    adapt(IsTotallyEqualSig)

    def __call__(self):
        # Dump:
        #   (<lop> IS (NOT) DISTINCT FROM <rop>)
        # Note that many backends do not support `IS DISTINCT FROM`
        # operator and need to reimplement this implementation using
        # the regular equality operator and `IS NULL`.
        self.format("({lop} IS {polarity:not}DISTINCT FROM {rop})",
                    self.arguments, polarity=-self.signature.polarity)


class DumpIsIn(DumpBySignature):
    """
    Serializes an N-ary equality (``={}``) operator.
    """

    adapt(IsInSig)

    def __call__(self):
        # Dump:
        #   (<lop> (NOT) IN (rop1, rop2, ...))
        self.format("({lop} {polarity:not}IN ({rops:union{, }}))",
                    self.arguments, self.signature)


class DumpAnd(DumpBySignature):
    """
    Serializes a logical "AND" (``&``) operator.
    """

    adapt(AndSig)

    def __call__(self):
        # Dump:
        #   (<op1> AND <op2> AND ...)
        self.format("({ops:union{ AND }})", self.arguments)


class DumpOr(DumpBySignature):
    """
    Serializes a logical "OR" (``|``) operator.
    """

    adapt(OrSig)

    def __call__(self):
        # Dump:
        #   (<op1> OR <op2> OR ...)
        self.format("({ops:union{ OR }})", self.arguments)


class DumpNot(DumpBySignature):
    """
    Serializes a logical "NOT" (``!``) operator.
    """

    adapt(NotSig)

    def __call__(self):
        # Dump:
        #   (NOT <op>)
        self.format("(NOT {op})", self.arguments)


class DumpIsNull(DumpBySignature):
    """
    Serializes an ``is_null()`` operator.
    """

    adapt(IsNullSig)

    def __call__(self):
        # Dump:
        #   (<op> IS (NOT) NULL)
        self.format("({op} IS {polarity:not}NULL)",
                    self.arguments, self.signature)


class DumpIfNull(DumpBySignature):
    """
    Serializes an ``if_null()`` operator.
    """

    adapt(IfNullSig)

    def __call__(self):
        # Dump:
        #   COALESCE(<lop>, <rop>)
        self.format("COALESCE({lop}, {rop})", self.arguments)


class DumpNullIf(DumpBySignature):
    """
    Serializes a ``null_if()`` operator.
    """

    adapt(NullIfSig)

    def __call__(self):
        # Dump:
        #   NULLIF(<lop>, <rop>)
        self.format("NULLIF({lop}, {rop})", self.arguments)


class DumpCompare(DumpBySignature):
    """
    Serializes a comparison operator.
    """

    adapt(CompareSig)

    def __call__(self):
        # Dump:
        #   (<lop> (<|<=|>|>=) <rop>)
        self.format("({lop} {relation:pass} {rop})",
                    self.arguments, relation=unicode(self.signature.relation))


class DumpSortDirection(DumpBySignature):

    adapt(SortDirectionSig)

    def __call__(self):
        # Note: the default serializer assumes that the `ASC` modifier
        # lists `NULL` values first, and the `DESC` modifier lists `NULL`
        # values last.  Backends for which it is not so must override
        # this adapter.
        self.format("{base} {direction:switch{ASC|DESC}}", self.arguments,
                    self.signature)


class DumpRowNumber(DumpBySignature):

    adapt(RowNumberSig)

    def __call__(self):
        self.write(u"ROW_NUMBER() OVER (")
        if self.phrase.partition:
            self.format("PARTITION BY {partition:union{, }}", self.arguments)
            if self.phrase.order:
                self.write(u" ")
        if self.phrase.order:
            self.format("ORDER BY {order:union{, }}", self.arguments)
        self.write(u")")


class DumpToPredicate(DumpBySignature):

    adapt(ToPredicateSig)

    def __call__(self):
        return self.state.dump(self.phrase.op)


class DumpFromPredicate(DumpBySignature):

    adapt(FromPredicateSig)

    def __call__(self):
        return self.state.dump(self.phrase.op)


class DumpPlaceholder(DumpBySignature):

    adapt(PlaceholderSig)

    def __call__(self):
        self.state.add_placeholder(self.signature.index, self.domain)
        self.format("{index:placeholder}",
                    index=unicode(self.signature.index+1))


def serialize(clause, state=None):
    """
    Translates a clause node to SQL.

    `clause` (:class:`htsql.core.tr.frame.Clause`)
        The clause to serialize.

    `state` (:class:`SerializingState` or ``None``)
        The serializing state to use.  If not set, a new serializing
        state is instantiated.
    """
    # Create a new serializing state if necessary.
    if state is None:
        state = SerializingState()
    # Realize and apply the `Serialize` adapter.
    return Serialize.__invoke__(clause, state)