This file is indexed.

/usr/lib/python2.7/dist-packages/gadfly/semantics.py is in python-gadfly 1.0.0-16.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
""" SQL semantics

:Author: Aaron Watters
:Maintainers: http://gadfly.sf.net/
:Copyright: Aaron Robert Watters, 1994
:Id: $Id: semantics.py,v 1.7 2002/05/11 02:59:05 richard Exp $:
"""

### trim unused methods.
### make assns use equivalence classes.

### maybe eventually implement disj-conj-eq optimizations

### note: for multithreading x.relbind(...) should ALWAYs return
###   a fresh copy of structure (sometimes in-place now).

### note: binding of order by is dubious with archiving,
###    should not bind IN PLACE, leave unbound elts alone!

import sys, traceback, types

from kjbuckets_select import kjbuckets
import serialize

Tuple = kjbuckets.kjDict
Graph = kjbuckets.kjGraph
Set = kjbuckets.kjSet

### debug
#sys.stderr = sys.stdin

# operations on simple tuples, mostly from kjbuckets
#def maketuple(thing):
#    """try to make a tuple from thing.
#       thing should be a dictionary or sequence of (name, value)
#       or other tuple."""
#    from types import DictType
#    if type(thing)==DictType:
#       return Tuple(thing.items() )
#    else: return Tuple(thing)

def no_ints_nulls(list):
    """in place remove all ints, Nones from a list (for null handling)"""
    tt = type
    nn = None
    from types import IntType
    count = 0
    for x in list:
        if tt(x) is not IntType and x is not nn:
            list[count] = x
            count = count+1
    del list[count:]
    return list

# stuff for bound tuples.

class HashJoiner:

    def __init__(self, bt, relname, attributes, relation, witness):
        self.relname = relname
        self.attributes = attributes
        self.relation = relation
        self.witness = witness
        self.bt = bt
        eqs = bt.eqs
        #print "relname", relname
        #print "attributes", attributes
        #print "relation", relation
        #print "witness", witness
        #print "bt", bt
        transform = self.transform = kjbuckets.kjDict()
        rbindings = self.rbindings = kjbuckets.kjSet()
        for a in attributes:
            b = (relname, a)
            transform[b] = a
            rbindings[b] = b
        self.eqs = eqs = eqs + kjbuckets.kjGraph(rbindings)
        witness = witness.remap(eqs)
        known = kjbuckets.kjSet(witness.keys()) & rbindings
        batts = tuple(known.items())
        if not batts:
            atts = ()
        elif len(batts)==1:
            atts = ( transform[batts[0]], )
        else:
            atts = transform.dump(batts)
        self.atts = atts
        self.batts = batts
        self.transform = transform
        eqs = bt.eqs
        #eqs = (rbindings * eqs)
        self.eqs = eqs = eqs + kjbuckets.kjGraph(rbindings)
        self.transformG = transformG = eqs * transform
        assns = self.assns = bt.assns
        self.rassns = assns.remap( ~transformG )

    def relbind(self, db, atts):
        rel = self.relation
        #print "rel is ", rel, type(rel)
        #print dir(rel)
        if rel.is_view:
            self.relation = rel.relbind(db, atts)
        return self

    def uncache(self):
        rel = self.relation
        if rel.is_view:
            self.relation.uncache()

    def join(self, subseq):
        relname = self.relname
        result = []
        assns = self.assns
        if not subseq: return result
        # apply equalities to unitary subseq (embedded subq)
        if len(subseq)==1:
            subseq0 = subseq[0]
            subseq0r = subseq0.remap(self.eqs)
            if subseq0r is None:
                return [] # inconsistent
            subseq0 = subseq0 + subseq0r + assns
            if subseq0.Clean() is None:
                return [] # inconsistent
            subseq = [subseq0]
        rassns = self.rassns
        #print "rassns", rassns
        #print "subseq", subseq
        if rassns is None:
            #print "inconsistent btup"
            return []
        relation = self.relation
        #print "assns", assns
        transformG = self.transformG
        #print "transformG", transformG
        transform = self.transform
        atts = self.atts
        batts = self.batts
        #print "batts, atts", batts, atts
        if not batts:
            #print "cross product", relname
            tuples = relation.rows()
            for t in tuples:
                #print "t is", t
                if rassns:
                    t = (t + rassns).Clean()
                if t is None:
                    #print "preselect fails"
                    continue
                new = t.remap(transformG)
                #print "new is", new
                if new is None:
                    #print "transform fails"
                    continue
                for subst in subseq:
                    #print "subst", subst
                    if subst:
                        add = (subst + new).Clean()
                    else:
                        add = new
                    #print "add is", add
                    if add is not None:
                        result.append(add)
        else:
            # hash join
            #print "hash join"
            # first try to use an index
            index = relation.choose_index(atts)
            #print transform
            if index is not None:
                #print "index join", index.name, relname
                #print index.index.keys()
                #print "rassns", rassns
                atts = index.attributes()
                invtransform = ~transform
                if len(atts)==1:
                    batts = (invtransform[atts[0]],)
                else:
                    batts = invtransform.dump(atts)
                hash_tups = 1
                tindex = index.index
                # memoize converted tuples
                tindex0 = {}
                test = tindex.has_key
                test0 = tindex0.has_key
                for i in xrange(len(subseq)):
                    subst = subseq[i]
                    #print "substs is", subst
                    its = subst.dump(batts)
                    #print "its", its
                    othersubsts = []
                    if test0(its):
                        othersubsts = tindex0[its]
                    elif test(its):
                        tups = tindex[its]
                        for t in tups:
                            #print "t before", t
                            t = (t+rassns).Clean()
                            #print "t after", t
                            if t is None: continue
                            new = t.remap(transformG)
                            #print "new", new
                            if new is None: continue
                            othersubsts.append(new)
                    tindex0[its] = othersubsts
                    for other in othersubsts:
                        #print "adding", other, subst
                        add = (other + subst).Clean()
                        if add is not None:
                            result.append(add)
            # hash join
            #print "hash join"
            else:
                tuples = relation.rows()
                if len(subseq)<len(tuples):
                    #print "hash subseq", relname
                    subseqindex = {}
                    test = subseqindex.has_key
                    for i in xrange(len(subseq)):
                        subst = subseq[i]
                        its = subst.dump(batts)
                        #print "items1", subseq, batts, its
                        if test(its):
                            subseqindex[its].append(subst)
                        else:
                            subseqindex[its] = [ subst ]
                    for t in tuples:
                        #print "on", t
                        if rassns:
                            t = (t+rassns).Clean()
                        if t is None:
                            #print "preselect fails"
                            continue
                        its = t.dump(atts)
                        #print "items2", its
                        if test(its):
                            new = t.remap(transformG)
                            #print "...new", new
                            if new is None:
                                #print "transform fails"
                                continue
                            l = subseqindex[its]
                            for subst in l:
                                add = (subst + new).Clean()
                                #print "adding", add
                                if add is not None:
                                    result.append(add)
                else:
                    #print "hash tuples", relname
                    tindex = {}
                    test = tindex.has_key
                    for i in xrange(len(tuples)):
                        t = tuples[i]
                        if rassns:
                            t = (t + rassns).Clean()
                        if t is None:
                            #print "preselect fails"
                            continue
                        new = t.remap(transformG)
                        #print "new is", new
                        if new is None:
                            #print "transform fails"
                            continue
                        its = t.dump(atts)
                        #print "items3", its
                        if test(its):
                            tindex[its].append(new)
                        else:
                            tindex[its] = [ new ]
                    for subst in subseq:
                        its = subst.dump(batts)
                        #print "items4", its
                        if test(its):
                            n = tindex[its]
                            for new in n:
                                add = (subst + new).Clean()
                                if add is not None:
                                    result.append(add)
        #print "hashjoin result"
        #for x in result:
            #print x
            #break
        return result

class SimpleRecursive:
    """Simple Recursive structure, only requires initargs"""
    def demarshal(self, args):
        pass
    def marshaldata(self):
        return ()

