Graphite-Tattle /inc/flourish/fSQLSchemaTranslation.php

Language PHP Lines 5387
MD5 Hash c841b19e95f63f33b476ebaaadffc4d0
Repository https://github.com/trbs/Graphite-Tattle.git View Raw File
   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
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
<?php
/**
 * Adds cross-database `CREATE TABLE`, `ALTER TABLE` and `COMMENT ON COLUMN` statements to fSQLTranslation
 * 
 * @copyright  Copyright (c) 2011 Will Bond
 * @author     Will Bond [wb] <will@flourishlib.com>
 * @license    http://flourishlib.com/license
 * 
 * @package    Flourish
 * @link       http://flourishlib.com/fSQLSchemaTranslation
 * 
 * @version    1.0.0b2
 * @changes    1.0.0b2   Fixed detection of explicitly named SQLite foreign key constraints [wb, 2011-08-23]
 * @changes    1.0.0b    The initial implementation [wb, 2011-05-09]
 */
class fSQLSchemaTranslation
{
	/**
	 * Converts a SQL identifier to lower case and removes double quotes
	 *
	 * @param  string $identifier  The SQL identifier
	 * @return string  The unescaped identifier
	 */
	static private function unescapeIdentifier($identifier)
	{
		return str_replace('"', '', strtolower($identifier));
	}


	/**
	 * Composes text using fText if loaded
	 * 
	 * @param  string  $message    The message to compose
	 * @param  mixed   $component  A string or number to insert into the message
	 * @param  mixed   ...
	 * @return string  The composed and possible translated message
	 */
	static protected function compose($message)
	{
		$args = array_slice(func_get_args(), 1);
		
		if (class_exists('fText', FALSE)) {
			return call_user_func_array(
				array('fText', 'compose'),
				array($message, $args)
			);
		} else {
			return vsprintf($message, $args);
		}
	}


	/**
	 * Accepts a CREATE TABLE statement and parses out the column definitions
	 *
	 * The return value is an associative array with the keys being column
	 * names and the values being arrays containing the following keys:
	 *  - definition:       (string) the complete column definition
	 *  - pieces:           (array) an associative array that can be joined back together to make the definition
	 *    - beginning
	 *    - column_name
	 *    - data_type
	 *    - not_null
	 *    - null
	 *    - default
	 *    - unique
	 *    - primary_key
	 *    - check_constraint
	 *    - foreign_key
	 *    - deferrable
	 *    - comment/end
	 *
	 * @param  string $sql  The SQL `CREATE TABLE` statement
	 * @return array  An associative array of information for each column - see method description for details
	 */
	static private function parseSQLiteColumnDefinitions($sql)
	{
		preg_match_all(
			'#(?<=,|\(|\*/|\n)(\s*)[`"\'\[]?(\w+)[`"\'\]]?(\s+(?:[a-z]+)(?:\(\s*(\d+)(?:\s*,\s*(\d+))?\s*\))?)(?:(\s+NOT\s+NULL)|(\s+NULL)|(\s+DEFAULT\s+([^, \'\n]*|\'(?:\'\'|[^\']+)*\'))|(\s+UNIQUE)|(\s+PRIMARY\s+KEY(?:\s+AUTOINCREMENT)?)|(\s+CHECK\s*\("?\w+"?\s+IN\s+\(\s*(?:(?:[^, \'\n]+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \'\n]+|\'(?:\'\'|[^\']+)*\')\)\)))*(\s+REFERENCES\s+[\'"`\[]?\w+[\'"`\]]?\s*\(\s*[\'"`\[]?\w+[\'"`\]]?\s*\)\s*(?:\s+(?:ON\s+DELETE|ON\s+UPDATE)\s+(?:CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))*(\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?)?((?:\s*(?:/\*\s*((?:(?!\*/).)*?)\s*\*/))?\s*(?:,[ \t]*(?:--[ \t]*([^\n]*?)[ \t]*(?=\n)|/\*\s*((?:(?!\*/).)*?)\s*\*/)?|(?:--[ \t]*([^\n]*?)[ \t]*(?=\n))?\s*(?=\))))#msi',
			$sql,
			$matches,
			PREG_SET_ORDER
		);

		$output = array();
		foreach ($matches as $match) {
			$comment = '';
			foreach (array(16, 17, 18, 19) as $key) {
				if (isset($match[$key])) {
					$comment .= $match[$key];
				}
			}
			$output[strtolower($match[2])] = array(
				'definition'       => $match[0],
				'pieces'           => array(
					'beginning'        => $match[1],
					'column_name'      => $match[2],
					'data_type'        => $match[3],
					'not_null'         => $match[6],
					'null'             => $match[7],
					'default'          => $match[8],
					'unique'           => $match[10],
					'primary_key'      => $match[11],
					'check_constraint' => $match[12],
					'foreign_key'      => $match[13],
					'deferrable'       => $match[14],
					'comment/end'      => $match[15]
				)
			);
		}

		return $output;
	}
	
		
	/**
	 * Removes a search string from a `CREATE TABLE` statement
	 *
	 * @param  string $create_table_sql  The SQL `CREATE TABLE` statement
	 * @param  string $search            The string to remove
	 * @return string  The modified `CREATE TABLE` statement
	 */
	static private function removeFromSQLiteCreateTable($create_table_sql, $search)
	{
		if (preg_match('#,(\s*--.*)?\s*$#D', $search)) {
			$regex = '#' . preg_quote($search, '#') . '#';
		} else {
			$regex = '#,(\s*/\*.*?\*/\s*|\s*--[^\n]+\n\s*)?\s*' . preg_quote($search, '#') . '\s*#';
		}
		return preg_replace($regex, "\\1\n", $create_table_sql);
	}
	
	
	/**
	 * The fDatabase instance
	 * 
	 * @var fDatabase
	 */
	private $database;

	/**
	 * Database-specific schema information needed for translation
	 * 
	 * @var array
	 */
	private $schema_info;
	
	
	/**
	 * Sets up the class
	 * 
	 * @param  fDatabase $database    The database being translated for
	 * @return fSQLSchemaTranslation
	 */
	public function __construct($database)
	{
		$this->database    = $database;
		$this->schema_info = array();
	}
	
	
	/**
	 * All requests that hit this method should be requests for callbacks
	 * 
	 * @internal
	 * 
	 * @param  string $method  The method to create a callback for
	 * @return callback  The callback for the method requested
	 */
	public function __get($method)
	{
		return array($this, $method);		
	}


	/**
	 * Adds a SQLite index to the internal schema tracker
	 *
	 * @param  string $name   The index name
	 * @param  string $table  The table the index applies to
	 * @param  string $sql    The SQL definition of the index 
	 * @return void
	 */
	private function addSQLiteIndex($name, $table, $sql)
	{
		if (!isset($this->schema_info['sqlite_indexes'])) {
			$this->schema_info['sqlite_indexes'] = array();
		}

		$this->schema_info['sqlite_indexes'][$name] = array(
			'table' => $table,
			'sql'   => $sql
		);
	}


	/**
	 * Stores the SQL used to create a table
	 * 
	 * @param  string $table  The table to set the `CREATE TABLE` statement for
	 * @param  string $sql    The SQL used to create the table
	 * @return void
	 */
	private function addSQLiteTable($table, $sql)
	{
		if (!isset($this->schema_info['sqlite_create_tables'])) {
			$this->getSQLiteTables();
		}

		$this->schema_info['sqlite_create_tables'][$table] = $sql;
	}


	/**
	 * Adds a SQLite trigger to the internal schema tracker
	 *
	 * @param  string $name   The trigger name
	 * @param  string $table  The table the trigger applies to
	 * @param  string $sql    The SQL definition of the trigger 
	 * @return void
	 */
	private function addSQLiteTrigger($name, $table, $sql)
	{
		if (!isset($this->schema_info['sqlite_triggers'])) {
			$this->schema_info['sqlite_triggers'] = array();
		}

		$this->schema_info['sqlite_triggers'][$name] = array(
			'table' => $table,
			'sql'   => $sql
		);
	}
	
	
	/**
	 * Creates a trigger for SQLite that handles an on delete clause
	 * 
	 * @param  array  &$extra_statements   An array of extra SQL statements to be added to the SQL
	 * @param  string $referencing_table   The table that contains the foreign key
	 * @param  string $referencing_column  The column the foreign key constraint is on
	 * @param  string $referenced_table    The table the foreign key references
	 * @param  string $referenced_column   The column the foreign key references
	 * @param  string $delete_clause       What is to be done on a delete
	 * @return string  The trigger
	 */
	private function createSQLiteForeignKeyTriggerOnDelete(&$extra_statements, $referencing_table, $referencing_column, $referenced_table, $referenced_column, $delete_clause)
	{
		switch (strtolower($delete_clause)) {
			case 'no action':
			case 'restrict':
				$name = 'fkd_res_' . $referencing_table . '_' . $referencing_column;
				$extra_statements[] = 'CREATE TRIGGER ' . $name . '
							 BEFORE DELETE ON "' . $referenced_table . '"
							 FOR EACH ROW BEGIN
								 SELECT RAISE(ROLLBACK, \'delete on table "' . $referenced_table . '" can not be executed because it would violate the foreign key constraint on column "' . $referencing_column . '" of table "' . $referencing_table . '"\')
								 WHERE (SELECT "' . $referencing_column . '" FROM "' . $referencing_table . '" WHERE "' . $referencing_column . '" = OLD."' . $referenced_table . '") IS NOT NULL;
							 END';
				$this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
				break;
			
			case 'set null':
				$name = 'fkd_nul_' . $referencing_table . '_' . $referencing_column;
				$extra_statements[] = 'CREATE TRIGGER ' . $name . '
							 BEFORE DELETE ON "' . $referenced_table . '"
							 FOR EACH ROW BEGIN
								 UPDATE "' . $referencing_table . '" SET "' . $referencing_column . '" = NULL WHERE "' . $referencing_column . '" = OLD."' . $referenced_column . '";
							 END';
				$this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
				break;
				
			case 'cascade':
				$name = 'fkd_cas_' . $referencing_table . '_' . $referencing_column;
				$extra_statements[] = 'CREATE TRIGGER ' . $name . '
							 BEFORE DELETE ON "' . $referenced_table . '"
							 FOR EACH ROW BEGIN
								 DELETE FROM "' . $referencing_table . '" WHERE "' . $referencing_column . '" = OLD."' . $referenced_column . '";
							 END';
				$this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
				break;
		}
	}
	
	
	/**
	 * Creates a trigger for SQLite that handles an on update clause
	 * 
	 * @param  array  &$extra_statements   An array of extra SQL statements to be added to the SQL
	 * @param  string $referencing_table   The table that contains the foreign key
	 * @param  string $referencing_column  The column the foreign key constraint is on
	 * @param  string $referenced_table    The table the foreign key references
	 * @param  string $referenced_column   The column the foreign key references
	 * @param  string $update_clause       What is to be done on an update
	 * @return string  The trigger
	 */
	private function createSQLiteForeignKeyTriggerOnUpdate(&$extra_statements, $referencing_table, $referencing_column, $referenced_table, $referenced_column, $update_clause)
	{
		switch (strtolower($update_clause)) {
			case 'no action':
			case 'restrict':
				$name = 'fku_res_' . $referencing_table . '_' . $referencing_column;
				$extra_statements[] = 'CREATE TRIGGER ' . $name . '
							 BEFORE UPDATE ON "' . $referenced_table . '"
							 FOR EACH ROW BEGIN
								 SELECT RAISE(ROLLBACK, \'update on table "' . $referenced_table . '" can not be executed because it would violate the foreign key constraint on column "' . $referencing_column . '" of table "' . $referencing_table . '"\')
								 WHERE (SELECT "' . $referencing_column . '" FROM "' . $referencing_table . '" WHERE "' . $referencing_column . '" = OLD."' . $referenced_column . '") IS NOT NULL;
							 END';
				$this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
				break;
			
			case 'set null':
				$name = 'fku_nul_' . $referencing_table . '_' . $referencing_column;
				$extra_statements[] = 'CREATE TRIGGER ' . $name . '
							 BEFORE UPDATE ON "' . $referenced_table . '"
							 FOR EACH ROW BEGIN
								 UPDATE "' . $referencing_table . '" SET "' . $referencing_column . '" = NULL WHERE OLD."' . $referenced_column . '" <> NEW."' . $referenced_column . '" AND "' . $referencing_column . '" = OLD."' . $referenced_column . '";
							 END';
				$this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
				break;
				
			case 'cascade':
				$name = 'fku_cas_' . $referencing_table . '_' . $referencing_column;
				$extra_statements[] = 'CREATE TRIGGER ' . $name . '
							 BEFORE UPDATE ON "' . $referenced_table . '"
							 FOR EACH ROW BEGIN
								 UPDATE "' . $referencing_table . '" SET "' . $referencing_column . '" = NEW."' . $referenced_column . '" WHERE OLD."' . $referenced_column . '" <> NEW."' . $referenced_column . '" AND "' . $referencing_column . '" = OLD."' . $referenced_column . '";
							 END';
				$this->addSQLiteTrigger($name, $referenced_table, end($extra_statements));
				break;
		}
	}
	
	
	/**
	 * Creates a trigger for SQLite that prevents inserting or updating to values the violate a `FOREIGN KEY` constraint
	 * 
	 * @param  array  &$extra_statements   An array of extra SQL statements to be added to the SQL
	 * @param  string  $referencing_table     The table that contains the foreign key
	 * @param  string  $referencing_column    The column the foriegn key constraint is on
	 * @param  string  $referenced_table      The table the foreign key references
	 * @param  string  $referenced_column     The column the foreign key references
	 * @param  boolean $referencing_not_null  If the referencing columns is set to not null
	 * @return string  The trigger
	 */
	private function createSQLiteForeignKeyTriggerValidInsertUpdate(&$extra_statements, $referencing_table, $referencing_column, $referenced_table, $referenced_column, $referencing_not_null)
	{
		// Verify key on inserts
		$name = 'fki_ver_' . $referencing_table . '_' . $referencing_column;
		$sql  = 'CREATE TRIGGER ' . $name . '
					  BEFORE INSERT ON "' . $referencing_table . '"
					  FOR EACH ROW BEGIN
						  SELECT RAISE(ROLLBACK, \'insert on table "' . $referencing_table . '" violates foreign key constraint on column "' . $referencing_column . '"\')
							  WHERE ';
		if (!$referencing_not_null) {
			$sql .= 'NEW."' . $referencing_column . '" IS NOT NULL AND ';
		}
		$sql .= ' (SELECT "' . $referenced_column . '" FROM "' . $referenced_table . '" WHERE "' . $referenced_column . '" = NEW."' . $referencing_column . '") IS NULL;
					  END';
					  
		$extra_statements[] = $sql;
		$this->addSQLiteTrigger($name, $referencing_table, end($extra_statements));
					
		// Verify key on updates
		$name = 'fku_ver_' . $referencing_table . '_' . $referencing_column;
		$sql = 'CREATE TRIGGER ' . $name . '
					  BEFORE UPDATE ON "' . $referencing_table . '"
					  FOR EACH ROW BEGIN
						  SELECT RAISE(ROLLBACK, \'update on table "' . $referencing_table . '" violates foreign key constraint on column "' . $referencing_column . '"\')
							  WHERE ';
		if (!$referencing_not_null) {
			$sql .= 'NEW."' . $referencing_column . '" IS NOT NULL AND ';
		}
		$sql .= ' (SELECT "' . $referenced_column . '" FROM "' . $referenced_table . '" WHERE "' . $referenced_column . '" = NEW."' . $referencing_column . '") IS NULL;
					  END';
		
		$extra_statements[] = $sql;
		$this->addSQLiteTrigger($name, $referencing_table, end($extra_statements));
	}
	
	
	/**
	 * Generates a 30 character constraint name for use with `ALTER TABLE` statements
	 *
	 * @param  string $sql    The `ALTER TABLE` statement
	 * @param  string $type   A 2-character string representing the type of constraint
	 */
	private function generateConstraintName($sql, $type)
	{
		$constraint = '_' . $type;
		$constraint = '_' . substr(time(), -8) . $constraint;
		return substr(md5(strtolower($sql)), 0, 30 - strlen($constraint)) . $constraint;
	}


	/**
	 * Returns the check constraint for a table and column
	 *
	 * @param  string $schema  The schema the table is in
	 * @param  string $table   The table the column is in
	 * @param  string $column  The column to get the check constraint for
	 * @return array|NULL  An associative array with the keys: `name` and `definition` or `NULL`
	 */
	private function getDB2CheckConstraint($schema, $table, $column)
	{
		$constraint = $this->database->query(
			"SELECT
				CH.TEXT,
				CH.CONSTNAME
			FROM
				SYSCAT.COLUMNS AS C INNER JOIN
				SYSCAT.COLCHECKS AS CC ON
					C.TABSCHEMA = CC.TABSCHEMA AND
					C.TABNAME = CC.TABNAME AND
					C.COLNAME = CC.COLNAME AND
					CC.USAGE = 'R' INNER JOIN
				SYSCAT.CHECKS AS CH ON
					C.TABSCHEMA = CH.TABSCHEMA AND
					C.TABNAME = CH.TABNAME AND
					CH.TYPE = 'C' AND
					CH.CONSTNAME = CC.CONSTNAME
			WHERE
				LOWER(C.TABSCHEMA) = %s AND
				LOWER(C.TABNAME) = %s AND
				LOWER(C.COLNAME) = %s",
			$schema,
			$table,
			$column
		);

		if (!$constraint->countReturnedRows()) {
			return NULL;
		}

		$row = $constraint->fetchRow();
		return array(
			'name'       => $row['constname'],
			'definition' => $row['text']
		);
	}


	/**
	 * Returns the foreign key constraints that involve a specific table or table and column
	 *
	 * @param  string $schema  The schema the table is in
	 * @param  string $table   The table the column is in
	 * @param  string $column  The column to get the foreign keys for and the foreign keys that point to
	 * @return array  An associative array of the key being the constraint name and the value being an associative array containing the keys: `schema`, `table`, `column`, `foreign_schema`, `foreign_table`, `foreign_column`, `on_delete` and `on_cascade`
	 */
	private function getDB2ForeignKeyConstraints($schema, $table, $column=NULL)
	{
		if ($column) {
			$where_conditions = "((
			 	LOWER(R.TABSCHEMA) = %s AND
				LOWER(R.TABNAME) = %s AND
				LOWER(K.COLNAME) = %s
			) OR (
				LOWER(R.REFTABSCHEMA) = %s AND
				LOWER(R.REFTABNAME) = %s AND
				LOWER(FK.COLNAME) = %s
			))";
			$params = array(
				strtolower($schema),
				strtolower($table),
				strtolower($column),
				strtolower($schema),
				strtolower($table),
				strtolower($column)
			);
		} else {
			$where_conditions = "LOWER(R.REFTABSCHEMA) = %s AND LOWER(R.REFTABNAME) = %s";
			$params = array(
				strtolower($schema),
				strtolower($table)
			);
		}

		array_unshift(
			$params,
			"SELECT
				 R.CONSTNAME AS CONSTRAINT_NAME,
				 TRIM(LOWER(R.TABSCHEMA)) AS \"SCHEMA\",
				 LOWER(R.TABNAME) AS \"TABLE\",
				 LOWER(K.COLNAME) AS \"COLUMN\",
				 TRIM(LOWER(R.REFTABSCHEMA)) AS FOREIGN_SCHEMA,
				 LOWER(R.REFTABNAME) AS FOREIGN_TABLE,
				 LOWER(FK.COLNAME) AS FOREIGN_COLUMN,
				 CASE R.DELETERULE WHEN 'C' THEN 'CASCADE' WHEN 'A' THEN 'NO ACTION' WHEN 'R' THEN 'RESTRICT' ELSE 'SET NULL' END AS ON_DELETE,
				 CASE R.UPDATERULE WHEN 'A' THEN 'NO ACTION' WHEN 'R' THEN 'RESTRICT' END AS ON_UPDATE
			 FROM
				 SYSCAT.REFERENCES AS R INNER JOIN 
				 SYSCAT.KEYCOLUSE AS K ON
				 	R.CONSTNAME = K.CONSTNAME AND
				 	R.TABSCHEMA = K.TABSCHEMA AND
				 	R.TABNAME = K.TABNAME INNER JOIN
				 SYSCAT.KEYCOLUSE AS FK ON
				 	R.REFKEYNAME = FK.CONSTNAME AND
				 	R.REFTABSCHEMA = FK.TABSCHEMA AND
				 	R.REFTABNAME = FK.TABNAME
			 WHERE
				 $where_conditions
			 ORDER BY
			 	 LOWER(R.CONSTNAME) ASC"
		);

		$constraints = call_user_func_array($this->database->query, $params);

		$keys = array();
		foreach ($constraints as $constraint) {
			$name = $constraint['constraint_name'] . $constraint['table'];
			$keys[$name] = $constraint;
		}

		return $keys;
	}


	/**
	 * Returns the primary key for a table
	 *
	 * @param  string $schema  The schema the table is in
	 * @param  string $table   The table to get the primary key for
	 * @return array  The columns in the primary key
	 */
	private function getDB2PrimaryKeyConstraint($schema, $table)
	{
		$constraints = $this->database->query(
			"SELECT
				 LOWER(C.COLNAME) AS \"COLUMN\"
			 FROM
				 SYSCAT.INDEXES AS I INNER JOIN
				 SYSCAT.INDEXCOLUSE AS C ON
				 	I.INDSCHEMA = C.INDSCHEMA AND
				 	I.INDNAME = C.INDNAME
			 WHERE
				 I.UNIQUERULE IN ('P') AND
				 LOWER(I.TABSCHEMA) = %s AND
				 LOWER(I.TABNAME) = %s
			 ORDER BY
			 	 LOWER(I.INDNAME) ASC
			",
			strtolower($schema),
			strtolower($table)
		);

		$key = array();
		foreach ($constraints as $constraint) {
			$key[] = $constraint['column'];
		}

		return $key;
	}


	/**
	 * Returns the unique keys for a table and column
	 *
	 * @param  string $schema  The schema the table is in
	 * @param  string $table   The table to get the unique keys for
	 * @param  string $column  The column to filter the unique keys by
	 * @return array  An associative array of the key being the constraint name and the value being the columns in the unique key
	 */
	private function getDB2UniqueConstraints($schema, $table, $column)
	{
		$constraints = $this->database->query(
			"SELECT
				 CD.CONSTNAME AS CONSTRAINT_NAME,
				 LOWER(C.COLNAME) AS \"COLUMN\"
			 FROM
				 SYSCAT.INDEXES AS I INNER JOIN
				 SYSCAT.CONSTDEP AS CD ON
					I.TABSCHEMA = CD.TABSCHEMA AND
					I.TABNAME = CD.TABNAME AND
					CD.BTYPE = 'I' AND
					CD.BNAME = I.INDNAME INNER JOIN
				 SYSCAT.INDEXCOLUSE AS C ON
				 	I.INDSCHEMA = C.INDSCHEMA AND
				 	I.INDNAME = C.INDNAME
			 WHERE
				 I.UNIQUERULE IN ('U') AND
				 LOWER(I.TABSCHEMA) = %s AND
				 LOWER(I.TABNAME) = %s
			 ORDER BY
			 	 LOWER(I.INDNAME) ASC
			",
			strtolower($schema),
			strtolower($table)
		);

		$keys = array();
		foreach ($constraints as $constraint) {
			if (!isset($keys[$constraint['constraint_name']])) {
				$keys[$constraint['constraint_name']] = array();
			}
			$keys[$constraint['constraint_name']][] = $constraint['column'];
		}

		$new_keys = array();
		$column = strtolower($column);
		foreach ($keys as $name => $columns) {
			if (!in_array($column, $columns)) {
				continue;
			}
			$new_keys[$name] = $columns;
		}
		$keys = $new_keys;

		return $keys;
	}


	/**
	 * Returns the check constraint for a column, if it exists
	 *
	 * @param  string $schema  The schema the column is inside of
	 * @param  string $table   The table the column is part of
	 * @param  string $column  The column name
	 * @return array|NULL  An associative array with the keys `name` and `definition`, or `NULL`
	 */
	private function getMSSQLCheckConstraint($schema, $table, $column)
	{
		$constraint = $this->database->query(
			"SELECT
				cc.check_clause AS 'constraint',
				ccu.constraint_name
			FROM
				INFORMATION_SCHEMA.COLUMNS AS c INNER JOIN
				INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON
					c.column_name = ccu.column_name AND
					c.table_name = ccu.table_name AND
					c.table_catalog = ccu.table_catalog INNER JOIN
				INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS cc ON
					ccu.constraint_name = cc.constraint_name AND
					ccu.constraint_catalog = cc.constraint_catalog
			WHERE
				LOWER(c.table_schema) = %s AND
				LOWER(c.table_name) = %s AND
				LOWER(c.column_name) = %s AND
				c.table_catalog = DB_NAME()",
			strtolower($schema),
			strtolower($table),
			strtolower($column)
		);
		
		if (!$constraint->countReturnedRows()) {
			return NULL;
		}
		
		$row = $constraint->fetchRow();
		return array(
			'name'       => $row['constraint_name'],
			'definition' => $row['constraint']
		);
	}


	/**
	 * Returns the foreign key constraints that a column is part of
	 *
	 * @param  string       $schema  The schema the column is inside of
	 * @param  string       $table   The table the column is part of
	 * @param  string|array $column  The column name(s)
	 * @return array  An array of constraint names that reference the column(s)
	 */
	private function getMSSQLForeignKeyConstraints($schema, $table, $column)
	{
		settype($column, 'array');

		$constraints = $this->database->query(
			"SELECT
				LOWER(tc.table_schema + '.' + tc.table_name) AS 'table',
				LOWER(tc.table_schema) AS 'schema',
				LOWER(tc.table_name) AS 'table_without_schema',
				LOWER(kcu.column_name) AS 'column',
				kcu.constraint_name AS name
			FROM
				information_schema.table_constraints AS tc INNER JOIN
				information_schema.key_column_usage AS kcu ON
					tc.constraint_name = kcu.constraint_name AND
					tc.constraint_catalog = kcu.constraint_catalog AND
					tc.constraint_schema = kcu.constraint_schema AND
					tc.table_name = kcu.table_name INNER JOIN
				information_schema.referential_constraints AS rc ON
					kcu.constraint_name = rc.constraint_name  AND
					kcu.constraint_catalog = rc.constraint_catalog AND
					kcu.constraint_schema = rc.constraint_schema INNER JOIN
				information_schema.constraint_column_usage AS ccu ON
					ccu.constraint_name = rc.unique_constraint_name  AND
					ccu.constraint_catalog = rc.constraint_catalog AND
					ccu.constraint_schema = rc.constraint_schema
			WHERE
				tc.constraint_type = 'FOREIGN KEY' AND
				(
					LOWER(tc.table_schema) = %s AND
					LOWER(ccu.table_name) = %s AND
					LOWER(ccu.column_name) IN (%s)
				) OR (
					LOWER(tc.table_schema) = %s AND
					LOWER(kcu.table_name) = %s AND
					LOWER(kcu.column_name) IN (%s)
				) AND
				tc.constraint_catalog = DB_NAME()",
			strtolower($schema),
			strtolower($table),
			array_map('strtolower', $column),
			strtolower($schema),
			strtolower($table),
			array_map('strtolower', $column)
		);

		return $constraints->fetchAllRows();
	}


	/**
	 * Returns the default constraint for a column, if it exists
	 *
	 * @param  string $schema  The schema the column is inside of
	 * @param  string $table   The table the column is part of
	 * @param  string $column  The column name
	 * @return array|NULL  An associative array with the keys `name` and `definition`, or `NULL`
	 */
	private function getMSSQLDefaultConstraint($schema, $table, $column)
	{
		$constraint = $this->database->query(
			"SELECT
				dc.name,
				CAST(dc.definition AS VARCHAR(MAX)) AS definition
			FROM
				information_schema.columns AS c INNER JOIN
				sys.default_constraints AS dc ON
					OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)) = dc.parent_object_id AND
					COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'ColumnId') = dc.parent_column_id
			WHERE
				LOWER(c.table_schema) = %s AND
				LOWER(c.table_name) = %s AND
				LOWER(c.column_name) = %s AND
				c.table_catalog = DB_NAME()",
			strtolower($schema),
			strtolower($table),
			strtolower($column)
		);
		
