Source

baseten / Resources / BaseTenModifications.sql.m4

   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
--
-- BaseTenModifications.sql.m4
-- BaseTen
--
-- Copyright 2008-2010 Marko Karppinen & Co. LLC.
-- 
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
-- 
--     http://www.apache.org/licenses/LICENSE-2.0
-- 
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--

changequote(`{{', `}}')
-- ' -- Fix for syntax coloring in SQL mode.
define({{_bx_version_}}, {{0.940}})dnl
define({{_bx_compat_version_}}, {{0.25}})dnl


\unset ON_ERROR_ROLLBACK
\set ON_ERROR_STOP


BEGIN; -- Schema, helper functions and classes

DROP SCHEMA IF EXISTS "baseten" CASCADE;
CREATE SCHEMA "baseten";
COMMENT ON SCHEMA "baseten" IS 'Schema used by BaseTen. Please use the provided functions to edit.';
-- Privileges are set a bit later.

CREATE FUNCTION "baseten".create_plpgsql () RETURNS VOID AS $$
	CREATE LANGUAGE plpgsql;
$$ VOLATILE LANGUAGE SQL;

SELECT "baseten".create_plpgsql () 
FROM (
	SELECT EXISTS (
		SELECT lanname
		FROM pg_language 
		WHERE lanname = 'plpgsql'
	) AS exists
) AS plpgsql 
WHERE plpgsql.exists = false;

DROP FUNCTION "baseten".create_plpgsql ();

CREATE FUNCTION "baseten".prepare () RETURNS VOID AS $$
	BEGIN		
		PERFORM rolname FROM pg_roles WHERE rolname = 'basetenread';
		IF NOT FOUND THEN
			CREATE ROLE basetenread WITH
				INHERIT
				NOSUPERUSER
				NOCREATEDB
				NOCREATEROLE
				NOLOGIN;
		END IF;
			
		PERFORM rolname FROM pg_roles WHERE rolname = 'basetenuser';
		IF NOT FOUND THEN
			CREATE ROLE basetenuser WITH
				INHERIT
				NOSUPERUSER
				NOCREATEDB
				NOCREATEROLE
				NOLOGIN;
		END IF;
		
		PERFORM rolname FROM pg_roles WHERE rolname = 'basetenowner';
		IF NOT FOUND THEN
			CREATE ROLE basetenowner WITH
				INHERIT
				NOSUPERUSER
				NOCREATEDB
				NOCREATEROLE
				NOLOGIN;
		END IF;
	END;
$$ VOLATILE LANGUAGE plpgsql;
SELECT "baseten".prepare ();
DROP FUNCTION "baseten".prepare ();


REVOKE ALL PRIVILEGES ON SCHEMA "baseten" FROM PUBLIC;
GRANT USAGE ON SCHEMA "baseten" TO basetenread;


-- Helper functions

CREATE FUNCTION "baseten".array_cat (anyarray, anyarray)
	RETURNS anyarray AS $$
	SELECT $1 || $2;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".array_cat (anyarray, anyarray) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".array_cat (anyarray, anyarray) TO basetenread;


-- From the manual
CREATE AGGREGATE "baseten".array_accum
( 
	sfunc = array_append, 
	basetype = anyelement, 
	stype = anyarray, 
	initcond = '{}' 
);
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".array_accum (anyelement) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".array_accum (anyelement) TO basetenread;


CREATE AGGREGATE "baseten".array_cat
( 
	sfunc = "baseten".array_cat, 
	basetype = anyarray, 
	stype = anyarray, 
	initcond = '{}' 
);
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".array_cat (anyarray) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".array_cat (anyarray) TO basetenread;


-- Takes two one-dimensional arrays the first one of which is smaller or equal in size to the other.
-- Returns an array where each corresponding element is concatenated so that the third paramter 
-- comes in the middle
CREATE FUNCTION "baseten".array_cat_each (TEXT [], TEXT [], TEXT)
	RETURNS TEXT [] AS $$
DECLARE
	source1 ALIAS FOR $1;
	source2 ALIAS FOR $2;
	delim ALIAS FOR $3;
	destination TEXT [];
BEGIN
	FOR i IN array_lower (source1, 1)..array_upper (source1, 1) LOOP
		destination [i] = source1 [i] || delim || source2 [i];
	END LOOP;
	RETURN destination;
END;
$$ IMMUTABLE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".array_cat_each (TEXT [], TEXT [], TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".array_cat_each (TEXT [], TEXT [], TEXT) TO basetenread;


-- Prepends each element of an array with the first parameter
CREATE FUNCTION "baseten".array_prepend_each (TEXT, TEXT []) RETURNS TEXT [] AS $$
DECLARE
	prefix ALIAS FOR $1;
	source ALIAS FOR $2;
	destination TEXT [];
BEGIN
	FOR i IN array_lower (source, 1)..array_upper (source, 1) LOOP
		destination [i] = prefix || source [i];
	END LOOP;
	RETURN destination;
END;
$$ IMMUTABLE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".array_prepend_each (TEXT, TEXT [])  FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".array_prepend_each (TEXT, TEXT []) TO basetenread;


-- Appends each element of an array with the first parameter
CREATE FUNCTION "baseten".array_append_each (TEXT, TEXT []) RETURNS TEXT [] AS $$
DECLARE
	suffix ALIAS FOR $1;
	source ALIAS FOR $2;
	destination TEXT [];
BEGIN
	FOR i IN array_lower (source, 1)..array_upper (source, 1) LOOP
		destination [i] = source [i] || suffix;
	END LOOP;
	RETURN destination;
END;
$$ IMMUTABLE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".array_append_each (TEXT, TEXT []) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".array_append_each (TEXT, TEXT []) TO basetenread;


CREATE FUNCTION "baseten".split_part (string TEXT, delimiter TEXT, field INTEGER) RETURNS TEXT AS $$
DECLARE
	retval TEXT;
BEGIN
	SELECT split_part ($1, $2, $3) INTO retval;
	IF 0 = length (retval) THEN
		retval := null;
	END IF;
	RETURN retval;
END;
$$ IMMUTABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".split_part (TEXT, TEXT, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".split_part (TEXT, TEXT, INTEGER) TO basetenread;


CREATE FUNCTION "baseten".running_backend_pids () RETURNS SETOF INTEGER AS $$
	SELECT 
		pg_stat_get_backend_pid (idset.id) AS pid 
	FROM pg_stat_get_backend_idset () AS idset (id);
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".running_backend_pids () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".running_backend_pids () TO basetenread;


CREATE FUNCTION "baseten".false_indices (BOOLEAN [], INT2 []) RETURNS INT2 [] AS $$
DECLARE
	comparisons ALIAS FOR $1;
	indices ALIAS FOR $2;
	retval INT2 [] DEFAULT '{}'::INT2 [];
BEGIN
	FOR i IN array_lower (comparisons, 1)..array_upper (comparisons, 1) LOOP
		IF NOT (comparisons [i]) THEN
			retval := array_append (retval, indices [i]);
		END IF;
	END LOOP;
	
	IF 0 = COALESCE (array_upper (retval, 1), 0) THEN
		retval := null;
	END IF;
	
	RETURN retval;
END;
$$ IMMUTABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".false_indices (BOOLEAN [], INT2 []) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".false_indices (BOOLEAN [], INT2 []) TO basetenread;


define({{eq_function}}, {{
CREATE FUNCTION "baseten".eq ($1, $1) RETURNS BOOLEAN AS $$
	SELECT ${{}}1 ~= ${{}}2;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".eq ($1, $1) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".eq ($1, $1) TO basetenread
}})dnl
eq_function({{point}});
eq_function({{box}});
eq_function({{polygon}});
eq_function({{circle}});


CREATE FUNCTION "baseten".eq (lseg, lseg) RETURNS BOOLEAN AS $$
	SELECT ($1 [0] ~= $2 [0]) AND ($1 [1] ~= $2 [1]);
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".eq (lseg, lseg) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".eq (lseg, lseg) TO basetenread;


CREATE FUNCTION "baseten".eq (path, path) RETURNS BOOLEAN AS $$
BEGIN
	IF isopen ($1) <> isopen ($2) THEN
		RETURN false;
	END IF;
	
	IF npoints ($1) <> npoints ($2) THEN
		RETURN false;
	END IF;
	
	FOR i IN 0..npoints ($1) LOOP
		IF NOT (($1 [0] ~= $2 [0]) AND ($1 [1] ~= $2 [1])) THEN
			RETURN false;
		END IF;
	END LOOP;
	
	RETURN true;
END;
$$ IMMUTABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".eq (path, path) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".eq (path, path) TO basetenread;


CREATE FUNCTION "baseten".eq (anynonarray, anynonarray) RETURNS BOOLEAN AS $$
	SELECT $1 = $2;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".eq (anynonarray, anynonarray) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".eq (anynonarray, anynonarray) TO basetenread;


CREATE FUNCTION "baseten".eq (anyarray, anyarray) RETURNS BOOLEAN AS $$
BEGIN
	IF array_ndims ($1) = array_ndims ($2) THEN
		RETURN false;
	END IF;
	
	IF array_upper ($1, 1) = array_upper ($2, 1) THEN
		RETURN false;
	END IF;
	
	FOR i IN 0..array_upper ($1, 1) LOOP
		IF $1 [i] OPERATOR ("baseten".=) $2 [i] THEN
			RETURN false;
		END IF;
	END LOOP;
	
	RETURN true;
END;
$$ IMMUTABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".eq (anyarray, anyarray) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".eq (anyarray, anyarray) TO basetenread;


define({{eq_operator}}, {{
CREATE OPERATOR "baseten".= (
	PROCEDURE = "baseten".eq,
	LEFTARG = $1,
	RIGHTARG = $1,
	COMMUTATOR = OPERATOR ("baseten".=),
	HASHES
)}})dnl
eq_operator({{point}});
eq_operator({{box}});
eq_operator({{polygon}});
eq_operator({{circle}});
eq_operator({{lseg}});
eq_operator({{path}});
eq_operator({{anynonarray}});
eq_operator({{anyarray}});


define({{same_function}}, {{
CREATE FUNCTION "baseten".same ($1, $1) RETURNS BOOLEAN AS $$
	SELECT (
		${{}}1 IS NULL AND ${{}}2 IS NULL
	) OR (
		${{}}1 IS NOT NULL AND
		${{}}2 IS NOT NULL AND
		${{}}1 OPERATOR ("baseten".=) ${{}}2
	);
$$ IMMUTABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".same ($1, $1) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".same ($1, $1) TO basetenread
}})dnl
same_function({{anynonarray}});
same_function({{anyarray}});