class BoundTuple:

    clean = 1  # false if inconsistent
    closed = 0 # true if equality constraints inferred

    def __init__(self, **bindings):
        """bindings are name>simpletuple associations."""
        self.eqs = Graph()
        self.assns = Tuple()
        for (name, simpletuple) in bindings.items():
            # XXXX TODO FIXME.
            # there _is_ no 'bind()' method! Fortunately, afaics
            # this constructor is never called with args.
            self.bind(name, simpletuple)

    def initargs(self):
        return ()

    def marshaldata(self):
        #print "btp marshaldata", self
        return (self.eqs.items(), self.assns.items(), self.clean, self.closed)

    def demarshal(self, args):
        (eitems, aitems, self.clean, self.closed) = args
        self.eqs = kjbuckets.kjGraph(eitems)
        self.assns = kjbuckets.kjDict(aitems)

    def relbind(self, dict, db):
        """return bindings of self wrt dict rel>att"""
        result = BoundTuple()
        e2 = result.eqs
        a2 = result.assns
        for ((a,b), (c,d)) in self.eqs.items():
            if a is None:
                try:
                    a = dict[b]
                except KeyError:
                    raise NameError, `b`+": ambiguous or unknown attribute"
            if c is None:
                try:
                    c = dict[d]
                except KeyError:
                    raise NameError, `d`+": ambiguous or unknown attribute"
            e2[(a,b)] = (c,d)
        for ((a,b), v) in self.assns.items():
            if a is None:
                try:
                    a = dict[b]
                except KeyError:
                    raise NameError, `b`+": ambiguous or unknown attribute"
            a2[(a,b)] = v
        result.closed = self.closed
        result.clean = self.clean
        return result

    #def known(self, relname):
    #    """return ([(relname, a1), ...], [a1, ...])
    #       for attributes ai of relname known in self."""
    #    atts = []
    #    batts = []
    #    for x in self.assns.keys():
    #        (r,a) = x
    #        if r==relname:
    #           batts.append(x)
    #           atts.append(a)
    #    return (batts, atts)

    def relorder(self, db, allrels):
        """based on known constraints, pick an
           ordering for materializing relations.
           db is database (ignored currently)
           allrels is names of all relations to include (list)."""
        ### not very smart about indices yet!!!
        if len(allrels)<2:
            # doesn't matter
            return allrels
        order = []
        eqs = self.eqs
        assns = self.assns
        kjSet = kjbuckets.kjSet
        kjGraph = kjbuckets.kjGraph
        pinned = kjSet()
        has_index = kjSet()
        needed = kjSet(allrels)
        akeys = assns.keys()
        for (r,a) in akeys:
            pinned[r]=r # pinned if some value known
        known_map = kjGraph(akeys)
        for r in known_map.keys():
            rknown = known_map.neighbors(r)
            if db.has_key(r):
                rel = db[r]
                index = rel.choose_index(rknown)
                if index is not None:
                    has_index[r] = r # has an index!
        if pinned: pinned = pinned & needed
        if has_index: has_index = has_index & needed
        related = kjGraph()
        for ( (r1, a1), (r2, a2) ) in eqs.items():
            related[r1]=r2 # related if equated to other
            related[r2]=r1 # redundant if closed.
        if related: related = needed * related * needed
        chosen = kjSet()
        pr = kjSet(related) & pinned
        # choose first victim
        if has_index:
            choice = has_index.choose_key()
        elif pr:
            choice = pr.choose_key()
        elif pinned:
            choice = pinned.choose_key()
        elif related:
            choice = related.choose_key()
        else:
            return allrels[:] # give up!
        while pinned or related or has_index:
            order.append(choice)
            chosen[choice] = 1
            if pinned.has_key(choice):
                del pinned[choice]
            if related.has_key(choice):
                del related[choice]
            if has_index.has_key(choice):
                del has_index[choice]
            nexts = related * chosen
            if nexts:
                # prefer a relation related to chosen
                choice = nexts.choose_key()
            elif pinned:
                # otherwise one that is pinned
                choice = pinned.choose_key()
            elif related:
                # otherwise one that relates to something...
                choice = related.choose_key()
        others = kjSet(allrels) - chosen
        if others: order = order + others.items()
        return order

    def domain(self):
        kjSet = kjbuckets.kjSet
        return kjSet(self.eqs) + kjSet(self.assns)

    def __repr__(self):
        result = []
        for ( (name, att), value) in self.assns.items():
            result.append( "%s.%s=%s" % (name, att, `value`) )
        for ( (name, att), (name2, att2) ) in self.eqs.items():
            result.append( "%s.%s=%s.%s" % (name, att, name2, att2) )
        if self.clean:
            if not result: return "TRUE"
        else:
            result.insert(0, "FALSE")
        result.sort()
        return ' & '.join(result)

    def equate(self, equalities):
        """add equalities to self, only if not closed.
           equalities should be seq of ( (name, att), (name, att) )
           """
        if self.closed: raise ValueError, "cannot add equalities! Closed!"
        e = self.eqs
        for (a, b) in equalities:
            e[a] = b

    def close(self):
        """infer equalities, if consistent.
           only recompute equality closure if not previously closed.
           return None on inconsistency.
        """
        neweqs = self.eqs
        if not self.closed:
            self.eqs = neweqs = (neweqs + ~neweqs).tclosure() # sym, trans closure
            self.closed = 1
        # add trivial equalities to self
        for x in self.assns.keys():
            if not neweqs.member(x,x):
                neweqs[x] = x
        newassns = self.assns.remap(neweqs)
        if newassns is not None and self.clean:
            self.assns = newassns
            #self.clean = 1
            return self
        else:
            self.clean = 0
            return None

    def share_eqs(self):
        """make clone of self that shares equalities, closure.
           note: will share future side effects to eqs too."""
        result = BoundTuple()
        result.eqs = self.eqs
        result.closed = self.closed
        return result

    def __add__(self, other):
        """combine self with other, return closure."""
        result = self.share_eqs()
        se = self.eqs
        oe = other.eqs
        if (se is not oe) and (se != oe):
            result.eqs = se + oe
            result.closed = 0
        ra= result.assns = self.assns + other.assns
        result.clean = result.clean and (ra.Clean() is not None)
        return result.close()

    def __and__(self, other):
        """return closed constraints common to self and other."""
        result = BoundTuple()
        se = self.eqs
        oe = other.eqs
        if (se is oe) or (se == oe):
            result.eqs = self.eqs
            result.closed = self.closed
        else:
            result.eqs = self.eqs & other.eqs
        result.assns = self.assns & other.assns
        result.clean = self.clean and other.clean
        return result.close()

    def __hash__(self):
        # note: equalities don't enter into hash computation!
        # (some may be spurious)
        self.close()
        return hash(self.assns)# ^ hash(self.eqs)

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        sa = self.assns
        oa = other.assns
        test = cmp(sa, oa)
        if test: return test
        kjSet = kjbuckets.kjSet
        kjGraph = kjbuckets.kjSet
        se = self.eqs
        se = kjGraph(se) - kjGraph(kjSet(se))
        oe = other.eqs
        oe = kjGraph(oe) - kjGraph(kjSet(oe))
        return cmp(se, oe)

class BoundExpression(SimpleRecursive):
    """superclass for all bound expressions.
       except where overloaded expressions are binary
       with self.left and self.right
    """

    contains_aggregate = 0 # default

    def __init__(self, left, right):
        self.left = left
        self.right = right
        self.contains_aggregate = left.contains_aggregate or right.contains_aggregate

    def initargs(self):
        return (self.left, self.right)

    def uncache(self):
        """prepare for execution, clear cached data."""
        self.left.uncache()
        self.right.uncache()

    # eventually add converters...
    def equate(self,other):
        """return predicate equating self and other.
           Overload for special cases, please!"""
        return NontrivialEqPred(self, other)

    def attribute(self):
        return (None, `self`)

    def le(self, other):
        """predicate self<=other"""
        return LessEqPred(self, other)

    # these should be overridden for 2 const case someday...
    def lt(self, other):
        """predicate self<other"""
        return LessPred(self, other)

    def __coerce__(self, other):
        return (self, other)

    def __add__(self, other):
        return BoundAddition(self, other)

    def __sub__(self, other):
        return BoundSubtraction(self, other)

    def __mul__(self, other):
        return BoundMultiplication(self, other)

    def __neg__(self):
        return BoundMinus(self)

    def __div__(self, other):
        return BoundDivision(self, other)

    def relbind(self, dict, db):
        Class = self.__class__
        return Class(self.left.relbind(dict, db), self.right.relbind(dict, db))

    def __repr__(self):
        # XXXX not all subclasses are guaranteed to have a self.op
        return "(%s)%s(%s)" % (self.left, self.op, self.right)

    def domain(self):
        return self.left.domain() + self.right.domain()
    # always overload value

class BoundMinus(BoundExpression, SimpleRecursive):
    def __init__(self, thing):
        self.thing = thing
        self.contains_aggregate = thing.contains_aggregate
    def initargs(self):
        return (self.thing,)
    def __repr__(self):
        return "-(%s)" % (self.thing,)
    def value(self, contexts):
        from types import IntType
        tt = type
        result = self.thing.value(contexts)
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                result[i] = -result[i]
        return result
    def relbind(self, dict, db):
        Class = self.__class__
        return Class(self.thing.relbind(dict,db))
    def uncache(self):
        self.thing.uncache()
    def domain(self):
        return self.thing.domain()


### stuff for aggregation
class Average(BoundMinus):

    contains_aggregate = 1

    def __init__(self, expr, distinct=0):
        self.distinct = distinct
        if expr.contains_aggregate:
            raise ValueError, `expr`+": aggregate in aggregate "+self.name
        self.thing = expr

    name = "Average"
    def __repr__(self):
        distinct = ""
        if self.distinct:
            distinct = "distinct "
        return "%s(%s%s)" % (self.name, distinct, self.thing)

    def relbind(self, dict, db):
        Class = self.__class__
        return Class(self.thing.relbind(dict,db), self.distinct)

    def value(self, contexts):
        if not contexts: return [] # ???
        test = contexts[0]
        if not test or test.has_key(None):
            return self.agg_value(contexts)
        else:
            return [self.all_value(contexts)]

    def dvalues(self, values):
        d = {}
        for i in xrange(len(values)):
            d[values[i]] = 1
        return d.keys()

    def all_value(self, contexts):
        thing = self.thing
        values = self.clean(thing.value(contexts), contexts)
        if self.distinct:
            values = self.dvalues(values)
        return self.op(values)

    def clean(self, values, contexts):
        D = {}
        from types import IntType
        tt = type
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                D[i] = values[i]
        return D.values()

    def agg_value(self, contexts):
        from types import IntType
        tt = type
        result = list(contexts)
        for i in xrange(len(contexts)):
            context = contexts[i]
            if tt(context) is not IntType:
                result[i] = self.all_value( context[None] )
        return result

    def op(self, values):
        sum = 0
        for x in values:
            sum = sum+x
        return sum/(len(values)*1.0)

class Sum(Average):
    name = "Sum"
    def op(self, values):
        if not values: return 0
        sum = values[0]
        for x in values[1:]:
            sum = sum+x
        return sum

class Median(Average):
    name = "Median"
    def op(self, values):
        if not values:
            raise ValueError, "Median of empty set"
        values = list(values)
        values.sort()
        lvals = len(values)
        return values[int(lvals/2)]

class Maximum(Average):
    name = "Maximum"
    def op(self, values):
        return max(values)

class Minimum(Average):
    name = "Minimum"
    def op(self, values):
        return min(values)