		if (!$constraint->countReturnedRows()) {
			return NULL;
		}
		
		$row = $constraint->fetchRow();
		return array(
			'name'       => $row['name'],
			'definition' => $row['definition']
		);
	}


	/**
	 * Returns the primary key constraints for a table
	 *
	 * @param  string $schema  The schema the table is inside of
	 * @param  string $table   The table to get the constraint for
	 * @return array|NULL  An associative array with the keys `name`, `columns` and `autoincrement` or `NULL`
	 */
	private function getMSSQLPrimaryKeyConstraint($schema, $table)
	{
		$column_info = $this->database->query(
			"SELECT
				kcu.constraint_name AS constraint_name,
				LOWER(kcu.column_name) AS column_name,
				CASE
					WHEN
					  COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'IsIdentity') = 1 AND
					  OBJECTPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), 'IsMSShipped') = 0
					THEN '1'
					ELSE '0'
				  END AS auto_increment
			FROM
				information_schema.table_constraints AS con INNER JOIN
				information_schema.key_column_usage AS kcu ON
					con.table_name = kcu.table_name AND
					con.table_schema = kcu.table_schema AND
					con.constraint_name = kcu.constraint_name INNER JOIN
				information_schema.columns AS c ON
					c.table_name = kcu.table_name AND
					c.table_schema = kcu.table_schema AND
					c.column_name = kcu.column_name
			WHERE
				con.constraint_type = 'PRIMARY KEY' AND
				LOWER(con.table_schema) = %s AND
				LOWER(con.table_name) = %s AND
				con.table_catalog = DB_NAME()",
			strtolower($schema),
			strtolower($table)
		);

		if (!$column_info->countReturnedRows()) {
			return NULL;
		}

		$output = array(
			'columns' => array()
		);
		foreach ($column_info as $row) {
			$output['columns'][]     = $row['column_name'];
			$output['name']          = $row['constraint_name'];
			$output['autoincrement'] = (boolean) $row['auto_increment'];
		}

		return $output;
	}


	/**
	 * Returns the unique constraints that a column is part of
	 *
	 * @param  string $schema  The schema the column is inside of
	 * @param  string $table   The table the column is part of
	 * @param  string $column  The column name
	 * @return array  An associative array of constraint_name => columns
	 */
	private function getMSSQLUniqueConstraints($schema, $table, $column)
	{
		$constraint_columns = $this->database->query(
			"SELECT
				c.constraint_name,
				LOWER(kcu.column_name) AS column_name
			FROM
				information_schema.table_constraints AS c INNER JOIN
				information_schema.key_column_usage AS kcu ON
					c.table_name = kcu.table_name AND
					c.constraint_name = kcu.constraint_name
			WHERE
				c.constraint_name IN (
					SELECT
						c.constraint_name
					FROM
						information_schema.table_constraints AS c INNER JOIN
						information_schema.key_column_usage AS kcu ON
							c.table_name = kcu.table_name AND
							c.constraint_name = kcu.constraint_name
					WHERE
						c.constraint_type = 'UNIQUE' AND
						LOWER(c.table_schema) = %s AND
						LOWER(c.table_name) = %s AND
						LOWER(kcu.column_name) = %s AND
						c.table_catalog = DB_NAME()
						
				) AND
				LOWER(c.table_schema) = %s AND
				c.table_catalog = DB_NAME()
			ORDER BY
				c.constraint_name
			",
			strtolower($schema),
			strtolower($table),
			strtolower($column),
			strtolower($schema)
		);

		$unique_constraints = array();
		foreach ($constraint_columns as $row) {
			if (!isset($unique_constraints[$row['constraint_name']])) {
				$unique_constraints[$row['constraint_name']] = array();
			}
			$unique_constraints[$row['constraint_name']][] = $row['column_name'];
		}
		
		return $unique_constraints;
	}


	/**
	 * Returns info about all foreign keys that involve the table and one of the columns specified
	 *
	 * @param  string       $table    The table
	 * @param  string|array $columns  The column, or an array of valid column names
	 * @column array  An array of associative arrays containing the keys `constraint_name`, `table`, `column`, `foreign_table` and `foreign_column`
	 */
	private function getMySQLForeignKeys($table, $columns)
	{
		if (is_string($columns)) {
			$columns = array($columns);
		}
		$columns = array_map('strtolower', $columns);

		$tables = $this->getMySQLTables();
		
		$keys = array();
		foreach ($tables as $_table) {
			$row = $this->database->query("SHOW CREATE TABLE %r", $_table)->fetchRow();
			
			preg_match_all(
				'#CONSTRAINT\s+"(\w+)"\s+FOREIGN KEY \("([^"]+)"\) REFERENCES "([^"]+)" \("([^"]+)"\)(?:\sON\sDELETE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?(?:\sON\sUPDATE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?#',
				$row['Create Table'],
				$matches,
				PREG_SET_ORDER
			);

			foreach ($matches as $match) {
				$points_to_column = strtolower($match[3]) == strtolower($table) && in_array(strtolower($match[4]), $columns);
				$is_column        = strtolower($_table) == strtolower($table) && in_array(strtolower($match[2]), $columns);

				if (!$points_to_column && !$is_column) {
					continue;
				}

				$temp = array(
					'constraint_name' => $match[1],
					'table'           => $_table,
					'column'          => $match[2],
					'foreign_table'   => $match[3],
					'foreign_column'  => $match[4],
					'on_delete'       => 'NO ACTION',
					'on_update'       => 'NO ACTION'
				);
				if (!empty($match[5])) {
					$temp['on_delete'] = $match[5];
				}
				if (!empty($match[6])) {
					$temp['on_update'] = $match[6];
				}

				$keys[] = $temp;
			}
		}

		return $keys;
	}


	/**
	 * Returns a list of all tables in the database
	 *
	 * @return array  An array of table names
	 */
	private function getMySQLTables()
	{
		if (!isset($this->schema_info['version'])) {
			$version = $this->database->query("SELECT version()")->fetchScalar();
			$this->schema_info['version'] = substr($version, 0, strpos($version, '.'));
		}
		if ($this->schema_info['version'] <= 4) {
			$sql = 'SHOW TABLES';
		} else {
			$sql = "SHOW FULL TABLES WHERE table_type = 'BASE TABLE'";	
		}

		$result = $this->database->query($sql);
		$tables = array();

		foreach ($result as $row) {
			$keys = array_keys($row);
			$tables[] = $row[$keys[0]];
		}

		return $tables;
	}
	


	/**
	 * Returns an an array of the column name for a table
	 * 
	 * @param  string $table  The table to retrieve the column names for
	 * @return array  The column names for the table
	 */
	private function getSQLiteColumns($table)
	{
		$create_sql = $this->getSQLiteCreateTable($table);

		return array_keys(self::parseSQLiteColumnDefinitions($create_sql));
	}


	/**
	 * Returns the SQL used to create a table
	 * 
	 * @param  string $table  The table to retrieve the `CREATE TABLE` statement for
	 * @return string  The `CREATE TABLE` SQL statement
	 */
	private function getSQLiteCreateTable($table)
	{
		if (!isset($this->schema_info['sqlite_create_tables'])) {
			$this->getSQLiteTables();
		}

		if (!isset($this->schema_info['sqlite_create_tables'][$table])) {
			return NULL;
		}

		return $this->schema_info['sqlite_create_tables'][$table];
	}


	/**
	 * Returns a list of all foreign keys that reference the table, and optionally, column specified
	 * 
	 * @param  string  $table   All foreign keys returned will point to this table
	 * @param  string  $column  Only foreign keys pointing to this column will be returned
	 * @return array  An array of arrays containing they keys: `table`, `column`, `foreign_table`, `foreign_column`, `on_delete` and `on_update`
	 */
	private function getSQLiteForeignKeys($table, $column=NULL)
	{
		$output = array();
		foreach ($this->getSQLiteTables() as $_table) {
			$create_sql = $this->getSQLiteCreateTable($_table);

			if (stripos($create_sql, 'references') === FALSE) {
				continue;
			}

			preg_match_all('#(?<=,|\(|\*/|\n)\s*[`"\[\']?(\w+)[`"\]\']?\s+(?:[a-z]+)(?:\([^)]*\))?(?:(?:\s+NOT\s+NULL)|(?:\s+NULL)|(?:\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|(?:\s+UNIQUE)|(?:\s+PRIMARY\s+KEY(?:\s+AUTOINCREMENT)?)|(?:\s+CHECK\s*\("?\w+"?\s+IN\s+\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\)\)))*\s+REFERENCES\s+[\'"`\[]?(\w+)[\'"`\]]?\s*\(\s*[\'"`\[]?(\w+)[\'"`\]]?\s*\)\s*(?:(?:\s+ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))|(?:\s+ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?\s*(?:,|/\*|(?:--[^\n]*\n)?\s*(?=\)))#mis', $create_sql, $matches, PREG_SET_ORDER);

			preg_match_all('#(?<=,|\(|\*/|\n)\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*\(?\s*["`\[]?(\w+)["`\]]?\s*\)?\s+REFERENCES\s+["`\[]?(\w+)["`\]]?\s*\(\s*["`\[]?(\w+)["`\]]?\s*\)\s*(?:(?:\s+ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))|(?:\s+ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?\s*(?:,|/\*|(?:--[^\n]*\n)?\s*(?=\)))#mis', $create_sql, $matches2, PREG_SET_ORDER);

			foreach (array_merge($matches, $matches2) as $match) {
				$_column        = $match[1];
				$foreign_table  = $match[2];
				$foreign_column = $match[3];
				$on_delete      = empty($match[4]) ? 'NO ACTION' : $match[4];
				$on_update      = empty($match[5]) ? 'NO ACTION' : $match[5];

				if ($foreign_table != $table || ($column !== NULL && $column != $foreign_column)) {
					continue;
				}

				if (!$on_delete) {
					$on_delete = 'NO ACTION';
				}
				if (!$on_update) {
					$on_update = 'NO ACTION';
				}

				$output[] = array(
					'table'          => $_table,
					'column'         => $_column,
					'foreign_table'  => $foreign_table,
					'foreign_column' => $foreign_column,
					'on_delete'      => $on_delete,
					'on_update'      => $on_update
				);
			}
		}

		return $output;
	}


	/**
	 * Returns the indexes in the current SQLite database
	 * 
	 * @return array  An associative array with the key being the index name and the value an associative arrays, each containing the keys: `table`, `sql`
	 */
	private function getSQLiteIndexes($table=NULL)
	{
		if (!isset($this->schema_info['sqlite_indexes'])) {
			$this->schema_info['sqlite_indexes'] = array();
			$rows = $this->database->query(
				"SELECT tbl_name AS \"table\", name, sql FROM sqlite_master WHERE type = 'index' AND sql <> ''"
			)->fetchAllRows();
			foreach ($rows as $row) {
				$this->schema_info['sqlite_indexes'][$row['name']] = array(
					'table' => $row['table'],
					'sql'   => $row['sql']
				);
			}
		}

		$output = $this->schema_info['sqlite_indexes'];

		if ($table) {
			$new_output = array();
			foreach ($output as $name => $index) {
				if ($index['table'] != $table) {
					continue;
				}

				$new_output[$name] = $index;
			}
			$output = $new_output;
		}

		return $output;
	}


	/**
	 * Returns the tables in the current SQLite database
	 * 
	 * @return array
	 */
	private function getSQLiteTables()
	{
		if (!isset($this->schema_info['sqlite_create_tables'])) {
			$this->schema_info['sqlite_create_tables'] = array();
			$res = $this->database->query(
				"SELECT name, sql FROM sqlite_master WHERE type = 'table'"
			)->fetchAllRows();
			foreach ($res as $row) {
				$this->schema_info['sqlite_create_tables'][$row['name']] = $row['sql'];
			}
		}

		$tables = array_keys($this->schema_info['sqlite_create_tables']);

		natcasesort($tables);

		return $tables;
	}


	/**
	 * Returns the triggers in the current SQLite database
	 * 
	 * @return array  An associative array with the key being the trigger name and the value an associative arrays, each containing the keys: `table`, `sql`
	 */
	private function getSQLiteTriggers($exclude_table=NULL)
	{
		if (!isset($this->schema_info['sqlite_triggers'])) {
			$this->schema_info['sqlite_triggers'] = array();
			$rows = $this->database->query(
				"SELECT tbl_name AS \"table\", name, sql FROM sqlite_master WHERE type = 'trigger'"
			)->fetchAllRows();
			foreach ($rows as $row) {
				$this->schema_info['sqlite_triggers'][$row['name']] = array(
					'table' => $row['table'],
					'sql'   => $row['sql']
				);
			}
		}

		$output = $this->schema_info['sqlite_triggers'];

		if ($exclude_table) {
			$new_output = array();
			foreach ($output as $name => $trigger) {
				if ($trigger['table'] == $exclude_table) {
					continue;
				}

				$new_output[$name] = $trigger;
			}
			$output = $new_output;
		}

		return $output;
	}
	
	
	/**
	 * Removes the SQLite indexes from the internal schema tracker
	 *
	 * @param  string $table   The table to remove the indexes for
	 * @return void
	 */
	private function removeSQLiteIndexes($table)
	{
		if (!isset($this->schema_info['sqlite_indexes'])) {
			return;
		}

		$indexes = $this->schema_info['sqlite_indexes'];

		$new_indexes = array();
		foreach ($indexes as $name => $index) {
			if ($index['table'] == $table) {
				continue;
			}
			$new_indexes[$name] = $index;
		}

		$this->schema_info['sqlite_indexes'] = $new_indexes;
	}


	/**
	 * Removes a table from the list of SQLite table
	 * 
	 * @param  string $table  The table to remove
	 * @return void
	 */
	private function removeSQLiteTable($table)
	{
		if (!isset($this->schema_info['sqlite_create_tables'])) {
			return;
		}

		unset($this->schema_info['sqlite_create_tables'][$table]);
	}


	/**
	 * Removes a SQLite trigger from the internal schema tracker
	 *
	 * @param  string $name   The trigger name
	 * @return void
	 */
	private function removeSQLiteTrigger($name)
	{
		if (!isset($this->schema_info['sqlite_triggers'])) {
			return;
		}

		unset($this->schema_info['sqlite_triggers'][$name]);
	}


	/**
	 * Removes the SQLite triggers for a table from the internal schema tracker
	 *
	 * @param  string $table   The table to remove the triggers for
	 * @return void
	 */
	private function removeSQLiteTriggers($table)
	{
		if (!isset($this->schema_info['sqlite_triggers'])) {
			return;
		}

		$triggers = $this->schema_info['sqlite_triggers'];

		$new_triggers = array();
		foreach ($triggers as $name => $trigger) {
			if ($trigger['table'] == $table) {
				continue;
			}
			$new_triggers[$name] = $trigger;
		}

		$this->schema_info['sqlite_triggers'] = $new_triggers;
	}


	/**
	 * Throws an fSQLException with the information provided
	 *
	 * @param  string $error  The error that occured
	 * @param  string $sql    The SQL statement that caused the error
	 * @return void
	 */
	private function throwException($error, $sql)
	{
		$db_type_map = array(
			'db2'        => 'DB2',
			'mssql'      => 'MSSQL',
			'mysql'      => 'MySQL',
			'oracle'     => 'Oracle',
			'postgresql' => 'PostgreSQL',
			'sqlite'     => 'SQLite'
		);
		
		throw new fSQLException(
			'%1$s error (%2$s) in %3$s',
			$db_type_map[$this->database->getType()],
			$error,
			$sql
		);
	}
	
	
	/**
	 * Translates a Flourish SQL DDL statement into the dialect for the current database
	 * 
	 * @internal
	 * 
	 * @param  string $sql                  The SQL statement to translate
	 * @param  array &$rollback_statements  SQL statements to rollback the returned SQL statements if something goes wrong - only applicable for MySQL `ALTER TABLE` statements
	 * @return array  An array containing the translated `$sql` statement and an array of extra statements
	 */
	public function translate($sql, &$rollback_statements=NULL)
	{
		$reset_sqlite_info = FALSE;
		if (!isset($this->schema_info['sqlite_schema_info'])) {
			$this->schema_info['sqlite_schema_info'] = TRUE;
			$reset_sqlite_info = TRUE;
		}

		$new_sql   = $sql;
		$exception = NULL;

		try {
			$extra_statements = array();
			if (!is_array($rollback_statements)) {
				$rollback_statements = array();
			}
			$new_sql = $this->translateCreateTableStatements($new_sql, $extra_statements);
			$new_sql = $this->translateAlterTableStatements($new_sql, $extra_statements, $rollback_statements);

			if ($this->database->getType() == 'sqlite') {
				$new_sql = $this->translateSQLiteDropTableStatements($new_sql, $extra_statements);
			}

		} catch (Exception $e) {
			$exception = $e;
		}
		
		if ($reset_sqlite_info) {
			unset($this->schema_info['sqlite_schema_info']);
			unset($this->schema_info['sqlite_create_tables']);
			unset($this->schema_info['sqlite_indexes']);
			unset($this->schema_info['sqlite_triggers']);
		}

		if ($exception) {
			throw $exception;
		}

		return array($new_sql, $extra_statements);
	}
	
	
	/**
	 * Translates the structure of `CREATE TABLE` statements to the database specific syntax
	 * 
	 * @param  string $sql                   The SQL to translate
	 * @param  array  &$extra_statements     Any extra SQL statements that need to be added
	 * @param  array  &$rollback_statements  SQL statements to rollback `$sql` and `$extra_statements` if something goes wrong
	 * @return string  The translated SQL
	 */
	private function translateAlterTableStatements($sql, &$extra_statements, &$rollback_statements=NULL)
	{
		if (!preg_match('#^\s*ALTER\s+TABLE\s+(\w+|"[^"]+")\s+(.*)$#siD', $sql, $table_matches) && !preg_match('#^\s*COMMENT\s+ON\s+COLUMN\s+"?((?:\w+"?\."?)?\w+)"?\.("?\w+"?\s+IS\s+(?:\'.*\'|%\d+\$s))\s*$#Dis', $sql, $table_matches)) {
			return $sql;
		}
		
		$statement = $table_matches[2];
		
		$data = array(
			'table' => $table_matches[1]
		);

		if (preg_match('#"?(\w+)"?\s+IS\s+(\'.*\'|:string\w+|%\d+\$s)\s*$#Dis', $statement, $statement_matches)) {
			$data['type']        = 'column_comment';
			$data['column_name'] = trim($statement_matches[1], '"');
			$data['comment']     = $statement_matches[2];

		} elseif (preg_match('#RENAME\s+TO\s+(\w+|"[^"]+")\s*$#isD', $statement, $statement_matches)) {
			$data['type']           = 'rename_table';
			$data['new_table_name'] = trim($statement_matches[1], '"');

		} elseif (preg_match('#RENAME\s+COLUMN\s+(\w+|"[^"]+")\s+TO\s+(\w+|"[^"]+")\s*$#isD', $statement, $statement_matches)) {
			$data['type']            = 'rename_column';
			$data['column_name']     = trim($statement_matches[1], '"');
			$data['new_column_name'] = trim($statement_matches[2], '"');

		} elseif (preg_match('#ADD\s+COLUMN\s+("?(\w+)"?.*)$#isD', $statement, $statement_matches)) {
			$data['type']              = 'add_column';
			$data['column_definition'] = $statement_matches[1];
			$data['column_name']       = $statement_matches[2];

		} elseif (preg_match('#DROP\s+COLUMN\s+(\w+|"[^"]+")\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'drop_column';
			$data['column_name'] = trim($statement_matches[1], '"');

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+TYPE\s+(.*?)\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'alter_type';
			$data['column_name'] = trim($statement_matches[1], '"');
			$data['data_type']   = $statement_matches[2];

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+DROP\s+DEFAULT\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'drop_default';
			$data['column_name'] = trim($statement_matches[1], '"');

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+SET\s+DEFAULT\s+(.*?)\s*$#isD', $statement, $statement_matches)) {
			$data['type']          = 'set_default';
			$data['column_name']   = trim($statement_matches[1], '"');
			$data['default_value'] = trim($statement_matches[2], '"');

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+DROP\s+NOT\s+NULL\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'drop_not_null';
			$data['column_name'] = trim($statement_matches[1], '"');

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+SET\s+NOT\s+NULL(\s+DEFAULT\s+(.*))?\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'set_not_null';
			$data['column_name'] = trim($statement_matches[1], '"');
			if (isset($statement_matches[2])) {
				$data['default'] = $statement_matches[3];
			}

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+DROP\s+CHECK\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'drop_check_constraint';
			$data['column_name'] = trim($statement_matches[1], '"');

		} elseif (preg_match('#ALTER\s+COLUMN\s+(\w+|"[^"]+")\s+SET\s+CHECK\s+IN\s+(\(.*?\))\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'set_check_constraint';
			$data['column_name'] = trim($statement_matches[1], '"');
			$data['constraint']  = ' CHECK(' . $statement_matches[1] . ' IN ' . $statement_matches[2] . ')';

		} elseif (preg_match('#DROP\s+PRIMARY\s+KEY\s*$#isD', $statement, $statement_matches)) {
			$data['type'] = 'drop_primary_key';

		} elseif (preg_match('#ADD\s+PRIMARY\s+KEY\s*\(\s*([^\)]+?)\s*\)(\s+AUTOINCREMENT)?\s*$#isD', $statement, $statement_matches)) {
			$data['type']         = 'add_primary_key';
			$data['column_names'] = preg_split(
				'#"?\s*,\s*"?#',
				trim($statement_matches[1], '"'),
				-1,
				PREG_SPLIT_NO_EMPTY
			);
			$data['autoincrement'] = count($data['column_names']) == 1 && !empty($statement_matches[2]);
			if (count($data['column_names']) == 1) {
				$data['column_name'] = reset($data['column_names']);
			}

		} elseif (preg_match('#DROP\s+FOREIGN\s+KEY\s*\(\s*(\w+|"[^"]+")\s*\)\s*$#isD', $statement, $statement_matches)) {
			$data['type']        = 'drop_foreign_key';
			$data['column_name'] = trim($statement_matches[1], '"');

		} elseif (preg_match('#ADD\s+FOREIGN\s+KEY\s*\((\w+|"[^"]+")\)\s+REFERENCES\s+("?(\w+)"?\s*\(\s*"?(\w+)"?\s*\)\s*.*)\s*$#isD', $statement, $statement_matches)) {
			$data['type']           = 'add_foreign_key';
			$data['column_name']    = trim($statement_matches[1], '"');
			$data['references']     = $statement_matches[2];
			$data['foreign_table']  = self::unescapeIdentifier($statement_matches[3]);
			$data['foreign_column'] = self::unescapeIdentifier($statement_matches[4]);

		} elseif (preg_match('#DROP\s+UNIQUE\s*\(\s*([^\)]+?)\s*\)\s*$#isD', $statement, $statement_matches)) {
			$data['type']         = 'drop_unique';
			$data['column_names'] = preg_split(
				'#"?\s*,\s*"?#',
				trim($statement_matches[1], '"'),
				-1,
				PREG_SPLIT_NO_EMPTY
			);
			if (count($data['column_names']) == 1) {
				$data['column_name'] = reset($data['column_names']);
			}

		} elseif (preg_match('#ADD\s+UNIQUE\s*\(\s*([^\)]+?)\s*\)\s*$#isD', $statement, $statement_matches)) {
			$data['type']         = 'add_unique';
			$data['column_names'] = preg_split(
				'#"?\s*,\s*"?#',
				trim($statement_matches[1], '"'),
				-1,
				PREG_SPLIT_NO_EMPTY
			);
			if (count($data['column_names']) == 1) {
				$data['column_name'] = reset($data['column_names']);
			}

		} else {
			return $sql;
		}

		$data['table'] = self::unescapeIdentifier($data['table']);
		if (isset($data['new_table_name'])) {
			$data['new_table_name'] = self::unescapeIdentifier($data['new_table_name']);
		}
		if (isset($data['column_name'])) {
			$data['column_name'] = self::unescapeIdentifier($data['column_name']);
		}
		if (isset($data['column_names'])) {
			$data['column_names'] = array_map(
				array('fSQLSchemaTranslation', 'unescapeIdentifier'),
				$data['column_names']
			);
		}
		if (isset($data['new_column_name'])) {
			$data['new_column_name'] = self::unescapeIdentifier($data['new_column_name']);
		}
		
		if ($this->database->getType() == 'db2') {
			$sql = $this->translateDB2AlterTableStatements($sql, $extra_statements, $data);
		}
		if ($this->database->getType() == 'mssql') {
			$sql = $this->translateMSSQLAlterTableStatements($sql, $extra_statements, $data);
		}
		if ($this->database->getType() == 'mysql') {
			$sql = $this->translateMySQLAlterTableStatements($sql, $extra_statements, $rollback_statements, $data);
		}
		if ($this->database->getType() == 'oracle') {
			$sql = $this->translateOracleAlterTableStatements($sql, $extra_statements, $data);
		}
		if ($this->database->getType() == 'postgresql') {
			$sql = $this->translatePostgreSQLAlterTableStatements($sql, $extra_statements, $data);
		}
		if ($this->database->getType() == 'sqlite') {
			if ($data['type'] == 'rename_table') {
				$sql = $this->translateSQLiteRenameTableStatements($sql, $extra_statements, $data);
			} else {
				$sql = $this->translateSQLiteAlterTableStatements($sql, $extra_statements, $data);
			}
		}

		// All databases except for MySQL and Oracle support transactions around data definition queries
		// All of the Oracle statements will fail on the first query, if at all, so we don't need to
		// worry too much. MySQL is a huge pain though.
		if (!in_array($this->database->getType(), array('mysql', 'oracle'))) {
			array_unshift($extra_statements, $sql);
			
			if (!$this->database->isInsideTransaction()) {
				$sql = "BEGIN";
				$extra_statements[] = "COMMIT";
				$rollback_statements[] = "ROLLBACK";
				
			} else {
				$sql = array_shift($extra_statements);
			}
		}
		
		return $sql;
	}/**
	 * Translates the structure of `CREATE TABLE` statements to the database specific syntax
	 * 
	 * @param  string $sql                The SQL to translate
	 * @param  array  &$extra_statements  Any extra SQL statements that need to be added
	 * @return string  The translated SQL
	 */
	private function translateCreateTableStatements($sql, &$extra_statements)
	{
		if (!preg_match('#^\s*CREATE\s+TABLE\s+["`\[]?(\w+)["`\]]?#i', $sql, $table_matches) ) {
			return $sql;
		}
		
		$table = $table_matches[1];
		$sql = $this->translateDataTypes($sql);
		
		if ($this->database->getType() == 'db2') {
			$regex = array(
				'#("[^"]+"|\w+)\s+boolean(.*?)(,|\)|$)#im'   => '\1 CHAR(1)\2 CHECK(\1 IN (\'0\', \'1\'))\3',
				'#\binteger(?:\(\d+\))?\s+autoincrement\b#i' => 'INTEGER GENERATED BY DEFAULT AS IDENTITY',
				'#\)\s*$#D'                                  => ') CCSID UNICODE'
			);
			$sql = preg_replace(array_keys($regex), array_values($regex), $sql);

			// DB2 only supports some ON UPDATE clauses
			$sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL))#i', '', $sql);
			
		} elseif ($this->database->getType() == 'mssql') {
			$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER IDENTITY', $sql);	
		
		} elseif ($this->database->getType() == 'mysql') {
			
			$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER AUTO_INCREMENT', $sql);
			
			// Make sure MySQL uses InnoDB tables, translate check constraints to enums and fix column-level foreign key definitions
			preg_match_all('#(?<=,|\()\s*(["`]?\w+["`]?)\s+(?:[a-z]+)(?:\(\d+\))?(?:\s+unsigned|\s+zerofill|\s+character\s+set\s+[^ ]+|\s+collate\s+[^ ]+|\s+NULL|\s+NOT\s+NULL|(\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|\s+UNIQUE|\s+PRIMARY\s+KEY|(\s+CHECK\s*\(\w+\s+IN\s+(\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\))\)))*(\s+REFERENCES\s+["`]?\w+["`]?\s*\(\s*["`]?\w+["`]?\s*\)\s*(?:\s+(?:ON\s+DELETE|ON\s+UPDATE)\s+(?:CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))*)?\s*(,|\s*(?=\))|$)#miD', $sql, $matches, PREG_SET_ORDER);
			
			foreach ($matches as $match) {
				// MySQL has the enum data type, so we switch check constraints to that
				if (!empty($match[3])) {
					$replacement = "\n " . $match[1] . ' enum' . $match[4] . $match[2] . $match[5] . $match[6];
					$sql = str_replace($match[0], $replacement, $sql);
					// This allows us to do a str_replace below for converting foreign key syntax
					$match[0] = $replacement;
				}
				
				// Even InnoDB table types don't allow specify foreign key constraints in the column
				// definition, so we move it to its own definition on the next line
				if (!empty($match[5])) {
					$updated_match_0 = str_replace($match[5], ",\nFOREIGN KEY (" . $match[1] . ') ' . $match[5], $match[0]);
					$sql = str_replace($match[0], $updated_match_0, $sql);	
				}
			}
			
			$sql = preg_replace('#\)\s*;?\s*$#D', ')ENGINE=InnoDB, CHARACTER SET utf8', $sql);
		
		} elseif ($this->database->getType() == 'oracle') {

			// If NOT NULL DEFAULT '' is present, both are removed since Oracle converts '' to NULL
			$sql = preg_replace('#(\bNOT\s+NULL\s+DEFAULT\s+\'\'|\bDEFAULT\s+\'\'\s+NOT\s+NULL)#', '', $sql);

			// Oracle does not support ON UPDATE clauses
			$sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL|NO\s+ACTION|RESTRICT))#i', '', $sql);

			// Create sequences and triggers for Oracle
			if (stripos($sql, 'autoincrement') !== FALSE && preg_match('#(?<=,|\(|^)\s*("?\w+"?)\s+(?:[a-z]+)(?:\((?:\d+)\))?.*?\bAUTOINCREMENT\b[^,\)]*(?:,|\s*(?=\)))#mi', $sql, $matches)) {
				$column        = $matches[1];
				
				$table_column  = substr(str_replace('"' , '', $table) . '_' . str_replace('"', '', $column), 0, 26);
				
				$sequence_name = $table_column . '_seq';
				$trigger_name  = $table_column . '_trg';
				
				$sequence = 'CREATE SEQUENCE ' . $sequence_name;
				
				$trigger  = 'CREATE OR REPLACE TRIGGER '. $trigger_name . "\n";
				$trigger .= "BEFORE INSERT ON " . $table . "\n";
				$trigger .= "FOR EACH ROW\n";
				$trigger .= "BEGIN\n";
				$trigger .= "  IF :new." . $column . " IS NULL THEN\n";
				$trigger .= "	SELECT " . $sequence_name . ".nextval INTO :new." . $column . " FROM dual;\n";
				$trigger .= "  END IF;\n";
				$trigger .= "END;";
				
				$extra_statements[] = $sequence;
				$extra_statements[] = $trigger;	
				
				$sql = preg_replace('#\s+autoincrement\b#i', '', $sql);
			}
					
		} elseif ($this->database->getType() == 'postgresql') {
			$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'SERIAL', $sql);
			
		} elseif ($this->database->getType() == 'sqlite') {
			
			// Data type translation
			if (version_compare($this->database->getVersion(), 3, '>=')) {
				$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY AUTOINCREMENT', $sql);
				$sql = preg_replace("#datetime\(\s*CURRENT_TIMESTAMP\s*,\s*'localtime'\s*\)#i", 'CURRENT_TIMESTAMP', $sql);
			} else {
				$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY', $sql);
				$sql = preg_replace('#CURRENT_TIMESTAMP\(\)#i', 'CURRENT_TIMESTAMP', $sql);
			}

			// SQLite 3.6.19 and newer, may or may not have native foreign key support
			$toggle_foreign_key_support = FALSE;
			if (!isset($this->schema_info['foreign_keys_enabled'])) {
				$toggle_foreign_key_support = TRUE;
				$foreign_keys_res = $this->database->query('PRAGMA foreign_keys');
				if ($foreign_keys_res->countReturnedRows() && $foreign_keys_res->fetchScalar()) {
					$this->schema_info['foreign_keys_enabled'] = TRUE;
				} else {
					$this->schema_info['foreign_keys_enabled'] = FALSE;
				}
			}

			// Create foreign key triggers for SQLite
			if (stripos($sql, 'REFERENCES') !== FALSE && !$this->schema_info['foreign_keys_enabled']) {
				
				preg_match_all('#(?:(?<=,|\(|\*/|\n)\s*(?:`|"|\[)?(\w+)(?:`|"|\])?\s+(?:[a-z]+)(?:\(\s*(?:\d+)(?:\s*,\s*(?:\d+))?\s*\))?(?:(\s+NOT\s+NULL)|(?:\s+NULL)|(?:\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|(?:\s+UNIQUE)|(?:\s+PRIMARY\s+KEY(?:\s+AUTOINCREMENT)?)|(?:\s+CHECK\s*\(\w+\s+IN\s+\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\)\)))*(?:\s+REFERENCES\s+["`\[]?(\w+)["`\]]?\s*\(\s*["`\[]?(\w+)["`\]]?\s*\)\s*(?:(?:\s+ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))|(?:\s+ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?)?(?:\s*(?:/\*(?:(?!\*/).)*\*/))?\s*(?:,(?:[ \t]*--[^\n]*\n)?|(?:--[^\n]*\n)?\s*(?=\))))|(?:(?<=,|\(|\*/|\n)\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*\(?\s*["`\[]?(\w+)["`\]]?\s*\)?\s+REFERENCES\s+["`\[]?(\w+)["`\]]?\s*\(\s*["`\[]?(\w+)["`\]]?\s*\)\s*(?:(?:\s+ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))|(?:\s+ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?\s*(?:,(?:[ \t]*--[^\n]*\n)?|(?:--[^\n]*\n)?\s*(?=\))))#mis', $sql, $matches, PREG_SET_ORDER);
				
				$not_null_columns = array();
				foreach ($matches as $match) {
					// Find all of the not null columns
					if (!empty($match[2])) {
						$not_null_columns[] = $match[1];
					}
					
					// If neither of these fields is matched, we don't have a foreign key
					if (empty($match[3]) && empty($match[7])) {
						continue;
					}

					if (!empty($match[1])) {
						$column         = $match[1];
						$foreign_table  = $match[3];
						$foreign_column = $match[4];
						$on_delete      = isset($match[5]) ? $match[5] : NULL;
						$on_update      = isset($match[6]) ? $match[6] : NULL;
					} else {
						$column         = $match[7];
						$foreign_table  = $match[8];
						$foreign_column = $match[9];
						$on_delete      = isset($match[10]) ? $match[10] : NULL;
						$on_update      = isset($match[11]) ? $match[11] : NULL;
					}

					if (!$on_delete) {
						$on_delete = 'NO ACTION';
					}
					if (!$on_update) {
						$on_update = 'NO ACTION';
					}
					
					$this->createSQLiteForeignKeyTriggerValidInsertUpdate(
						$extra_statements,
						$table,
						$column,
						$foreign_table,
						$foreign_column,
						in_array($column, $not_null_columns)
					);
					
					$this->createSQLiteForeignKeyTriggerOnDelete(
						$extra_statements,
						$table,
						$column,
						$foreign_table,
						$foreign_column,
						$on_delete
					);
					$this->createSQLiteForeignKeyTriggerOnUpdate(
						$extra_statements,
						$table,
						$column,
						$foreign_table,
						$foreign_column,
						$on_update
					);
				}	
			}

			if ($toggle_foreign_key_support) {
				unset($this->schema_info['foreign_keys_enabled']);
			}
		}
		
		return $sql;
	}


	/**
	 * Translates basic data types
	 *
	 * @param string $sql  The SQL to translate
	 * @return string  The translated SQL
	 */
	private function translateDataTypes($sql)
	{
		switch ($this->database->getType()) {
			case 'db2':
				$regex = array(
					'#\btext\b#i'       => 'CLOB(1 G)',
					'#\bblob\b(?!\()#i' => 'BLOB(2 G)'
				);
				break;

			case 'mssql':
				$regex = array(
					'#\bblob\b#i'      => 'IMAGE',
					'#\btimestamp\b#i' => 'DATETIME',
					'#\btime\b#i'      => 'DATETIME',
					'#\bdate\b#i'      => 'DATETIME',
					'#\bboolean\b#i'   => 'BIT',
					'#\bvarchar\b#i'   => 'NVARCHAR',
					'#\bchar\b#i'      => 'NCHAR',
					'#\btext\b#i'      => 'NTEXT'
				);
				break;
			
			case 'mysql':
				$regex = array(
					'#\btext\b#i'      => 'LONGTEXT',
					'#\bblob\b#i'      => 'LONGBLOB',
					'#\btimestamp\b#i' => 'DATETIME'
				);
				break;

			case 'oracle':
				$regex = array(
					'#\bbigint\b#i'  => 'INTEGER',
					'#\bboolean\b#i' => 'NUMBER(1)',
					'#\btext\b#i'    => 'CLOB',
					'#\bvarchar\b#i' => 'VARCHAR2',
					'#\btime\b#i'    => 'TIMESTAMP'
				);
				break;

			case 'postgresql':
				$regex = array(
					'#\bblob\b#i' => 'BYTEA'
				);
				break;
			
			case 'sqlite':
				// SQLite doesn't have ALTER TABLE statements, so everything for data
				// types is handled via ::translateCreateTableStatements()
				$regex = array();
				break;
		}

		return preg_replace(array_keys($regex), array_values($regex), $sql);
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE` statements to the appropriate 
	 * statements for DB2
	 *
	 * @param string $sql                The SQL statements that will be executed against the database
	 * @param array  &$extra_statements  Any extra SQL statements required for DB2
	 * @param array  $data               Data parsed from the `ALTER TABLE` statement
	 * @return strin  The modified SQL statement
	 */
	private function translateDB2AlterTableStatements($sql, &$extra_statements, $data)
	{
		$data['schema']               = strtolower($this->database->getUsername());
		$data['table_without_schema'] = $data['table'];
		if (strpos($data['table'], '.') !== FALSE) {
			list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
		}

		if (in_array($data['type'], array('drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
			$column_info = $this->database->query(
				"SELECT
					C.COLNAME
				FROM
					SYSCAT.TABLES AS T LEFT JOIN
					SYSCAT.COLUMNS AS C ON
						T.TABSCHEMA = C.TABSCHEMA AND
						T.TABNAME = C.TABNAME AND
						LOWER(C.COLNAME) = %s
				WHERE
					LOWER(T.TABSCHEMA) = %s AND
					LOWER(T.TABNAME) = %s",
				isset($data['column_name']) ? $data['column_name'] : '',
				$data['schema'],
				$data['table_without_schema']
			);

			if (!$column_info->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not exist',
						$data['table']
					),
					$sql
				);
			}

			if (isset($data['column_name'])) {
				$row = $column_info->fetchRow();
				if (!strlen($row['colname'])) {
					$this->throwException(
						self::compose(
							'The column "%1$s" does not exist in the table "%2$s"',
							$data['column_name'],
							$data['table']
						),
						$sql
					);
				}
			}
		}

		if ($data['type'] == 'column_comment') {
			// DB2 handles the normalized syntax
		
		} elseif ($data['type'] == 'rename_table') {
			
			$foreign_key_constraints = $this->getDB2ForeignKeyConstraints(
				$data['schema'],
				$data['table_without_schema']
			);
			foreach ($foreign_key_constraints as $constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$constraint['schema'] . '.' . $constraint['table'],
					$constraint['constraint_name']
				);
			}

			$sql = $this->database->escape(
				"RENAME TABLE %r TO %r",
				$data['table'],
				$data['new_table_name']
			);

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

			foreach ($foreign_key_constraints as $constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $constraint['on_delete'] . ' ON UPDATE ' . $constraint['on_update'],
					$constraint['schema'] . '.' . $constraint['table'],
					$constraint['column'],
					$constraint['foreign_schema'] . '.' . $data['new_table_name'],
					$constraint['foreign_column']
				);
			}
		
		} elseif ($data['type'] == 'rename_column') {
			
			$data['column_name'] = strtolower($data['column_name']);

			$foreign_key_constraints = $this->getDB2ForeignKeyConstraints(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			foreach ($foreign_key_constraints as $constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$constraint['schema'] . '.' . $constraint['table'],
					$constraint['constraint_name']
				);
			}

			$unique_constraints = $this->getDB2UniqueConstraints(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			foreach ($unique_constraints as $name => $columns) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP UNIQUE %r",
					$data['table'],
					$name
				);
			}

			$check_constraint = $this->getDB2CheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$check_constraint['name']
				);
			}

			$primary_key_columns = $this->getDB2PrimaryKeyConstraint(
				$data['schema'],
				$data['table_without_schema']
			);
			if (in_array($data['column_name'], $primary_key_columns)) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP PRIMARY KEY",
					$data['table']
				);
			}
			
			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

			if (in_array($data['column_name'], $primary_key_columns)) {
				$key = array_search($data['column_name'], $primary_key_columns);
				$primary_key_columns[$key] = $data['new_column_name'];
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD PRIMARY KEY (%r)",
					$data['table'],
					$primary_key_columns
				);
			}

			if ($check_constraint) {
				$check_constraint['definition'] = preg_replace(
					'#^\s*"?' . preg_quote($data['column_name'], '#') . '"?#i',
					$this->database->escape('%r', $data['new_column_name']),
					$check_constraint['definition']
				);
				$constraint_name = $this->generateConstraintName($sql, 'ck');
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD CONSTRAINT %r CHECK(",
					$data['table'],
					$constraint_name
				) . $check_constraint['definition'] . ')';
			}

			foreach ($unique_constraints as $name => $columns) {
				$key = array_search($data['column_name'], $columns);
				$columns[$key] = $data['new_column_name'];
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD UNIQUE (%r)",
					$data['table'],
					$columns
				);
			}

			foreach ($foreign_key_constraints as $constraint) {
				if ($constraint['table'] == $data['table_without_schema'] && $constraint['column'] == $data['column_name']) {
					$constraint['column'] = $data['new_column_name'];
				} else {
					$constraint['foreign_column'] = $data['new_column_name'];
				}

				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $constraint['on_delete'] . ' ON UPDATE ' . $constraint['on_update'],
					$constraint['schema'] . '.' . $constraint['table'],
					$constraint['column'],
					$constraint['foreign_schema'] . '.' . $constraint['foreign_table'],
					$constraint['foreign_column']
				);
			}

		} elseif ($data['type'] == 'add_column') {
			
			$sql = $this->translateDataTypes($sql);

			// DB2 only supports some ON UPDATE clauses
			$sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL))#i', '', $sql);
			
			// Boolean translation is more context-sensitive, hence it is not part of translateDataTypes()
			$sql = preg_replace('#("[^"]+"|\w+)\s+boolean\b(.*)$#iD', '\1 CHAR(1)\2 CHECK(\1 IN (\'0\', \'1\'))', $sql);
			
			if (preg_match('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', $sql)) {
				$sql = preg_replace('# autoincrement\b#i', '', $sql);
				$sql = preg_replace('# PRIMARY\s+KEY\b#i', ' NOT NULL DEFAULT 0', $sql);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r DROP DEFAULT",
					$data['table'],
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET GENERATED BY DEFAULT AS IDENTITY",
					$data['table'],
					$data['column_name']
				);
				//$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
				// REORGE implicitly commits
				//$extra_statements[] = "BEGIN";
				$extra_statements[] = $this->database->escape(
					"UPDATE %r SET %r = DEFAULT",
					$data['table'],
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD PRIMARY KEY (%r)",
					$data['table'],
					$data['column_name']
				);
			}

		} elseif ($data['type'] == 'drop_column') {
			$sql .= ' CASCADE';
			// Certain operations in DB2 require calling REORG
			$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
			// REORGE implicitly commits
			$extra_statements[] = "BEGIN";

		} elseif ($data['type'] == 'alter_type') {
			
			$data['data_type'] = $this->translateDataTypes($data['data_type']);

			$sql = $this->database->escape(
				"ALTER TABLE %r ALTER COLUMN %r SET DATA TYPE " . $data['data_type'],
				$data['table'],
				$data['column_name']
			);
			// Certain operations in DB2 require calling REORG
			$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
			// REORGE implicitly commits
			$extra_statements[] = "BEGIN";

		} elseif ($data['type'] == 'set_default') {
			// DB2 handles the normalized syntax

		} elseif ($data['type'] == 'drop_default') {
			// DB2 complains if you try to drop the default for a column without a default
			$column_info = $this->database->query(
				"SELECT
					C.DEFAULT
				FROM
					SYSCAT.COLUMNS AS C
				WHERE
					LOWER(C.TABSCHEMA) = %s AND
					LOWER(C.TABNAME) = %s AND
					LOWER(C.COLNAME) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($column_info->countReturnedRows()) {
				$default = $column_info->fetchScalar();
				if ($default === NULL) {
					$sql = "SELECT 'noop - no constraint to drop' FROM SYSIBM.SYSDUMMY1";
				}
			}

		} elseif ($data['type'] == 'set_not_null') {
			$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
			// REORGE implicitly commits
			$extra_statements[] = "BEGIN";

			if (isset($data['default'])) {
				$sql = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET NOT NULL",
					$data['table'],
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET DEFAULT ",
					$data['table'],
					$data['column_name']
				) . $data['default'];
			}

		} elseif ($data['type'] == 'drop_not_null') {
			// DB2 handles the normalized syntax
			// Certain operations in DB2 require calling REORG
			$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
			// REORGE implicitly commits
			$extra_statements[] = "BEGIN";

		} elseif ($data['type'] == 'drop_check_constraint') {
			$check_constraint = $this->getDB2CheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if (!$check_constraint) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a check constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$check_constraint['name']
			);		

		} elseif ($data['type'] == 'set_check_constraint') {
			$check_constraint = $this->getDB2CheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$check_constraint['name']
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r ADD CONSTRAINT %r",
				$data['table'],
				$this->generateConstraintName($sql, 'ck')
			) . $data['constraint'];

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

		} elseif ($data['type'] == 'drop_primary_key') {
			// We drop the default value when dropping primary keys to get
			// rid of autoincrementing functionality
			$primary_key_columns = $this->getDB2PrimaryKeyConstraint(
				$data['schema'],
				$data['table_without_schema']
			);
			if (count($primary_key_columns) == 1) {
				$is_identity = (boolean) $this->database->query(
					"SELECT
						CASE WHEN C.IDENTITY = 'Y' AND (C.GENERATED = 'D' OR C.GENERATED = 'A') THEN '1' ELSE '0' END AS AUTO_INCREMENT
					FROM
						SYSCAT.COLUMNS AS C
					WHERE
						LOWER(C.TABSCHEMA) = %s AND
						LOWER(C.TABNAME) = %s AND
						LOWER(C.COLNAME) = %s",
					$data['schema'],
					$data['table_without_schema'],
					reset($primary_key_columns)
				)->fetchScalar();

				if ($is_identity) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r ALTER COLUMN %r DROP IDENTITY",
						$data['table'],
						reset($primary_key_columns)
					);
				}
			}

		} elseif ($data['type'] == 'add_primary_key') {
			
			if ($data['autoincrement']) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET GENERATED BY DEFAULT AS IDENTITY",
					$data['table'],
					$data['column_name']
				);
				//$extra_statements[] = "CALL SYSPROC.ADMIN_CMD('REORG TABLE " . $this->database->escape('%r', $data['table']) . "')";
				// REORGE implicitly commits
				//$extra_statements[] = "BEGIN";
				$extra_statements[] = $this->database->escape(
					"UPDATE %r SET %r = DEFAULT",
					$data['table'],
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD PRIMARY KEY (%r)",
					$data['table'],
					$data['column_name']
				);

				$sql = array_shift($extra_statements);
			}

		} elseif ($data['type'] == 'drop_foreign_key') {
			$constraint = $this->database->query(
				"SELECT
					R.CONSTNAME AS CONSTRAINT_NAME
				FROM
					SYSCAT.REFERENCES AS R INNER JOIN 
					SYSCAT.KEYCOLUSE AS K ON
						R.CONSTNAME = K.CONSTNAME AND
						R.TABSCHEMA = K.TABSCHEMA AND
						R.TABNAME = K.TABNAME INNER JOIN
					SYSCAT.KEYCOLUSE AS FK ON
						R.REFKEYNAME = FK.CONSTNAME AND
						R.REFTABSCHEMA = FK.TABSCHEMA AND
						R.REFTABNAME = FK.TABNAME
				WHERE
					LOWER(R.TABSCHEMA) = %s AND
					LOWER(R.TABNAME) = %s AND
					LOWER(K.COLNAME) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if (!$constraint->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint->fetchScalar()
			);

		} elseif ($data['type'] == 'add_foreign_key') {
			
			// DB2 only supports some ON UPDATE clauses
			$sql = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL))#i', '', $sql);

		} elseif ($data['type'] == 'drop_unique') {
			$constraint_rows = $this->database->query(
				"SELECT
					CD.CONSTNAME AS CONSTRAINT_NAME,
					LOWER(C.COLNAME) AS COLUMN
				FROM
					SYSCAT.INDEXES AS I INNER JOIN
					SYSCAT.CONSTDEP AS CD ON
						I.TABSCHEMA = CD.TABSCHEMA AND
						I.TABNAME = CD.TABNAME AND
						CD.BTYPE = 'I' AND
						CD.BNAME = I.INDNAME INNER JOIN
					SYSCAT.INDEXCOLUSE AS C ON
						I.INDSCHEMA = C.INDSCHEMA AND
						I.INDNAME = C.INDNAME
				WHERE
					LOWER(I.TABSCHEMA) = %s AND
					LOWER(I.TABNAME) = %s AND
					I.UNIQUERULE = 'U'",
				$data['schema'],
				$data['table_without_schema']
			);
			$constraints = array();
			foreach ($constraint_rows as $row) {
				if (!isset($constraints[$row['constraint_name']])) {
					$constraints[$row['constraint_name']] = array();
				}
				$constraints[$row['constraint_name']][] = $row['column'];
			}
			$constraint_name = NULL;
			sort($data['column_names']);
			foreach ($constraints as $name => $columns) {
				sort($columns);
				if ($columns == $data['column_names']) {
					$constraint_name = $name;
					break;
				}
			}
			if (!$constraint_name) {
				if (count($data['column_names']) > 1) {
					$message = self::compose(
						'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
						join('", "', $data['column_names']),
						$data['table']
					);
				} else {
					$message = self::compose(
						'The column "%1$s" in the table "%2$s" does not have a unique constraint',
						reset($data['column_names']),
						$data['table']
					);
				}
				$this->throwException($message, $sql);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP UNIQUE %r",
				$data['table'],
				$constraint_name
			);

		} elseif ($data['type'] == 'add_unique') {
			// DB2 handles the normalized syntax
		}

		return $sql;
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE` statements to the appropriate 
	 * statements for MSSQL
	 *
	 * @param string $sql                The SQL statements that will be executed against the database
	 * @param array  &$extra_statements  Any extra SQL statements required for MSSQL
	 * @param array  $data               Data parsed from the `ALTER TABLE` statement
	 * @return string  The modified SQL statement
	 */
	private function translateMSSQLAlterTableStatements($sql, &$extra_statements, $data)
	{
		$data['schema']               = 'dbo';
		$data['table_without_schema'] = $data['table'];
		if (strpos($data['table'], '.') !== FALSE) {
			list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
		}

		if (in_array($data['type'], array('set_not_null', 'drop_not_null', 'drop_default', 'drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
			$column_info = $this->database->query(
				"SELECT
					t.table_name,
					c.column_name
				FROM
					information_schema.tables AS t LEFT JOIN
					information_schema.columns AS c ON
						c.table_name = t.table_name AND
						c.table_schema = t.table_schema AND
						LOWER(c.column_name) = %s
				WHERE
					LOWER(t.table_name) = %s AND
					LOWER(t.table_schema) = %s AND
					t.table_catalog = DB_NAME()",
				isset($data['column_name']) ? $data['column_name'] : '',
				$data['table_without_schema'],
				$data['schema']
			);

			if (!$column_info->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not exist',
						$data['table']
					),
					$sql
				);
			}

			if (isset($data['column_name'])) {
				$row = $column_info->fetchRow();
				if (!strlen($row['column_name'])) {
					$this->throwException(
						self::compose(
							'The column "%1$s" does not exist in the table "%2$s"',
							$data['column_name'],
							$data['table']
						),
						$sql
					);
				}
			}
		}

		if (in_array($data['type'], array('set_not_null', 'drop_not_null'))) {
			$column_info = $this->database->query(
				"SELECT
					c.data_type                AS 'type',
					c.character_maximum_length AS max_length,
					c.numeric_precision        AS precision,
					c.numeric_scale            AS decimal_places
				FROM
					information_schema.columns AS c
				WHERE
					LOWER(c.table_name) = %s AND
					LOWER(c.table_schema) = %s AND
					LOWER(c.column_name) = %s AND
					c.table_catalog = DB_NAME()",
				$data['table_without_schema'],
				$data['schema'],
				$data['column_name']
			);

			$row = $column_info->fetchRow();
			$data_type = $row['type'];
			if ($row['max_length']) {
				$data_type .= '(' . $row['max_length'] . ')';
			}
			if (!preg_match('#^\s*int#i', $row['type']) && $row['precision']) {
				$data_type .= '(' . $row['precision'];
				if ($row['decimal_places']) {
					$data_type .= ', ' . $row['decimal_places'];
				}
				$data_type .= ')';
			}
		}

		if ($data['type'] == 'column_comment') {
			$get_sql = "SELECT
					CAST(ex.value AS VARCHAR(7500)) AS 'comment'
				FROM
					INFORMATION_SCHEMA.COLUMNS AS c";
			if (version_compare($this->database->getVersion(), 9, '<')) {
				$get_sql .= " INNER JOIN sysproperties AS ex ON ex.id = OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)) AND ex.smallid = COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'ColumnId') AND ex.name = 'MS_Description' AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), 'IsMsShipped') = 0 ";
			} else {
				$get_sql .= " INNER JOIN SYS.EXTENDED_PROPERTIES AS ex ON ex.major_id = OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)) AND ex.minor_id = COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), c.column_name, 'ColumnId') AND ex.name = 'MS_Description' AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(c.table_schema) + '.' + QUOTENAME(c.table_name)), 'IsMsShipped') = 0 ";
			}
			$get_sql .= "WHERE
				LOWER(c.table_name) = %s AND
				LOWER(c.table_schema) = %s AND
				LOWER(c.column_name) = %s AND
				c.table_catalog = DB_NAME()";
			$result = $this->database->query($get_sql, $data['table_without_schema'], $data['schema'], $data['column_name']);
			
			$stored_procedure = 'sys.sp_addextendedproperty';
			if ($result->countReturnedRows()) {
				$stored_procedure = 'sys.sp_updateextendedproperty';
			}

			$sql = "EXECUTE " . $stored_procedure . " @name='MS_Description', @value=" . $data['comment'] . $this->database->escape(
				", @level0type='SCHEMA', @level0name=%s, @level1type='TABLE',  @level1name=%s, @level2type='COLUMN', @level2name=%s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);

		} elseif ($data['type'] == 'rename_table') {
			$sql = $this->database->escape(
				"EXECUTE sp_rename %r, %r",
				$data['table'],
				$data['new_table_name']
			);

		} elseif ($data['type'] == 'rename_column') {

			// Find any check constraints and remove them, they will be re-added after the rename
			$check_constraint = $this->getMSSQLCheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);

			if ($check_constraint) {
				$check_constraint['definition'] = preg_replace(
					'#(\[)' . $data['column_name'] . '(\]\s*=\s*\')#i',
					'\1' . $data['new_column_name'] . '\2',
					$check_constraint['definition']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$check_constraint['name']
				);
			}

			$sql = $this->database->escape(
				'EXECUTE sp_rename "' . $data['table'] . '.' . $data['column_name'] . '", %r',
				$data['new_column_name']
			);

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD CONSTRAINT %r CHECK",
					$data['table'],
					$this->generateConstraintName($sql, 'ck')
				) . $check_constraint['definition'];
			}

		} elseif ($data['type'] == 'add_column') {
			$sql = $this->database->escape(
				'ALTER TABLE %r ADD ',
				$data['table']
			) . $data['column_definition'];

			$sql = $this->translateDataTypes($sql);
			$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER IDENTITY', $sql);

		} elseif ($data['type'] == 'drop_column') {

			// We must find all constraints that reference this column and drop them first
			$foreign_key_constraints = $this->getMSSQLForeignKeyConstraints(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			foreach ($foreign_key_constraints as $constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$constraint['table'],
					$constraint['name']
				);
			}

			$unique_constraints = $this->getMSSQLUniqueConstraints(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			foreach ($unique_constraints as $constraint_name => $constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$constraint_name
				);
			}

			$check_constraint = $this->getMSSQLCheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$check_constraint['name']
				);
			}

			$default_constraint = $this->getMSSQLDefaultConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($default_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$default_constraint['name']
				);
			}

			$primary_key_constraint = $this->getMSSQLPrimaryKeyConstraint(
				$data['schema'],
				$data['table_without_schema']
			);
			if ($primary_key_constraint && in_array($data['column_name'], $primary_key_constraint['columns'])) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$primary_key_constraint['name']
				);
			}

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);


		} elseif ($data['type'] == 'alter_type') {
			
			$default_constraint = $this->getMSSQLDefaultConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($default_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$default_constraint['name']
				);
			}

			$check_constraint = $this->getMSSQLCheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);

			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$check_constraint['name']
				);
			}

			// Check if the column is NOT NULL since we have to specify that when changing the type
			$column_info = $this->database->query(
				"SELECT
					c.is_nullable
				FROM
					INFORMATION_SCHEMA.COLUMNS AS c
				WHERE
					LOWER(c.table_schema) = %s AND
					LOWER(c.table_name) = %s AND
					LOWER(c.column_name) = %s AND
					c.table_catalog = DB_NAME()",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);

			$not_null = FALSE;
			if ($column_info->countReturnedRows()) {
				$row = $column_info->fetchRow();
				$not_null = $row['is_nullable'] == 'NO';
			}

			$unique_constraints = $this->getMSSQLUniqueConstraints(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			foreach ($unique_constraints as $constraint_name => $columns) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$constraint_name
				);
			}

			$primary_key_constraint = $this->getMSSQLPrimaryKeyConstraint(
				$data['schema'],
				$data['table_without_schema']
			);

			if ($primary_key_constraint && in_array($data['column_name'], $primary_key_constraint['columns'])) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$primary_key_constraint['name']
				);
			}


			$data['data_type'] = $this->translateDataTypes($data['data_type']);

			$sql = $this->database->escape(
				"ALTER TABLE %r ALTER COLUMN %r " . $data['data_type'] . ($not_null ? ' NOT NULL' : ''),
				$data['table'],
				$data['column_name']
			);

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

			if ($default_constraint) {
				$extra_statements[] =$this->database->escape("ALTER TABLE %r ADD DEFAULT ", $data['table']) . 
					$default_constraint['definition'] .
					$this->database->escape(" FOR %r", $data['column_name']);
			}

			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD CONSTRAINT %r CHECK",
					$data['table'],
					$this->generateConstraintName($sql, 'ck')
				) . $check_constraint['definition'];
			}

			foreach ($unique_constraints as $constraint_name => $columns) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD UNIQUE (%r)",
					$data['table'],
					$columns
				);
			}

			if ($primary_key_constraint && in_array($data['column_name'], $primary_key_constraint['columns'])) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD PRIMARY KEY (%r)",
					$data['table'],
					$primary_key_constraint['columns']
				);
			}

		} elseif ($data['type'] == 'set_default') {
			// SQL Server requires removing any existing default constraint
			$default_constraint = $this->getMSSQLDefaultConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($default_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$default_constraint['name']
				);
			}
			$sql = $this->database->escape("ALTER TABLE %r ADD DEFAULT ", $data['table']) . 
				$data['default_value'] . 
				$this->database->escape(" FOR %r", $data['column_name']);
			
			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

		} elseif ($data['type'] == 'drop_default') {
			$default_constraint = $this->getMSSQLDefaultConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if (!$default_constraint) {
				$sql = "SELECT 'noop - no constraint to drop'";
			} else {
				$sql = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$default_constraint['name']
				);
			}

		} elseif ($data['type'] == 'set_not_null') {
			$sql = $this->database->escape(
				"ALTER TABLE %r ALTER COLUMN %r " . $data_type . " NOT NULL",
				$data['table'],
				$data['column_name']
			);
			if (isset($data['default'])) {
				$default_constraint = $this->getMSSQLDefaultConstraint(
					$data['schema'],
					$data['table_without_schema'],
					$data['column_name']
				);
				if ($default_constraint) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r DROP CONSTRAINT %r",
						$data['table'],
						$default_constraint['name']
					);
				}
				$extra_statements[] = $this->database->escape("ALTER TABLE %r ADD DEFAULT ", $data['table']) . 
					$data['default'] . 
					$this->database->escape(" FOR %r", $data['column_name']);
			}
		
		} elseif ($data['type'] == 'drop_not_null') {
			$sql = $this->database->escape(
				"ALTER TABLE %r ALTER COLUMN %r " . $data_type . " NULL",
				$data['table'],
				$data['column_name']
			);
		
		} elseif ($data['type'] == 'drop_check_constraint') {
			$check_constraint = $this->getMSSQLCheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if (!$check_constraint) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a check constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$check_constraint['name']
			);
		
		} elseif ($data['type'] == 'set_check_constraint') {
			$check_constraint = $this->getMSSQLCheckConstraint(
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if ($check_constraint) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$check_constraint['name']
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r ADD CONSTRAINT %r",
				$data['table'],
				$this->generateConstraintName($sql, 'ck')
			) . $data['constraint'];

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);
		
		} elseif ($data['type'] == 'drop_primary_key') {
			
			$primary_key_constraint = $this->getMSSQLPrimaryKeyConstraint(
				$data['schema'],
				$data['table_without_schema']
			);
			if (!$primary_key_constraint) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not have a primary key constraint',
						$data['table']
					),
					$sql
				);
			}

			$foreign_key_constraints = $this->getMSSQLForeignKeyConstraints(
				$data['schema'],
				$data['table_without_schema'],
				$primary_key_constraint['columns']
			);
			foreach ($foreign_key_constraints as $foreign_key_constraint) {
				// Don't drop the constraints on the primary key columns themselves since that isn't necessary
				$same_schema = $foreign_key_constraint['table_without_schema'] == $data['table_without_schema'];
				$same_table  = $foreign_key_constraint['schema'] == $data['schema'];
				if ($same_schema && $same_table && in_array($foreign_key_constraint['column'], $primary_key_constraint['columns'])) {
					continue;
				}
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$foreign_key_constraint['table'],
					$foreign_key_constraint['name']
				);
			}

			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$primary_key_constraint['name']
			);

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

			if ($primary_key_constraint['autoincrement']) {
				
				$primary_key_column = reset($primary_key_constraint['columns']);
				$unique_constraints = $this->getMSSQLUniqueConstraints(
					$data['schema'],
					$data['table_without_schema'],
					$primary_key_column
				);

				foreach ($unique_constraints as $constraint_name => $columns) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r DROP CONSTRAINT %r",
						$data['table'],
						$constraint_name
					);
				}
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD %r INTEGER",
					$data['table'],
					'fl_tmp_identity_col'
				);
				$extra_statements[] = $this->database->escape(
					"UPDATE %r SET %r = %r",
					$data['table'],
					'fl_tmp_identity_col',
					$primary_key_column
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r INTEGER NOT NULL",
					$data['table'],
					'fl_tmp_identity_col'
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP COLUMN %r",
					$data['table'],
					$primary_key_column
				);
				$extra_statements[] = $this->database->escape(
					'EXEC sp_rename "' . $data['table'] . '.fl_tmp_identity_col", %r',
					$primary_key_column
				);
				foreach ($unique_constraints as $constraint_name => $columns) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r ADD UNIQUE (%r)",
						$data['table'],
						$columns
					);
				}
			}
			
		} elseif ($data['type'] == 'add_primary_key') {
			
			if ($data['autoincrement']) {
				$unique_constraints = $this->getMSSQLUniqueConstraints(
					$data['schema'],
					$data['table_without_schema'],
					$data['column_name']
				);
				foreach ($unique_constraints as $constraint_name => $columns) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r DROP CONSTRAINT %r",
						$data['table'],
						$constraint_name
					);
				}
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD %r INTEGER IDENTITY",
					$data['table'],
					'fl_tmp_identity_col'
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP COLUMN %r",
					$data['table'],
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					'EXEC sp_rename "' . $data['table'] . '.fl_tmp_identity_col", %r',
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD PRIMARY KEY (%r)",
					$data['table'],
					$data['column_name']
				);
				foreach ($unique_constraints as $constraint_name => $columns) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r ADD UNIQUE (%r)",
						$data['table'],
						$columns
					);
				}

				$sql = array_shift($extra_statements);
			}

		} elseif ($data['type'] == 'drop_foreign_key') {
			$constraint = $this->database->query(
				"SELECT
					kcu.constraint_name AS constraint_name
				FROM
					information_schema.table_constraints AS c INNER JOIN
					information_schema.key_column_usage AS kcu ON
						c.table_name = kcu.table_name AND
						c.constraint_name = kcu.constraint_name
				WHERE
					c.constraint_type = 'FOREIGN KEY' AND
					LOWER(c.table_name) = %s AND
					LOWER(c.table_schema) = %s AND
					LOWER(kcu.column_name) = %s AND
					c.table_catalog = DB_NAME()",
				$data['table_without_schema'],
				$data['schema'],
				$data['column_name']
			);
			if (!$constraint->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint->fetchScalar()
			);

		} elseif ($data['type'] == 'add_foreign_key') {
			// MSSQL handles the normalized syntax

		} elseif ($data['type'] == 'drop_unique') {
			$constraint_rows = $this->database->query(
				"SELECT
					c.constraint_name,
					LOWER(kcu.column_name) AS \"column\"
				FROM
					information_schema.table_constraints AS c INNER JOIN
					information_schema.key_column_usage AS kcu ON
						c.table_name = kcu.table_name AND
						c.constraint_name = kcu.constraint_name
				WHERE
					c.constraint_type = 'UNIQUE' AND
					LOWER(c.table_name) = %s AND
					LOWER(c.table_schema) = %s AND
					c.table_catalog = DB_NAME()",
				$data['table_without_schema'],
				$data['schema']
			);
			$constraints = array();
			foreach ($constraint_rows as $row) {
				if (!isset($constraints[$row['constraint_name']])) {
					$constraints[$row['constraint_name']] = array();
				}
				$constraints[$row['constraint_name']][] = $row['column'];
			}
			$constraint_name = NULL;
			sort($data['column_names']);
			foreach ($constraints as $name => $columns) {
				sort($columns);
				if ($columns == $data['column_names']) {
					$constraint_name = $name;
					break;
				}
			}
			if (!$constraint_name) {
				if (count($data['column_names']) > 1) {
					$message = self::compose(
						'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
						join('", "', $data['column_names']),
						$data['table']
					);
				} else {
					$message = self::compose(
						'The column "%1$s" in the table "%2$s" does not have a unique constraint',
						reset($data['column_names']),
						$data['table']
					);
				}
				$this->throwException($message, $sql);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint_name
			);

		} elseif ($data['type'] == 'add_unique') {
			// MSSQL handles the normalized syntax
		}
		

		return $sql;
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE` statements to the appropriate 
	 * statements for MySQL
	 *
	 * @param string $sql                   The SQL statements that will be executed against the database
	 * @param array  &$extra_statements     Any extra SQL statements required for MySQL
	 * @param array  &$rollback_statements  SQL statements to rollback `$sql` and `$extra_statements` if something goes wrong
	 * @param array  $data                  Data parsed from the `ALTER TABLE` statement
	 * @return string  The modified SQL statement
	 */
	private function translateMySQLAlterTableStatements($sql, &$extra_statements, &$rollback_statements, $data)
	{
		if ($data['type'] == 'rename_table') {
			$sql = $this->database->escape(
				"RENAME TABLE %r TO %r",
				$data['table'],
				$data['new_table_name']
			);
		}

		$before_statements = array();
		$after_statements  = array();

		if (in_array($data['type'], array('drop_column', 'rename_column', 'alter_type', 'set_not_null', 'drop_not_null', 'column_comment', 'drop_primary_key', 'drop_foreign_key', 'drop_unique', 'add_primary_key', 'drop_check_constraint', 'set_check_constraint'))) {
			// This fetches the original column definition to use with the CHANGE statement
			try {
				$row = $this->database->query("SHOW CREATE TABLE %r", $data['table'])->fetchRow();
			} catch (fSQLException $e) {
				// We catch and throw a new exception so the exception message
				// references the SQL statement passed to this method
				$this->throwException(
					self::compose(
						'The table "%1$s" does not exist',
						$data['table']
					),
					$sql
				);	
			}
			$create_sql = $row['Create Table'];
		}

		if ($data['type'] == 'drop_primary_key') {
			$data['column_names'] = array();
			if (preg_match('/PRIMARY KEY\s+\("(.*?)"\),?\n/U', $create_sql, $match)) {
				$data['column_names'] = explode('","', $match[1]);
			}
			if (count($data['column_names']) == 1) {
				$data['column_name'] = reset($data['column_names']);
			}
		}

		if (in_array($data['type'], array('rename_column', 'alter_type', 'set_not_null', 'drop_not_null', 'column_comment', 'add_primary_key', 'drop_primary_key', 'drop_foreign_key', 'drop_check_constraint', 'set_check_constraint', 'drop_unique')) && isset($data['column_name'])) {
			$found = preg_match(
				'#(?<=,|\()\s+(?:"|\`)' . $data['column_name'] . '(?:"|\`)(\s+(?:[a-z]+)(?:\([^)]+\))?(?: unsigned)?(?: zerofill)?(?: character set [^ ]+)?(?: collate [^ ]+)?)( NULL)?( NOT NULL)?( DEFAULT (?:(?:[^, \']*|\'(?:\'\'|[^\']+)*\')))?( auto_increment)?( COMMENT \'(?:\'\'|[^\']+)*\')?( ON UPDATE CURRENT_TIMESTAMP)?\s*(?:,|\s*(?=\)))#mi',
				$create_sql,
				$column_match
			);
			if (!$found) {
				$this->throwException(
					self::compose(
						'The column "%1$s" does not exist in the table "%2$s"',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			if (isset($column_match[4]) && strtolower($column_match[4]) == ' default null') {
				$column_match[4] = '';
			}
		}


		if ($data['type'] == 'column_comment') {
			$column_match[6] = ' COMMENT ' . $data['comment'];
			$column_def      = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY %r ",
				$data['table'],
				$data['column_name']
			) . $column_def;

		} elseif ($data['type'] == 'rename_column') {
			$column_def = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r CHANGE %r %r ",
				$data['table'],
				$data['column_name'],
				$data['new_column_name']
			) . $column_def;

		} elseif ($data['type'] == 'add_column') {
			
			$not_null   = preg_match('#\bNOT\s+NULL(\b|$)#iD', $data['column_definition']);
			$no_default = !preg_match('#\bDEFAULT\s+|\s+AUTOINCREMENT#i', $data['column_definition']);
			if ($not_null && $no_default && $this->database->query("SELECT COUNT(*) FROM %r", $data['table'])->fetchScalar()) {
				$this->throwException(
					self::compose(
						"It is not possible to add a column with a NOT NULL constraint that does not contain a DEFAULT value and is not an AUTOINCREMENT column for tables with existing rows"
					),
					$sql
				);
			}

			$sql = $this->translateDataTypes($sql);
			$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'INTEGER AUTO_INCREMENT', $sql);
			
			// Translate check constraints to enums and split out foreign key definitions
			preg_match_all(
				'#^\s*(["`]?\w+["`]?)(\s+(?:[a-z]+)(?:\(\d+\))?(?:\s+unsigned|\s+zerofill)*)((?:\s+character\s+set\s+[^ ]+|\s+collate\s+[^ ]+|\s+NULL|\s+NOT\s+NULL|(\s+DEFAULT\s+(?:[^, \']*|\'(?:\'\'|[^\']+)*\'))|\s+UNIQUE|\s+PRIMARY\s+KEY)*)(\s+CHECK\s*\(\w+\s+IN\s+(\(\s*(?:(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\s*,\s*)*\s*(?:[^, \']+|\'(?:\'\'|[^\']+)*\')\))\))?(\s+REFERENCES\s+["`]?\w+["`]?\s*\(\s*["`]?\w+["`]?\s*\)\s*(?:\s+(?:ON\s+DELETE|ON\s+UPDATE)\s+(?:CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))*)?\s*$#iD',
				$data['column_definition'],
				$matches,
				PREG_SET_ORDER
			);
			
			foreach ($matches as $match) {
				// MySQL has the enum data type, so we switch check constraints to that
				if (!empty($match[5])) {
					$replacement = ' enum' . $match[6];
					$sql = str_replace($match[2], $replacement, $sql);
					$sql = str_replace($match[5], '', $sql);
				}

				// Even InnoDB table types don't allow specify foreign key constraints in the column
				// definition, so we have to create an extra statement
				if (!empty($match[7])) {
					$after_statements[] = $this->database->escape(
						"ALTER TABLE %r ADD FOREIGN KEY (%r) " . $match[7],
						$data['table'],
						$data['column_name']
					);
					$sql = str_replace($match[7], '', $sql);	
				}
			}

		} elseif ($data['type'] == 'drop_column') {
			preg_match_all('/\bUNIQUE\s+KEY\s+"([^"]+)"\s+\("(.*?)"\),?\n/i', $create_sql, $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
				$columns = explode('","', $match[2]);
				
				if (in_array($data['column_name'], $columns)) {
					// Set up an array of column names we need to drop the keys for
					if (!isset($data['column_names'])) {
						$data['column_names'] = $columns;
					} else {
						$data['column_names'] = array_merge($data['column_names'], $columns);
					}

					$before_statements[] = $this->database->escape(
						"ALTER TABLE %r DROP INDEX %r",
						$data['table'],
						$match[1]
					);
				}
			}

		} elseif ($data['type'] == 'alter_type') {
			
			// We ignore changes from enum to varchar since that will just destroy the check constraint functionality
			if (!(preg_match('#\s*enum\(#i', $column_match[1]) && preg_match('#\s*varchar(\(\d+\))?\s*$#iD', $data['data_type']))) {
				$data['data_type'] = $this->translateDataTypes($data['data_type']);
				$column_match[1]   = ' ' . $data['data_type'];
			}

			$column_def        = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY %r ",
				$data['table'],
				$data['column_name']
			) . $column_def;

		} elseif ($data['type'] == 'set_default') {
			// MySQL handles the normalized syntax

		} elseif ($data['type'] == 'drop_default') {
			// MySQL handles the normalized syntax

		} elseif ($data['type'] == 'set_not_null') {
			$column_match[2] = '';
			$column_match[3] = ' NOT NULL';
			if (isset($data['default'])) {
				$column_match[4] = ' DEFAULT ' . $data['default'];
			
			// If the column is being set to NOT NULL we have to drop NULL default values
			} elseif (preg_match('#^\s*DEFAULT\s+NULL\s*$#i', $column_match[4])) {
				$column_match[4] = '';
			}
			$column_def = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY %r ",
				$data['table'],
				$data['column_name']
			) . $column_def;

		} elseif ($data['type'] == 'drop_not_null') {
			$column_match[2] = '';
			$column_match[3] = '';
			$column_def = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY %r ",
				$data['table'],
				$data['column_name']
			) . $column_def;

		} elseif ($data['type'] == 'set_check_constraint') {
			
			preg_match("/^\s*CHECK\s*\(\s*\"?\w+\"?\s+IN\s+(\(\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s)(?:\s*,\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s))*\s*\))\s*\)\s*$/i", $data['constraint'], $match);
			$valid_values = $match[1];

			$column_match[1] = ' ENUM' . $valid_values;

			$column_def = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY %r ",
				$data['table'],
				$data['column_name']
			) . $column_def;

		} elseif ($data['type'] == 'drop_check_constraint') {
			
			$found = preg_match_all("/(?<!')'((''|[^']+)*)'/", $column_match[1], $matches, PREG_PATTERN_ORDER);
			if (!$found) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" is not an ENUM column',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}

			$valid_values = str_replace("''", "'", $matches[1]);
			$lengths      = array_map(array('fUTF8', 'len'), $valid_values);
			$longest      = max($lengths);

			$column_match[1] = ' VARCHAR(' . $longest . ')';

			$column_def = join('', array_slice($column_match, 1));
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY %r ",
				$data['table'],
				$data['column_name']
			) . $column_def;

		} elseif ($data['type'] == 'drop_primary_key') {
			
			// MySQL doesn't allow a column to be auto_increment if it is not a primary key
			if (count($data['column_names']) == 1) {
				$column_match[3] = ' NOT NULL';
				if (!empty($column_match[5])) {
					$column_match[5] = '';
				}
				$column_def = join('', array_slice($column_match, 1));
				$before_statements[] = $this->database->escape(
					"ALTER TABLE %r MODIFY %r ",
					$data['table'],
					$data['column_names'][0]
				) . $column_def;
			}

		} elseif ($data['type'] == 'add_primary_key') {
			
			if ($data['autoincrement']) {
				$sql = preg_replace('#\s+autoincrement#i', '', $sql);

				$column_match[5] = ' AUTO_INCREMENT';
				$column_def = join('', array_slice($column_match, 1));
				$after_statements[] = $this->database->escape(
					"ALTER TABLE %r MODIFY %r " . $column_def,
					$data['table'],
					$data['column_name']
				);
			}

		} elseif ($data['type'] == 'drop_foreign_key') {
			$found = preg_match(
				'#CONSTRAINT\s+"(\w+)"\s+FOREIGN KEY \("' . preg_quote($data['column_name'], '#') . '"\) REFERENCES "([^"]+)" \("([^"]+)"\)(?:\sON\sDELETE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?(?:\sON\sUPDATE\s(SET\sNULL|SET\sDEFAULT|CASCADE|NO\sACTION|RESTRICT))?#',
				$create_sql,
				$match
			);
			if (!$found) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP FOREIGN KEY %r",
				$data['table'],
				$match[1]
			);

		} elseif ($data['type'] == 'add_foreign_key') {
			// MySQL has terrible error messages for non-existent foreign tables and columns
			try {
				$row = $this->database->query("SHOW CREATE TABLE %r", $data['foreign_table'])->fetchRow();
			} catch (fSQLException $e) {
				// We catch and throw a new exception so the exception message
				// references the SQL statement passed to this method
				$this->throwException(
					self::compose(
						'The referenced table "%1$s" does not exist',
						$data['foreign_table']
					),
					$sql
				);	
			}
			$foreign_create_sql = $row['Create Table'];
			$found = preg_match(
				'#(?<=,|\()\s+(?:"|\`)' . $data['foreign_column'] . '(?:"|\`)(\s+(?:[a-z]+)(?:\([^)]+\))?(?: unsigned)?(?: zerofill)?(?: character set [^ ]+)?(?: collate [^ ]+)?)( NULL)?( NOT NULL)?( DEFAULT (?:(?:[^, \']*|\'(?:\'\'|[^\']+)*\')))?( auto_increment)?( COMMENT \'(?:\'\'|[^\']+)*\')?( ON UPDATE CURRENT_TIMESTAMP)?\s*(?:,|\s*(?=\)))#mi',
				$foreign_create_sql,
				$column_match
			);
			if (!$found) {
				$this->throwException(
					self::compose(
						'The referenced column "%1$s" does not exist in the referenced table "%2$s"',
						$data['foreign_column'],
						$data['foreign_table']
					),
					$sql
				);
			}

		} elseif ($data['type'] == 'drop_unique') {
			preg_match_all('/\bUNIQUE\s+KEY\s+"([^"]+)"\s+\("(.*?)"\),?\n/i', $create_sql, $matches, PREG_SET_ORDER);
			
			$matched = FALSE;
			foreach ($matches as $match) {
				$columns = explode('","', $match[2]);
				sort($columns);
				sort($data['column_names']);

				if ($columns != $data['column_names']) {
					continue;
				}
				$matched = TRUE;

				$sql = $this->database->escape(
					"ALTER TABLE %r DROP INDEX %r",
					$data['table'],
					$match[1]
				);
			}

			if (!$matched) {
				if (count($data['column_names']) > 1) {
					$message = self::compose(
						'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
						join('", "', $data['column_names']),
						$data['table']
					);
				} else {
					$message = self::compose(
						'The column "%1$s" in the table "%2$s" does not have a unique constraint',
						reset($data['column_names']),
						$data['table']
					);
				}
				$this->throwException($message, $sql);
			}

		} elseif ($data['type'] == 'add_unique') {
			// MySQL handles the normalized syntax
		}


		$foreign_keys          = array();
		$recreate_foreign_keys = FALSE;
		if (in_array($data['type'], array('drop_column', 'rename_column', 'alter_type', 'set_not_null', 'drop_not_null', 'drop_primary_key', 'drop_unique'))) {
			$foreign_keys = $this->getMySQLForeignKeys($data['table'], isset($data['column_names']) ? $data['column_names'] : $data['column_name']);
			
			$new_foreign_keys = array();
			foreach ($foreign_keys as $foreign_key) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP FOREIGN KEY %r",
					$foreign_key['table'],
					$foreign_key['constraint_name']
				);

				$rollback_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $foreign_key['on_delete'] . " ON UPDATE " . $foreign_key['on_update'],
					$foreign_key['table'],
					$foreign_key['column'],
					$foreign_key['foreign_table'],
					$foreign_key['foreign_column']
				);

				if ($data['type'] == 'rename_column') {
					if ($foreign_key['foreign_table'] == $data['table']) {
						$foreign_key['foreign_column'] = $data['new_column_name'];
					} elseif ($foreign_key['table'] == $data['table']) {
						$foreign_key['column'] = $data['new_column_name'];
					}
				}
				$new_foreign_keys[] = $foreign_key;
			}
			$foreign_keys = $new_foreign_keys;
			$recreate_foreign_keys = TRUE;
		}

		// Put the original SQL into the middle of the extra statements to ensure
		// the column change is not made until all of the foreign keys have been dropped
		$extra_statements = array_merge($extra_statements, $before_statements);
		$extra_statements[] = $sql;
		$extra_statements = array_merge($extra_statements, $after_statements);
		$sql = array_shift($extra_statements);
			
		if ($recreate_foreign_keys) {
			foreach ($foreign_keys as $foreign_key) {
				// Once a primary key is dropped, it can no longer be references by foreign
				// keys since the values can't be guaranteed to be unique
				if ($data['type'] == 'drop_primary_key' && $foreign_key['foreign_table'] == $data['table']) {
					continue;
				}

				// For a dropped column we want to recreate the foreign keys that
				// reference other columns in unique contraints, but we need
				// to skip those referncing the column specifically
				if ($data['type'] == 'drop_column') {
					$referenced_column = $foreign_key['foreign_table'] == $data['table'] && $foreign_key['foreign_column'] == $data['column_name'];
					$column_itself     = $foreign_key['table'] == $data['table'] && $foreign_key['column'] == $data['column_name'];
					if ($referenced_column || $column_itself) {
						continue;
					}
				}

				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON DELETE " . $foreign_key['on_delete'] . " ON UPDATE " . $foreign_key['on_update'],
					$foreign_key['table'],
					$foreign_key['column'],
					$foreign_key['foreign_table'],
					$foreign_key['foreign_column']
				);
			}
		}

		return $sql;
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE` statements to the appropriate 
	 * statements for Oracle
	 *
	 * @param string $sql                The SQL statements that will be executed against the database
	 * @param array  &$extra_statements  Any extra SQL statements required for Oracle
	 * @param array  $data               Data parsed from the `ALTER TABLE` statement
	 * @return string  The modified SQL statement
	 */
	private function translateOracleAlterTableStatements($sql, &$extra_statements, $data)
	{
		$data['schema']               = strtolower($this->database->getUsername());
		$data['table_without_schema'] = $data['table'];
		if (strpos($data['table'], '.') !== FALSE) {
			list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
		}

		if (in_array($data['type'], array('drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
			$column_info = $this->database->query(
				"SELECT
					ATC.COLUMN_NAME
				FROM
					ALL_TABLES AT LEFT JOIN
					ALL_TAB_COLUMNS ATC ON
						ATC.OWNER = AT.OWNER AND
						ATC.TABLE_NAME = AT.TABLE_NAME AND
						LOWER(ATC.COLUMN_NAME) = %s
				WHERE
					LOWER(AT.OWNER) = %s AND
					LOWER(AT.TABLE_NAME) = %s",
				isset($data['column_name']) ? $data['column_name'] : '',
				$data['schema'],
				$data['table_without_schema']
			);

			if (!$column_info->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not exist',
						$data['table']
					),
					$sql
				);
			}

			if (isset($data['column_name'])) {
				$row = $column_info->fetchRow();
				if (!strlen($row['column_name'])) {
					$this->throwException(
						self::compose(
							'The column "%1$s" does not exist in the table "%2$s"',
							$data['column_name'],
							$data['table']
						),
						$sql
					);
				}
			}
		}

		if ($data['type'] == 'drop_check_constraint' || $data['type'] == 'set_check_constraint') {
			$constraints = $this->database->query(
				"SELECT
					AC.CONSTRAINT_NAME,
					AC.SEARCH_CONDITION
				FROM
					ALL_TAB_COLUMNS ATC INNER JOIN
					ALL_CONS_COLUMNS ACC ON
						ATC.OWNER = ACC.OWNER AND
						ATC.COLUMN_NAME = ACC.COLUMN_NAME AND
						ATC.TABLE_NAME = ACC.TABLE_NAME AND
						ACC.POSITION IS NULL INNER JOIN
					ALL_CONSTRAINTS AC ON
						AC.OWNER = ACC.OWNER AND
						AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
						AC.CONSTRAINT_TYPE = 'C' AND
						AC.STATUS = 'ENABLED'
				WHERE
					LOWER(ATC.OWNER) = %s AND
					LOWER(ATC.TABLE_NAME) = %s AND
					LOWER(ATC.COLUMN_NAME) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);

			$constraint_name = NULL;
			foreach ($constraints as $row) {
				if (preg_match("#^\s*\"?\w+\"?\s+IN\s+(\(\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s)(?:\s*,\s*(?:(?<!')'(?:''|[^']+)*'|%\d+\\\$s))*\s*\))\s*$#i", $row['search_condition'])) {
					$constraint_name = $row['constraint_name'];
					break;
				}
			}
		}

		if ($data['type'] == 'set_not_null' || $data['type'] == 'drop_not_null') {
			$not_null_result = $this->database->query(
				"SELECT
					ATC.NULLABLE
				FROM
					ALL_TAB_COLUMNS ATC
				WHERE
					LOWER(ATC.OWNER) = %s AND
					LOWER(ATC.TABLE_NAME) = %s AND
					LOWER(ATC.COLUMN_NAME) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);

			$not_null = $not_null_result->countReturnedRows() && $not_null_result->fetchScalar() == 'N';
		}

		if ($data['type'] == 'set_not_null' && isset($data['default']) && $data['default'] == "''") {
			$data['type'] = 'drop_not_null';
			$data['default'] = ' NULL';
		}

		if ($data['type'] == 'column_comment') {
			// Oracle handles the normalized syntax

		} elseif ($data['type'] == 'rename_table') {
			// Oracle handles the normalized syntax

		} elseif ($data['type'] == 'rename_column') {
			// When renaming a primary key column we need to check
			// for triggers that implement autoincrement
			$res = $this->database->query(
				"SELECT
					TRIGGER_NAME,
					TRIGGER_BODY
				FROM
					ALL_TRIGGERS
				WHERE
					TRIGGERING_EVENT LIKE 'INSERT%' AND
					STATUS = 'ENABLED' AND
					TRIGGER_NAME NOT LIKE 'BIN\$%' AND
					LOWER(TABLE_NAME) = %s AND
					LOWER(OWNER) = %s",
				$data['table_without_schema'],
				$data['schema']
			);
					
			foreach ($res as $row) {
				if (!preg_match('#\s+:new\."?' . preg_quote($data['column_name'], '#') . '"?\s+FROM\s+DUAL#i', $row['trigger_body'])) {
					continue;
				}
				$trigger  = 'CREATE OR REPLACE TRIGGER '. $row['trigger_name'] . "\n";
				$trigger .= "BEFORE INSERT ON " . $data['table_without_schema'] . "\n";
				$trigger .= "FOR EACH ROW\n";
				$trigger .= preg_replace(
					'#( :new\.)' . preg_quote($data['column_name'], '#') . '( )#i',
					'\1' . $data['new_column_name'] . '\2',
					$row['trigger_body']
				);

				$extra_statements[] = $trigger;
			}

		} elseif ($data['type'] == 'add_column') {
			// If NOT NULL DEFAULT '' is present, both are removed since Oracle converts '' to NULL
			$data['column_definition'] = preg_replace('#(\bNOT\s+NULL\s+DEFAULT\s+\'\'|\bDEFAULT\s+\'\'\s+NOT\s+NULL)#', '', $data['column_definition']);

			// Oracle does not support ON UPDATE clauses
			$data['column_definition'] = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL|NO\s+ACTION|RESTRICT))#i', '', $data['column_definition']);

			// Oracle requires NOT NULL to come after the DEFAULT value or UNIQUE constraint
			$data['column_definition'] = preg_replace('#(\s+NOT\s+NULL)((?:\s+UNIQUE|\s+DEFAULT\s+(?:[^, \'\n]*|\'(?:\'\'|[^\']+)*\'))+)#i', '\2\1', $data['column_definition']);

			$sql = $this->database->escape(
				'ALTER TABLE %r ADD ',
				$data['table']
			) . $data['column_definition'];

			$sql = $this->translateDataTypes($sql);
			
			// Create sequences and triggers for Oracle
			if (stripos($sql, 'autoincrement') !== FALSE && preg_match('#^\s*(?:[a-z]+)(?:\((?:\d+)\))?.*?\bAUTOINCREMENT\b.*$#iD', $sql, $matches)) {

				// If we are creating a new autoincrementing primary key on an existing
				// table we have to take some extra steps to pre-populate the
				// auto-incrementing column, otherwise Oracle will error out
				if (preg_match('#\bPRIMARY\s+KEY\b#i', $sql)) {
					$sql = preg_replace('# PRIMARY\s+KEY\b#i', '', $sql);
					$extra_statements[] = $this->database->escape(
						"UPDATE %r SET %r = ROWNUM",
						$data['table'],
						$data['column_name']
					);

					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r ADD CONSTRAINT %r PRIMARY KEY (%r)",
						$data['table'],
						$this->generateConstraintName($sql, 'pk'),
						$data['column_name']
					);
				}

				$table_column  = substr(str_replace('"' , '', $data['table']) . '_' . str_replace('"', '', $data['column_name']), 0, 26);
				
				$sequence_name = $table_column . '_seq';
				$trigger_name  = $table_column . '_trg';
				
				$sequence = "DECLARE
					create_seq_sql VARCHAR2(200);
    			BEGIN
					SELECT
						'CREATE SEQUENCE " . $sequence_name . " START WITH ' || (SQ.TOTAL_ROWS + 1)
					INTO
						create_seq_sql
					FROM
						(SELECT COUNT(*) TOTAL_ROWS FROM " . $data['table'] . ") SQ \;
					EXECUTE IMMEDIATE create_seq_sql\;
				END\;";
				
				$trigger  = 'CREATE OR REPLACE TRIGGER '. $trigger_name . "\n";
				$trigger .= "BEFORE INSERT ON " . $data['table'] . "\n";
				$trigger .= "FOR EACH ROW\n";
				$trigger .= "BEGIN\n";
				$trigger .= "  IF :new." . $data['column_name'] . " IS NULL THEN\n";
				$trigger .= "	SELECT " . $sequence_name . ".nextval INTO :new." . $data['column_name'] . " FROM dual;\n";
				$trigger .= "  END IF;\n";
				$trigger .= "END;";
				
				$extra_statements[] = $sequence;
				$extra_statements[] = $trigger;	
				
				$sql = preg_replace('#\s+autoincrement\b#i', '', $sql);
			}

		} elseif ($data['type'] == 'drop_column') {
			$sql .= ' CASCADE CONSTRAINTS';

			// Drop any triggers and sequences that implement autoincrement for the column
			$res = $this->database->query(
				"SELECT
					TRIGGER_NAME,
					TRIGGER_BODY
				FROM
					ALL_TRIGGERS
				WHERE
					TRIGGERING_EVENT LIKE 'INSERT%' AND
					STATUS = 'ENABLED' AND
					TRIGGER_NAME NOT LIKE 'BIN\$%' AND
					LOWER(TABLE_NAME) = %s AND
					LOWER(OWNER) = %s",
				$data['table_without_schema'],
				$data['schema']
			);
					
			foreach ($res as $row) {
				if (!preg_match('#SELECT\s+"?(\w+)"?\.nextval\s+INTO\s+:new\."?' . preg_quote($data['column_name'], '#') . '"?\s+FROM\s+dual#i', $row['trigger_body'], $match)) {
					continue;
				}

				$extra_statements[] = $this->database->escape("DROP SEQUENCE %r", $match[1]);
				$extra_statements[] = $this->database->escape("DROP TRIGGER %r", $row['trigger_name']);
			}

		} elseif ($data['type'] == 'alter_type') {
			
			$data['data_type'] = $this->translateDataTypes($data['data_type']);

			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY (%r ",
				$data['table'],
				$data['column_name']
			) . $data['data_type'] . ')';

		} elseif ($data['type'] == 'set_default') {
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY (%r DEFAULT ",
				$data['table'],
				$data['column_name']
			) . $data['default_value'] . ')';

		} elseif ($data['type'] == 'drop_default') {
			$sql = $this->database->escape(
				"ALTER TABLE %r MODIFY (%r DEFAULT NULL)",
				$data['table'],
				$data['column_name']
			);

		} elseif ($data['type'] == 'set_not_null') {

			// If it is already NOT NULL, don't set it again since it will cause an error
			if ($not_null_result->countReturnedRows() && $not_null) {
				if (isset($data['default'])) {
					$sql = $this->database->escape(
						"ALTER TABLE %r MODIFY (%r DEFAULT ",
						$data['table'],
						$data['column_name']
					) . $data['default'] . ')';
				} else {
					$sql = "SELECT 'noop - no NOT NULL to set' FROM dual";
				}
			} else {
				$sql = $this->database->escape(
					"ALTER TABLE %r MODIFY (%r",
					$data['table'],
					$data['column_name']
				);
				if (isset($data['default'])) {
					$sql .= ' DEFAULT ' . $data['default'];	
				}
				$sql .= ' NOT NULL)';
			}

		} elseif ($data['type'] == 'drop_not_null') {
			
			if (!$not_null_result->countReturnedRows() || $not_null) {
				$sql = $this->database->escape(
					"ALTER TABLE %r MODIFY (%r",
					$data['table'],
					$data['column_name']
				);
				if (isset($data['default'])) {
					$sql .= ' DEFAULT ' . $data['default'];	
				}
				$sql .= ' NULL)';

			// If it is already NULL, don't set it again since it will cause an error
			} else {
				if (isset($data['default'])) {
					$sql = $this->database->escape(
						"ALTER TABLE %r MODIFY (%r DEFAULT",
						$data['table'],
						$data['column_name']
					) . $data['default'] . ')';
				} else {
					$sql = "SELECT 'noop - no NOT NULL to drop' FROM dual";
				}
			}

		} elseif ($data['type'] == 'drop_check_constraint') {
			
			if (!$constraint_name) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a check constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint_name
			);
		
		} elseif ($data['type'] == 'set_check_constraint') {
			
			if ($constraint_name) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$constraint_name
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r ADD CONSTRAINT %r",
				$data['table'],
				$this->generateConstraintName($sql, 'ck')
			) . $data['constraint'];

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);
		
		} elseif ($data['type'] == 'drop_primary_key') {
			
			$constraint_columns = $this->database->query(
				"SELECT
					AC.CONSTRAINT_NAME CONSTRAINT_NAME,
					LOWER(ACC.COLUMN_NAME) \"COLUMN\",
					ANC.SEARCH_CONDITION
				FROM
					ALL_CONSTRAINTS AC INNER JOIN
					ALL_CONS_COLUMNS ACC ON
						AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
						AC.OWNER = ACC.OWNER LEFT JOIN
					ALL_CONS_COLUMNS ANCC ON
						ACC.OWNER = ANCC.OWNER AND
						ACC.TABLE_NAME = ANCC.TABLE_NAME AND
						ACC.COLUMN_NAME = ANCC.COLUMN_NAME LEFT JOIN
					ALL_CONSTRAINTS ANC ON
						ANC.CONSTRAINT_NAME = ANCC.CONSTRAINT_NAME AND
						ANC.OWNER = ANCC.OWNER AND
						ANC.CONSTRAINT_TYPE = 'C' AND
						ANC.STATUS = 'ENABLED'
				WHERE
					AC.CONSTRAINT_TYPE = 'P' AND
					LOWER(AC.OWNER) = %s AND
					LOWER(AC.TABLE_NAME) = %s",
				$data['schema'],
				$data['table_without_schema']
			);

			$constraint_name     = NULL;
			$primary_key_columns = array();
			$nullable            = FALSE;
			foreach ($constraint_columns as $row) {
				$constraint_name       = $row['constraint_name'];
				$primary_key_columns[] = $row['column'];
				$nullable              = strtolower($row['search_condition']) != '"' . $row['column'] . '" is not null';
			}

			if (!$constraint_name) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not have a primary key constraint',
						$data['table']
					),
					$sql
				);
			}

			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r CASCADE",
				$data['table'],
				$constraint_name
			);

			// When dropping a primary key we want to drop any trigger
			// and sequence used to implement autoincrement
			$res = $this->database->query(
				"SELECT
					TRIGGER_NAME,
					TRIGGER_BODY
				FROM
					ALL_TRIGGERS
				WHERE
					TRIGGERING_EVENT LIKE 'INSERT%' AND
					STATUS = 'ENABLED' AND
					TRIGGER_NAME NOT LIKE 'BIN\$%' AND
					LOWER(TABLE_NAME) = %s AND
					LOWER(OWNER) = %s",
				$data['table_without_schema'],
				$data['schema']
			);
					
			foreach ($res as $row) {
				if (!preg_match('#SELECT\s+"?(\w+)"?\.nextval\s+INTO\s+:new\.("?\w+"?)\s+FROM\s+DUAL#i', $row['trigger_body'], $match)) {
					continue;
				}
				$extra_statements[] = $this->database->escape(
					"DROP TRIGGER %r",
					$data['schema'] . '.' . $row['trigger_name']
				);
				$extra_statements[] = $this->database->escape(
					"DROP SEQUENCE %r",
					$data['schema'] . '.' . $match[1]
				);
			}

			if (count($primary_key_columns) == 1 && $nullable) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r MODIFY (%r NOT NULL)",
					$data['table'],
					reset($primary_key_columns)
				);
			}

		} elseif ($data['type'] == 'add_primary_key') {
			
			$sql = $this->database->escape(
				"ALTER TABLE %r ADD CONSTRAINT %r PRIMARY KEY (%r)",
				$data['table'],
				$this->generateConstraintName($sql, 'pk'),
				$data['column_names']
			);

			if ($data['autoincrement']) {
				
				$extra_statements[] = $sql;

				$sql = $this->database->escape(
					"UPDATE %r SET %r = ROWNUM",
					$data['table'],
					$data['column_name']
				);

				$table_column  = substr(str_replace('"' , '', $data['table']) . '_' . str_replace('"', '', $data['column_name']), 0, 26);
				
				$sequence_name = $table_column . '_seq';
				$trigger_name  = $table_column . '_trg';
				
				$sequence = "DECLARE
					create_seq_sql VARCHAR2(200);
    			BEGIN
					SELECT
						'CREATE SEQUENCE " . $sequence_name . " START WITH ' || (SQ.TOTAL_ROWS + 1)
					INTO
						create_seq_sql
					FROM
						(SELECT COUNT(*) TOTAL_ROWS FROM " . $data['table'] . ") SQ \;
					EXECUTE IMMEDIATE create_seq_sql\;
				END\;";
				
				$trigger  = 'CREATE OR REPLACE TRIGGER '. $trigger_name . "\n";
				$trigger .= "BEFORE INSERT ON " . $data['table'] . "\n";
				$trigger .= "FOR EACH ROW\n";
				$trigger .= "BEGIN\n";
				$trigger .= "  IF :new." . $data['column_name'] . " IS NULL THEN\n";
				$trigger .= "	SELECT " . $sequence_name . ".nextval INTO :new." . $data['column_name'] . " FROM dual;\n";
				$trigger .= "  END IF;\n";
				$trigger .= "END;";
				
				$extra_statements[] = $sequence;
				$extra_statements[] = $trigger;
			}

		} elseif ($data['type'] == 'drop_foreign_key') {
			$constraint = $this->database->query(
				"SELECT
					AC.CONSTRAINT_NAME CONSTRAINT_NAME
				FROM
					ALL_CONSTRAINTS AC INNER JOIN
					ALL_CONS_COLUMNS ACC ON
						AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
						AC.OWNER = ACC.OWNER
				WHERE
					AC.CONSTRAINT_TYPE = 'R' AND
					LOWER(AC.OWNER) = %s AND
					LOWER(AC.TABLE_NAME) = %s AND
					LOWER(ACC.COLUMN_NAME) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']			
			);
			if (!$constraint->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint->fetchScalar()
			);

		} elseif ($data['type'] == 'add_foreign_key') {

			// Oracle does not support ON UPDATE clauses
			$data['references'] = preg_replace('#(\sON\s+UPDATE\s+(CASCADE|SET\s+NULL|NO\s+ACTION|RESTRICT))#i', '', $data['references']);

			$sql = $this->database->escape(
				"ALTER TABLE %r ADD CONSTRAINT %r FOREIGN KEY (%r) REFERENCES " . $data['references'],
				$data['table'],
				$this->generateConstraintName($sql, 'fk'),
				$data['column_name']
			);

		} elseif ($data['type'] == 'drop_unique') {
			$constraint_rows = $this->database->query(
				"SELECT
					AC.CONSTRAINT_NAME,
					LOWER(ACC.COLUMN_NAME) \"COLUMN\"
				FROM
					ALL_CONSTRAINTS AC INNER JOIN
					ALL_CONS_COLUMNS ACC ON
						AC.CONSTRAINT_NAME = ACC.CONSTRAINT_NAME AND
						AC.OWNER = ACC.OWNER
				WHERE
					AC.CONSTRAINT_TYPE = 'U' AND
					LOWER(AC.OWNER) = %s AND
					LOWER(AC.TABLE_NAME) = %s",
				$data['schema'],
				$data['table_without_schema']			
			);
			$constraints = array();
			foreach ($constraint_rows as $row) {
				if (!isset($constraints[$row['constraint_name']])) {
					$constraints[$row['constraint_name']] = array();
				}
				$constraints[$row['constraint_name']][] = $row['column'];
			}
			$constraint_name = NULL;
			sort($data['column_names']);
			foreach ($constraints as $name => $columns) {
				sort($columns);
				if ($columns == $data['column_names']) {
					$constraint_name = $name;
					break;
				}
			}
			if (!$constraint_name) {
				if (count($data['column_names']) > 1) {
					$message = self::compose(
						'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
						join('", "', $data['column_names']),
						$data['table']
					);
				} else {
					$message = self::compose(
						'The column "%1$s" in the table "%2$s" does not have a unique constraint',
						reset($data['column_names']),
						$data['table']
					);
				}
				$this->throwException($message, $sql);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r CASCADE",
				$data['table'],
				$constraint_name
			);

		} elseif ($data['type'] == 'add_unique') {
			$sql = $this->database->escape(
				"ALTER TABLE %r ADD CONSTRAINT %r UNIQUE (%r)",
				$data['table'],
				$this->generateConstraintName($sql, 'uc'),
				$data['column_names']
			);
		}
		
		return $sql;
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE` statements to the appropriate 
	 * statements for PostgreSQL
	 *
	 * @param string $sql                The SQL statements that will be executed against the database
	 * @param array  &$extra_statements  Any extra SQL statements required for PostgreSQL
	 * @param array  $data               Data parsed from the `ALTER TABLE` statement
	 * @return string  The modified SQL statement
	 */
	private function translatePostgreSQLAlterTableStatements($sql, &$extra_statements, $data)
	{
		$data['schema']               = 'public';
		$data['table_without_schema'] = $data['table'];
		if (strpos($data['table'], '.') !== FALSE) {
			list ($data['schema'], $data['table_without_schema']) = explode('.', $data['table']);
		}

		if (in_array($data['type'], array('drop_check_constraint', 'drop_primary_key', 'drop_foreign_key', 'drop_unique'))) {
			$column_info = $this->database->query(
				"SELECT
					col.attname AS column_name
				FROM
					pg_namespace AS n INNER JOIN
					pg_class AS t ON
						t.relnamespace = n.oid LEFT JOIN
					pg_attribute AS col ON
						col.attrelid = t.oid AND
						LOWER(col.attname) = %s AND
						col.attisdropped = FALSE
				WHERE
					LOWER(n.nspname) = %s AND
					LOWER(t.relname) = %s",
				isset($data['column_name']) ? $data['column_name'] : '',
				$data['schema'],
				$data['table_without_schema']
			);

			if (!$column_info->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not exist',
						$data['table']
					),
					$sql
				);
			}

			if (isset($data['column_name'])) {
				$row = $column_info->fetchRow();
				if (!strlen($row['column_name'])) {
					$this->throwException(
						self::compose(
							'The column "%1$s" does not exist in the table "%2$s"',
							$data['column_name'],
							$data['table']
						),
						$sql
					);
				}
			}
		}

		if ($data['type'] == 'drop_check_constraint' || $data['type'] == 'set_check_constraint') {
			$constraint = $this->database->query(
				"SELECT
					con.conname AS constraint_name
				FROM
					pg_attribute AS col INNER JOIN
					pg_class AS t ON col.attrelid = t.oid INNER JOIN
					pg_namespace AS n ON t.relnamespace = n.oid INNER JOIN
					pg_constraint AS con ON
						col.attnum = ANY (con.conkey) AND
						con.conrelid = t.oid
				WHERE
					NOT col.attisdropped AND
					(con.contype = 'c') AND
					LOWER(n.nspname) = %s AND
					LOWER(t.relname) = %s AND
					LOWER(col.attname) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			$constraint_name = NULL;
			if ($constraint->countReturnedRows()) {
				$constraint_name = $constraint->fetchScalar();
			}
		}

		if ($data['type'] == 'column_comment') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'rename_table') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'rename_column') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'add_column') {
			
			$sql = $this->translateDataTypes($sql);
			$sql = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\b#i', 'SERIAL', $sql);

		} elseif ($data['type'] == 'drop_column') {
			$sql .= ' CASCADE';

		} elseif ($data['type'] == 'alter_type') {
			$sql = $this->translateDataTypes($sql);

		} elseif ($data['type'] == 'set_default') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'drop_default') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'set_not_null') {
			if (isset($data['default'])) {
				$sql = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET NOT NULL",
					$data['table'],
					$data['column_name']
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET DEFAULT ",
					$data['table'],
					$data['column_name']
				) . $data['default'];
			}

		} elseif ($data['type'] == 'drop_not_null') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'set_check_constraint') {
			if ($constraint_name) {
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r DROP CONSTRAINT %r",
					$data['table'],
					$constraint_name
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r ADD ",
				$data['table']
			) . $data['constraint'];

			$extra_statements[] = $sql;
			$sql = array_shift($extra_statements);

		} elseif ($data['type'] == 'drop_check_constraint') {

			if (!$constraint_name) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a check constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint_name
			);

		} elseif ($data['type'] == 'drop_primary_key') {
			$column_info = $this->database->query(
				"SELECT
					con.conname AS constraint_name,
					col.attname AS column,
					format_type(col.atttypid, col.atttypmod) AS data_type,
					ad.adsrc AS default
				FROM
					pg_attribute AS col INNER JOIN
					pg_class AS t ON col.attrelid = t.oid INNER JOIN
					pg_namespace AS s ON t.relnamespace = s.oid INNER JOIN
					pg_constraint AS con ON
						col.attnum = ANY (con.conkey) AND
						con.conrelid = t.oid LEFT JOIN
					pg_attrdef AS ad ON t.oid = ad.adrelid AND
						col.attnum = ad.adnum
				WHERE
					NOT col.attisdropped AND
					con.contype = 'p' AND
					LOWER(t.relname) = %s AND
					LOWER(s.nspname) = %s",
				$data['table_without_schema'],
				$data['schema']
			);

			if (!$column_info->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The table "%1$s" does not have a primary key constraint',
						$data['table']
					),
					$sql
				);
			}

			$row = $column_info->fetchRow();
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r CASCADE",
				$data['table'],
				$row['constraint_name']
			);

			// Change serial columns to integers when removing the primary key
			if ($column_info->countReturnedRows() == 1) {
				if (preg_match('#^(int|bigint)#i', $row['data_type']) && preg_match('#^\s*nextval\(\'([^\']+)\'#i', $row['default'], $match)) {
					$extra_statements[] = $this->database->escape(
						"ALTER TABLE %r ALTER COLUMN %r DROP DEFAULT",
						$data['table'],
						$row['column']
					);
					$extra_statements[] = $this->database->escape(
						"DROP SEQUENCE %r",
						$match[1]
					);
				}
			}

		} elseif ($data['type'] == 'add_primary_key') {
			
			if ($data['autoincrement']) {
				$sequence_name = $this->generateConstraintName($sql, 'seq');
				$extra_statements[] = $this->database->escape(
					"CREATE SEQUENCE %r",
					$sequence_name
				);
				$extra_statements[] = $this->database->escape(
					"SELECT setval(%s, MAX(%r)) FROM %r",
					$sequence_name,
					$data['column_name'],
					$data['table'] 
				);
				$extra_statements[] = $this->database->escape(
					"ALTER TABLE %r ALTER COLUMN %r SET DEFAULT nextval(%s::regclass)",
					$data['table'],
					$data['column_name'],
					$sequence_name
				);

				$sql = preg_replace('#\s+autoincrement#i', '', $sql);
			}

		} elseif ($data['type'] == 'drop_foreign_key') {
			$constraint = $this->database->query(
				"SELECT
					con.conname AS constraint_name
				FROM
					pg_attribute AS col INNER JOIN
					pg_class AS t ON col.attrelid = t.oid INNER JOIN
					pg_namespace AS n ON t.relnamespace = n.oid INNER JOIN
					pg_constraint AS con ON
						col.attnum = ANY (con.conkey) AND
						con.conrelid = t.oid
				WHERE
					NOT col.attisdropped AND
					(con.contype = 'f') AND
					LOWER(n.nspname) = %s AND
					LOWER(t.relname) = %s AND
					LOWER(col.attname) = %s",
				$data['schema'],
				$data['table_without_schema'],
				$data['column_name']
			);
			if (!$constraint->countReturnedRows()) {
				$this->throwException(
					self::compose(
						'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint->fetchScalar()
			);

		} elseif ($data['type'] == 'add_foreign_key') {
			// PostgreSQL handles the normalized syntax

		} elseif ($data['type'] == 'drop_unique') {
			$constraint_rows = $this->database->query(
				"SELECT
					con.conname AS constraint_name,
					LOWER(col.attname) AS column
				FROM
					pg_attribute AS col INNER JOIN
					pg_class AS t ON col.attrelid = t.oid INNER JOIN
					pg_namespace AS n ON t.relnamespace = n.oid INNER JOIN
					pg_constraint AS con ON
						col.attnum = ANY (con.conkey) AND
						con.conrelid = t.oid
				WHERE
					NOT col.attisdropped AND
					(con.contype = 'u') AND
					LOWER(n.nspname) = %s AND
					LOWER(t.relname) = %s",
				$data['schema'],
				$data['table_without_schema']
			);
			$constraints = array();
			foreach ($constraint_rows as $row) {
				if (!isset($constraints[$row['constraint_name']])) {
					$constraints[$row['constraint_name']] = array();
				}
				$constraints[$row['constraint_name']][] = $row['column'];
			}
			$constraint_name = NULL;
			sort($data['column_names']);
			foreach ($constraints as $name => $columns) {
				sort($columns);
				if ($columns == $data['column_names']) {
					$constraint_name = $name;
					break;
				}
			}
			if (!$constraint_name) {
				if (count($data['column_names']) > 1) {
					$message = self::compose(
						'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
						join('", "', $data['column_names']),
						$data['table']
					);
				} else {
					$message = self::compose(
						'The column "%1$s" in the table "%2$s" does not have a unique constraint',
						reset($data['column_names']),
						$data['table']
					);
				}
				$this->throwException($message, $sql);
			}
			$sql = $this->database->escape(
				"ALTER TABLE %r DROP CONSTRAINT %r",
				$data['table'],
				$constraint_name
			);

		} elseif ($data['type'] == 'add_unique') {
			// PostgreSQL handles the normalized syntax
		}

		return $sql;
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE` statements to the appropriate 
	 * statements for SQLite
	 *
	 * @param string $sql                The SQL statements that will be executed against the database
	 * @param array  &$extra_statements  Any extra SQL statements required for SQLite
	 * @param array  $data               Data parsed from the `ALTER TABLE` statement
	 * @return string  The modified SQL statement
	 */
	private function translateSQLiteAlterTableStatements($sql, &$extra_statements, $data)
	{
		$toggle_foreign_key_support = FALSE;
		if (!isset($this->schema_info['foreign_keys_enabled'])) {
			$toggle_foreign_key_support = TRUE;
			$foreign_keys_res = $this->database->query('PRAGMA foreign_keys');
			if ($foreign_keys_res->countReturnedRows() && $foreign_keys_res->fetchScalar()) {
				$this->schema_info['foreign_keys_enabled'] = TRUE;
				$this->database->query("PRAGMA foreign_keys = 0");
			} else {
				$this->schema_info['foreign_keys_enabled'] = FALSE;
			}
		}
		
		
		$temp_create_table_sql = $this->getSQLiteCreateTable($data['table']);
		if ($temp_create_table_sql === NULL) {
			$this->throwException(
				self::compose(
					'The table "%1$s" does not exist',
					$data['table']
				),
				$sql
			);
		}
		$temp_create_table_sql = preg_replace(
			'#(^\s*CREATE\s+TABLE\s+)(?:`|\'|"|\[)?(\w+)(?:`|\'|"|\])?(\s*\()#i',
			'\1"fl_tmp_' . $data['table'] . '"\3',
			$temp_create_table_sql
		);

		if ($data['type'] == 'drop_primary_key' && !preg_match('#\bPRIMARY\s+KEY\b#', $temp_create_table_sql)) {
			$this->throwException(
				self::compose(
					'The table "%1$s" does not have a primary key constraint',
					$data['table']
				),
				$sql
			);
		}

		if ($data['type'] == 'add_primary_key' && preg_match('#\bPRIMARY\s+KEY\b#', $temp_create_table_sql)) {
			$this->throwException(
				self::compose(
					'The table "%1$s" already has a primary key constraint',
					$data['table']
				),
				$sql
			);
		}

		if ($data['type'] == 'drop_unique') {
			$dropped_unique = FALSE;
		}
		if ($data['type'] == 'drop_foreign_key') {
			$dropped_foreign_key = FALSE;
		}

		if (in_array($data['type'], array('column_comment', 'alter_type', 'set_not_null', 'drop_not_null', 'drop_default', 'set_default', 'drop_primary_key', 'add_primary_key', 'drop_foreign_key', 'add_foreign_key', 'drop_unique', 'add_unique', 'set_check_constraint', 'drop_check_constraint'))) {

			$column_info = self::parseSQLiteColumnDefinitions($temp_create_table_sql);

			if (isset($data['column_name']) && !isset($column_info[$data['column_name']])) {
				$this->throwException(
					self::compose(
						'The column "%1$s" does not exist in the table "%2$s"',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}

			foreach ($column_info as $column => $info) {
				
				if (isset($data['column_name']) && $column == $data['column_name']) {
					if ($data['type'] == 'alter_type') {
						$info['pieces']['data_type'] = ' ' . $data['data_type'];

					} elseif ($data['type'] == 'set_not_null') {
						$info['pieces']['not_null'] = ' NOT NULL';
						$info['pieces']['null']     = '';
						if (isset($data['default'])) {
							$info['pieces']['default'] = ' DEFAULT ' . $data['default'];
						}

					} elseif ($data['type'] == 'drop_not_null') {
						$info['pieces']['not_null'] = '';
						$info['pieces']['null']     = '';

					} elseif ($data['type'] == 'set_default') {
						$info['pieces']['default'] = ' DEFAULT ' . $data['default_value'];

					} elseif ($data['type'] == 'drop_default') {
						$info['pieces']['default'] = '';

					} elseif ($data['type'] == 'set_check_constraint') {
						$info['pieces']['check_constraint'] = $data['constraint'];

					} elseif ($data['type'] == 'drop_check_constraint') {
						$info['pieces']['check_constraint'] = '';

					} elseif ($data['type'] == 'add_primary_key') {
						$info['pieces']['primary_key'] = ' PRIMARY KEY' . (version_compare($this->database->getVersion(), 3, '>=') && $data['autoincrement'] ? ' AUTOINCREMENT' : '');

					} elseif ($data['type'] == 'drop_foreign_key') {
						if (trim($info['pieces']['foreign_key'])) {
							$dropped_foreign_key = TRUE;
						}
						$info['pieces']['foreign_key'] = '';

					} elseif ($data['type'] == 'add_foreign_key') {
						$foreign_create_table = $this->getSQLiteCreateTable($data['foreign_table']);
						if ($foreign_create_table === NULL) {
							$this->throwException(
								self::compose(
									'The referenced table "%1$s" does not exist',
									$data['foreign_table']
								),
								$sql
							);
						}
						$foreign_column_info = self::parseSQLiteColumnDefinitions($foreign_create_table);
						if (!isset($foreign_column_info[$data['foreign_column']])) {
							$this->throwException(
								self::compose(
									'The referenced column "%1$s" does not exist in the referenced table "%2$s"',
									$data['foreign_column'],
									$data['foreign_table']
								),
								$sql
							);
						}

						$info['pieces']['foreign_key'] = ' REFERENCES ' . $data['references'];

					} elseif ($data['type'] == 'drop_unique') {
						if (trim($info['pieces']['unique'])) {
							$dropped_unique = TRUE;
						}
						$info['pieces']['unique'] = '';

					} elseif ($data['type'] == 'add_unique') {
						$info['pieces']['unique'] = ' UNIQUE';

					} elseif ($data['type'] == 'column_comment') {
						if (preg_match('#(^\s*,)|(^\s*/\*\s*((?:(?!\*/).)*?)\s*\*/\s*,)#', $info['pieces']['comment/end'])) {
							$info['pieces']['comment/end'] = ',';
						}
						$comment = str_replace("''", "'", substr($data['comment'], 1, -1));
						if (strlen(trim($comment))) {
							$info['pieces']['comment/end'] .= ' -- ' . $comment . "\n";
						}
					}

				} elseif ($data['type'] == 'drop_primary_key') {
					if (trim($info['pieces']['primary_key'])) {
						$data['column_name'] = $column;
					}
					$info['pieces']['not_null'] = ' NOT NULL';
					$info['pieces']['primary_key'] = '';
				}

				$temp_create_table_sql = str_replace(
					$info['definition'],
					join('', $info['pieces']),
					$temp_create_table_sql
				);
			}
		}


		$primary_key_regex = '#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?PRIMARY\s+KEY\s*\(\s*((?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?)\s*\)\s*(?:,|\s*(?=\)))#mi';
		$foreign_key_regex = '#(?<=,|\(|\*/|\n)(\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?FOREIGN\s+KEY\s*\(?\s*[\'"`\[]?(\w+)[\'"`\]]?\s*\)?)\s+REFERENCES\s+[\'"`\[]?(\w+)[\'"`\]]?\s*\(\s*[\'"`\[]?(\w+)[\'"`\]]?\s*\)\s*(?:(?:\s+ON\s+DELETE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT))|(?:\s+ON\s+UPDATE\s+(CASCADE|NO\s+ACTION|RESTRICT|SET\s+NULL|SET\s+DEFAULT)))*(?:\s+(?:DEFERRABLE|NOT\s+DEFERRABLE))?\s*(?:,(?:[ \t]*--[^\n]*\n)?|(?:--[^\n]*\n)?\s*(?=\)))#mis';
		$unique_constraint_regex = '#(?<=,|\()\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?UNIQUE\s*\(\s*((?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?)\s*\)\s*(?:,|\s*(?=\)))#mi';
		if (isset($data['column_name'])) {
			$column_regex = '#(?:`|\'|"|\[|\b)' . preg_quote($data['column_name'], '#') . '(?:`|\'|"|\]|\b)#i';
		}

		if ($data['type'] == 'drop_primary_key' || $data['type'] == 'drop_column') {
			// Drop any table-level primary keys
			preg_match_all($primary_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);

			foreach ($matches as $match) {
				$columns = preg_split('#[\'"`\]]?\s*,\s*[\'"`\[]?#', strtolower(trim($match[1], '\'[]`"')));
				sort($columns);

				if ($data['type'] == 'drop_primary_key' && count($columns) == 1) {
					$data['column_name'] = reset($columns);

				} elseif ($data['type'] == 'drop_column') {
					if (!in_array($data['column_name'], $columns)) {
						continue;
					}
				}

				$temp_create_table_sql = self::removeFromSQLiteCreateTable($temp_create_table_sql, $match[0]);
			}
		}


		if ($data['type'] == 'drop_foreign_key' || $data['type'] == 'drop_column') {
			// Drop any table-level foreign keys
			preg_match_all($foreign_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
				// Ignore foreign keys for other columns
				if (strtolower($match[2]) != $data['column_name']) {
					continue;
				}
				$dropped_foreign_key = TRUE;

				$temp_create_table_sql = self::removeFromSQLiteCreateTable($temp_create_table_sql, $match[0]);
			}
		}


		if ($data['type'] == 'drop_foreign_key' && !$dropped_foreign_key) {
			$this->throwException(
				self::compose(
					'The column "%1$s" in the table "%2$s" does not have a foreign key constraint',
					$data['column_name'],
					$data['table']
				),
				$sql
			);
		}


		if ($data['type'] == 'drop_unique' || $data['type'] == 'drop_column') {
			// Drop any table-level unique keys
			preg_match_all($unique_constraint_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
				$columns = preg_split('#[\'"`\]]?\s*,\s*[\'"`\[]?#', strtolower(trim($match[1], '\'[]`"')));
				sort($columns);

				if ($data['type'] == 'drop_column') {
					if (!in_array($data['column_name'], $columns)) {
						continue;
					}

				} else {
					sort($data['column_names']);
					if ($columns != $data['column_names']) {
						continue;
					}
					$dropped_unique = TRUE;
				}
				
				$temp_create_table_sql = self::removeFromSQLiteCreateTable($temp_create_table_sql, $match[0]);	
			}
		}


		if ($data['type'] == 'rename_column') {
			// Rename the column in the column definition and check constraint
			$column_info = self::parseSQLiteColumnDefinitions($temp_create_table_sql);
			if (!isset($column_info[$data['column_name']])) {
				$this->throwException(
					self::compose(
						'The column "%1$s" does not exist in the table "%2$s"',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			if (isset($column_info[$data['new_column_name']])) {
				$this->throwException(
					self::compose(
						'The column "%1$s" already exists in the table "%2$s"',
						$data['new_column_name'],
						$data['table']
					),
					$sql
				);
			}
			$info = $column_info[$data['column_name']];

			$temp_create_table_sql = str_replace(
				$info['definition'],
				preg_replace(
					'#^(\s*)[`"\'\[]?' . preg_quote($data['column_name'], '#') . '[`"\'\]]?(\s+)#i',
					'\1"' . $data['new_column_name'] . '"\2',
					$info['definition']
				),
				$temp_create_table_sql
			);
			if ($info['pieces']['check_constraint']) {
				$temp_create_table_sql = str_replace(
					$info['pieces']['check_constraint'],
					preg_replace(
						'#^(\s*CHECK\s*\(\s*)[`"\'\[]?' . preg_quote($data['column_name'], '#') . '[`"\'\]]?(\s+)#i',
						'\1"' . $data['new_column_name'] . '"\2',
						$info['pieces']['check_constraint']
					),
					$temp_create_table_sql
				);
			}
			

			// Rename the column in table-level primary key
			preg_match_all($primary_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
				$temp_create_table_sql = str_replace(
					$match[0],
					preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[0]),
					$temp_create_table_sql
				);
			}
			

			// Rename the column in table-level foreign key definitions
			preg_match_all($foreign_key_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
				$temp_create_table_sql = str_replace(
					$match[0],
					str_replace(
						$match[1],
						preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[1]),
						$match[0]
					),
					$temp_create_table_sql
				);
			}
			

			// Rename the column in table-level unique constraints
			preg_match_all($unique_constraint_regex, $temp_create_table_sql, $matches, PREG_SET_ORDER);
			foreach ($matches as $match) {
				$temp_create_table_sql = str_replace(
					$match[0],
					preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[0]),
					$temp_create_table_sql
				);
			}
		}

		
		if ($data['type'] == 'drop_column') {
			$column_info = self::parseSQLiteColumnDefinitions($temp_create_table_sql);
			if (!isset($column_info[$data['column_name']])) {
				$this->throwException(
					self::compose(
						'The column "%1$s" does not exist in the table "%2$s"',
						$data['column_name'],
						$data['table']
					),
					$sql
				);
			}
			$temp_create_table_sql = self::removeFromSQLiteCreateTable(
				$temp_create_table_sql,
				$column_info[$data['column_name']]['definition']
			);
		}

		
		if ($data['type'] == 'add_primary_key' && count($data['column_names']) > 1) {
			$temp_create_table_sql = preg_replace(
				'#\s*\)\s*$#D',
				$this->database->escape(",\n    PRIMARY KEY(%r)\n)", $data['column_names']),
				$temp_create_table_sql
			);
		}


		if ($data['type'] == 'add_unique' && count($data['column_names']) > 1) {
			$temp_create_table_sql = preg_replace(
				'#\s*\)\s*$#D',
				$this->database->escape(",\n    UNIQUE(%r)\n)", $data['column_names']),
				$temp_create_table_sql
			);
		}


		if ($data['type'] == 'add_column') {

			if (!preg_match('#\s*"?\w+"?\s+\w+#', $data['column_definition'])) {
				$this->throwException(
					self::compose(
						'Please specify a data type for the column "%1$s"',
						$data['column_name']
					),
					$sql
				);
			}

			preg_match(
				'#^(.*?)((?:(?<=,|\*/|\n)\s*(?:CONSTRAINT\s+["`\[]?\w+["`\]]?\s+)?\b(?:FOREIGN\s+KEY\b|PRIMARY\s+KEY\b|UNIQUE\b).*)|(?:\s*\)\s*))$#Dis',
				$temp_create_table_sql,
				$match
			);

			if (trim($match[2]) != ')') {
				$prefix = '';
				$suffix = ',';
			} else {
				$prefix = ',';
				$suffix = '';
			}

			// Be sure to add any necessary comma before a single-line SQL comment
			// because if it is placed after, the comma will be part of the comment
			if ($prefix) {
				$original_match_1 = $match[1];
				$match[1] = preg_replace('#(\s*--[^\n]+)(\s*)?$#Di', ',\1\2', $match[1]);
				if ($match[1] != $original_match_1) {
					$prefix = '';
				}
			}

			if (version_compare($this->database->getVersion(), 3, '>=')) {
				$data['column_definition'] = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY AUTOINCREMENT', $data['column_definition']);
				$data['column_definition'] = preg_replace("#datetime\(\s*CURRENT_TIMESTAMP\s*,\s*'localtime'\s*\)#i", 'CURRENT_TIMESTAMP', $data['column_definition']);

			} else {
				$data['column_definition'] = preg_replace('#\binteger(?:\(\d+\))?\s+autoincrement\s+primary\s+key\b#i', 'INTEGER PRIMARY KEY', $data['column_definition']);
				$data['column_definition'] = preg_replace('#CURRENT_TIMESTAMP\(\)#i', 'CURRENT_TIMESTAMP', $data['column_definition']);
			}

			$match[1] .= $prefix . "\n\t" . $data['column_definition'] . $suffix;

			$temp_create_table_sql = $match[1] . $match[2];
		}
		

		// Clean up extra line breaks
		$temp_create_table_sql = preg_replace('#\n([ \t]*\n)+#', "\n", $temp_create_table_sql);


		// SQLite 3 supports renaming a table, so we need the full create
		// table with all of the translated triggers, etc
		if (version_compare($this->database->getVersion(), 3, '>=')) {
			
			// We rename string placeholders to prevent confusion with
			// string placeholders that are added by call to fDatabase
			$temp_create_table_sql = str_replace(
				'%',
				'%%', 
				$temp_create_table_sql
			);

			$extra_statements = array_merge(
				$extra_statements,
				str_replace(
					'%%',
					'%',
					$this->database->preprocess(
						$temp_create_table_sql,
						array(),
						TRUE
					)
				)
			);

		// For SQLite 2 we can't rename the table, so we end up needing to
		// create a new one so the temporary table doesn't need triggers
		} else {
			$extra_statements[] = $temp_create_table_sql;
		}
		$this->addSQLiteTable('fl_tmp_' . $data['table'], $temp_create_table_sql);

		
		// Next we copy the data from the original table to the temp table
		if ($data['type'] == 'rename_column') {
			$column_names     = $this->getSQLiteColumns($data['table']);
			$new_column_names = $column_names;
			$column_position  = array_search($data['column_name'], $new_column_names);
			$new_column_names[$column_position] = $data['new_column_name'];

		} elseif ($data['type'] == 'drop_column') {
			$column_names     = array_diff(
				$this->getSQLiteColumns($data['table']),
				array($data['column_name'])
			);
			$new_column_names = $column_names;

		} else {
			$column_names     = $this->getSQLiteColumns($data['table']);
			$new_column_names = $column_names;
		}
		
		$extra_statements[] = $this->database->escape(
			"INSERT INTO %r (%r) SELECT %r FROM %r",
			'fl_tmp_' . $data['table'],
			$new_column_names,
			$column_names,
			$data['table']
		);

		
		// Recreate the indexes for the temp table
		$indexes = $this->getSQLiteIndexes($data['table']);
		foreach ($indexes as $name => $index) {
			$create_sql = $index['sql'];
			preg_match(
				'#^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:[\'"`\[]?\w+[\'"`\]]?\.)?[\'"`\[]?\w+[\'"`\]]?\s+(ON\s+[\'"`\[]?\w+[\'"`\]]?)\s*(\((\s*(?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?\s*)\))\s*$#Di',
				$create_sql,
				$match
			);
			$columns = preg_split(
				'#[\'"`\]]?\s*,\s*[\'"`\[]?#',
				strtolower(trim($match[4], '\'[]`"'))
			);
			
			if ($data['type'] == 'rename_column') {
				$create_sql = str_replace(
					$match[3],
					preg_replace($column_regex, '"' . $data['new_column_name'] . '"', $match[3]),
					$create_sql
				);
			
			} elseif ($data['type'] == 'drop_column') {
				if (in_array($data['column_name'], $columns)) {
					continue;
				}

			} elseif ($data['type'] == 'drop_unique') {
				sort($columns);
				sort($data['column_names']);

				if ($columns == $data['column_names']) {
					$dropped_unique = TRUE;
					continue;
				}
			}

			// The index needs to be altered to be created on the new table
			$create_sql = str_replace(
				$match[2],
				preg_replace(
					'#(?:`|\'|"|\[|\b)?' . preg_quote($data['table'], '#') . '(?:`|\'|"|\]|\b)?#',
					'"fl_tmp_' . $data['table'] . '"',
					$match[2]
				),
				$create_sql
			);

			// We fix the name of the index to keep in sync with the table name
			if (version_compare($this->database->getVersion(), 3, '>=')) {
				$new_name = $name;
			} else {
				$new_name = preg_replace(
					'#^' . preg_quote($data['table'], '#') . '#',
					'fl_tmp_' . $data['table'],
					$name
				);
			}

			// Ensure we have a unique index name
			while (isset($indexes[$new_name])) {
				if (preg_match('#(?<=_)(\d+)$#D', $new_name, $match)) {
					$new_name = preg_replace('#(?<=_)\d+$#D', $match[1] + 1, $new_name);
				} else {
					$new_name .= '_2';
				}
			}

			$create_sql = preg_replace(
				'#[\'"`\[]?' . preg_quote($name, '#') . '[\'"`\]]?(\s+ON\s+)#i',
				'"' . $new_name . '"\1',
				$create_sql
			);

			$this->addSQLiteIndex($new_name, 'fl_tmp_' . $data['table'], $create_sql);

			$extra_statements[] = $create_sql;
		}


		if ($data['type'] == 'drop_unique' && !$dropped_unique) {
			if (count($data['column_names']) > 1) {
				$message = self::compose(
					'The columns "%1$s" in the table "%2$s" do not have a unique constraint',
					join('", "', $data['column_names']),
					$data['table']
				);
			} else {
				$message = self::compose(
					'The column "%1$s" in the table "%2$s" does not have a unique constraint',
					reset($data['column_names']),
					$data['table']
				);
			}
			$this->throwException($message, $sql);
		}
		

		if (in_array($data['type'], array('rename_column', 'drop_column')) || ($data['type'] == 'drop_primary_key' && isset($data['column_name']))) {
			$foreign_keys = $this->getSQLiteForeignKeys($data['table'], $data['column_name']);
		
			foreach ($foreign_keys as $key) {
				$extra_statements = array_merge(
					$extra_statements,
					$this->database->preprocess(
						"ALTER TABLE %r DROP FOREIGN KEY (%r)",
						array($key['table'], $key['column']),
						TRUE
					)
				);
			}
		}
		
		
		// Drop the original table
		$extra_statements = array_merge(
			$extra_statements,
			$this->database->preprocess(
				"DROP TABLE %r",
				array($data['table']),
				TRUE
			)
		);
		
		
		// Rename the temp table to the original name
		$extra_statements = array_merge(
			$extra_statements,
			$this->database->preprocess(
				"ALTER TABLE %r RENAME TO %r",
				array('fl_tmp_' . $data['table'], $data['table']),
				TRUE
			)
		);


		// Re-add the foreign key constraints for renamed columns
		if ($data['type'] == 'rename_column') {
			foreach ($foreign_keys as $key) {
				$extra_statements = array_merge(
					$extra_statements,
					$this->database->preprocess(
						"ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON UPDATE " . $key['on_update'] . " ON DELETE " . $key['on_delete'],
						array($key['table'], $key['column'], $data['table'], $data['new_column_name']),
						TRUE
					)
				);
			}
		}

		
		// Finally, we turn back on foreign keys
		if ($toggle_foreign_key_support) {
			if ($this->schema_info['foreign_keys_enabled']) {
				$this->database->query("PRAGMA foreign_keys = 1");
			}
			unset($this->schema_info['foreign_keys_enabled']);
		}

		// Remove any nested transactions
		$extra_statements = array_diff($extra_statements, array("BEGIN", "COMMIT"));

		// Overwrite the original ALTER TABLE SQL
		$sql = array_shift($extra_statements);

		return $sql;
	}


	/**
	 * Translates `DROP TABLE` statements for SQLite
	 * 
	 * @param  string $sql                The SQL to translate
	 * @param  array  &$extra_statements  Any extra SQL statements that need to be added
	 * @return string  The translated SQL
	 */
	private function translateSQLiteDropTableStatements($sql, &$extra_statements)
	{
		if (preg_match('#^\s*DROP\s+TABLE\s+[["\'`]?(\w+)["\'`\]]?\s*$#iD', $sql, $match)) {
			$dependent_tables = array();
			$foreign_keys     = $this->getSQLiteForeignKeys($match[1]);
			foreach ($foreign_keys as $foreign_key) {
				$dependent_tables[] = $foreign_key['table'];
			}
			$dependent_tables = array_unique($dependent_tables);

			// We want to find triggers on tables that this table relies on and drop them
			$triggers = $this->getSQLiteTriggers($match[1]);
			foreach ($triggers as $name => $trigger) {
				if (in_array($trigger['table'], $dependent_tables)) {
					continue;
				}
				$matched_from_update = preg_match(
					'#(\s+(?:FROM|UPDATE)\s+)(`' . $match[1] . '`|"' . $match[1] . '"|\'' . $match[1] . '\'|' . $match[1] . '|\[' . $match[1] . '\])#i',
					$trigger['sql']
				);
				if ($matched_from_update) {
					$extra_statements[] = "DROP TRIGGER " . $name;
					$this->removeSQLiteTrigger($name);
				}
			}
			$this->removeSQLiteIndexes($match[1]);
			$this->removeSQLiteTriggers($match[1]);
			$this->removeSQLiteTable($match[1]);
		}

		return $sql;
	}


	/**
	 * Translates Flourish SQL `ALTER TABLE * RENAME TO` statements to the appropriate 
	 * statements for SQLite
	 *
	 * @param string $sql                The SQL statements that will be executed against the database
	 * @param array  &$extra_statements  Any extra SQL statements required for SQLite
	 * @param array  $data               Data parsed from the `ALTER TABLE` statement
	 * @return string  The modified SQL statement
	 */
	private function translateSQLiteRenameTableStatements($sql, &$extra_statements, $data)
	{
		$tables = $this->getSQLiteTables();
		if (in_array($data['new_table_name'], $tables)) {
			$this->throwException(
				self::compose(
					'A table with the name "%1$s" already exists',
					$data['new_table_name']
				),
				$sql
			);
		}
		if (!in_array($data['table'], $tables)) {
			$this->throwException(
				self::compose(
					'The table specified, "%1$s", does not exist',
					$data['table']
				),
				$sql
			);
		}

		// We start by dropping all references to this table
		$foreign_keys = $this->getSQLiteForeignKeys($data['table']);
		foreach ($foreign_keys as $foreign_key) {
			$extra_statements = array_merge(
				$extra_statements,
				$this->database->preprocess(
					"ALTER TABLE %r DROP FOREIGN KEY (%r)",
					array(
						$foreign_key['table'],
						$foreign_key['column']
					),
					TRUE
				)
			);
		}

		// SQLite 2 does not natively support renaming tables, so we have to do
		// it by creating a new table name and copying all data and indexes
		if (version_compare($this->database->getVersion(), 3, '<')) {

			$renamed_create_sql = preg_replace(
				'#^\s*CREATE\s+TABLE\s+["\[`\']?\w+["\]`\']?\s+#i',
				'CREATE TABLE "' . $data['new_table_name'] . '" ', 
				$this->getSQLiteCreateTable($data['table'])
			);

			$this->addSQLiteTable($data['new_table_name'], $renamed_create_sql);

			// We rename string placeholders to prevent confusion with
			// string placeholders that are added by call to fDatabase
			$renamed_create_sql = str_replace(
				':string_',
				':sub_string_', 
				$renamed_create_sql
			);

			$create_statements = str_replace(
				':sub_string_',
				':string_',
				$this->database->preprocess(
					$renamed_create_sql,
					array(),
					TRUE
				)
			);

			$extra_statements[] = array_shift($create_statements);

			// Recreate the indexes on the new table
			$indexes = $this->getSQLiteIndexes($data['table']);
			foreach ($indexes as $name => $index) {
				$create_sql = $index['sql'];
				preg_match(
					'#^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:[\'"`\[]?\w+[\'"`\]]?\.)?[\'"`\[]?\w+[\'"`\]]?\s+(ON\s+[\'"`\[]?\w+[\'"`\]]?)\s*(\((\s*(?:\s*[\'"`\[]?\w+[\'"`\]]?\s*,\s*)*[\'"`\[]?\w+[\'"`\]]?\s*)\))\s*$#Di',
					$create_sql,
					$match
				);

				// Fix the table name to the new table
				$create_sql = str_replace(
					$match[1],
					preg_replace(
						'#(?:`|\'|"|\[|\b)?' . preg_quote($data['table'], '#') . '(?:`|\'|"|\]|\b)?#i',
						'"' . $data['new_table_name'] . '"',
						$match[1]
					),
					$create_sql
				);

				// We change the name of the index to keep it in sync
				// with the new table name
				$new_name = preg_replace(
					'#^' . preg_quote($data['table'], '#') . '_#i',
					$data['new_table_name'] . '_',
					$name
				);
				$create_sql = preg_replace(
					'#[\'"`\[]?' . preg_quote($name, '#') . '[\'"`\]]?(\s+ON\s+)#i',
					'"' . $new_name . '"\1',
					$create_sql
				);
				
				$extra_statements[] = $create_sql;
				$this->addSQLiteIndex($new_name, $data['new_table_name'], $create_sql);
			}


			$column_names = $this->getSQLiteColumns($data['table']);
			$extra_statements[] = $this->database->escape(
				"INSERT INTO %r (%r) SELECT %r FROM %r",
				$data['new_table_name'],
				$column_names,
				$column_names,
				$data['table']
			);


			$extra_statements = array_merge(
				$extra_statements,
				$create_statements
			);


			$extra_statements = array_merge(
				$extra_statements,
				$this->database->preprocess(
					"DROP TABLE %r",
					array($data['table']),
					TRUE
				)
			);

		
		// SQLite 3 natively supports renaming tables, but it does not fix
		// references to the old table name inside of trigger bodies
		} else {

			// We add the rename SQL in the middle so it happens after we drop the
			// foreign key constraints and before we re-add them
			$extra_statements[] = $sql;
			$this->addSQLiteTable(
				$data['new_table_name'],
				preg_replace(
					'#^\s*CREATE\s+TABLE\s+[\'"\[`]?\w+[\'"\]`]?\s+#i',
					'CREATE TABLE "' . $data['new_table_name'] . '" ',
					$this->getSQLiteCreateTable($data['table'])
				)
			);
			$this->removeSQLiteTable($data['table']);

			// Copy the trigger definitions to the new table name
			foreach ($this->getSQLiteTriggers() as $name => $trigger) {
				if ($trigger['table'] == $data['table']) {
					$this->addSQLiteTrigger($name, $data['new_table_name'], $trigger['sql']);
				}
			}

			// Move the index definitions to the new table name
			foreach ($this->getSQLiteIndexes($data['table']) as $name => $index) {
				$this->addSQLiteIndex(
					$name,
					$data['new_table_name'],
					preg_replace(
						'#(\s+ON\s+)["\'`\[]?\w+["\'`\]]?#',
						'\1"' . preg_quote($data['new_table_name'], '#') . '"',
						$index['sql']
					)
				);
			}

			foreach ($this->getSQLiteTriggers() as $name => $trigger) {
				$create_sql = $trigger['sql'];
				$create_sql = preg_replace(
					'#( on table )"' . $data['table'] . '"#i',
					'\1"' . $data['new_table_name'] . '"',
					$create_sql
				);
				$create_sql = preg_replace(
					'#(\s+FROM\s+)(`' . $data['table'] . '`|"' . $data['table'] . '"|\'' . $data['table'] . '\'|' . $data['table'] . '|\[' . $data['table'] . '\])#i',
					'\1"' . $data['new_table_name'] . '"',
					$create_sql
				);
				if ($create_sql != $trigger['sql']) {
					$extra_statements[] = $this->database->escape("DROP TRIGGER %r", $name);
					$this->removeSQLiteTrigger($name);
					$this->addSQLiteTrigger($name, $data['new_table_name'], $create_sql);
					$extra_statements[] = $create_sql;
				}
			}
		}


		// Here we recreate the references that we dropped at the beginning
		foreach ($foreign_keys as $foreign_key) {
			$extra_statements = array_merge(
				$extra_statements,
				$this->database->preprocess(
					"ALTER TABLE %r ADD FOREIGN KEY (%r) REFERENCES %r(%r) ON UPDATE " . $foreign_key['on_update'] . " ON DELETE " . $foreign_key['on_delete'],
					array(
						$foreign_key['table'],
						$foreign_key['column'],
						$data['new_table_name'],
						$foreign_key['foreign_column']
					),
					TRUE
				)
			);
		}

		// Remove any nested transactions
		$extra_statements = array_diff($extra_statements, array("BEGIN", "COMMIT"));

		// Since the actual rename or create/drop has to happen after adjusting
		// foreign keys, we previously added it in the appropriate place and
		// now need to provide the first statement to be run
		return array_shift($extra_statements);
	}
}



/**
 * Copyright (c) 2011 Will Bond <will@flourishlib.com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
Back to Top