define({{between_operator}}, {{
CREATE FUNCTION "baseten".between ($1 [2], $1) RETURNS BOOLEAN AS $$
	SELECT ${{}}1[1] <= ${{}}2 AND ${{}}2 <= ${{}}1[2];
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON  FUNCTION "baseten".between ($1 [2], $1) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".between ($1 [2], $1) TO basetenread;

CREATE OPERATOR "baseten".<<>> (
	PROCEDURE = "baseten".between,
	LEFTARG = $1[2],
	RIGHTARG = $1
)}})dnl
between_operator({{SMALLINT}});
between_operator({{INTEGER}});
between_operator({{BIGINT}});
between_operator({{NUMERIC}});
between_operator({{REAL}});
between_operator({{DOUBLE PRECISION}});
between_operator({{TIMESTAMP WITHOUT TIME ZONE}});
between_operator({{TIMESTAMP WITH TIME ZONE}});
between_operator({{INTERVAL}});
between_operator({{DATE}});
between_operator({{TIME WITHOUT TIME ZONE}});
between_operator({{TIME WITH TIME ZONE}});


-- No privileges on types
CREATE TYPE "baseten".reltype AS (
	oid OID,
	nspname NAME,
	relname NAME
);


CREATE TYPE "baseten".view_type AS (
	oid OID,
	parent OID,
	root OID,
	generation SMALLINT
);


CREATE TYPE "baseten".observation_type AS (
	identifier INTEGER,
	notification_name TEXT,
	function_name TEXT,
	table_name TEXT
);


CREATE FUNCTION "baseten".reltype (OID, NAME, NAME) RETURNS "baseten".reltype AS $$
	SELECT $1, $2, $3;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".reltype (OID, NAME, NAME) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".reltype (OID, NAME, NAME) TO basetenread;


CREATE FUNCTION "baseten".reltype (OID) RETURNS "baseten".reltype AS $$
DECLARE
	retval "baseten".reltype;
BEGIN
	SELECT $1, n.nspname, c.relname
		FROM pg_class c
		INNER JOIN pg_namespace n ON (c.relnamespace = n.oid)
		WHERE c.oid = $1
		INTO STRICT retval;
	RETURN retval;
END;
$$ STABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".reltype (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".reltype (OID) TO basetenread;


CREATE FUNCTION "baseten".quote_ident ("baseten".reltype) RETURNS TEXT AS $$
	SELECT quote_ident ($1.nspname) || '.' || quote_ident ($1.relname);
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".quote_ident ("baseten".reltype) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".quote_ident ("baseten".reltype) TO basetenread;


CREATE FUNCTION "baseten".quote_ident (TEXT, TEXT) RETURNS TEXT AS $$
	SELECT quote_ident ($1) || '.' || quote_ident ($2);
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".quote_ident (TEXT, TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".quote_ident (TEXT, TEXT) TO basetenread;


CREATE FUNCTION "baseten".quote_ident_bx (TEXT) RETURNS TEXT AS $$
	SELECT "baseten".quote_ident ('baseten', $1);
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".quote_ident_bx (TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".quote_ident_bx (TEXT) TO basetenread;


-- Debugging helpers
CREATE FUNCTION "baseten".oidof (TEXT, TEXT) RETURNS "baseten".reltype AS $$
	SELECT c.oid, n.nspname, c.relname
	FROM pg_class c
	INNER JOIN pg_namespace n ON (c.relnamespace = n.oid)
	WHERE c.relname = $2 AND n.nspname = $1;
$$ STABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".oidof (TEXT, TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".oidof (TEXT, TEXT) TO basetenread;


CREATE FUNCTION "baseten".oidof (TEXT) RETURNS "baseten".reltype AS $$
	SELECT "baseten".oidof ('public', $1);
$$ STABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".oidof (TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".oidof (TEXT) TO basetenread;


-- Views' primary keys
CREATE TABLE "baseten".view_pkey (
	nspname NAME NOT NULL DEFAULT 'public',
	relname NAME NOT NULL,
	attname NAME NOT NULL,
	PRIMARY KEY (nspname, relname, attname)
);
COMMENT ON TABLE "baseten".view_pkey IS 'Primary keys for views. This table may be modified by hand.';
COMMENT ON COLUMN "baseten".view_pkey.nspname IS 'Namespace name';
COMMENT ON COLUMN "baseten".view_pkey.relname IS 'View name';
COMMENT ON COLUMN "baseten".view_pkey.attname IS 'Column name';
GRANT SELECT ON TABLE "baseten".view_pkey TO basetenread;


CREATE TABLE "baseten".relation (
	id SERIAL PRIMARY KEY,
	nspname NAME NOT NULL,
	relname NAME NOT NULL,
	relkind CHAR (1) NOT NULL,
	enabled BOOLEAN NOT NULL DEFAULT false,
	UNIQUE (nspname, relname)
);
REVOKE ALL PRIVILEGES ON TABLE "baseten".relation FROM PUBLIC;
GRANT SELECT ON TABLE "baseten".relation TO basetenread;


CREATE TABLE "baseten".foreign_key (
	conid SERIAL PRIMARY KEY,
	conname NAME NOT NULL,
	conrelid INTEGER NOT NULL REFERENCES "baseten".relation (id) ON UPDATE CASCADE ON DELETE CASCADE,
	confrelid INTEGER NOT NULL REFERENCES "baseten".relation (id) ON UPDATE CASCADE ON DELETE CASCADE,
	conkey NAME[] NOT NULL,
	confkey NAME[] NOT NULL,
	confdeltype CHAR NOT NULL,
	conkey_is_unique BOOLEAN NOT NULL,
	UNIQUE (conrelid, conname)
);
REVOKE ALL PRIVILEGES ON TABLE "baseten".foreign_key FROM PUBLIC;
GRANT SELECT ON TABLE "baseten".foreign_key TO basetenread;


-- We can do all sorts of joins here because this view isn't cached.
CREATE VIEW "baseten"._primary_key AS
	SELECT 
		r.id,
		c.oid,
		r.relkind,
		r.nspname,
		r.relname,
		a.attnum,
		a.attname,
		n2.nspname AS typnspname,
		t.typname
	FROM baseten.relation r
	INNER JOIN pg_class c ON (c.relname = r.relname)
	INNER JOIN pg_namespace n1 ON (n1.nspname = r.nspname AND n1.oid = c.relnamespace)
	LEFT OUTER JOIN pg_constraint co ON (r.relkind = 'r' AND co.conrelid = c.oid AND co.contype = 'p') -- Tables
	LEFT OUTER JOIN "baseten".view_pkey vp ON (r.relkind = 'v' AND vp.nspname = n1.nspname AND vp.relname = c.relname) -- Views
	INNER JOIN pg_attribute a ON (a.attrelid = c.oid AND (
		(r.relkind = 'r' AND a.attnum = ANY (co.conkey)) OR
		(r.relkind = 'v' AND vp.attname = a.attname)
	))
	INNER JOIN pg_type t ON (t.oid = a.atttypid)
	INNER JOIN pg_namespace n2 ON (n2.oid = t.typnamespace)
	ORDER BY r.id, a.attnum;
REVOKE ALL PRIVILEGES ON "baseten"._primary_key FROM PUBLIC;
GRANT SELECT ON "baseten"._primary_key TO basetenread;


CREATE VIEW "baseten".relation_oids AS
    SELECT c.oid, r.enabled
    FROM "baseten".relation r
    INNER JOIN pg_class c ON (c.relname = r.relname)
    INNER JOIN pg_namespace n ON (n.nspname = r.nspname AND n.oid = c.relnamespace);
REVOKE ALL PRIVILEGES ON "baseten".relation_oids FROM PUBLIC;
GRANT SELECT ON "baseten".relation_oids TO basetenread;


CREATE VIEW "baseten".view_pkey_oids AS
    SELECT c.oid, "baseten".array_accum (v.attname) AS attnames
    FROM "baseten".view_pkey v
    INNER JOIN pg_class c ON (c.relname = v.relname)
    INNER JOIN pg_namespace n ON (n.nspname = v.nspname AND n.oid = c.relnamespace)
    GROUP BY c.oid;
REVOKE ALL PRIVILEGES ON "baseten".view_pkey_oids FROM PUBLIC;
GRANT SELECT ON "baseten".view_pkey_oids TO basetenread;


CREATE FUNCTION "baseten"._fkey_columns_max () RETURNS INTEGER AS $$
	SELECT max (array_upper (conkey, 1)) FROM pg_constraint c WHERE c.contype = 'f';
$$ STABLE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._fkey_columns_max () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._fkey_columns_max () TO basetenread;


CREATE VIEW "baseten"._fkey_column_names AS
SELECT 
	c.oid, 
	"baseten".array_accum (a1.attname) AS conkey,
	"baseten".array_accum (a2.attname) AS confkey
FROM pg_constraint c 
INNER JOIN generate_series (1, "baseten"._fkey_columns_max ()) AS s (idx) ON (s.idx <= array_upper (c.conkey, 1))
INNER JOIN pg_attribute a1 ON (a1.attrelid = c.conrelid  AND a1.attnum = c.conkey [s.idx])
INNER JOIN pg_attribute a2 ON (a2.attrelid = c.confrelid AND a2.attnum = c.confkey [s.idx])
GROUP BY c.oid;
REVOKE ALL PRIVILEGES ON "baseten"._fkey_column_names FROM PUBLIC;
GRANT SELECT ON "baseten"._fkey_column_names TO basetenread;


CREATE VIEW "baseten"._foreign_keys AS
SELECT
    c.conname,
    r1.id AS conrelid,
    r2.id AS confrelid,
    f.conkey,
    f.confkey,
    c.confdeltype,
    c2.oid IS NOT NULL AS conkey_is_unique
FROM pg_constraint c
INNER JOIN "baseten"._fkey_column_names f ON (f.oid = c.oid)
INNER JOIN pg_class cl1 ON (cl1.oid = c.conrelid)
INNER JOIN pg_class cl2 ON (cl2.oid = c.confrelid)
INNER JOIN pg_namespace n1 ON (n1.oid = cl1.relnamespace)
INNER JOIN pg_namespace n2 ON (n2.oid = cl2.relnamespace)
INNER JOIN "baseten".relation r1 ON (r1.nspname = n1.nspname AND r1.relname = cl1.relname)
INNER JOIN "baseten".relation r2 ON (r2.nspname = n2.nspname AND r2.relname = cl2.relname)
LEFT OUTER JOIN pg_constraint c2 ON (
    c2.conrelid = c.conrelid AND
    c2.conkey = c.conkey AND
    c2.contype = 'u'
)
WHERE (
    c.contype = 'f'
);
REVOKE ALL PRIVILEGES ON "baseten"._foreign_keys FROM PUBLIC;
GRANT SELECT ON "baseten"._foreign_keys TO basetenread;


CREATE TABLE "baseten".ignored_fkey (
	nspname NAME,
	relname NAME,
	fkeyname NAME,
	PRIMARY KEY (nspname, relname, fkeyname)
);
REVOKE ALL PRIVILEGES ON "baseten".ignored_fkey FROM PUBLIC;
GRANT SELECT ON "baseten".ignored_fkey TO basetenread;