class Count(Average):
    name = "Count"
    distinct = 0
    def __init__(self, thing, distinct = 0):
        if thing=="*":
            self.thing = "*"
        else:
            Average.__init__(self, thing, distinct)

    def domain(self):
        thing = self.thing
        if thing=="*":
            return kjbuckets.kjSet()
        return thing.domain()

    def all_value(self, contexts):
        thing = self.thing
        if thing=="*" or not self.distinct:
            test = self.clean(contexts, contexts)
            #print "count len", len(test), contexts[0]
            return len(test)
        return Average.all_value(self, contexts)
    def op(self, values):
        return len(values)
    def relbind(self, dict, db):
        if self.thing=="*":
            return self
        return Average.relbind(self, dict, db)
    def uncache(self):
        if self.thing!="*": self.thing.uncache()

def aggregate(assignments, exprlist):
    """aggregates are a assignments with special
       attribute None > list of subtuple"""
    lexprs = len(exprlist)
    if lexprs<1:
        raise ValueError, "aggregate on no expressions?"
    lassns = len(assignments)
    pairs = list(exprlist)
    for i in xrange(lexprs):
        expr = exprlist[i]
        attributes = [expr.attribute()]*lassns
        values = expr.value(assignments)
        pairs[i] = map(None, attributes, values)
    #for x in pairs:
        #print "pairs", x
    if lexprs>1:
        newassnpairs = apply(map, (None,)+tuple(pairs))
    else:
        newassnpairs = pairs[0]
    #for x in newassnpairs:
        #print "newassnpairs", x
    xassns = range(lassns)
    dict = {}
    test = dict.has_key
    for i in xrange(lassns):
        thesepairs = newassnpairs[i]
        thissubassn = assignments[i]
        if test(thesepairs):
            dict[thesepairs].append(thissubassn)
        else:
            dict[thesepairs] = [thissubassn]
    items = dict.items()
    result = list(items)
    kjDict = kjbuckets.kjDict
    if lexprs>1:
        for i in xrange(len(items)):
            (pairs, subassns) = items[i]
            #print "pairs", pairs
            #print "subassns", subassns
            D = kjDict(pairs)
            D[None] = subassns
            result[i] = D
    else:
        for i in xrange(len(items)):
            (pair, subassns) = items[i]
            #print "pair", pair
            #print "subassns", subassns
            result[i] = kjDict( [pair, (None, subassns)] )
    return result

### stuff for order_by
class DescExpr(BoundMinus):
    """special wrapper used only for order by descending
       for things with no -thing operation (eg, strings)"""

    def __init__(self, thing):
        self.thing = thing
        self.contains_aggregate = thing.contains_aggregate

    def value(self, contexts):
        from types import IntType, StringType
        tt = type
        result = self.thing.value(contexts)
        allwrap = None
        allnowrap = None
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                resulti = result[i]
                # currently assume only value needing wrapping is string
                if tt(resulti) is StringType:
                    if allnowrap is not None:
                        raise ValueError, "(%s, %s) cannot order desc" % (allnowrap, resulti)
                    allwrap = resulti
                    result[i] = descOb(resulti)
                else:
                    if allwrap is not None:
                        raise ValueError, "(%s, %s) cannot order desc" % (allwrap, resulti)
                    allnowrap = resulti
                    result[i] = -resulti
        return result
    def __repr__(self):
        return "DescExpr(%s)" % (self.thing,)
    def orderbind(self, order):
        """order is list of (att, expr)."""
        Class = self.__class__
        return Class(self.thing.orderbind(order))

class SimpleColumn(SimpleRecursive):
    """a simple column name for application to a list of tuples"""
    contains_aggregate = 0
    def __init__(self, name):
        self.name = name
    def relbind(self, dict, db):
        # already bound!
        return self
    def orderbind(self, whatever):
        # already bound!
        return self
    def initargs(self):
        return (self.name,)
    def value(self, simpletuples):
        from types import IntType
        tt = type
        name = self.name
        result = list(simpletuples)
        for i in xrange(len(result)):
            ri = result[i]
            if tt(ri) is not IntType:
                result[i] = ri[name]
            else:
                result[i] = None # ???
        return result
    def __repr__(self):
        return "<SimpleColumn %s>" % (self.name,)

class NumberedColumn(BoundMinus):
    """order by column number"""
    contains_aggregate = 0
    def __init__(self, num):
        self.thing = num
    def __repr__(self):
        return "<NumberedColumn %s>" % (self.thing,)
    def relbind(self, dict, db):
        from types import IntType
        if type(self.thing)!=IntType:
            raise ValueError, `self.thing`+": not a numbered column"
        return self
    def orderbind(self, order):
        return SimpleColumn( order[self.thing-1][0] )

class OrderExpr(BoundMinus):
    """order by expression."""
    def orderbind(self, order):
        expratt = self.thing.attribute()
        for (att, exp) in order:
            if exp.attribute()==expratt:
                return SimpleColumn(att)
        else:
            raise NameError, `self`+": invalid ordering specification"
    def __repr__(self):
        return "<order expression %s>" % (self.thing,)

class descOb:

    """special wrapper only used for sorting in descending order
       should only be compared with other descOb instances.
       should only wrap items that cannot be easily "order inverted",
       (eg, strings).
    """

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

    def __cmp__(self, other):
        #test = cmp(self.__class__, other.__class__)
        #if test: return test
        return -cmp(self.ob,other.ob)

    def __coerce__(self, other):
        return (self, other)

    def __hash__(self):
        return hash(self.ob)

    def __repr__(self):
        return "descOb(%s)" % (self.ob,)

def PositionedSort(num, ord):
    nc = NumberedColumn(num)
    if ord=="DESC":
        return DescExpr(nc)
    return nc

def NamedSort(name, ord):
    oe = OrderExpr(name)
    if ord=="DESC":
        return DescExpr(oe)
    return oe

def relbind_sequence(order_list, dict, db):
    result = list(order_list)
    for i in xrange(len(order_list)):
        result[i] = result[i].relbind(dict,db)
    return result

def orderbind_sequence(order_list, order):
    result = list(order_list)
    for i in xrange(len(order_list)):
        result[i] = result[i].orderbind(order)
    return result

def order_tuples(order_list, tuples):
    lorder_list = len(order_list)
    ltuples = len(tuples)
    if lorder_list<1:
        raise ValueError, "order on empty list?"
    order_map = list(order_list)
    for i in xrange(lorder_list):
        order_map[i] = order_list[i].value(tuples)
    if len(order_map)>1:
        order_vector = apply(map, (None,)+tuple(order_map) )
    else:
        order_vector = order_map[0]
    #G = kjbuckets.kjGraph()
    pairs = map(None, range(ltuples), tuples)
    ppairs = map(None, order_vector, pairs)
    G = kjbuckets.kjGraph(ppairs)
    #for i in xrange(ltuples):
    #    G[ order_vector[i] ] = (i, tuples[i])
    Gkeys = G.keys()
    Gkeys.sort()
    result = list(tuples)
    index = 0
    for x in Gkeys:
        #print x
        for (i, y) in G.neighbors(x):
            #print "   ", y
            result[index]=y
            index = index+1
    if index!=ltuples:
        raise ValueError, \
         "TUPLE LOST IN ORDERING COMPUTATION! (%s,%s)" % (ltuples, index)
    return result

class BoundAddition(BoundExpression):
    """promised addition."""
    op = "+"
    def value(self, contexts):
        from types import IntType
        tt = type
        lvs = self.left.value(contexts)
        rvs = self.right.value(contexts)
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                lvs[i] = lvs[i] + rvs[i]
        return lvs

class BoundSubtraction(BoundExpression):
    """promised subtraction."""
    op = "-"
    def value(self, contexts):
        from types import IntType
        tt = type
        lvs = self.left.value(contexts)
        rvs = self.right.value(contexts)
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                lvs[i] = lvs[i] - rvs[i]
        return lvs

class BoundMultiplication(BoundExpression):
    """promised multiplication."""
    op = "*"
    def value(self, contexts):
        from types import IntType
        tt = type
        lvs = self.left.value(contexts)
        rvs = self.right.value(contexts)
        #print lvs
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                lvs[i] = lvs[i] * rvs[i]
        return lvs

class BoundDivision(BoundExpression):
    """promised division."""
    op = "/"
    def value(self, contexts):
        from types import IntType
        tt = type
        lvs = self.left.value(contexts)
        rvs = self.right.value(contexts)
        for i in xrange(len(contexts)):
            if tt(contexts[i]) is not IntType:
                lvs[i] = lvs[i] / rvs[i]
        return lvs

class BoundAttribute(BoundExpression):
    """bound attribute: initialize with relname=None if
       implicit."""

    contains_aggregate = 0

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

    def initargs(self):
        return (self.rel, self.name)

    def relbind(self, dict, db):
        if self.rel is not None: return self
        name = self.name
        try:
            rel = dict[name]
        except KeyError:
            raise NameError, `name` + ": unknown or ambiguous"
        return BoundAttribute(rel, name)

    def uncache(self):
        pass

    def __repr__(self):
        return "%s.%s" % (self.rel, self.name)

    def attribute(self):
        """return (rename, attribute) for self."""
        return (self.rel, self.name)

    def domain(self):
        return kjbuckets.kjSet([ (self.rel, self.name) ])

    def value(self, contexts):
        """return value of self in context (bound tuple)."""
        #print "value of ", self, "in", contexts
        from types import IntType
        tt = type
        result = list(contexts)
        ra = (self.rel, self.name)
        for i in xrange(len(result)):
            if tt(result[i]) is not IntType:
                result[i] = contexts[i][ra]
        return result

    def equate(self, other):
        oc = other.__class__
        if oc==BoundAttribute:
            result = BoundTuple()
            result.equate([(self.attribute(), other.attribute())])
            return BTPredicate(result)
        elif oc==Constant:
            result = BoundTuple()
            result.assns[ self.attribute() ] = other.value([1])[0]
            return BTPredicate(result)
        else:
            return NontrivialEqPred(self, other)

class Constant(BoundExpression):
    contains_aggregate = 0

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

    def __hash__(self):
        return hash(self.value0)

    def initargs(self):
        return (self.value0,)

    def domain(self):
        return kjbuckets.kjSet()

    def __add__(self, other):
        if other.__class__==Constant:
            return Constant(self.value0 + other.value0)
        return BoundAddition(self, other)

    def __sub__(self, other):
        if other.__class__==Constant:
            return Constant(self.value0 - other.value0)
        return BoundSubtraction(self, other)

    def __mul__(self, other):
        if other.__class__==Constant:
            return Constant(self.value0 * other.value0)
        return BoundMultiplication(self, other)

    def __neg__(self):
        return Constant(-self.value0)

    def __div__(self, other):
        if other.__class__==Constant:
            return Constant(self.value0 / other.value0)
        return BoundDivision(self, other)

    def relbind(self, dict, db):
        return self

    def uncache(self):
        pass

    def value(self, contexts):
        """return the constant value associated with self."""
        return [self.value0] * len(contexts)

    def equate(self,other):
        if other.__class__==Constant:
            if other.value0 == self.value0:
                return BTPredicate() #true
            else:
                return ~BTPredicate() #false
        else:
            return other.equate(self)

    def attribute(self):
        """invent a pair to identify a constant"""
        return ('unbound', `self`)

    def __repr__(self):
        return str(self.value0)
        #return "<const %s at %s>" % (`self.value0`, id(self))

class TupleCollector:
    """Translate a sequence of assignments to simple tuples.
       (for implementing the select list of a SELECT).
    """
    contains_aggregate = 0
    contains_nonaggregate = 0

    def __init__(self):
        self.final = None
        self.order = []
        self.attorder = []
        self.exporder = []

    def initargs(self):
        return ()

    def marshaldata(self):
        exps = map(serialize.serialize, self.exporder)
        return (self.attorder, exps,
                self.contains_aggregate, self.contains_nonaggregate)

    def demarshal(self, args):
        (self.attorder, exps, self.contains_aggregate,
         self.contains_nonaggregate) = args
        exporder = self.exporder = map(serialize.deserialize, exps)
        self.order = map(None, self.attorder, exporder)

    def uncache(self):
        for exp in self.exporder:
            exp.uncache()

    def domain(self):
        all=[]
        for e in self.exporder:
            all = all+e.domain().items()
        return kjbuckets.kjSet(all)

    def __repr__(self):
        l = []
        for (att, exp) in self.order:
            l.append( "%s as %s" % (exp, att) )
        return ', '.join(l)

    def addbinding(self, attribute, expression):
        """bind att>expression."""
        self.order.append((attribute, expression) )
        self.attorder.append(attribute )
        self.exporder.append(expression)
        if expression.contains_aggregate:
            self.contains_aggregate = 1
        else:
            self.contains_nonaggregate = 1

    def map(self, assnlist):
        """remap btlist by self. return (tuplelist, attorder)"""
        # DON'T eliminate nulls
        from types import IntType
        tt = type
        values = []
        for exp in self.exporder:
            values.append(exp.value(assnlist))
        if len(values)>1:
            valtups = apply(map, (None,) + tuple(values) )
        else:
            valtups = values[0]
        kjUndump = kjbuckets.kjUndump
        undumper = tuple(self.attorder)
        for i in xrange(len(valtups)):
            test = assnlist[i]
            if tt(test) is IntType or test is None:
                valtups[i] = 0 # null/false
            else:
                tup = valtups[i]
                valtups[i] = kjUndump(undumper, tup)
        return (valtups, self.attorder)

    def relbind(self, dict, db):
        """disambiguate missing rel names if possible.
           also choose output names appropriately."""
        # CURRENTLY THIS IS AN "IN PLACE" OPERATION
        order = self.order
        attorder = self.attorder
        exporder = self.exporder
        known = {}
        for i in xrange(len(order)):
            (att, exp) = order[i]
            #print exp
            exp = exp.relbind(dict, db)
            if att is None:
                # choose a name for this column
                #print exp
                (rname, aname) = exp.attribute()
                if known.has_key(aname):
                    both = rname+"."+aname
                    att = both
                    count = 0
                    while known.has_key(att):
                        # crank away!
                        count = count+1
                        att = both+"."+`count`
                else:
                    att = aname
            else:
                if known.has_key(att):
                    raise NameError, `att`+" ambiguous in select list"
            order[i] = (att, exp)
            exporder[i] = exp
            attorder[i] = att
            known[att] = att
        return self

class BTPredicate(SimpleRecursive):
    """superclass for bound tuple predicates.
       Eventually should be modified to use "compile" for speed
       to generate an "inlined" evaluation function.
       self(bt) returns bt with additional equality constraints
       (possible) or None if predicate fails."""

    false = 0
    constraints = None
    contains_aggregate = 0

    def __init__(self, constraints=None):
        """default interpretation: True."""
        if constraints is not None:
            self.constraints = constraints.close()

    def initargs(self):
        return (self.constraints,)

    def relbind(self, dict, db):
        c = self.constraints
        if c is None: return self
        return BTPredicate( self.constraints.relbind(dict, db) )

    def uncache(self):
        pass

    #def evaluate(self, db, relnames):
        #"""evaluate the predicate over database bindings."""
        # pretty simple strategy right now...
        ### need to do something about all/distinct...
        #c = self.constraints
        #if c is None:
        #  c = BoundTuple()
        #order = c.relorder(db, relnames)
        #if not order:
        #   raise ValueError, "attempt to evaluate over no relations: "+`relnames`
        #result = [c]
        #for r in order:
        #    result = hashjoin(result, r, db[r])
        #if self.__class__==BTPredicate:
        #   # if it's just equality conjunction, we're done
        #   return result
        #else:
        #   # apply additional constraints
        #   return self(result)

    def domain(self):
        c = self.constraints
        kjSet = kjbuckets.kjSet
        if c is None: return kjSet()
        return c.domain()

    def __repr__(self):
        if self.false: return "FALSE"
        c = self.constraints
        if c is None: c = "true"
        return "[pred](%s)" % c

    def detrivialize(self):
        """hook added to allow elimination of trivialities
           return None if completely true, or simpler form
           or self, if no simplification is possible."""
        if self.false: return self
        if not self.constraints: return None
        return self

    def negated_constraints(self):
        """equality constraints always false of satisfactory tuple."""
        return BoundTuple() # there aren't any

    def __call__(self, assignments, toplevel=0):
        """apply self to sequence of assignments
           return copy of asssignments with false results
           replaced by 0!  Input may have 0's!"""
        # optimization
        #   if toplevel, the btpred has been evaluated during join.
        if toplevel:
            return list(assignments)
        from types import IntType
        tt = type
        lbt = len(assignments)
        if self.false: return [0] * lbt
        c = self.constraints
        if c is None or not c:
            result = assignments[:] # no constraints
        else:
            assns = c.assns
            eqs = c.eqs
            eqsinteresting = 0
            for (a,b) in eqs.items():
                if a!=b:
                    eqsinteresting = 1
            result = assignments[:]
            for i in xrange(lbt):
                this = assignments[i]
                #print "comparing", self, "to", this
                if type(this) is IntType: continue
                this = (this + assns).Clean()
                if this is None:
                    result[i] = 0
                elif eqsinteresting:
                    this = this.remap(eqs)
                    if this is None:
                        result[i] = 0
        return result

    def __and__(self, other):
        """NOTE: all subclasses must define an __and__!!!"""
        #print "BTPredicate.__and__", (self, other)
        if self.__class__==BTPredicate and other.__class__==BTPredicate:
            c = self.constraints
            o = other.constraints
            if c is None: return other
            if o is None: return self
            if self.false: return self
            if other.false: return other
            # optimization for simple constraints
            all = (c+o)
            result = BTPredicate( all ) # all constraints
            if all is None: result.false = 1
        else:
            result = other & self
        return result

    def __or__(self, other):
        if self.__class__==BTPredicate and other.__class__==BTPredicate:
            c = self.constraints
            o = other.constraints
            if c is None: return self # true dominates
            if o is None: return other
            if other.false: return self
            if self.false: return other
            if self == other: return self
        result = BTor_pred([self, other])
        return result

    def __invert__(self):
        if self.false:
            return BTPredicate()
        if not self.constraints:
            result = BTPredicate()
            result.false = 1
            return result
        return BTnot_pred(self)

    def __cmp__(self, other):
        test = cmp(other.__class__, self.__class__)
        if test: return test
        if self.false and other.false: return 0
        return cmp(self.constraints, other.constraints)

    def __hash__(self):
        if self.false: return 11111
        return hash(self.constraints)