CREATE TABLE "baseten".relationship (
	conid			INTEGER NOT NULL REFERENCES "baseten".foreign_key (conid),
	dstconid		INTEGER REFERENCES "baseten".foreign_key (conid), -- Only used for mtm.
	name			VARCHAR (255) NOT NULL,
	inversename		VARCHAR (255) NOT NULL, --Inverse relationships are currently mandatory.
	kind			CHAR (1) NOT NULL,
	is_inverse		BOOLEAN NOT NULL,
	is_deprecated	BOOLEAN NOT NULL DEFAULT false,
	has_rel_names	BOOLEAN NOT NULL,
	has_views		BOOLEAN NOT NULL DEFAULT false,
	srcid			INTEGER NOT NULL REFERENCES "baseten".relation (id),
	srcnspname		TEXT NOT NULL,
	srcrelname		TEXT NOT NULL,
	dstid			INTEGER NOT NULL REFERENCES "baseten".relation (id),
	dstnspname		TEXT NOT NULL,
	dstrelname		TEXT NOT NULL,
	helperid		INTEGER REFERENCES "baseten".relation (id),
	helpernspname	TEXT,
	helperrelname	TEXT
);
REVOKE ALL PRIVILEGES ON "baseten".relationship FROM PUBLIC;
GRANT SELECT ON "baseten".relationship TO basetenread;


CREATE TABLE "baseten"._deprecated_relationship_name (
	LIKE "baseten".relationship INCLUDING DEFAUlTS INCLUDING CONSTRAINTS INCLUDING INDEXES,
	is_ambiguous BOOLEAN NOT NULL DEFAULT false
);
REVOKE ALL PRIVILEGES ON "baseten"._deprecated_relationship_name FROM PUBLIC;
GRANT SELECT ON "baseten"._deprecated_relationship_name TO basetenread;


-- For modification tracking
CREATE SEQUENCE "baseten".modification_id_seq MAXVALUE 2147483647 CYCLE;
CREATE TABLE "baseten".modification (
	"baseten_modification_id"				INTEGER PRIMARY KEY DEFAULT nextval ('"baseten"."modification_id_seq"'),
	"baseten_modification_relid"			INTEGER NOT NULL REFERENCES "baseten".relation (id),
	"baseten_modification_timestamp"		TIMESTAMP (6) WITHOUT TIME ZONE NULL DEFAULT NULL,
	"baseten_modification_insert_timestamp" TIMESTAMP (6) WITHOUT TIME ZONE NOT NULL DEFAULT clock_timestamp (),
	"baseten_modification_type"				CHAR NOT NULL,
	"baseten_modification_cols"				INT2 [],
	"baseten_modification_backend_pid"		INTEGER NOT NULL DEFAULT pg_backend_pid ()
);
ALTER SEQUENCE "baseten".modification_id_seq OWNED BY "baseten".modification."baseten_modification_id";
REVOKE ALL PRIVILEGES ON SEQUENCE "baseten".modification_id_seq FROM PUBLIC;
REVOKE ALL PRIVILEGES ON "baseten".modification FROM PUBLIC;
GRANT SELECT ON "baseten".modification TO basetenread;
GRANT USAGE ON SEQUENCE "baseten".modification_id_seq TO basetenuser;


CREATE SEQUENCE "baseten".lock_id_seq MAXVALUE 2147483647 CYCLE;
CREATE TABLE "baseten".lock (
	"baseten_lock_id"				INTEGER PRIMARY KEY DEFAULT nextval ('"baseten"."lock_id_seq"'),
	"baseten_lock_relid"			INTEGER NOT NULL REFERENCES "baseten".relation (id),
	"baseten_lock_timestamp"		TIMESTAMP (6) WITHOUT TIME ZONE NOT NULL DEFAULT clock_timestamp (),
	"baseten_lock_query_type"		CHAR (1) NOT NULL DEFAULT 'U',	 -- U == UPDATE, D == DELETE
	"baseten_lock_cleared"			BOOLEAN NOT NULL DEFAULT FALSE,
	"baseten_lock_savepoint_idx"	BIGINT NOT NULL,
	"baseten_lock_backend_pid"		INTEGER NOT NULL DEFAULT pg_backend_pid ()
);
ALTER SEQUENCE "baseten".lock_id_seq OWNED BY "baseten".lock."baseten_lock_id";
REVOKE ALL PRIVILEGES ON SEQUENCE "baseten".lock_id_seq FROM PUBLIC;
REVOKE ALL PRIVILEGES ON "baseten".lock FROM PUBLIC;
GRANT SELECT ON "baseten".lock TO basetenread;
GRANT USAGE ON SEQUENCE "baseten".lock_id_seq TO basetenuser;


-- Functions

CREATE FUNCTION "baseten".version () RETURNS NUMERIC AS $$
	SELECT _bx_version_::NUMERIC;
$$ IMMUTABLE LANGUAGE SQL;
COMMENT ON FUNCTION "baseten".version () IS 'Schema version';
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".version () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".version () TO basetenread;


CREATE FUNCTION "baseten".compatibilityversion () RETURNS NUMERIC AS $$
	SELECT _bx_compat_version_::NUMERIC;
$$ IMMUTABLE LANGUAGE SQL;
COMMENT ON FUNCTION "baseten".compatibilityversion () IS 'Schema compatibility version';
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".compatibilityversion () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".compatibilityversion () TO basetenread;


CREATE FUNCTION "baseten".relation_id (OID) RETURNS INTEGER AS $$
	SELECT r.id
	FROM pg_class c
	INNER JOIN pg_namespace n ON (n.oid = c.relnamespace)
	INNER JOIN "baseten".relation r USING (relname, nspname)
	WHERE c.oid = $1;
$$ STABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".relation_id (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".relation_id (OID) TO basetenread;


CREATE FUNCTION "baseten".relation_id_ex (OID) RETURNS INTEGER AS $$
DECLARE
	relid ALIAS FOR $1;
	retval INTEGER;
BEGIN
	SELECT "baseten".relation_id (relid) INTO STRICT retval;
	IF retval IS NULL THEN
		RAISE EXCEPTION 'Relation with OID % was not found', relid;
	END IF;
	RETURN retval;
END;
$$ STABLE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".relation_id_ex (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".relation_id_ex (OID) TO basetenread;


CREATE FUNCTION "baseten"._view_hierarchy (OID, OID, INTEGER) 
	RETURNS SETOF "baseten".view_type AS $$
DECLARE
	parent ALIAS FOR $1;
	root ALIAS FOR $2;
	generation ALIAS FOR $3;
	currentoid OID;
	retval "baseten".view_type;
	subview "baseten".view_type;
BEGIN
	retval.root = root;
	retval.parent = parent;
	retval.generation = generation::SMALLINT;

	-- Fetch dependent views
	FOR currentoid IN SELECT viewoid FROM "baseten"._view_dependency WHERE reloid = parent
	LOOP
		retval.oid := currentoid;
		RETURN NEXT retval;

		-- Recursion to subviews
		FOR subview IN SELECT * 
		FROM "baseten"._view_hierarchy (currentoid, root, generation + 1) LOOP
			RETURN NEXT subview;
		END LOOP;
	END LOOP;
	RETURN;