class BTor_pred(BTPredicate):

    def __init__(self, members, *othermembers):
        # replace any OR in members with its members
        #print "BTor_pred", members
        members = list(members) + list(othermembers)
        for m in members[:]:
            if m.__class__==BTor_pred:
                members.remove(m)
                members = members + m.members
        #print "before", members
        members = self.members = kjbuckets.kjSet(members).items()
        #print members
        for m in members[:]:
            if m.false: members.remove(m)
        self.constraints = None # common constraints
        for m in members:
            if m.contains_aggregate:
                self.contains_aggregate = 1
        if members:
            # common constraints are those in all members
            constraints = members[0].constraints
            for m in members[1:]:
                mc = m.constraints
                if not constraints or not mc:
                    constraints = None
                    break
                constraints = constraints & mc
            self.constraints = constraints
        #print members

    def initargs(self):
        return ((),) + tuple(self.members)

    def relbind(self, dict, db):
        ms = []
        for m in self.members:
            ms.append( m.relbind(dict, db) )
        return BTor_pred(ms)

    def uncache(self):
        for m in self.members:
            m.uncache()

    def domain(self):
        all = BTPredicate.domain(self).items()
        for x in self.members:
            all = all + x.domain().items()
        return kjbuckets.kjSet(all)

    def __repr__(self):
        c = self.constraints
        m = self.members
        mr = map(repr, m)
        mr.sort()
        mr = ' | '.join(mr)
        if not mr: mr = "FALSE_OR"
        if c:
            mr = "[disj](%s and %s)" % (c, mr)
        return mr

    def detrivialize(self):
        """hook added to allow elimination of trivialities
           return None if completely true, or simpler form
           or self, if no simplification is possible."""
        ms = self.members
        for i in xrange(len(ms)):
            ms[i] = ms[i].detrivialize()
        # now suck out subordinate ors
        someor = None
        for m in ms:
            if m.__class__== BTor_pred:
                someor = m
                ms.remove(m)
                break
        if someor is not None:
            result = someor
            for m in ms:
                result = result + m
            return result.detrivialize()
        allfalse = 1
        for m in ms:
            if m is None: allfalse=0; break # true member
            allfalse = allfalse & m.false
        if allfalse: return ~BTPredicate() # boundary case
        ms[:] = filter(None, ms)
        if not ms: return None # all true.
        ms[:] = kjbuckets.kjSet(ms).items()
        if len(ms)==1: return ms[0] # or of 1
        return self

    def __call__(self, boundtuples, toplevel=0):
        # apply common constraints first
        lbt = len(boundtuples)
        # boundary case for or is false
        members = self.members
        if not members:
            return [0] * lbt
        current = BTPredicate.__call__(self, boundtuples, toplevel)

        # now apply first alternative
        alt1 = members[0](current)

        # determine questionables
        questionables = current[:]
        rng = xrange(len(current))
        from types import IntType
        for i in rng:
            if not isinstance(alt1[i], IntType):
                questionables[i] = 0

        # now test other alternatives
        for m in self.members[1:]:
            passm = m(questionables)
            for i in rng:
                test = passm[i]
                if not isinstance(test, IntType):
                    questionables[i] = 0
                    alt1[i] = test
        return alt1

    def negated_constraints(self):
        """the negated constraints of an OR are
           the negated constraints of *all* members"""
        ms = self.members
        result = ms.negated_constraints()
        for m in ms[1:]:
            if not result: return result
            mc = m.negated_constraints()
            if not mc: return mc
            result = result & mc
        return result

    def __and__(self, other):
        """push "and" down"""
        newmembers = self.members[:]
        for i in xrange(len(newmembers)):
            newmembers[i] = newmembers[i] & other
        return BTor_pred(newmembers)

    def __or__(self, other):
        """collapse two ors, otherwise just add new member"""
        if self.__class__==BTor_pred and other.__class__==BTor_pred:
            return BTor_pred(self.members+other.members)
        return BTor_pred(self.members + [other])

    def __invert__(self):
        """translate to and-not"""
        ms = self.members
        if not ms: return BTPredicate() # boundary case
        result = ~ms[0]
        for m in ms[1:]:
            result = result & ~m
        return result

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        kjSet = kjbuckets.kjSet
        test = cmp(kjSet(self.members), kjSet(other.members))
        if test: return test
        return BTPredicate.__cmp__(self, other)

    def __hash__(self):
        return hash(kjbuckets.kjSet(self.members))

class BTnot_pred(BTPredicate):

    def __init__(self, thing):
        self.negated = thing
        self.contains_aggregate = thing.contains_aggregate
        self.constraints = thing.negated_constraints()

    def initargs(self):
        return (self.negated,)

    def relbind(self, dict, db):
        return BTnot_pred( self.negated.relbind(dict, db) )

    def uncache(self):
        self.negated.uncache()

    def domain(self):
        result = BTPredicate.domain(self) + self.negated.domain()
        #print "neg domain is", `self`, result
        return result

    def __repr__(self):
        c = self.constraints
        n = self.negated
        r = "(NOT %s)" % n
        if c: r = "[neg](%s & %s)" % (c, r)
        return r

    def detrivialize(self):
        """hook added to allow elimination of trivialities
           return None if completely true, or simpler form
           or self, if no simplification is possible."""
        # first, fix or/and/not precedence
        thing = self.negated
        if thing.__class__ == BTnot_pred:
            return thing.negated.detrivialize()
        if thing.__class__ == BTor_pred:
            # translate to and_not
            members = thing.members[:]
            for i in xrange(len(members)):
                members[i] = ~members[i]
            result = BTand_pred(members)
            return result.detrivialize()
        if thing.__class__ == BTand_pred:
            # translate to or_not
            members = thing.members[:]
            c = thing.constraints # precondition
            if c is not None:
                members.append(BTPredicate(c))
            for i in xrange(len(members)):
                members[i] = ~members[i]
            result = BTor_pred(members)
            return result.detrivialize()
        self.negated = thing = self.negated.detrivialize()
        if thing is None: return ~BTPredicate() # uniquely false
        if thing.false: return None # uniquely true
        return self

    def __call__(self, boundtuples, toplevel=0):
        from types import IntType
        tt = type
        current = BTPredicate.__call__(self, boundtuples, toplevel)
        omit = self.negated(current)
        for i in xrange(len(current)):
            if tt(omit[i]) is not IntType:
                current[i]=0
        return current

    def negated_constraints(self):
        """the negated constraints of a NOT are the
           negated constraints of the thing negated."""
        return self.negated.constraints

    def __and__(self, other):
        """do the obvious thing."""
        return BTand_pred([self, other])

    def __or__(self, other):
        """do the obvious thing"""
        return BTor_pred([self, other])

    def __invert__(self):
        return self.negated

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        test = cmp(self.negated,other.negated)
        if test: return test
        return BTPredicate.__cmp__(self,other)

    def __hash__(self):
        return hash(self.negated)^787876^hash(self.constraints)

class BTand_pred(BTPredicate):

    def __init__(self, members, precondition=None, *othermembers):
        #print "BTand_pred", (members, precondition)
        members = list(members) + list(othermembers)
        members = self.members = kjbuckets.kjSet(members).items()
        self.constraints = precondition # common constraints
        if members:
            # common constraints are those in any member
            if precondition is not None:
                constraints = precondition
            else:
                constraints = BoundTuple()
            for i in xrange(len(members)):
                m = members[i]
                mc = m.constraints
                if mc:
                    #print "constraints", constraints
                    constraints = constraints + mc
                    if constraints is None: break
                if m.__class__==BTPredicate:
                    members[i] = None # subsumed above
            members = self.members = filter(None, members)
            for m in members:
                if m.contains_aggregate:
                    self.contains_aggregate=1
            ### consider propagating constraints down?
            self.constraints = constraints
            if constraints is None: self.false = 1

    def initargs(self):
        #print "self.members", self.members
        #print "self.constraints", self.constraints
        #return (list(self.members), self.constraints)
        return ((), self.constraints) + tuple(self.members)

    def relbind(self, dict, db):
        ms = []
        for m in self.members:
            ms.append( m.relbind(dict, db) )
        c = self.constraints.relbind(dict, db)
        return BTand_pred(ms, c)

    def uncache(self):
        for m in self.members:
            m.uncache()

    def domain(self):
        all = BTPredicate.domain(self).items()
        for x in self.members:
            all = all + x.domain().items()
        return kjbuckets.kjSet(all)

    def __repr__(self):
        m = self.members
        c = self.constraints
        r = map(repr, m)
        if self.false: r.insert(0, "FALSE")
        r = ' AND '.join(r)
        r = "(%s)" % r
        if c: r = "[conj](%s and %s)" % (c, r)
        return r

    def detrivialize(self):
        """hook added to allow elimination of trivialities
           return None if completely true, or simpler form
           or self, if no simplification is possible."""
        # first apply demorgan's law to push ands down
        # (exponential in worst case).
        #print "detrivialize"
        #print self
        ms = self.members
        some_or = None
        c = self.constraints
        for m in ms:
            if m.__class__==BTor_pred:
                some_or = m
                ms.remove(m)
                break
        if some_or is not None:
            result = some_or
            if c is not None:
                some_or = some_or & BTPredicate(c)
            for m in ms:
                result = result & m # preserves or/and precedence
            if result.__class__!=BTor_pred:
                raise RuntimeError, "what the?"
            result = result.detrivialize()
            #print "or detected, returning"
            #print result
            return result
        for i in xrange(len(ms)):
            ms[i] = ms[i].detrivialize()
        ms[:] = filter(None, ms)
        if not ms:
            #print "returning boundary case of condition"
            if c is None:
                return None
            else:
                return BTPredicate(c).detrivialize()
        ms[:] = kjbuckets.kjSet(ms).items()
        if len(ms)==1 and c is None:
            #print "and of 1, returning"
            #print ms[0]
            return ms[0] # and of 1
        return self

    def __call__(self, boundtuples, toplevel=0):
        # apply common constraints first
        current = BTPredicate.__call__(self, boundtuples, toplevel)
        for m in self.members:
            current = m(current)
        return current

    def negated_constraints(self):
        """the negated constraints of an AND are
           the negated constraints of *any* member"""
        ms = self.members
        result = BoundTuple()
        for m in ms:
            mc = m.negated_constraints()
            if mc: result = result + mc
        return result

    def __and__(self, other):
        """push "and" down if other is an or"""
        if other.__class__==BTor_pred:
            return other & self
        c = self.constraints
        # merge in other and
        if other.__class__==BTand_pred:
            allmem = self.members+other.members
            oc = other.constraints
            if c is None:
                c = oc
            elif oc is not None:
                c = c+oc
            return BTand_pred(allmem, c)
        return BTand_pred(self.members + [other], c)

    def __or__(self, other):
        """do the obvious thing."""
        return BTor_pred([self, other])

    def __invert__(self):
        """translate to or-not"""
        ms = self.members
        if not ms: return ~BTPredicate() # boundary case
        result = ~ms[0]
        for m in ms[1:]:
            result = result | ~m
        return result

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        kjSet = kjbuckets.kjSet
        test = cmp(kjSet(self.members), kjSet(other.members))
        if test: return test
        return BTPredicate.__cmp__(self, other)

    def __hash__(self):
        return hash(kjbuckets.kjSet(self.members))

class NontrivialEqPred(BTPredicate):
    """equation of nontrivial expressions."""

    def __init__(self, left, right):
        #print "making pred", self.__class__, left, right
        # maybe should used reflexivity...
        self.left = left
        self.right = right
        self.contains_aggregate = left.contains_aggregate or right.contains_aggregate

    def initargs(self):
        return (self.left, self.right)

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        test = cmp(self.right, other.right)
        if test: return test
        return cmp(other.left, other.left)

    def hash(self, other):
        return hash(self.left) ^ hash(self.right)

    def relbind(self, dict, db):
        Class = self.__class__
        return Class(self.left.relbind(dict,db), self.right.relbind(dict,db) )

    def uncache(self):
        self.left.uncache()
        self.right.uncache()

    def domain(self):
        return self.left.domain() + self.right.domain()

    op = "=="

    def __repr__(self):
        return "(%s)%s(%s)" % (self.left, self.op, self.right)

    def detrivialize(self):
        return self

    def __call__(self, assigns, toplevel=0):
        from types import IntType
        tt = type
        lv = self.left.value(assigns)
        rv = self.right.value(assigns)
        result = assigns[:]
        for i in xrange(len(assigns)):
            t = assigns[i]
            if type(t) is not IntType and lv[i]!=rv[i]:
                result[i] = 0
        return result

    def negated_constraints(self):
        return None

    def __and__(self, other):
        return BTand_pred( [self, other] )

    def __or__(self, other):
        return BTor_pred( [self, other] )

    def __invert__(self):
        return BTnot_pred(self)

class BetweenPredicate(NontrivialEqPred):
    """e1 BETWEEN e2 AND e3"""
    def __init__(self, middle, lower, upper):
        self.middle = middle
        self.lower = lower
        self.upper = upper

    def initargs(self):
        return (self.middle, self.lower, self.upper)

    def domain(self):
        return (
    self.middle.domain() + self.lower.domain() + self.upper.domain())

    def relbind(self, dict, db):
        self.middle = self.middle.relbind(dict, db)
        self.lower = self.lower.relbind(dict, db)
        self.upper = self.upper.relbind(dict, db)
        return self

    def uncache(self):
        self.middle.uncache()
        self.upper.uncache()
        self.lower.uncache()

    def __repr__(self):
        return "(%s BETWEEN %s AND %s)" % (
         self.middle, self.lower, self.upper)

    def __hash__(self):
        return hash(self.middle)^~hash(self.lower)^hash(self.upper)^55

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        test = cmp(self.lower, other.lower)
        if test: return test
        test = cmp(self.middle, other.middle)
        if test: return test
        return cmp(self.upper, other.upper)

    def __call__(self, assigns, toplevel=0):
        from types import IntType
        tt = type
        lowv = self.lower.value(assigns)
        upv = self.upper.value(assigns)
        midv = self.middle.value(assigns)
        result = assigns[:]
        for i in xrange(len(assigns)):
            t = assigns[i]
            if tt(t) is not IntType:
                midvi = midv[i]
                if lowv[i]>midvi or upv[i]<midvi:
                    result[i] = 0
        return result

class ExistsPred(NontrivialEqPred):
    """EXISTS subquery."""
    contains_aggregate = 0

    def __init__(self, subq):
        self.cached_result = None
        self.cachable = None
        self.subq = subq

    def initargs(self):
        return (self.subq,)

    def domain(self):
        result = self.subq.unbound()
        # if there are no outer bindings, evaluate ONCE!
        if not result:
            self.cachable = 1
        return result

    def relbind(self, dict, db):
        self.subq = self.subq.relbind(db, dict)
        return self

    def uncache(self):
        self.cached_result = None
        self.subq.uncache()

    def __repr__(self):
        return "\nEXISTS\n%s\n" % (self.subq,)

    def __call__(self, assigns, toplevel=0):
        ### should optimize!!!
        #print "exists"
        #print self.subq
        from types import IntType
        tt = type
        eval = self.subq.eval
        result = assigns[:]
        # shortcut: if cachable, eval only once and cache
        if self.cachable:
            test = self.cached_result
            if test is None:
                self.cached_result = test = eval()
            #print "exists cached", self.cached_result
            if test:
                return result
            else:
                return [0] * len(result)
        kjDict = kjbuckets.kjDict
        for i in xrange(len(assigns)):
            #print "exists uncached"
            assignsi = assigns[i]
            if tt(assignsi) is IntType: continue
            testbtup = BoundTuple()
            testbtup.assns = kjDict(assignsi)
            test = eval(outerboundtuple=testbtup).rows()
            #for x in test:
                #print "exists for", assignsi
                #print x
                #break
            if not test:
                result[i] = 0
        return result

    def __hash__(self):
        return hash(self.subq)^3333

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        return cmp(self.subq, other.subq)

class QuantEQ(NontrivialEqPred):
    """Quantified equal any predicate"""

    def __init__(self, expr, subq):
        self.expr = expr
        self.subq = subq
        self.cachable = 0
        self.cached_column = None
        self.att = None

    def initargs(self):
        return (self.expr, self.subq)

    def uncache(self):
        self.cached_column = None

    def domain(self):
        first = self.subq.unbound()
        if not first:
            self.cachable = 1
        more = self.expr.domain()
        return first + more

    def relbind(self, dict, db):
        subq = self.subq = self.subq.relbind(db, dict)
        self.expr = self.expr.relbind(dict, db)
        # test that subquery is single column and determine att
        sl = subq.select_list
        atts = sl.attorder
        if len(atts)<>1:
            raise ValueError, \
              "Quantified predicate requires unit select list: %s" % atts
        self.att = atts[0]
        return self

    fmt = "(%s %s ANY %s)"
    op = "="

    def __repr__(self):
        return self.fmt % (self.expr, self.op, self.subq)

    def __call__(self, assigns, toplevel=0):
        cached_column = self.cached_column
        cachable = self.cachable
        expr = self.expr
        subq = self.subq
        att = self.att
        if cachable:
            if cached_column is None:
                subqr = subq.eval().rows()
                cc = self.cached_column = dump_single_column(subqr, att)
            #print self, "cached", self.cached_column
        exprvals = expr.value(assigns)
        kjDict = kjbuckets.kjDict
        compare = self.compare
        tt = type
        from types import IntType
        result = assigns[:]
        for i in xrange(len(assigns)):
            assignsi = assigns[i]
            if tt(assignsi) is IntType: continue
            thisval = exprvals[i]
            testbtup = BoundTuple()
            testbtup.assns = kjDict(assignsi)
            if not cachable:
                subqr = subq.eval(outerboundtuple=testbtup).rows()
                cc = dump_single_column(subqr, att)
                #print self, "uncached", cc, thisval
            if not compare(thisval, cc):
                #print "eliminated", assignsi
                result[i] = 0
        return result

    def compare(self, value, column):
        return value in column

    def __hash__(self):
        return hash(self.subq) ^ ~hash(self.expr)

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        test = cmp(self.expr, other.expr)
        if test: return test
        return cmp(self.subq, other.subq)

# "expr IN (subq)" same as "expr = ANY (subq)"
InPredicate = QuantEQ

class InLits(NontrivialEqPred):
    """expr IN literals, support dynamic bindings."""
    def __init__(self, expr, lits):
        self.expr = expr
        self.lits = lits
        self.cached_lits = None

    def initargs(self):
        return (self.expr, self.lits)

    def uncache(self):
        self.cached_lits = None

    def domain(self):
        d = []
        for l in self.lits:
            d0 = l.domain()
            if d0:
                d = d + d0.items()
        d0 = self.expr.domain()
        if d:
            kjSet = kjbuckets.kjSet
            return d0 + kjSet(d)
        else:
            return d0

    def relbind(self, dict, db):
        newlits = []
        for l in self.lits:
            newlits.append(l.relbind(dict, db))
        self.lits = newlits
        self.expr = self.expr.relbind(dict, db)
        return self

    fmt = "(%s IN %s)"

    def __repr__(self):
        return self.fmt % (self.expr, self.lits)

    def __call__(self, assigns, toplevel=0):
        # LITERALS ARE CONSTANT! NEED ONLY LOOK FOR ONE ASSIGN.
        tt = type
        from types import IntType
        litvals = self.cached_lits
        if litvals is None:
            assigns0 = []
            for asn in assigns:
                if tt(asn) is not IntType:
                    assigns0.append(asn)
                    break
            if not assigns0:
                # all false/unknown
                return assigns
            litvals = []
            for lit in self.lits:
                value = lit.value(assigns0)
                litvals.append(value[0])
            self.cached_lits = litvals
        expr = self.expr
        exprvals = expr.value(assigns)
        result = assigns[:]
        for i in xrange(len(assigns)):
            assignsi = assigns[i]
            if tt(assignsi) is IntType: continue
            thisval = exprvals[i]
            if thisval not in litvals:
                #print "eliminated", assignsi
                result[i] = 0
        return result

    def compare(self, value, column):
        return value in column

    def __hash__(self):
        return 10 ^ hash(self.expr)

    def __cmp__(self, other):
        test = cmp(self.__class__, other.__class__)
        if test: return test
        test = cmp(self.expr, other.expr)
        if test: return test
        return cmp(self.lits, other.lits)

class QuantNE(QuantEQ):
    """Quantified not equal any predicate"""
    op = "<>"
    def compare(self, value, column):
        for x in column:
            if value!=x: return 1
        return 0

### note: faster NOT IN using QuantNE?

class QuantLT(QuantEQ):
    """Quantified less than any predicate"""
    op = "<"
    def uncache(self):
        self.testval = self.cached = self.cached_column = None
    def compare(self, value, column):
        if self.cachable:
            if self.cached:
                testval = self.testval
            else:
                testval = self.testval = max(column)
                self.cached = 1
        else:
            testval = max(column)
        return value < testval

class QuantLE(QuantLT):
    """Quantified less equal any predicate"""
    op = "<="
    def compare(self, value, column):
        if self.cachable:
            if self.cached:
                testval = self.testval
            else:
                testval = self.testval = max(column)
                self.cached = 1
        else:
            testval = max(column)
        return value <= testval