END;
$$ STABLE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._view_hierarchy (OID, OID, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._view_hierarchy (OID, OID, INTEGER) TO basetenread;


CREATE FUNCTION "baseten"._view_hierarchy (OID) RETURNS SETOF "baseten".view_type AS $$
DECLARE
	relid ALIAS FOR $1;
	retval "baseten".view_type;
BEGIN
	-- First return the table itself.
	retval.root = relid;
	retval.parent = NULL;
	retval.generation = 0::SMALLINT;
	retval.oid = relid;
	RETURN NEXT retval;

	-- Fetch dependent views.
	FOR retval IN SELECT * FROM "baseten"._view_hierarchy (relid, relid, 1) 
	LOOP
		RETURN NEXT retval;
	END LOOP;
	RETURN;
END;
$$ STABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._view_hierarchy (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._view_hierarchy (OID) TO basetenread;


CREATE FUNCTION "baseten"._rel_view_hierarchy () RETURNS SETOF "baseten".view_type AS $$
DECLARE
	reloid OID;
	retval "baseten".view_type;
BEGIN
	FOR reloid IN 
		SELECT DISTINCT ON (rs.srcid) 
			c.oid 
		FROM "baseten".relationship rs
		INNER JOIN "baseten".relation r ON (r.id = rs.srcid)
		INNER JOIN pg_class c ON (r.relname = c.relname)
		INNER JOIN pg_namespace n ON (r.nspname = n.nspname AND c.relnamespace = n.oid)
	LOOP
		FOR retval IN SELECT * FROM "baseten"._view_hierarchy (reloid)
		LOOP
			RETURN NEXT retval;
		END LOOP;
	END LOOP;
	RETURN;
END;
$$ STABLE LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._rel_view_hierarchy () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._rel_view_hierarchy () TO basetenread;


-- Note that system views aren't correctly listed.
CREATE VIEW "baseten"._view_dependency_v AS 
	SELECT DISTINCT 
		d1.refobjid AS viewoid, 
		n1.oid		AS viewnamespace, 
		n1.nspname	AS viewnspname, 
		c1.relname	AS viewrelname, 
		d2.refobjid AS reloid, 
		c2.relkind	AS relkind, 
		n2.oid		AS relnamespace, 
		n2.nspname	AS relnspname, 
		c2.relname	AS relname 
	FROM pg_depend d1
	INNER JOIN pg_rewrite r ON r.oid = d1.objid AND r.ev_class = d1.refobjid AND rulename = '_RETURN'
	INNER JOIN pg_depend d2 ON r.oid = d2.objid AND d2.refobjid <> d1.refobjid AND d2.deptype = 'n'
	INNER JOIN pg_class c1 ON c1.oid = d1.refobjid AND c1.relkind = 'v'
	INNER JOIN pg_class c2 ON c2.oid = d2.refobjid
	INNER JOIN pg_namespace n1 ON n1.oid = c1.relnamespace
	INNER JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
	INNER JOIN pg_class c3 ON c3.oid = d1.classid AND c3.relname = 'pg_rewrite'
	INNER JOIN pg_class c4 ON c4.oid = d1.refclassid AND c4.relname = 'pg_class'
	WHERE d1.deptype = 'n';
REVOKE ALL PRIVILEGES ON "baseten"._view_dependency_v FROM PUBLIC;
GRANT SELECT ON "baseten"._view_dependency_v TO basetenread;


CREATE TABLE "baseten"._view_dependency AS SELECT * FROM "baseten"._view_dependency_v LIMIT 0;
REVOKE ALL PRIVILEGES ON "baseten"._view_dependency FROM PUBLIC;
GRANT SELECT ON "baseten"._view_dependency TO basetenread;


CREATE VIEW "baseten"._rel_view_hierarchy_v AS
	SELECT
		r1.id,
		r2.id AS root,
		r1.nspname,
		r1.relname,
		r2.nspname AS rootnspname,
		r2.relname AS rootrelname,
		"baseten".array_accum (a.attname) AS attributes
	FROM "baseten"._rel_view_hierarchy () h
	INNER JOIN pg_attribute a ON (a.attrelid = h.oid)
	INNER JOIN pg_class c1 ON (c1.oid = h.oid)
	INNER JOIN pg_class c2 ON (c2.oid = h.root)
	INNER JOIN pg_namespace n1 ON (n1.oid = c1.relnamespace)
	INNER JOIN pg_namespace n2 ON (n2.oid = c2.relnamespace)
	INNER JOIN "baseten".relation r1 ON (n1.nspname = r1.nspname AND c1.relname = r1.relname)
	INNER JOIN "baseten".relation r2 ON (n2.nspname = r2.nspname AND c2.relname = r2.relname)
	GROUP BY r1.id, r2.id, r1.nspname, r1.relname, r2.nspname, r2.relname;
	
	
CREATE TABLE "baseten"._rel_view_hierarchy AS SELECT * FROM "baseten"._rel_view_hierarchy_v LIMIT 0;
REVOKE ALL PRIVILEGES ON "baseten"._rel_view_hierarchy FROM PUBLIC;
GRANT SELECT ON "baseten"._rel_view_hierarchy TO basetenread;


CREATE VIEW "baseten"._rel_view_oneto_v AS
	SELECT
		r.conid,
		COALESCE (h1.id, srcid) AS srcid,
		COALESCE (h2.id, dstid) AS dstid,
		r.kind,
		r.is_inverse
	FROM
		(
			SELECT DISTINCT
				conid,
				srcid,
				dstid,
				kind,
				is_inverse
			FROM "baseten".relationship
			WHERE kind IN ('t', 'o')
		) r
	INNER JOIN "baseten".foreign_key f ON (f.conid = r.conid)
	INNER JOIN "baseten"._rel_view_hierarchy h1 ON (h1.root = r.srcid AND h1.attributes @> (CASE WHEN r.is_inverse THEN f.conkey ELSE f.confkey END))
	INNER JOIN "baseten"._rel_view_hierarchy h2 ON (h2.root = r.dstid AND h2.attributes @> (CASE WHEN r.is_inverse THEN f.confkey ELSE f.conkey END))
	WHERE NOT (h1.id = h1.root AND h2.id = h2.root);


CREATE TABLE "baseten"._rel_view_oneto AS SELECT * FROM "baseten"._rel_view_oneto_v LIMIT 0;
REVOKE ALL PRIVILEGES ON "baseten"._rel_view_oneto FROM PUBLIC;
GRANT SELECT ON "baseten"._rel_view_oneto TO basetenread;


CREATE VIEW "baseten"._rel_view_manytomany_v AS
	SELECT
		r.conid,
		r.dstconid,
		COALESCE (h1.id, r.srcid) AS srcid,
		COALESCE (h2.id, r.dstid) AS dstid,
		r.helperid
	FROM
		(
			SELECT DISTINCT ON (conid, dstconid, srcid, dstid) 
				conid,
				dstconid,
				srcid,
				dstid,
				helperid
			FROM "baseten".relationship
			WHERE kind = 'm'
		) r
	INNER JOIN "baseten".foreign_key f1 ON (f1.conid = r.conid)
	INNER JOIN "baseten".foreign_key f2 ON (f2.conid = r.dstconid)
	INNER JOIN "baseten"._rel_view_hierarchy h1 ON (h1.root = r.srcid AND h1.attributes @> f1.confkey)
	INNER JOIN "baseten"._rel_view_hierarchy h2 ON (h2.root = r.dstid AND h2.attributes @> f2.confkey)
	WHERE NOT (h1.id = h1.root AND h2.id = h2.root);


CREATE TABLE "baseten"._rel_view_manytomany AS SELECT * FROM "baseten"._rel_view_manytomany_v LIMIT 0;
REVOKE ALL PRIVILEGES ON "baseten"._rel_view_manytomany FROM PUBLIC;
GRANT SELECT ON "baseten"._rel_view_manytomany TO basetenread;


CREATE FUNCTION "baseten"._assign_relation_ids () RETURNS VOID AS $$
	DELETE FROM "baseten".relation r 
	WHERE ROW (r.relname, r.nspname, r.relkind) NOT IN (
		SELECT c.relname, n.nspname, c.relkind
		FROM pg_class c
		INNER JOIN pg_namespace n ON (c.relnamespace = n.oid)
		WHERE c.relkind IN ('r', 'v')
	);

	INSERT INTO "baseten".relation (relname, nspname, relkind)
		SELECT c.relname, n.nspname, c.relkind
		FROM pg_class c
		INNER JOIN pg_namespace n ON (c.relnamespace = n.oid)
		WHERE 
			c.relkind IN ('r', 'v') AND
			NOT (
				n.nspname = 'baseten' OR
				n.nspname = 'information_schema' OR
				n.nspname LIKE 'pg_%' OR
				ROW (c.relname, n.nspname) IN (
					SELECT r.relname, r.nspname FROM "baseten".relation r
				) 
			);
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._assign_relation_ids () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._assign_relation_ids () TO basetenowner;


CREATE FUNCTION "baseten"._assign_foreign_key_ids () RETURNS VOID AS $$
    -- Remove foreign keys where they don't match exactly.
    DELETE FROM "baseten".foreign_key
    WHERE ROW (
        conname,
        conrelid,
        confrelid,
        conkey,
        confkey,
        confdeltype,
        conkey_is_unique
    ) NOT IN (
        SELECT
            conname,
            conrelid,
            confrelid,
            conkey,
            confkey,
            confdeltype,
            conkey_is_unique
        FROM "baseten"._foreign_keys
    );

    INSERT INTO "baseten".foreign_key (
        conname,
        conrelid,
        confrelid,
        conkey,
        confkey,
        confdeltype,
        conkey_is_unique
    )
    SELECT
        fk.conname,
        fk.conrelid,
        fk.confrelid,
        fk.conkey,
        fk.confkey,
        fk.confdeltype,
        fk.conkey_is_unique
    FROM "baseten"._foreign_keys fk
    INNER JOIN "baseten".relation r ON (r.id = fk.conrelid)
    WHERE (NOT (
        (ROW (r.nspname, r.relname, fk.conname) IN (SELECT * FROM "baseten".ignored_fkey)) OR
        (ROW (fk.conrelid, fk.conname) IN (
            SELECT conrelid, conname
            FROM "baseten".foreign_key
        ))
    ));
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._assign_foreign_key_ids () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._assign_foreign_key_ids () TO basetenowner;


CREATE FUNCTION "baseten".assign_internal_ids () RETURNS VOID AS $$
	SELECT "baseten"._assign_relation_ids ();
	SELECT "baseten"._assign_foreign_key_ids ();
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".assign_internal_ids () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".assign_internal_ids () TO basetenowner;


CREATE FUNCTION "baseten".refresh_view_caches () RETURNS void AS $$
	TRUNCATE 
		"baseten"._view_dependency, 
		"baseten"._rel_view_hierarchy, 
		"baseten"._rel_view_oneto, 
		"baseten"._rel_view_manytomany;
	INSERT INTO "baseten"._view_dependency		SELECT * from "baseten"._view_dependency_v;
	INSERT INTO "baseten"._rel_view_hierarchy	SELECT * from "baseten"._rel_view_hierarchy_v;
	INSERT INTO "baseten"._rel_view_oneto		SELECT * from "baseten"._rel_view_oneto_v;
	INSERT INTO "baseten"._rel_view_manytomany	SELECT * from "baseten"._rel_view_manytomany_v;
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".refresh_view_caches () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".refresh_view_caches () TO basetenowner;


CREATE VIEW "baseten"._rel_table_oneto AS
	SELECT -- MTO, OTO
		f.conid,
		CASE WHEN 1 = COALESCE (g.idx, 1) THEN 
			COALESCE ("baseten".split_part (f.conname, '__', 1), r1.nspname || '_' || r1.relname || '_' || f.conname)
		ELSE 
			r2.relname::TEXT
		END AS name,
		CASE WHEN 1 = COALESCE (g.idx, 1) THEN 
			COALESCE ("baseten".split_part (f.conname, '__', 2), r1.nspname || '_' || r1.relname || '_' || f.conname)
		ELSE 
			r1.relname::TEXT || CASE WHEN f.conkey_is_unique THEN '' ELSE 'Set' END
		END AS inversename,
		CASE WHEN true = f.conkey_is_unique THEN 'o' ELSE 't' END AS kind,
		true AS is_inverse,
		2 = COALESCE (g.idx, 1) AS has_rel_names,
		f.conrelid AS srcid,
		r1.nspname AS srcnspname,
		r1.relname AS srcrelname,
		f.confrelid AS dstid,
		r2.nspname AS dstnspname,
		r2.relname AS dstrelname
	FROM "baseten".foreign_key f
	INNER JOIN "baseten".relation r1 ON (r1.id = f.conrelid)
	INNER JOIN "baseten".relation r2 ON (r2.id = f.confrelid)
	LEFT JOIN generate_series (1, 2) g (idx) ON (NOT (r2.relname = split_part (f.conname, '__', 1) OR r1.relname = split_part (f.conname, '__', 2)))
	--WHERE r1.enabled = true AND r2.enabled = true
	UNION ALL
	SELECT -- OTM, OTO
		f.conid,
		CASE WHEN 1 = COALESCE (g.idx, 1) THEN 
			COALESCE ("baseten".split_part (f.conname, '__', 2), r1.nspname || '_' || r1.relname || '_' || f.conname)
		ELSE 
			r1.relname::TEXT || CASE WHEN f.conkey_is_unique THEN '' ELSE 'Set' END
		END AS bane,
		CASE WHEN 1 = COALESCE (g.idx, 1) THEN 
			COALESCE ("baseten".split_part (f.conname, '__', 1), r1.nspname || '_' || r1.relname || '_' || f.conname)
		ELSE 
			r2.relname::TEXT
		END AS inversename,
		CASE WHEN true = f.conkey_is_unique THEN 'o' ELSE 't' END AS kind,
		false AS is_inverse,
		2 = COALESCE (g.idx, 1) AS has_rel_names,
		f.confrelid AS srcid,
		r2.nspname AS srcnspname,
		r2.relname AS srcrelname,
		f.conrelid AS dstid,
		r1.nspname AS dstnspname,
		r1.relname AS dstrelname
	FROM "baseten".foreign_key f
	INNER JOIN "baseten".relation r1 ON (r1.id = f.conrelid)
	INNER JOIN "baseten".relation r2 ON (r2.id = f.confrelid)
	LEFT JOIN generate_series (1, 2) g (idx) ON (NOT (r2.relname = split_part (f.conname, '__', 1) OR r1.relname = split_part (f.conname, '__', 2)));
	--WHERE r1.enabled = true AND r2.enabled = true;


CREATE VIEW "baseten"._rel_table_manytomany AS
	SELECT
		f1.conid AS conid,
		f2.conid AS dstconid,
		CASE WHEN 1 = COALESCE (g.idx, 1) THEN f1.conname ELSE r2.relname || 'Set' END AS name,
		CASE WHEN 1 = COALESCE (g.idx, 1) THEN f2.conname ELSE r1.relname || 'Set' END AS inversename,
		'm' AS kind,
		false AS is_inverse,
		2 = COALESCE (g.idx, 1) AS has_rel_names,
		f1.confrelid AS srcid,
		r1.nspname AS srcnspname,
		r1.relname AS srcrelname,
		f2.confrelid AS dstid,
		r2.nspname AS dstnspname,
		r2.relname AS dstrelname,
		f1.conrelid AS helperid,
		rh.nspname AS helpernspname,
		rh.relname AS helperrelname
	FROM "baseten".foreign_key f1
	INNER JOIN "baseten".foreign_key f2 ON (f1.conrelid = f2.conrelid AND f1.confrelid <> f2.confrelid)
	INNER JOIN (
		SELECT 
			conrelid,
			COUNT (conid) AS count
		FROM "baseten".foreign_key
		GROUP BY conrelid
	) c ON (c.conrelid = f1.conrelid AND 2 = c.count)
	INNER JOIN "baseten".relation rh ON (rh.id = f1.conrelid)
	INNER JOIN pg_class ch ON (ch.relname = rh.relname)
	INNER JOIN pg_namespace nh ON (nh.oid = ch.relnamespace AND nh.nspname = rh.nspname)
	INNER JOIN (
		SELECT
			c.conrelid AS reloid,
			"baseten".array_accum (a.attname) AS attnames
		FROM pg_constraint c
		INNER JOIN pg_attribute a ON (a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey))
		WHERE c.contype = 'p'
		GROUP BY c.conrelid
	) p ON (p.reloid = ch.oid AND p.attnames @> (f1.conkey || f2.conkey))
	INNER JOIN "baseten".relation r1 ON (r1.id = f1.confrelid)
	INNER JOIN "baseten".relation r2 ON (r2.id = f2.confrelid)
	LEFT JOIN generate_series (1, 2) g (idx) ON (NOT (r2.relname = f1.conname OR r1.relname = f2.conname));
	--WHERE r1.enabled = true AND r2.enabled = true;


CREATE VIEW "baseten"._rel_view AS
	SELECT
		rel.conid,
		rel.dstconid,
		r2.relname || CASE WHEN 'm' = rel.kind OR ('t' = rel.kind AND rel.is_inverse = false) THEN 'Set' ELSE '' END AS name,
		r1.relname || CASE WHEN 'm' = rel.kind OR ('t' = rel.kind AND rel.is_inverse = true)  THEN 'Set' ELSE '' END AS inversename,
		rel.kind,
		rel.is_inverse,
		true AS has_rel_names,
		true AS has_views,
		rel.srcid,
		r1.nspname AS srcnspname,
		r1.relname AS srcrelname,
		rel.dstid,
		r2.nspname AS dstnspname,
		r2.relname AS dstrelname,
		rel.helperid,
		r3.nspname AS helpernspname,
		r3.relname AS helperrelname
	FROM
		(
			SELECT 
				conid,
				null::INTEGER AS dstconid,
				kind,
				is_inverse,
				srcid,
				dstid,
				null::INTEGER AS helperid
			FROM "baseten"._rel_view_oneto
			UNION ALL
			SELECT
				conid,
				dstconid,
				'm' AS kind,
				false AS is_inverse,
				srcid,
				dstid,
				helperid
			FROM "baseten"._rel_view_manytomany
		) rel
	INNER JOIN "baseten".relation r1 ON (r1.id = rel.srcid)
	INNER JOIN "baseten".relation r2 ON (r2.id = rel.dstid)
	LEFT OUTER JOIN "baseten".relation r3 ON (r3.id = rel.helperid);
	--WHERE r1.enabled = true AND r2.enabled = true AND (
    --    r3.id IS NULL OR r3.enabled = true
    --);


CREATE FUNCTION "baseten"._insert_relationships () RETURNS VOID AS $$
	SELECT "baseten".assign_internal_ids ();

	-- OTO, OTM
	INSERT INTO "baseten".relationship
		(
			conid,
			name,
			inversename,
			kind,
			is_inverse,
			has_rel_names,
			srcid,
			srcnspname,
			srcrelname,
			dstid,
			dstnspname,
			dstrelname
		)
		SELECT * FROM "baseten"._rel_table_oneto;
		
	-- MTM
	INSERT INTO "baseten".relationship
		(
			conid,
			dstconid,
			name,
			inversename,
			kind,
			is_inverse,
			has_rel_names,
			srcid,
			srcnspname,
			srcrelname,
			dstid,
			dstnspname,
			dstrelname,
			helperid,
			helpernspname,
			helperrelname
		)
		SELECT * FROM "baseten"._rel_table_manytomany;
    
	-- Views
	SELECT "baseten".refresh_view_caches ();
	INSERT INTO "baseten".relationship
		(
			conid,
			dstconid,
			name,
			inversename,
			kind,
			is_inverse,
			has_rel_names,
			has_views,
			srcid,
			srcnspname,
			srcrelname,
			dstid,
			dstnspname,
			dstrelname,
			helperid,
			helpernspname,
			helperrelname
		)
		SELECT * FROM "baseten"._rel_view;
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._insert_relationships () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._insert_relationships () TO basetenowner;


CREATE FUNCTION "baseten"._insert_deprecated_relationships () RETURNS VOID AS $$
	-- Deprecated names
	INSERT INTO "baseten"._deprecated_relationship_name
		SELECT
			conid,
			dstconid,
			substring (name from 1 for length (name) - 3) AS name, -- Remove 'Set'
			substring (inversename from 1 for length (inversename) - 3) AS inversename, -- Remove 'Set'
			kind,
			is_inverse,
			true AS is_deprecated,
			has_rel_names,
			has_views,
			srcid,
			srcnspname,
			srcrelname,
			dstid,
			dstnspname,
			dstrelname,
			helperid,
			helpernspname,
			helperrelname,
			false AS is_ambiguous
		FROM "baseten".relationship
		WHERE kind = 'm' AND has_rel_names = true
		UNION ALL
		SELECT
			conid,
			dstconid,
			name || '__deprecation_placeholder' AS name,
			substring (inversename from 1 for length (inversename) - 3) AS inversename, -- Remove 'Set'
			kind,
			is_inverse,
			true AS is_deprecated,
			has_rel_names,
			has_views,
			srcid,
			srcnspname,
			srcrelname,
			dstid,
			dstnspname,
			dstrelname,
			helperid,
			helpernspname,
			helperrelname,
			false AS is_ambiguous
		FROM "baseten".relationship
		WHERE kind = 't' AND has_rel_names = true AND is_inverse = true
		UNION ALL
		SELECT
			conid,
			dstconid,
			substring (name from 1 for length (name) - 3) AS name, -- Remove 'Set'
			inversename || '__deprecation_placeholder' AS inversename,
			kind,
			is_inverse,
			true AS is_deprecated,
			has_rel_names,
			has_views,
			srcid,
			srcnspname,
			srcrelname,
			dstid,
			dstnspname,
			dstrelname,
			helperid,
			helpernspname,
			helperrelname,
			false AS is_ambiguous
		FROM "baseten".relationship
		WHERE kind = 't' AND has_rel_names = true AND is_inverse = false;
	
	-- Mark relationships that have to-one duplicates.
	UPDATE "baseten"._deprecated_relationship_name d
		SET is_ambiguous = true
		FROM "baseten".relationship r
		WHERE 
			d.name = r.name AND
			d.srcnspname = r.srcnspname AND
			d.srcrelname = r.srcrelname;
	
	-- Mark duplicates' inverse relationships.
	UPDATE "baseten"._deprecated_relationship_name d1
		SET is_ambiguous = true
		FROM "baseten"._deprecated_relationship_name d2
		WHERE 
			d1.conid = d2.conid AND
			d1.kind = d2.kind AND
			d1.kind IN ('t', 'o') AND
			d2.is_ambiguous = true;
	UPDATE "baseten"._deprecated_relationship_name d1
		SET is_ambiguous = true
		FROM "baseten"._deprecated_relationship_name d2
		WHERE
			d1.conid = d2.conid AND
			d1.dstconid = d2.dstconid AND
			d1.kind = d2.kind AND
			d1.kind = 'm' AND
			d2.is_ambiguous = true;
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._insert_deprecated_relationships () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._insert_deprecated_relationships () TO basetenowner;


CREATE FUNCTION "baseten"._remove_ambiguous_relationships () RETURNS VOID AS $$
	DELETE FROM "baseten".relationship r1
	USING (
		SELECT name, srcid 
		FROM (
			SELECT 
				count (name), 
				name, 
				srcid 
			FROM baseten.relationship 
			GROUP BY name, srcid
		) r
		WHERE r.count = 2
	) r2
	WHERE r1.name = r2.name AND r1.srcid = r2.srcid;
	
	DELETE FROM "baseten".relationship r1
	USING (
		SELECT 
			r1.name, 
			r1.srcid 
		FROM baseten.relationship r1 
		LEFT OUTER JOIN baseten.relationship r2 ON (
			r1.inversename = r2.name AND
			r1.name = r2.inversename AND
			r1.dstid = r2.srcid AND 
			r1.srcid = r2.dstid 
		)
		WHERE r2.conid IS NULL
	) r2
	WHERE r1.name = r2.name AND r1.srcid = r2.srcid;
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._remove_ambiguous_relationships () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._remove_ambiguous_relationships () TO basetenowner;


CREATE FUNCTION "baseten"._mod_notification (OID) RETURNS TEXT AS $$
	SELECT 'baseten_mod__' || "baseten".relation_id_ex ($1);
$$ STABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._mod_notification (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._mod_notification (OID) TO basetenread;


CREATE FUNCTION "baseten"._mod_table (INTEGER) RETURNS TEXT AS $$
	SELECT 'mod__' || $1;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._mod_table (INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._mod_table (INTEGER) TO basetenread;


CREATE FUNCTION "baseten"._mod_table (OID) RETURNS TEXT AS $$
	SELECT 'mod__' || "baseten".relation_id_ex ($1);
$$ STABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._mod_table (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._mod_table (OID) TO basetenread;


-- Returns the modification rule or trigger name associated with the given operation.
CREATE FUNCTION "baseten"._mod_rule (TEXT)
RETURNS TEXT AS $$
	SELECT '~baseten_modification_' || upper ($1);
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._mod_rule (TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._mod_rule (TEXT) TO basetenread;


CREATE FUNCTION "baseten"._mod_insert_fn (OID)
RETURNS TEXT AS $$
	SELECT 'mod_insert_fn__' || "baseten".relation_id_ex ($1);
$$ STABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._mod_insert_fn (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._mod_insert_fn (OID) TO basetenread;


CREATE FUNCTION "baseten"._lock_fn (INTEGER) RETURNS TEXT AS $$
	SELECT 'lock_fn__' || $1;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._lock_fn (INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._lock_fn (INTEGER) TO basetenread;


CREATE FUNCTION "baseten"._lock_fn (OID) RETURNS TEXT AS $$
	SELECT 'lock_fn__' || "baseten".relation_id_ex ($1);
$$ STABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._lock_fn (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._lock_fn (OID) TO basetenread;


CREATE FUNCTION "baseten"._lock_table (INTEGER) RETURNS TEXT AS $$
	SELECT 'lock__' || $1;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._lock_table (INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._lock_table (INTEGER) TO basetenread;


CREATE FUNCTION "baseten"._lock_table (OID) RETURNS TEXT AS $$
	SELECT 'lock__' || "baseten".relation_id_ex ($1);
$$ STABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._lock_table (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._lock_table (OID) TO basetenread;


CREATE FUNCTION "baseten"._lock_notification (INTEGER) RETURNS TEXT AS $$
	SELECT 'baseten_lock__' || $1;
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._lock_notification (INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._lock_notification (INTEGER) TO basetenread;


CREATE FUNCTION "baseten"._lock_notification (OID) RETURNS TEXT AS $$
	SELECT 'baseten_lock__' || "baseten".relation_id_ex ($1);
$$ STABLE CALLED ON NULL INPUT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten"._lock_notification (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten"._lock_notification (OID) TO basetenread;


CREATE VIEW "baseten".pending_locks AS
	SELECT 
		baseten_lock_relid AS relid, 
		max (baseten_lock_timestamp) AS last_date, 
		"baseten"._lock_table (baseten_lock_relid) AS lock_table_name 
	FROM "baseten".lock 
	WHERE baseten_lock_cleared = true AND baseten_lock_backend_pid != pg_backend_pid ()
	GROUP BY relid, lock_table_name;
REVOKE ALL PRIVILEGES ON "baseten".pending_locks FROM PUBLIC;
GRANT SELECT ON "baseten".pending_locks TO basetenread;


-- Removes tracked modifications which are older than 5 minutes and set the modification timestamps 
-- that have been left to null values from the last commit. Since the rows that have the same 
-- backend PID as the current process might not yet be visible to other transactions. 
-- FIXME: If we knew the current transaction status, the WHERE clause could be rewritten as follows:
-- WHERE "baseten_modification_timestamp" IS NULL 
--	   AND ("baseten_modification_backend_pid" != pg_backend_pid () OR pg_xact_status = 'IDLE');
-- Also, if the connection is not autocommitting, we might end up doing some unnecessary work.
-- For now, we trust the user to set the function parameter if the performing connection isn't in the
-- middle of a transaction.
CREATE FUNCTION "baseten".mod_cleanup (BOOLEAN) RETURNS VOID AS $$
	DELETE FROM "baseten".modification 
		WHERE "baseten_modification_timestamp" < CURRENT_TIMESTAMP - INTERVAL '5 minutes';
	UPDATE "baseten".modification SET "baseten_modification_timestamp" = clock_timestamp ()
		WHERE "baseten_modification_timestamp" IS NULL AND ($1 OR "baseten_modification_backend_pid" != pg_backend_pid ());
$$ VOLATILE CALLED ON NULL INPUT LANGUAGE SQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".mod_cleanup (BOOLEAN) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".mod_cleanup (BOOLEAN) TO basetenread;


-- A trigger function for notifying the front ends and removing old tracked modifications
CREATE FUNCTION "baseten".mod_notify () RETURNS TRIGGER AS $$
BEGIN
	EXECUTE 'NOTIFY ' || TG_ARGV [0];
	RETURN NEW;
END;
$$ VOLATILE LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".mod_notify () FROM PUBLIC;


-- Removes tracked locks for which a backend no longer exists
-- FIXME: add a check to the function to ensure that the connection is autocommitting
CREATE FUNCTION "baseten".lock_cleanup () RETURNS VOID AS $$ 
	DELETE FROM "baseten".lock
		WHERE ("baseten_lock_timestamp" < pg_postmaster_start_time ()) -- Locks cannot be older than postmaster
			OR ("baseten_lock_backend_pid" NOT IN  (SELECT pid FROM "baseten".running_backend_pids () AS r (pid))) -- Locks have to be owned by a running backend
			OR ("baseten_lock_cleared" = true AND "baseten_lock_timestamp" < CURRENT_TIMESTAMP - INTERVAL '5 minutes'); -- Cleared locks older than 5 minutes may be removed
$$ VOLATILE LANGUAGE SQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".lock_cleanup () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".lock_cleanup () TO basetenread;


-- Unlock for this connection.
CREATE FUNCTION "baseten".lock_unlock () RETURNS VOID AS $$ 
	UPDATE "baseten".lock 
	SET "baseten_lock_cleared" = true, "baseten_lock_timestamp" = CURRENT_TIMESTAMP 
	WHERE "baseten_lock_backend_pid" = pg_backend_pid ()
		AND "baseten_lock_timestamp" < CURRENT_TIMESTAMP;
	NOTIFY "baseten_unlocked_locks";
$$ VOLATILE LANGUAGE SQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".lock_unlock () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".lock_unlock () TO basetenuser;


-- Step back lock marks
CREATE FUNCTION "baseten".lock_step_back () RETURNS VOID AS $$ 
	UPDATE "baseten".lock 
	SET "baseten_lock_cleared" = true, "baseten_lock_timestamp" = CURRENT_TIMESTAMP 
	WHERE baseten_lock_backend_pid = pg_backend_pid () 
		AND "baseten_lock_savepoint_idx" = 
			(SELECT max ("baseten_lock_savepoint_idx") 
			 FROM "baseten".lock
			 WHERE "baseten_lock_backend_pid" = pg_backend_pid ()
			);
	NOTIFY "baseten_unlocked_locks";
$$ VOLATILE LANGUAGE SQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".lock_step_back () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".lock_step_back () TO basetenuser;


-- A trigger function for notifying the front ends and removing old tracked locks
CREATE FUNCTION "baseten".lock_notify () RETURNS TRIGGER AS $$
BEGIN
	PERFORM "baseten".lock_cleanup ();
	EXECUTE 'NOTIFY ' || TG_ARGV [0];
	RETURN NEW;
END;
$$ VOLATILE LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".lock_notify () FROM PUBLIC;


CREATE FUNCTION "baseten".is_enabled (INTEGER) RETURNS boolean AS $$
	SELECT CASE WHEN 1 = COUNT (r.id) THEN true ELSE false END
	FROM "baseten".relation r
	WHERE r.id = $1 AND r.enabled = true;
$$ STABLE STRICT LANGUAGE SQL;
COMMENT ON FUNCTION "baseten".is_enabled (INTEGER) IS 'Checks for observing compatibility. Returns a boolean.';
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".is_enabled (INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".is_enabled (INTEGER) TO basetenread;


CREATE FUNCTION "baseten".is_enabled (OID) RETURNS boolean AS $$
	SELECT "baseten".is_enabled ("baseten".relation_id ($1));
$$ STABLE STRICT LANGUAGE SQL;
COMMENT ON FUNCTION "baseten".is_enabled (OID) IS 'Checks for observing compatibility. Returns a boolean.';
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".is_enabled (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".is_enabled (OID) TO basetenread;


CREATE FUNCTION "baseten".is_enabled_ex (INTEGER) RETURNS VOID AS $$
BEGIN
	IF NOT ("baseten".is_enabled ($1)) THEN
		RAISE EXCEPTION 'Relation with ID % has not been enabled', $1;
	END IF;
	RETURN;
END;
$$ VOLATILE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".is_enabled_ex (INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".is_enabled_ex (INTEGER) TO basetenread;


CREATE FUNCTION "baseten".is_enabled_ex (OID) RETURNS VOID AS $$
BEGIN
	IF NOT ("baseten".is_enabled ($1)) THEN
		RAISE EXCEPTION 'Relation with OID % has not been enabled', $1;
	END IF;
	RETURN;
END;
$$ VOLATILE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".is_enabled_ex (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".is_enabled_ex (OID) TO basetenread;


-- A convenience function for observing modifications
-- Subscribes the caller to receive the approppriate notification
CREATE FUNCTION "baseten".mod_observe (OID) RETURNS "baseten".observation_type AS $$
DECLARE
	reloid ALIAS FOR $1;
	relid INTEGER;
	nname TEXT;
	retval "baseten".observation_type;
BEGIN
	PERFORM "baseten".is_enabled_ex (reloid);
	SELECT "baseten".relation_id_ex (reloid) INTO STRICT relid;
	nname := "baseten"._mod_notification (reloid);
	--RAISE NOTICE 'Observing: %', nname;
	EXECUTE 'LISTEN ' || quote_ident (nname);

	retval := (relid, nname, null::TEXT, null::TEXT);
	RETURN retval;
END;
$$ VOLATILE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".mod_observe (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".mod_observe (OID) TO basetenread;


CREATE FUNCTION "baseten".mod_observe_stop (OID) RETURNS VOID AS $$
DECLARE 
	relid ALIAS FOR $1;
BEGIN
	EXECUTE 'UNLISTEN ' || quote_ident ("baseten"._mod_notification (relid));
	RETURN;
END;
$$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".mod_observe_stop (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".mod_observe_stop (OID) TO basetenread;


-- A convenience function for observing locks
-- Subscribes the caller to receive the approppriate notification
CREATE FUNCTION "baseten".lock_observe (OID) RETURNS "baseten".observation_type AS $$
DECLARE
	reloid ALIAS FOR $1;
	relid INTEGER;
	nname TEXT;
	retval "baseten".observation_type;
BEGIN
	PERFORM "baseten".is_enabled_ex (reloid);
	SELECT "baseten".relation_id_ex (reloid) INTO STRICT relid;
	nname := "baseten"._lock_notification (relid);
	--RAISE NOTICE 'Observing: %', nname;
	EXECUTE 'LISTEN ' || quote_ident (nname);

	retval := (relid, nname, "baseten"._lock_fn (relid), "baseten"._lock_table (relid));
	RETURN retval;
END;
$$ VOLATILE CALLED ON NULL INPUT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".lock_observe (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".lock_observe (OID) TO basetenuser;


CREATE FUNCTION "baseten".lock_observe_stop (OID) RETURNS VOID AS $$
DECLARE 
	relid ALIAS FOR $1;
BEGIN
	EXECUTE 'UNLISTEN ' || quote_ident ("baseten"._lock_notification (relid));
	RETURN;
END;
$$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".lock_observe_stop (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".lock_observe_stop (OID) TO basetenuser;


-- Remove the modification tracking table, rules and the trigger
CREATE FUNCTION "baseten".disable (OID) RETURNS "baseten".reltype AS $$
DECLARE
	retval "baseten"."reltype";
BEGIN	 
	EXECUTE 'DROP FUNCTION IF EXISTS "baseten".' || "baseten"._mod_insert_fn ($1) || ' () CASCADE';
	EXECUTE 'DROP TABLE IF EXISTS "baseten".' || "baseten"._lock_table ($1) || ' CASCADE';
	EXECUTE 'DROP TABLE IF EXISTS "baseten".' || "baseten"._mod_table ($1) || ' CASCADE';
	UPDATE "baseten".relation r SET enabled = false WHERE r.id = "baseten".relation_id_ex ($1);
	retval := "baseten".reltype ($1);
	RETURN retval;
END;
$$ VOLATILE CALLED ON NULL INPUT LANGUAGE PLPGSQL SECURITY DEFINER;
COMMENT ON FUNCTION "baseten".disable (OID) IS 'Removes BaseTen tables for a specific relation';
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".disable (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".disable (OID) TO basetenowner;


-- A helper function
CREATE FUNCTION "baseten".enable_table_insert (OID, TEXT []) 
RETURNS VOID AS $marker$
DECLARE
	relid	ALIAS FOR $1;
	pkey	TEXT [] DEFAULT $2;
	rel		"baseten".reltype;
	query	TEXT;
	mtable	TEXT;
	fname	TEXT;
	fdecl	TEXT;
BEGIN
	SELECT "baseten"._mod_table (relid) INTO STRICT mtable;
	SELECT "baseten"._mod_insert_fn (relid) INTO STRICT fname;
	rel := "baseten".reltype (relid);
	-- Trigger functions cannot be written in SQL
	fdecl :=
		'CREATE OR REPLACE FUNCTION ' || "baseten".quote_ident_bx (fname) || ' () RETURNS TRIGGER AS $$ ' ||
		'BEGIN ' ||
			'INSERT INTO ' || "baseten".quote_ident_bx (mtable) || ' (' ||
				'"baseten_modification_type", "baseten_modification_cols", ' || array_to_string (pkey, ', ') ||
			') VALUES (' || 
				'''I'', null, ' || array_to_string ("baseten".array_prepend_each ('NEW.', pkey), ', ') || 
			'); ' ||
			'RETURN NEW; ' ||
		'END; ' ||
		'$$ VOLATILE LANGUAGE PLPGSQL SECURITY DEFINER';
	query := 
		'CREATE TRIGGER ' || quote_ident ("baseten"._mod_rule ('INSERT')) || ' ' ||
			'AFTER INSERT ON ' || "baseten".quote_ident (rel) || ' ' || 
			'FOR EACH ROW EXECUTE PROCEDURE ' || "baseten".quote_ident_bx (fname) || ' ()'; 
	EXECUTE fdecl;
	EXECUTE query;
	EXECUTE 'REVOKE ALL PRIVILEGES ON FUNCTION ' || "baseten".quote_ident_bx (fname) || ' () FROM PUBLIC';
	RETURN;
END;
$marker$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_table_insert (OID, TEXT []) FROM PUBLIC;


-- Another helper function
CREATE FUNCTION "baseten".enable_view_insert_default (OID, TEXT) 
RETURNS VOID AS $marker$
DECLARE
	relid			ALIAS FOR $1;
	default_value	ALIAS FOR $2;
	rel				"baseten".reltype;
	query			TEXT;
	insertion		TEXT;
BEGIN
	rel := "baseten".reltype (relid);
	insertion := 
		'INSERT INTO ' || "baseten".quote_ident_bx ("baseten"._mod_table (relid)) || ' (' ||
			'"baseten_modification_type", "baseten_modification_cols", id' ||
		') VALUES (' || 
			'''I'', null, ' || default_value || 
		')';
	query := 
		'CREATE RULE ' || quote_ident ("baseten"._mod_rule ('INSERT')) || ' ' ||
		'AS ON INSERT TO ' || quote_ident (rel) || ' ' ||
		'DO ALSO (' || insertion || ');';
	EXECUTE query;
	RETURN;
END;
$marker$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_view_insert_default (OID, TEXT) FROM PUBLIC;


-- Another helper function
CREATE FUNCTION "baseten".enable_update_non_pkey (OID, TEXT []) RETURNS VOID AS $$
DECLARE
	relid				ALIAS FOR $1;
	pkey				TEXT [] DEFAULT $2;
	rel					"baseten".reltype;
	atts				INTEGER DEFAULT 0;
	query				TEXT;
	comparisons_decl	TEXT;
	indices_decl		TEXT;
BEGIN
	SELECT
		COUNT (a.attname),
		array_to_string (
			"baseten".array_accum (
				'"baseten".same (OLD.' || quote_ident (a.attname) || ', NEW.' || quote_ident (a.attname) || ')'
			), ', '
		),
		'ARRAY [' || array_to_string (
			"baseten".array_accum (
				a.attnum
			), ', '
		) || ']::INT2 []'
	FROM pg_attribute a
	LEFT JOIN "baseten"._primary_key pk ON (
		pk.oid = relid AND
		pk.attnum = a.attnum
	)
	WHERE (
		a.attrelid = relid AND 
		1 <= a.attnum AND
		pk.id IS NULL
	)
	INTO STRICT atts, comparisons_decl, indices_decl;

	IF 0 < atts THEN
		-- Row-wise comparison cannot be used in the WHERE clause because it requires a btree operator.
		rel := "baseten".reltype (relid);
		query := 
			'CREATE RULE ' || quote_ident ("baseten"._mod_rule ('UPDATE')) || ' ' ||
			'AS ON UPDATE TO ' || "baseten".quote_ident (rel) || ' ' ||
			'WHERE ' || "baseten".enable_update_where_clause (pkey) || ' ' ||
			'DO ALSO (' ||
				'INSERT INTO ' || "baseten".quote_ident_bx ("baseten"._mod_table (relid)) || ' (' ||
					'"baseten_modification_type", "baseten_modification_cols", ' || array_to_string (pkey, ', ') ||
				') SELECT ' ||
					'''U'', ' ||
					'"baseten".false_indices (ARRAY [' || comparisons_decl || ']::BOOLEAN [], ' || indices_decl || '), ' ||
					array_to_string ("baseten".array_prepend_each ('NEW.', pkey), ', ') || ' ' ||
				'WHERE false IN (' || comparisons_decl || ')' ||
			');';
		EXECUTE query;
	END IF;
	RETURN;
END;
$$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_update_non_pkey (OID, TEXT []) FROM PUBLIC;


-- Another helper function
CREATE FUNCTION "baseten".enable_other (TEXT, OID, TEXT [])
RETURNS VOID AS $$
DECLARE
	querytype		TEXT DEFAULT $1;
	relid			ALIAS FOR $2;
	pkey			TEXT [] DEFAULT $3;
	rel				"baseten".reltype;
	query			TEXT;
	insertion		TEXT;
	whereclause		TEXT DEFAULT '';
BEGIN
	querytype	:= upper (querytype);
	rel := "baseten".reltype (relid);

	IF querytype = 'INSERT' THEN
		insertion := "baseten".enable_insert_query (relid, 'I', 'NEW.', pkey);
	ELSIF querytype = 'DELETE' THEN
		insertion := "baseten".enable_insert_query (relid, 'D', 'OLD.', pkey);
	ELSIF (querytype = 'UPDATE') OR (querytype = 'UPDATE_PK') THEN
		whereclause := array_to_string (
			"baseten".array_cat_each (
				"baseten".array_prepend_each ('OLD.', pkey),
				"baseten".array_prepend_each ('NEW.', pkey),
				' = '
			), ' AND '
		);
		IF querytype = 'UPDATE' THEN
			insertion := "baseten".enable_insert_query (relid, 'U', 'NEW.', pkey);
		ELSIF querytype = 'UPDATE_PK' THEN
			querytype := 'UPDATE';
			insertion :=
				"baseten".enable_insert_query (relid, 'D', 'OLD.', pkey) || '; ' ||
				"baseten".enable_insert_query (relid, 'I', 'NEW.', pkey);
			whereclause := 'NOT (' || whereclause || ')';
		END IF;
		whereclause := ' WHERE ' || whereclause;
	ELSE
		RAISE EXCEPTION 'Unexpected query type %', querytype;
	END IF;

	query :=
		'CREATE RULE ' || quote_ident ("baseten"._mod_rule ($1)) || ' ' || 
		'AS ON ' || querytype || ' ' ||
		'TO ' || "baseten".quote_ident (rel) || whereclause || ' ' || 
		'DO ALSO (' || insertion || ')';
	EXECUTE query;
	RETURN;
END;
$$ VOLATILE LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_other (TEXT, OID, TEXT []) FROM PUBLIC;


-- Another helper function
CREATE FUNCTION "baseten".enable_update_where_clause (TEXT []) RETURNS TEXT AS $$
	SELECT array_to_string (
		"baseten".array_cat_each (
			"baseten".array_prepend_each ('OLD.', $1),
			"baseten".array_prepend_each ('NEW.', $1),
			' = ' -- primary keys are required to have this operator.
		), ' AND '
	);
$$ IMMUTABLE STRICT LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_update_where_clause (TEXT []) FROM PUBLIC;


-- Another helper function
CREATE FUNCTION "baseten".enable_insert_query (OID, CHAR, TEXT, TEXT []) RETURNS TEXT AS $$
DECLARE
	relid		ALIAS FOR $1;
	operation	ALIAS FOR $2;
	refname		ALIAS FOR $3;
	pkey_fields ALIAS FOR $4;
	pkey		TEXT;
	pkey_values TEXT;
BEGIN
	pkey := array_to_string (pkey_fields, ', ');
	pkey_values := array_to_string ("baseten".array_prepend_each (refname, pkey_fields), ', ');

	RETURN
		'INSERT INTO ' || "baseten".quote_ident_bx ("baseten"._mod_table (relid)) || ' (' ||
			'"baseten_modification_type", "baseten_modification_cols", ' || pkey ||
		') VALUES (' || 
			'''' || operation || ''', null, ' || pkey_values || 
		')';
END;
$$ STABLE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_insert_query (OID, CHAR, TEXT, TEXT []) FROM PUBLIC;


CREATE FUNCTION "baseten".enable_lock_fn (OID) RETURNS VOID AS $marker$
DECLARE
	relid							ALIAS FOR $1;
	lock_table						TEXT;
	lock_fn							TEXT;
	lock_notification				TEXT;
	i_args							TEXT [];
	fn_args							TEXT;
	fn_code							TEXT;
	query							TEXT;
	pkey							TEXT [];
	pkey_types						TEXT [];
BEGIN
	SELECT "baseten"._lock_table (relid) INTO STRICT lock_table;
	SELECT "baseten"._lock_fn (relid) INTO STRICT lock_fn;
	SELECT "baseten"._lock_notification (relid) INTO STRICT lock_notification;
	SELECT
		"baseten".array_accum (quote_ident (p.attname)),
		"baseten".array_accum (quote_ident (p.typnspname) || '.' || quote_ident (p.typname))
		FROM "baseten"._primary_key p
		WHERE p.oid = relid
		GROUP BY p.oid
		INTO STRICT pkey, pkey_types;

	-- First argument is the modification type, second one the savepoint number.
	FOR i IN 1..(2 + array_upper (pkey_types, 1)) LOOP
		i_args [i] := '$' || i;
	END LOOP;
	fn_code := 
		'INSERT INTO "baseten".' || lock_table || ' ' ||
		'("baseten_lock_query_type", "baseten_lock_savepoint_idx", ' || array_to_string (pkey, ', ') || ') ' ||
		'VALUES' ||
		'(' || array_to_string (i_args, ', ') || ');' ||
		'NOTIFY ' || quote_ident (lock_notification) || ';';
	-- FIXME: add a check to the function to ensure that the connection is autocommitting
	fn_args := '(CHAR (1), BIGINT, ' || array_to_string (pkey_types, ', ') || ')';
	query := 
		'CREATE OR REPLACE FUNCTION "baseten".' || quote_ident (lock_fn) || ' ' || fn_args || ' ' ||
		'RETURNS VOID AS $$ ' || fn_code || ' $$ VOLATILE LANGUAGE SQL';
	EXECUTE query;
	EXECUTE 'REVOKE ALL PRIVILEGES ON FUNCTION "baseten".' || quote_ident (lock_fn) || ' ' || fn_args || ' FROM PUBLIC';
	EXECUTE 'GRANT EXECUTE ON FUNCTION "baseten".' || quote_ident (lock_fn) || ' ' || fn_args || ' TO basetenuser';
END;
$marker$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable_lock_fn (OID) FROM PUBLIC;


CREATE FUNCTION "baseten".enable (OID, BOOLEAN, TEXT) 
RETURNS "baseten".reltype AS $marker$
DECLARE
	reloid							ALIAS FOR $1;
	handle_view_default_value		ALIAS FOR $2;
	view_id_default_value			ALIAS FOR $3;
	is_view							BOOL;
	query							TEXT;
	
	relid_							INTEGER;
	mod_table						TEXT;
	lock_table						TEXT;
	
	pkey							TEXT [];
	pkey_decl						TEXT;
	rel								"baseten"."reltype";
	retval							"baseten"."reltype";
BEGIN
	PERFORM "baseten".assign_internal_ids ();
	UPDATE "baseten".relation SET enabled = true WHERE id = "baseten".relation_id_ex (reloid);
	SELECT "baseten"._mod_table (reloid) INTO STRICT mod_table;
	SELECT "baseten"._lock_table (reloid) INTO STRICT lock_table;
	SELECT 'v' = c.relkind FROM pg_class c WHERE c.oid = reloid INTO STRICT is_view;
	relid_ := "baseten".relation_id_ex (reloid);
	rel := "baseten".reltype (reloid);
	
	SELECT
		"baseten".array_accum (quote_ident (p.attname)),
		array_to_string ("baseten".array_accum (quote_ident (p.attname) || ' ' || "baseten".quote_ident (p.typnspname, p.typname) || ' NOT NULL'), ', ')
		FROM "baseten"._primary_key p
		WHERE p.oid = reloid
		GROUP BY p.oid
		INTO STRICT pkey, pkey_decl;

	-- Locking
	query := 
		'CREATE TABLE ' || "baseten".quote_ident_bx (lock_table) || ' (' ||
			'"baseten_lock_relid" INTEGER NOT NULL DEFAULT ' || relid_ || ', ' ||
			pkey_decl ||
		') INHERITS ("baseten".lock)';
	EXECUTE query;
	EXECUTE 'REVOKE ALL PRIVILEGES ON ' || "baseten".quote_ident_bx (lock_table) || ' FROM PUBLIC';
	EXECUTE 'GRANT SELECT ON ' || "baseten".quote_ident_bx (lock_table) || ' TO basetenread';
	EXECUTE 'GRANT INSERT ON ' || "baseten".quote_ident_bx (lock_table) || ' TO basetenuser';
	EXECUTE 'COMMENT ON TABLE ' || "baseten".quote_ident_bx (lock_table) || ' IS ''' || rel.nspname || '.' || rel.relname || '''';

	-- Trigger for the _lock_ table
	query :=
		'CREATE TRIGGER "lock_row" ' ||
		'AFTER INSERT ON ' || "baseten".quote_ident_bx (lock_table) || ' ' ||
		'FOR EACH STATEMENT EXECUTE PROCEDURE "baseten".lock_notify (''' || "baseten"._lock_notification (reloid) || ''')';
	EXECUTE query;

	-- Locking function
	PERFORM "baseten".enable_lock_fn (reloid);

	-- Modifications
	query :=
		'CREATE TABLE ' || "baseten".quote_ident_bx (mod_table) || ' (' ||
			'"baseten_modification_relid" INTEGER NOT NULL DEFAULT ' || relid_ || ', ' ||
			pkey_decl ||
		') INHERITS ("baseten".modification)';
	EXECUTE query;
	EXECUTE 'REVOKE ALL PRIVILEGES ON ' || "baseten".quote_ident_bx (mod_table) || ' FROM PUBLIC';
	EXECUTE 'GRANT INSERT ON ' || "baseten".quote_ident_bx (mod_table) || ' TO basetenuser';
	EXECUTE 'GRANT SELECT ON ' || "baseten".quote_ident_bx (mod_table) || ' TO basetenread';
	EXECUTE 'COMMENT ON TABLE ' || "baseten".quote_ident_bx (mod_table) || ' IS ''' || rel.nspname || '.' || rel.relname || '''';
	
	-- Triggers for the _modification_ table
	query :=
		'CREATE TRIGGER "modify_table" ' ||
		'AFTER INSERT ON ' || "baseten".quote_ident_bx (mod_table) || ' ' ||
		'FOR EACH STATEMENT EXECUTE PROCEDURE "baseten".mod_notify (''' || "baseten"._mod_notification (reloid) || ''')';
	EXECUTE query;
	
	-- Triggers for the enabled relation.
	IF is_view THEN
		IF handle_view_default_value THEN
			PERFORM "baseten".enable_view_insert_default (reloid, view_id_default_value);
		ELSE
			PERFORM "baseten".enable_other ('insert', reloid, pkey);
		END IF;
	ELSE
		PERFORM "baseten".enable_table_insert (reloid, pkey) ;
	END IF;
	--PERFORM "baseten".enable_other ('update', reloid, pkey);
	PERFORM "baseten".enable_update_non_pkey (reloid, pkey);
	PERFORM "baseten".enable_other ('update_pk', reloid, pkey);
	PERFORM "baseten".enable_other ('delete', reloid, pkey);

	retval := "baseten".reltype (reloid);
	RETURN retval;
END;
$marker$ VOLATILE CALLED ON NULL INPUT LANGUAGE PLPGSQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable (OID, BOOLEAN, TEXT) FROM PUBLIC;	
GRANT EXECUTE ON FUNCTION "baseten".enable (OID, BOOLEAN, TEXT) TO basetenowner;


CREATE FUNCTION "baseten".enable (OID) RETURNS "baseten".reltype AS $$
	SELECT "baseten".enable ($1, false, null);
$$ VOLATILE STRICT LANGUAGE SQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".enable (OID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".enable (OID) TO basetenowner;
COMMENT ON FUNCTION "baseten".enable (OID) IS 'BaseTen-enables a relation';


CREATE FUNCTION "baseten".modification (INTEGER, BOOL, TIMESTAMP, INTEGER)
RETURNS SETOF RECORD AS $marker$
DECLARE
	relid			ALIAS FOR $1;
	idle_xact		ALIAS FOR $2;
	earliest_date	ALIAS FOR $3;
	ignored_be_pid	INTEGER DEFAULT $4;
	query			TEXT;
	mtable			TEXT;
	pkey			TEXT;
	columns			TEXT;
	date_str		TEXT;
	order_by		TEXT;
	retval			RECORD;
BEGIN
	SELECT "baseten"._mod_table (relid) INTO STRICT mtable;
	SELECT 
		array_to_string ("baseten".array_accum (quote_ident (p.attname)), ', '),
		array_to_string ("baseten".array_append_each (' ASC', "baseten".array_accum (quote_ident (p.attname))), ', ')
		FROM "baseten"._primary_key p
		WHERE p.id = relid
		GROUP BY p.id
		INTO STRICT pkey, order_by;
	date_str := COALESCE (earliest_date, '-infinity');
	ignored_be_pid := COALESCE (ignored_be_pid, 0);
	columns := '"baseten_modification_type", "baseten_modification_cols", "baseten_modification_timestamp", "baseten_modification_insert_timestamp", ' || pkey;
	
	PERFORM "baseten".mod_cleanup (idle_xact);
	query :=
		'SELECT ' || columns || ' FROM (' ||
			'SELECT DISTINCT ON (' || pkey || ') ' || columns || ' ' ||
			'FROM ' || "baseten".quote_ident_bx (mtable) || ' ' ||
			'WHERE ("baseten_modification_timestamp" > ''' || date_str || '''::timestamp OR "baseten_modification_timestamp" IS NULL) AND ' ||
				'baseten_modification_backend_pid != ' || ignored_be_pid || ' ' ||
			'ORDER BY ' || order_by || ', "baseten_modification_type" ASC' ||
		') a ' ||
		'UNION ' || -- Not UNION ALL
		'SELECT ' || columns || ' FROM (' ||
			'SELECT DISTINCT ON (' || pkey || ') ' || columns || ' ' ||
			'FROM ' || "baseten".quote_ident_bx (mtable) || ' ' ||
			'WHERE ("baseten_modification_type" = ''D'' OR "baseten_modification_type" = ''I'') AND ' ||
				'("baseten_modification_timestamp" > ''' || date_str || '''::timestamp OR "baseten_modification_timestamp" IS NULL) AND ' ||
				'baseten_modification_backend_pid != ' || ignored_be_pid || ' ' ||
			'ORDER BY ' || order_by || ', "baseten_modification_timestamp" DESC, "baseten_modification_insert_timestamp" DESC' ||
		') b ' ||
		'ORDER BY "baseten_modification_timestamp" DESC, "baseten_modification_insert_timestamp" DESC';
	
	-- FIXME: for debugging
	--RAISE NOTICE 'Modifications: %', query;
	
	FOR retval IN EXECUTE query
	LOOP
		RETURN NEXT retval;
	END LOOP;
	RETURN;
END;		 
$marker$ VOLATILE STRICT LANGUAGE PLPGSQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".modification (INTEGER, BOOL, TIMESTAMP, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".modification (INTEGER, BOOL, TIMESTAMP, INTEGER) TO basetenread;


CREATE FUNCTION "baseten".prune () RETURNS VOID AS $$
	DELETE FROM "baseten".modification;
	DELETE FROM "baseten".lock;
	TRUNCATE 
		"baseten"._view_dependency, 
		"baseten"._rel_view_hierarchy, 
		"baseten"._rel_view_oneto, 
		"baseten"._rel_view_manytomany,
		"baseten"._deprecated_relationship_name;
$$ VOLATILE LANGUAGE SQL SECURITY DEFINER;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".prune () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".prune () TO basetenowner;


CREATE FUNCTION "baseten".refresh_caches () RETURNS VOID AS $$
	TRUNCATE "baseten".relationship, "baseten"._deprecated_relationship_name;
	SELECT "baseten".assign_internal_ids ();
	SELECT "baseten"._insert_relationships ();
	
	-- Deprecated names.
	SELECT "baseten"._insert_deprecated_relationships ();
	INSERT INTO "baseten".relationship
		SELECT
			conid,
		    dstconid,
		    name,
		    inversename,
		    kind,
		    is_inverse,
		    is_deprecated,
		    has_rel_names,
		    has_views,
		    srcid,
		    srcnspname,
		    srcrelname,
		    dstid,
		    dstnspname,
		    dstrelname,
		    helperid,
		    helpernspname,
		    helperrelname
		FROM "baseten"._deprecated_relationship_name
		WHERE is_ambiguous = false;
	
	SELECT "baseten"._remove_ambiguous_relationships ();
$$ VOLATILE LANGUAGE SQL;
REVOKE ALL PRIVILEGES ON FUNCTION "baseten".refresh_caches () FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "baseten".refresh_caches () TO basetenowner;


GRANT basetenread TO basetenuser;
GRANT basetenuser TO basetenowner;
SELECT "baseten".refresh_caches ();
COMMIT; -- Functions
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.