class QuantGE(QuantLT):
    """Quantified greater equal any predicate"""
    op = ">="
    def compare(self, value, column):
        if self.cachable:
            if self.cached:
                testval = self.testval
            else:
                testval = self.testval = min(column)
                self.cached = 1
        else:
            testval = min(column)
        return value >= testval

class QuantGT(QuantLT):
    """Quantified greater than any predicate"""
    op = ">"
    def compare(self, value, column):
        if self.cachable:
            if self.cached:
                testval = self.testval
            else:
                self.testval = testval = min(column)
                self.cached = 1
        else:
            testval = min(column)
        return value > testval

def dump_single_column(assigns, att):
    """dump single column assignment"""
    result = assigns[:]
    for i in xrange(len(result)):
        result[i] = result[i][att]
    return result

class LessPred(NontrivialEqPred):
    op = "<"
    def __call__(self, assigns, toplevel=0):
        from types import IntType
        #print '***********************************************'
        #print self.left, self.right
        #print assigns
        lv = self.left.value(assigns)
        rv = self.right.value(assigns)
        result = assigns[:]
        for i in xrange(len(assigns)):
            t = assigns[i]
            if not isinstance(t, IntType) and lv[i] >= rv[i]:
                result[i] = 0
        return result

    def __inv__(self):
        return LessEqPred(self.right, self.left)

    def __hash__(self):
        return hash(self.left)^hash(self.right)


class LessEqPred(LessPred):
    op = "<="
    def __call__(self, assigns, toplevel=0):
        from types import IntType
        tt = type
        lv = self.left.value(assigns)
        rv = self.right.value(assigns)
        result = assigns[:]
        for i in xrange(len(assigns)):
            t = assigns[i]
            if not isinstance(t, IntType) and lv[i] > rv[i]:
                result[i] = 0
        return result

    def __inv__(self):
        return LessPred(self.right, self.left)

class SubQueryExpression(BoundMinus, SimpleRecursive):
    """sub query expression (subq), must eval to single column, single value"""
    def __init__(self, subq):
        self.subq = subq
        self.att = self.cachable = self.cached = self.cached_value = None

    def initargs(self):
        return (self.subq,)

    def uncache(self):
        self.cached = self.cached_value = None

    def domain(self):
        result = self.subq.unbound()
        if not result:
            self.cachable = 1
        #print "expr subq domain", result
        return result

    def relbind(self, dict, db):
        subq = self.subq = self.subq.relbind(db, dict)
        # test that subquery is single column and determine att
        sl = subq.select_list
        atts = sl.attorder
        if len(atts)<>1:
            raise ValueError, \
              "Quantified predicate requires unit select list: %s" % atts
        self.att = atts[0]
        return self

    def __repr__(self):
        return "(%s)" % self.subq

    def value(self, contexts):
        subq = self.subq
        att = self.att
        if self.cachable:
            if self.cached:
                cached_value = self.cached_value
            else:
                self.cached = 1
                seval = subq.eval().rows()
                lse = len(seval)
                if lse<>1:
                    raise ValueError, \
           "const subquery expression must return 1 result: got %s" % lse
                self.cached_value = cached_value = seval[0][att]
            #print "const subq cached", cached_value
            return [cached_value] * len(contexts)
        from types import IntType
        tt = type
        result = contexts[:]
        kjDict = kjbuckets.kjDict
        for i in xrange(len(contexts)):
            contextsi = contexts[i]
            if tt(contextsi) is not IntType:
                testbtup = BoundTuple()
                testbtup.assns = kjDict(contextsi)
                #print "subq exp", testbtup
                seval = subq.eval(outerboundtuple=testbtup).rows()
                lse = len(seval)
                if lse<>1:
                    raise ValueError, \
           "dynamic subquery expression must return 1 result: got %s" % lse
                result[i] = seval[0][att]
                #print "nonconst subq uncached", result[i], contextsi
        return result

SELECT_TEMPLATE = """\
SELECT %s %s
FROM %s
WHERE %s
GROUP BY %s
HAVING %s %s
ORDER BY %s %s
"""

def dynamic_binding(ndynamic, dynamic):
    """create bindings from dynamic tuple for ndynamic parameters
       if a tuple is given create one
       if a list is given create many
    """
    from types import ListType, TupleType
    if not dynamic:
        if ndynamic>0:
            raise ValueError, `ndynamic`+" dynamic parameters unbound"
        return [kjbuckets.kjDict()]
    ldyn = len(dynamic)
    undumper = map(None, [0]*ndynamic, range(ndynamic))
    undumper = tuple(undumper)
    tdyn = type(dynamic)
    if tdyn is TupleType:
        ldyn = len(dynamic)
        if len(dynamic)!=ndynamic:
            raise ValueError, "%s,%s: wrong number of dynamics" % (ldyn,ndynamic)
        dynamic = [dynamic]
    elif tdyn is not ListType:
        raise TypeError, "dynamic parameters must be list or tuple"
    else:
        lens = map(len, dynamic)
        ndynamic = max(lens)
        if ndynamic!=min(lens):
            raise ValueError, "dynamic parameters of inconsistent lengths"
    undumper = map(None, [0]*ndynamic, range(ndynamic))
    undumper = tuple(undumper)
    result = list(dynamic)
    kjUndump = kjbuckets.kjUndump
    for i in xrange(len(dynamic)):
        dyn = dynamic[i]
        ldyn = len(dyn)
        #print undumper, dyn
        if ldyn==1:
            dynresult = kjUndump(undumper, dyn[0])
        else:
            dynresult = kjUndump(undumper, dyn)
        result[i] = dynresult
    return result

class Selector:
    """For implementing, eg the SQL SELECT statement."""
    def __init__(self, alldistinct,
                       select_list,
                       table_reference_list,
                       where_pred,
                       group_list,
                       having_cond,
                       union_select =None,
                       order_by_spec =None,
                       ndynamic=0, # number of dyn params expected
                       ):
        self.ndynamic = ndynamic
        self.alldistinct = alldistinct
        self.select_list = select_list
        self.table_list = table_reference_list
        self.where_pred = where_pred
        self.group_list = group_list
        self.having_cond = having_cond
        self.union_select = union_select
        self.order_by = order_by_spec
        #self.union_spec = "DISTINCT" # default union mode
        self.relbindings = None # binding of relations
        self.unbound_set = None # unbound attributes
        self.rel_atts = None # graph of alias>attname bound in self
        self.all_aggregate = 0
        if select_list!="*" and not group_list:
            if select_list.contains_aggregate:
            ### should restore this check somewhere else!
            #if select_list.contains_nonaggregate:
                  #raise ValueError, "aggregates/nonaggregates don't mix without grouping"
                self.all_aggregate = 1
        if where_pred and where_pred.contains_aggregate:
            raise ValueError, "aggregate in WHERE"
        self.query_plan = None

    def initargs(self):
        #print self.alldistinct
        #print self.select_list
        #print self.table_list
        #print self.where_pred
        #print self.having_cond
        #print self.union_select
        #print self.group_list
        #print self.order_by
        #print self.ndynamic
        # note: order by requires special handling
        return (self.alldistinct, self.select_list, self.table_list, self.where_pred,
                None, self.having_cond, self.union_select, None,
                self.ndynamic)

    def marshaldata(self):
        order_by = self.order_by
        if order_by:
            order_by = map(serialize.serialize, order_by)
        group_list = self.group_list
        if group_list:
            group_list = map(serialize.serialize, group_list)
        #print "marshaldata"
        #print order_by
        #print group_list
        return (order_by, group_list)

    def demarshal(self, data):
        (order_by, group_list) = data
        if order_by:
            order_by = map(serialize.deserialize, order_by)
        if group_list:
            group_list = map(serialize.deserialize, group_list)
        #print "demarshal"
        #print order_by
        #print group_list
        self.order_by = order_by
        self.group_list = group_list

    def unbound(self):
        result = self.unbound_set
        if result is None:
            raise ValueError, "binding not available"
        return result

    def uncache(self):
        wp = self.where_pred
        hc = self.having_cond
        sl = self.select_list
        if wp is not None: wp.uncache()
        if hc is not None: hc.uncache()
        sl.uncache()
        qp = self.query_plan
        if qp:
            for joiner in qp:
                joiner.uncache()

    def relbind(self, db, outerbindings=None):
        ad = self.alldistinct
        sl = self.select_list
        tl = self.table_list
        wp = self.where_pred
        gl = self.group_list
        hc = self.having_cond
        us = self.union_select
        ob = self.order_by
        test = db.bindings(tl)
        #print len(test)
        #for x in test:
            #print x
        (attbindings, relbindings, ambiguous, ambiguousatts) = test
        if outerbindings:
            # bind in outerbindings where unambiguous
            for (a,r) in outerbindings.items():
                if ((not attbindings.has_key(a))
                    and (not ambiguousatts.has_key(a)) ):
                    attbindings[a] = r
        # fix "*" select list
        if sl=="*":
            sl = TupleCollector()
            for (a,r) in attbindings.items():
                sl.addbinding(None, BoundAttribute(r,a))
            for (dotted, (r,a)) in ambiguous.items():
                sl.addbinding(dotted, BoundAttribute(r,a))
        sl = sl.relbind(attbindings, db)
        wp = wp.relbind(attbindings, db)
        if hc is not None: hc = hc.relbind(attbindings, db)
        if us is not None: us = us.relbind(db, attbindings)
        # bind grouping if present
        if gl:
            gl = relbind_sequence(gl, attbindings, db)
        # bind ordering list if present
        #print ob
        if ob:
            ob = relbind_sequence(ob, attbindings, db)
            ob = orderbind_sequence(ob, sl.order)
        result = Selector(ad, sl, tl, wp, gl, hc, us, ob)
        result.relbindings = relbindings
        result.ndynamic = self.ndynamic
        result.check_domains()
        result.plan_query()
        query_plan = result.query_plan
        for i in range(len(query_plan)):
            query_plan[i] = query_plan[i].relbind(db, attbindings)
        return result

    def plan_query(self):
        """generate a query plan (sequence of join operators)."""
        rel_atts = self.rel_atts # rel>attname
        where_pred = self.where_pred.detrivialize()
        #select_list = self.select_list
        # shortcut
        if where_pred is None:
            bt = BoundTuple()
        else:
            bt = self.where_pred.constraints
        if bt is None:
            bt = BoundTuple()
        eqs = kjbuckets.kjGraph(bt.eqs)
        witness = kjbuckets.kjDict()
        # set all known and unbound atts as witnessed
        for att in bt.assns.keys():
            witness[att] = 1
        #print self, "self.unbound_set", self.unbound_set
        for att in self.unbound_set.items():
            witness[att] = 1
        relbindings = self.relbindings
        allrels = relbindings.keys()
        #print relbindings
        allrels = bt.relorder(relbindings, allrels)
        #print allrels
        rel_atts = self.rel_atts
        plan = []
        for rel in allrels:
            relation = relbindings[rel]
            ratts = rel_atts.neighbors(rel)
            h = HashJoiner(bt, rel, ratts, relation, witness)
            plan.append(h)
            for a in ratts:
                ra = (rel, a)
                witness[ra] = 1
                eqs[ra] = ra
            witness = witness.remap(eqs)
        self.query_plan = plan

    def check_domains(self):
        """determine set of unbound names in self.
        """
        relbindings = self.relbindings
        sl = self.select_list
        wp = self.where_pred
        gl = self.group_list
        hc = self.having_cond
        us = self.union_select
        all = sl.domain().items()
        if wp is not None:
            all = all + wp.domain().items()
        # ignore group_list ???
        if hc is not None:
            all = all + hc.domain().items()
        kjSet = kjbuckets.kjSet
        kjGraph = kjbuckets.kjGraph
        alldomain = kjSet(all)
        rel_atts = self.rel_atts = kjGraph(all)
        allnames = kjSet()
        #print "relbindings", relbindings.keys()
        for name in relbindings.keys():
            rel = relbindings[name]
            for att in rel.attributes():
                allnames[ (name, att) ] = 1
        # union compatibility check
        if us is not None:
            us.check_domains()
            myatts = self.attributes()
            thoseatts = us.attributes()
            if myatts!=thoseatts:
                if len(myatts)!=len(thoseatts):
                    raise IndexError, "outer %s, inner %s: union select lists lengths differ"\
                      % (len(myatts), len(thoseatts))
            for p in map(None, myatts, thoseatts):
                (x,y)=p
                if x!=y:
                    raise NameError, "%s union names don't match" % (p,)
        self.unbound_set = alldomain - allnames

    def attributes(self):
        return self.select_list.attorder

    def eval(self, dynamic=None, outerboundtuple=None):
        """leaves a lot to be desired.
           dynamic and outerboundtuple are mutually
           exclusive.  dynamic is only pertinent to
           top levels, outerboundtuple to subqueries"""
        # only uncache if outerboundtuple is None (not subquery)
        # ???
        if outerboundtuple is None:
            self.uncache()
        query_plan = self.query_plan
        where_pred = self.where_pred.detrivialize()
        select_list = self.select_list
        # shortcut
        if where_pred is not None and where_pred.false:
            return store.Relation0(select_list.attorder, [])
        #print "where_pred", where_pred
        if where_pred is None or where_pred.constraints is None:
            assn0 = assn1 = kjbuckets.kjDict()
        else:
            assn1 = self.where_pred.constraints.assns
            assn0 = assn1 = kjbuckets.kjDict(assn1)
        # erase stored results from possible previous evaluation
        ndynamic = self.ndynamic
        if outerboundtuple is not None:
            assn1 = assn1 + outerboundtuple.assns
        elif ndynamic:
            dyn = dynamic_binding(ndynamic, dynamic)
            if len(dyn)!=1:
                raise ValueError, "only one dynamic subst for selection allowed"
            dyn = dyn[0]
            assn1 = assn1 + dyn
            #print "dynamic", bt
        #print "assn1", assn1
        # check unbound names
        unbound_set = self.unbound_set
        #print "unbound", unbound_set
        #print unbound_set
        #print self.rel_atts
        for pair in unbound_set.items():
            if not assn1.has_key(pair):
                raise KeyError, `pair`+": unbound in selection"
        assn1 = (unbound_set * assn1) + assn0
        #print "assn1 now", assn1
        substseq = [assn1]
        for h in query_plan:
            #print "***"
            #for x in substseq:
                #print x
            #print "***"
            substseq = h.join(substseq)
            if not substseq: break
            #print "***"
            #for x in substseq:
                #print x
            #print "***"
        # apply the rest of the where predicate at top level
        if substseq and where_pred is not None:
            #where_pred.uncache()
            substseq = where_pred(substseq, 1)
        # eliminate zeros/nulls
        substseq = no_ints_nulls(substseq)
        # apply grouping if present
        group_list = self.group_list
        if substseq and group_list:
            substseq = aggregate(substseq, group_list)
            having_cond = self.having_cond
            #print having_cond
            if having_cond is not None:
                #having_cond.uncache()
                substseq = no_ints_nulls(having_cond(substseq))
        elif self.all_aggregate:
            # universal group
            substseq = [kjbuckets.kjDict( [(None, substseq)] ) ]
        (tups, attorder) = select_list.map(substseq)
        # do UNION if present
        union_select = self.union_select
        if union_select is not None:
            tups = union_select.eval(tups, dynamic, outerboundtuple)
        # apply DISTINCT if appropriate
        if self.alldistinct=="DISTINCT":
            tups = kjbuckets.kjSet(tups).items()
        # apply ordering if present
        ob = self.order_by
        if ob:
            tups = order_tuples(ob, tups)
        return store.Relation0(attorder, tups)

    def __repr__(self):
        ndyn = ""
        if self.ndynamic:
            ndyn = "\n[%s dynamic parameters]" % self.ndynamic
        result = SELECT_TEMPLATE % (
          self.alldistinct,
          self.select_list,
          self.table_list,
          self.where_pred,
          self.group_list,
          self.having_cond,
          #union_spec,
          self.union_select,
          self.order_by,
          ndyn
          )
        return result

class Union(SimpleRecursive):
    """union clause."""

    def __init__(self, alldistinct, selection):
        self.alldistinct = alldistinct
        self.selection = selection

    def initargs(self):
        return (self.alldistinct, self.selection)

    def unbound(self):
        return self.selection.unbound()

    def relbind(self, db, outer=None):
        self.selection = self.selection.relbind(db, outer)
        return self

    def check_domains(self):
        self.selection.check_domains()

    def attributes(self):
        return self.selection.attributes()

    def eval(self, assns, dyn=None, outer=None):
        r = self.selection.eval(dyn, outer)
        rows = r.rows()
        allrows = rows + assns
        if self.alldistinct=="DISTINCT":
            allrows = kjbuckets.kjSet(allrows).items()
        return allrows

    def __repr__(self):
        return "\nUNION %s %s " % (self.alldistinct, self.selection)

class Intersect(Union):
    def eval(self, assns, dyn=None, outer=None):
        r = self.selection.eval(dyn, outer)
        rows = r.rows()
        kjSet = kjbuckets.kjSet
        allrows = (kjSet(assns) & kjSet(rows)).items()
        return allrows
    op = "INTERSECT"
    def __repr__(self):
        return "\n%s %s" % (self.op, self.selection)

class Except(Union):
    def eval(self, assns, dyn=None, outer=None):
        r = self.selection.eval(dyn, outer)
        rows = r.rows()
        kjSet = kjbuckets.kjSet
        allrows = (kjSet(assns) - kjSet(rows)).items()
        return allrows
    op = "EXCEPT"


class Parse_Context:
    """contextual information for parsing
         p.param() returns a new sequence number for external parameter.
    """
    # not serializable

    parameter_index = 0

    # no __init__ yet
    def param(self):
        temp = self.parameter_index
        self.parameter_index = temp+1
        return temp

    def ndynamic(self):
        return self.parameter_index

# update/delete/insert statements
import operations
CreateTable = operations.CreateTable
CreateIndex = operations.CreateIndex
DropIndex = operations.DropIndex
DropTable = operations.DropTable
UpdateOp = operations.UpdateOp
DeleteOp = operations.DeleteOp
InsertOp = operations.InsertOp
InsertValues = operations.InsertValues
InsertSubSelect = operations.InsertSubSelect
ColumnDef = operations.ColumnDef
CreateView = operations.CreateView
DropView = operations.DropView

# update storage structures from the database store
import store
Add_Tuples = store.Add_Tuples
Erase_Tuples = store.Erase_Tuples
Reset_Tuples = store.Reset_Tuples

#
# $Log: semantics.py,v $
# Revision 1.7  2002/05/11 02:59:05  richard
# Added info into module docstrings.
# Fixed docco of kwParsing to reflect new grammar "marshalling".
# Fixed bug in gadfly.open - most likely introduced during sql loading
# re-work (though looking back at the diff from back then, I can't see how it
# wasn't different before, but it musta been ;)
# A buncha new unit test stuff.
#
# Revision 1.6  2002/05/08 00:49:00  anthonybaxter
# El Grande Grande reindente! Ran reindent.py over the whole thing.
# Gosh, what a lot of checkins. Tests still pass with 2.1 and 2.2.
#
# Revision 1.5  2002/05/07 23:19:02  richard
# Removed circular import (at import time at least)
#
# Revision 1.4  2002/05/07 14:33:00  anthonybaxter
# added a couple of 'what the??' comments.
# fixed a spot where float division would cause breakge in future (in Median)
#
# Revision 1.3  2002/05/07 09:48:54  anthonybaxter
# argh argh bastard. Average, or any op derived from it,
# assumed that the first element would always be there.
# in the case of, say, the second part of an 'or' operation,
# it might be missing.
#
# Revision 1.2  2002/05/07 04:03:14  richard
# . major cleanup of test_gadfly
#
# Revision 1.1.1.1  2002/05/06 07:31:10  richard
#
#
#