summaryrefslogtreecommitdiffstats
path: root/src/share/database/scripts/pgsql/upgrade_006.2_to_007.0.sh.in
blob: 0feeb0ae0d005a7d2e933064f56d98f567c0ac64 (plain)
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
#!/bin/sh

# Copyright (C) 2021-2022 Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

# shellcheck disable=SC1091
# SC1091: Not following: ... was not specified as input (see shellcheck -x).

# Exit with error if commands exit with non-zero and if undefined variables are
# used.
set -eu

# shellcheck disable=SC2034
# SC2034: ... appears unused. Verify use (or export if used externally).
prefix="@prefix@"

# Include utilities. Use installed version if available and
# use build version if it isn't.
if [ -e @datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh ]; then
    . "@datarootdir@/@PACKAGE_NAME@/scripts/admin-utils.sh"
else
    . "@abs_top_builddir@/src/bin/admin/admin-utils.sh"
fi

VERSION=$(pgsql_version "$@")

if [ "$VERSION" != "6.2" ]; then
    printf 'This script upgrades 6.2 to 7.0. '
    printf 'Reported version is %s. Skipping upgrade.\n' "${VERSION}"
    exit 0
fi

psql "$@" >/dev/null <<EOF

START TRANSACTION;

-- This starts schema update to 7.0. It adds a lot (20+) of tables for the config backend.


-- Adding on update trigger in MySQL is as easy as using this column definition in CREATE TABLE:
-- modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- Sadly, Postgres has its own convoluted way of doing this. Luckily, the update pattern is
-- the same in many tables, so we can define the trigger function once and the use it everywhere.

-- First, we need to define a function that will do the actual job.
-- This is used in many, many tables.
CREATE OR REPLACE FUNCTION modification_ts_update()
  RETURNS trigger AS \$modification_ts_update\$
  BEGIN
    new.modification_ts = CURRENT_TIMESTAMP;
    RETURN NULL;
  END;

-- Second, we need to specify which language it was written in.
\$modification_ts_update\$ LANGUAGE plpgsql;


-- Create table modification and insert values for modification types.
CREATE TABLE modification (
  id smallint NOT NULL,
  modification_type VARCHAR(32) NOT NULL,
  PRIMARY KEY (id)
);
INSERT INTO modification VALUES (0,'create'), (1,'update'), (2,'delete');



-- Now create the table that holds different parameter data types.
CREATE TABLE parameter_data_type (
  id smallint NOT NULL,
  name VARCHAR(32) NOT NULL,
  PRIMARY KEY (id)
);
INSERT INTO parameter_data_type VALUES
    (0,'integer'),
    (1,'real'),
    (2,'boolean'),
    (4,'string');



-- This table doesn't exist in MySQL. However, it's nice to have an enum that explains what the values
-- in ddns_replace_client_name field in the dhcp{4,6}_shared_network table means.
CREATE TABLE ddns_replace_client_name_types (
  type INT8 PRIMARY KEY NOT NULL,
  name VARCHAR(32)
);
-- See enum ReplaceClientNameMode in src/lib/dhcpsrv/d2_client_cfg.h
INSERT INTO ddns_replace_client_name_types (type, name) VALUES
  (0, 'RCM_NEVER'),
  (1, 'RCM_ALWAYS'),
  (2, 'RCM_WHEN_PRESENT'),
  (3, 'RCM_WHEN_NOT_PRESENT');



-- Create table for DHCPv6 servers
CREATE TABLE dhcp6_server (
  id SERIAL PRIMARY KEY NOT NULL,
  tag VARCHAR(64) NOT NULL,
  description TEXT DEFAULT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(tag)
);
CREATE INDEX dhcp6_server_idx1 ON dhcp6_server (modification_ts);
CREATE UNIQUE INDEX dhcp6_server_idx2 ON dhcp6_server(tag);
CREATE TRIGGER dhcp6_server_modification_ts_update
  AFTER UPDATE ON dhcp6_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();

INSERT INTO dhcp6_server (tag, description) VALUES ('all','special type: all servers');

-- Create a table for storing IPv6 shared networks
CREATE TABLE dhcp6_shared_network (
  id SERIAL PRIMARY KEY NOT NULL,
  name VARCHAR(128) UNIQUE NOT NULL,
  client_class VARCHAR(128) DEFAULT NULL,
  interface VARCHAR(128) DEFAULT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  preferred_lifetime BIGINT DEFAULT NULL,
  rapid_commit BOOLEAN DEFAULT NULL,
  rebind_timer BIGINT DEFAULT NULL,
  relay TEXT DEFAULT NULL,
  renew_timer BIGINT DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  valid_lifetime BIGINT DEFAULT NULL,
  calculate_tee_times BOOLEAN DEFAULT NULL,
  t1_percent float DEFAULT NULL,
  t2_percent float DEFAULT NULL,
  interface_id BYTEA DEFAULT NULL, -- 128 bytes
  min_preferred_lifetime BIGINT DEFAULT NULL,
  max_preferred_lifetime BIGINT DEFAULT NULL,
  min_valid_lifetime BIGINT DEFAULT NULL,
  max_valid_lifetime BIGINT DEFAULT NULL,
  ddns_send_updates BOOLEAN DEFAULT NULL,
  ddns_override_no_update BOOLEAN DEFAULT NULL,
  ddns_override_client_update BOOLEAN DEFAULT NULL,
  ddns_replace_client_name INT8 DEFAULT NULL,
  ddns_generated_prefix VARCHAR(255) DEFAULT NULL,
  ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL,
  reservations_global BOOLEAN DEFAULT NULL,
  reservations_in_subnet BOOLEAN DEFAULT NULL,
  reservations_out_of_pool BOOLEAN DEFAULT NULL,
  cache_threshold float DEFAULT NULL,
  cache_max_age BIGINT DEFAULT NULL,
  CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name)
    REFERENCES ddns_replace_client_name_types (type)
);
CREATE INDEX dhcp6_shared_network_idx1 ON dhcp6_shared_network (name);

CREATE TRIGGER dhcp6_shared_network_modification_ts_update
  AFTER UPDATE ON dhcp6_shared_network
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- Now we need to create a relationship between defined shared networks and the servers
CREATE TABLE dhcp6_shared_network_server (
  shared_network_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (shared_network_id, server_id),
  CONSTRAINT fk_dhcp6_shared_network_server_server_id FOREIGN KEY (server_id)
    REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp6_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id)
    REFERENCES dhcp6_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX dhcp6_shared_network_server_idx1 ON dhcp6_shared_network_server (modification_ts);
CREATE INDEX dhcp6_shared_network_server_idx2 ON dhcp6_shared_network_server (server_id);



-- Create a list of IPv6 subnets
CREATE TABLE dhcp6_subnet (
  subnet_id BIGINT PRIMARY KEY NOT NULL,
  subnet_prefix VARCHAR(64) UNIQUE NOT NULL,
  client_class VARCHAR(128) DEFAULT NULL,
  interface VARCHAR(128) DEFAULT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  preferred_lifetime BIGINT DEFAULT NULL,
  rapid_commit BOOLEAN DEFAULT NULL,
  rebind_timer BIGINT DEFAULT NULL,
  relay TEXT DEFAULT NULL,
  renew_timer BIGINT DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  shared_network_name VARCHAR(128) DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  valid_lifetime BIGINT DEFAULT NULL,
  calculate_tee_times BOOLEAN DEFAULT NULL,
  t1_percent float DEFAULT NULL,
  t2_percent float DEFAULT NULL,
  interface_id BYTEA DEFAULT NULL,
  min_preferred_lifetime BIGINT DEFAULT NULL,
  max_preferred_lifetime BIGINT DEFAULT NULL,
  min_valid_lifetime BIGINT DEFAULT NULL,
  max_valid_lifetime BIGINT DEFAULT NULL,
  ddns_send_updates BOOLEAN DEFAULT NULL,
  ddns_override_no_update BOOLEAN DEFAULT NULL,
  ddns_override_client_update BOOLEAN DEFAULT NULL,
  ddns_replace_client_name INT8 DEFAULT NULL,
  ddns_generated_prefix VARCHAR(255) DEFAULT NULL,
  ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL,
  reservations_global BOOLEAN DEFAULT NULL,
  reservations_in_subnet BOOLEAN DEFAULT NULL,
  reservations_out_of_pool BOOLEAN DEFAULT NULL,
  cache_threshold float DEFAULT NULL,
  cache_max_age BIGINT DEFAULT NULL,
  CONSTRAINT fk_dhcp6_subnet_shared_network FOREIGN KEY (shared_network_name)
    REFERENCES dhcp6_shared_network (name) ON DELETE SET NULL ON UPDATE NO ACTION,
  CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name)
    REFERENCES ddns_replace_client_name_types (type)
);

CREATE TRIGGER dhcp6_subnet_modification_ts_update
  AFTER UPDATE ON dhcp6_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();

CREATE INDEX dhcp6_subnet_idx1 ON dhcp6_subnet (modification_ts);
CREATE INDEX dhcp6_subnet_idx2 ON dhcp6_subnet (shared_network_name);



-- Create a table that holds all address pools in IPv6.
CREATE TABLE dhcp6_pool (
  id SERIAL PRIMARY KEY NOT NULL,
  start_address inet NOT NULL,
  end_address inet NOT NULL,
  subnet_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  client_class VARCHAR(128) DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  CONSTRAINT fk_dhcp6_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id)
);
CREATE INDEX dhcp6_pool_idx1 ON dhcp6_pool (modification_ts);
CREATE INDEX dhcp6_pool_idx2 ON dhcp6_pool (subnet_id);

CREATE TRIGGER dhcp6_pool_modification_ts_update
  AFTER UPDATE ON dhcp6_pool
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- And now the same, but for PD pools.
CREATE TABLE dhcp6_pd_pool (
  id SERIAL PRIMARY KEY NOT NULL,
  prefix VARCHAR(45) NOT NULL,
  prefix_length SMALLINT NOT NULL,
  delegated_prefix_length SMALLINT NOT NULL,
  subnet_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  excluded_prefix VARCHAR(45) DEFAULT NULL,
  excluded_prefix_length SMALLINT NOT NULL,
  client_class VARCHAR(128) DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  CONSTRAINT fk_dhcp6_pd_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet(subnet_id)
);

CREATE INDEX dhcp6_pd_pool_idx1 ON dhcp6_pd_pool (modification_ts);
CREATE INDEX dhcp6_pd_pool_idx2 ON dhcp6_pd_pool (subnet_id);
CREATE TRIGGER dhcp6_pd_pool_modification_ts_update
  AFTER UPDATE ON dhcp6_pd_pool
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



CREATE TABLE dhcp6_subnet_server (
  subnet_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (subnet_id, server_id),
  CONSTRAINT fk_dhcp6_subnet_server_server_id
    FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp6_subnet_server_subnet_id
    FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION,
  UNIQUE (subnet_id, server_id)
);
CREATE INDEX dhcp6_subnet_server_idx1 ON dhcp6_subnet_server(server_id);
CREATE INDEX dhcp6_subnet_server_idx2 ON dhcp6_subnet_server(modification_ts);
CREATE TRIGGER dhcp6_subnet_server_modification_ts_update
  AFTER UPDATE ON dhcp6_subnet_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- Create table for storing global DHCPv6 parameters.
CREATE TABLE dhcp6_global_parameter (
  id SERIAL PRIMARY KEY NOT NULL,
  name VARCHAR(128) NOT NULL,
  value TEXT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  parameter_type SMALLINT NOT NULL,
  CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) REFERENCES parameter_data_type(id)
);

CREATE INDEX key_dhcp6_global_parameter_idx1 ON dhcp6_global_parameter(modification_ts);
CREATE INDEX key_dhcp6_global_parameter_idx2 ON dhcp6_global_parameter(name);

CREATE TRIGGER dhcp6_global_parameter_modification_ts_update
  AFTER UPDATE ON dhcp6_global_parameter
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


CREATE TABLE dhcp6_global_parameter_server (
  parameter_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (parameter_id, server_id),
  CONSTRAINT fk_dhcp6_global_parameter_server_parameter_id FOREIGN KEY (parameter_id)
    REFERENCES dhcp6_global_parameter(id) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp6_global_parameter_server_server_id FOREIGN KEY (server_id)
    REFERENCES dhcp6_server(id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX key_dhcp6_global_parameter_server_idx1 ON dhcp6_global_parameter_server(modification_ts);
CREATE TRIGGER dhcp6_global_parameter_server_modification_ts_update
  AFTER UPDATE ON dhcp6_global_parameter_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- Create a table for storing DHCPv6 options.
ALTER TABLE dhcp6_options
  ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL,
  ADD COLUMN pool_id BIGINT DEFAULT NULL,
  ADD COLUMN pd_pool_id BIGINT DEFAULT NULL,
  ADD CONSTRAINT fk_dhcp6_options_pd_pool FOREIGN KEY (pd_pool_id)
    REFERENCES dhcp6_pd_pool(id) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT fk_dhcp6_options_pool FOREIGN KEY (pool_id)
    REFERENCES dhcp6_pool (id) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT fk_dhcp6_options_shared_network FOREIGN KEY (shared_network_name)
    REFERENCES dhcp6_shared_network (name) ON DELETE CASCADE ON UPDATE CASCADE;

CREATE TRIGGER dhcp6_options_modification_ts_update
  AFTER UPDATE ON dhcp6_options
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();

-- Now create a table for associating defined options with servers.
CREATE TABLE dhcp6_options_server (
  option_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (option_id, server_id),
  CONSTRAINT fk_dhcp6_options_server_option_id FOREIGN KEY (option_id)
    REFERENCES dhcp6_options (option_id) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp6_options_server_server_id FOREIGN KEY (server_id)
    REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX dhcp6_options_server_idx1 ON dhcp6_options_server(server_id);
CREATE INDEX dhcp6_options_server_idx2 ON dhcp6_options_server(modification_ts);
CREATE TRIGGER dhcp6_options_server_modification_ts_update
  AFTER UPDATE ON dhcp6_options_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- This table is for storing IPv6 option definitions
CREATE TABLE dhcp6_option_def (
  id SERIAL PRIMARY KEY UNIQUE NOT NULL,
  code SMALLINT NOT NULL,
  name VARCHAR(128) NOT NULL,
  space VARCHAR(128) NOT NULL,
  type SMALLINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  is_array BOOLEAN NOT NULL,
  encapsulate VARCHAR(128) NOT NULL,
  record_types VARCHAR DEFAULT NULL,
  user_context JSON DEFAULT NULL
);
CREATE INDEX dhcp6_option_def_idx1 ON dhcp6_option_def(modification_ts);
CREATE INDEX dhcp6_option_def_idx2 ON dhcp6_option_def(code, space);
CREATE TRIGGER dhcp6_option_def_modification_ts_update
  AFTER UPDATE ON dhcp6_option_def
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- and another table for storing relationship between option definitions and servers.
CREATE TABLE dhcp6_option_def_server (
  option_def_id BIGINT NOT NULL REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION,
  server_id BIGINT NOT NULL REFERENCES dhcp6_server (id) ON DELETE CASCADE ON UPDATE NO ACTION,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (option_def_id, server_id)
);
CREATE TRIGGER dhcp6_option_def_server_modification_ts_update
  AFTER UPDATE ON dhcp6_option_def_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- Now create two tables for audit revisions...
CREATE TABLE dhcp6_audit_revision (
  id SERIAL PRIMARY KEY NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  log_message TEXT DEFAULT NULL,
  server_id BIGINT DEFAULT NULL
);
CREATE TRIGGER dhcp6_audit_revision_modification_ts_update
  AFTER UPDATE ON dhcp6_audit_revision
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- ... and the DHCPv6 audit itself.
CREATE TABLE dhcp6_audit (
  id SERIAL UNIQUE NOT NULL,
  object_type VARCHAR(256) NOT NULL,
  object_id BIGINT NOT NULL,
  modification_type SMALLINT NOT NULL,
  revision_id BIGINT NOT NULL,
  CONSTRAINT fk_dhcp6_audit_modification_type FOREIGN KEY (modification_type)
    REFERENCES modification (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp6_audit_revision FOREIGN KEY (revision_id)
    REFERENCES dhcp6_audit_revision (id) ON DELETE NO ACTION ON UPDATE CASCADE
);
CREATE TRIGGER dhcp6_audit_modification_ts_update
  AFTER UPDATE ON dhcp6_audit
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();
CREATE INDEX dhcp6_audit_idx1 ON dhcp6_audit (modification_type);
CREATE INDEX dhcp6_audit_idx2 ON dhcp6_audit (revision_id);


-- Create table for DHCPv4 servers
CREATE TABLE dhcp4_server (
  id SERIAL PRIMARY KEY NOT NULL,
  tag VARCHAR(64) NOT NULL,
  description TEXT DEFAULT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(tag)
);
CREATE INDEX dhcp4_server_modification_ts ON dhcp6_server (modification_ts);
CREATE TRIGGER dhcp4_server_modification_ts_update
  AFTER UPDATE ON dhcp4_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();

INSERT INTO dhcp4_server (tag, description) VALUES ('all','special type: all servers');

-- Create table for storing global DHCPv4 parameters.
CREATE TABLE dhcp4_global_parameter (
  id SERIAL PRIMARY KEY NOT NULL,
  name VARCHAR(128) NOT NULL,
  value TEXT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  parameter_type SMALLINT NOT NULL,
  CONSTRAINT fk_dhcp6_global_parameter_type FOREIGN KEY (parameter_type) REFERENCES parameter_data_type(id)
);
CREATE INDEX dhcp4_global_parameter_idx1 ON dhcp4_global_parameter(modification_ts);
CREATE INDEX dhcp4_global_parameter_idx2 ON dhcp4_global_parameter(name);

CREATE TRIGGER dhcp4_global_parameter_modification_ts_update
  AFTER UPDATE ON dhcp4_global_parameter
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();

-- and create mapping for the global DHCPv4 parameters mapping to servers
CREATE TABLE dhcp4_global_parameter_server (
  parameter_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (parameter_id, server_id),
  CONSTRAINT fk_dhcp4_global_parameter_server_parameter_id FOREIGN KEY (parameter_id)
    REFERENCES dhcp4_global_parameter(id) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp4_global_parameter_server_server_id FOREIGN KEY (server_id)
    REFERENCES dhcp4_server(id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX key_dhcp4_global_parameter_idx1 ON dhcp4_global_parameter_server(modification_ts);
CREATE TRIGGER dhcp4_global_parameter_server_modification_ts_update
  AFTER UPDATE ON dhcp4_global_parameter_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- Create a table for storing IPv4 shared networks
CREATE TABLE dhcp4_shared_network (
  id SERIAL PRIMARY KEY NOT NULL,
  name VARCHAR(128) UNIQUE NOT NULL,
  client_class VARCHAR(128) DEFAULT NULL,
  interface VARCHAR(128) DEFAULT NULL,
  match_client_id BOOLEAN DEFAULT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  rebind_timer BIGINT DEFAULT NULL,
  relay TEXT DEFAULT NULL,
  renew_timer BIGINT DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  valid_lifetime BIGINT DEFAULT NULL,
  authoritative BOOLEAN DEFAULT NULL,
  calculate_tee_times BOOLEAN DEFAULT NULL,
  t1_percent float DEFAULT NULL,
  t2_percent float DEFAULT NULL,
  boot_file_name VARCHAR(128) DEFAULT NULL,
  next_server inet DEFAULT NULL,   -- let's use type inet
  server_hostname VARCHAR(64) DEFAULT NULL,
  min_valid_lifetime BIGINT DEFAULT NULL,
  max_valid_lifetime BIGINT DEFAULT NULL,
  ddns_send_updates BOOLEAN DEFAULT NULL,
  ddns_override_no_update BOOLEAN DEFAULT NULL,
  ddns_override_client_update BOOLEAN DEFAULT NULL,
  ddns_replace_client_name INT8 DEFAULT NULL,
  ddns_generated_prefix VARCHAR(255) DEFAULT NULL,
  ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL,
  reservations_global BOOLEAN DEFAULT NULL,
  reservations_in_subnet BOOLEAN DEFAULT NULL,
  reservations_out_of_pool BOOLEAN DEFAULT NULL,
  cache_threshold float DEFAULT NULL,
  cache_max_age BIGINT DEFAULT NULL,
  CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name)
    REFERENCES ddns_replace_client_name_types (type)
);

CREATE UNIQUE INDEX dhcp4_shared_network_idx1 ON dhcp4_shared_network (name);
CREATE INDEX dhcp4_shared_network_idx2 ON dhcp4_shared_network (modification_ts);

CREATE TRIGGER dhcp4_shared_network_modification_ts_update
  AFTER UPDATE ON dhcp4_shared_network
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- Now we need to create a relationship between defined shared networks and the servers
CREATE TABLE dhcp4_shared_network_server (
  shared_network_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (shared_network_id, server_id),
  CONSTRAINT fk_dhcp4_shared_network_server_server_id FOREIGN KEY (server_id)
    REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp4_shared_network_server_shared_network_id FOREIGN KEY (shared_network_id)
    REFERENCES dhcp4_shared_network (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX dhcp4_shared_network_server_idx1 ON dhcp4_shared_network_server (modification_ts);
CREATE INDEX dhcp4_shared_network_server_idx2 ON dhcp4_shared_network_server (server_id);



-- Create a list of IPv4 subnets
CREATE TABLE dhcp4_subnet (
  subnet_id BIGINT PRIMARY KEY NOT NULL,
  subnet_prefix VARCHAR(64) UNIQUE NOT NULL,
  interface_4o6 VARCHAR(128) DEFAULT NULL,
  interface_id_4o6 VARCHAR(128) DEFAULT NULL,
  subnet_4o6 VARCHAR(64) DEFAULT NULL,
  boot_file_name VARCHAR(128) DEFAULT NULL,
  client_class VARCHAR(128) DEFAULT NULL,
  interface VARCHAR(128) DEFAULT NULL,
  match_client_id BOOLEAN DEFAULT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  next_server inet DEFAULT NULL,
  rebind_timer BIGINT DEFAULT NULL,
  relay TEXT DEFAULT NULL,
  renew_timer BIGINT DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  server_hostname VARCHAR(64) DEFAULT NULL,
  shared_network_name VARCHAR(128) DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  valid_lifetime BIGINT DEFAULT NULL,
  authoritative BOOLEAN DEFAULT NULL,
  calculate_tee_times BOOLEAN DEFAULT NULL,
  t1_percent float DEFAULT NULL,
  t2_percent float DEFAULT NULL,
  min_valid_lifetime BIGINT DEFAULT NULL,
  max_valid_lifetime BIGINT DEFAULT NULL,
  ddns_send_updates BOOLEAN DEFAULT NULL,
  ddns_override_no_update BOOLEAN DEFAULT NULL,
  ddns_override_client_update BOOLEAN DEFAULT NULL,
  ddns_replace_client_name INT8 DEFAULT NULL,
  ddns_generated_prefix VARCHAR(255) DEFAULT NULL,
  ddns_qualifying_suffix VARCHAR(255) DEFAULT NULL,
  reservations_global BOOLEAN DEFAULT NULL,
  reservations_in_subnet BOOLEAN DEFAULT NULL,
  reservations_out_of_pool BOOLEAN DEFAULT NULL,
  cache_threshold float DEFAULT NULL,
  cache_max_age BIGINT DEFAULT NULL,
  CONSTRAINT fk_dhcp4_subnet_shared_network FOREIGN KEY (shared_network_name)
    REFERENCES dhcp4_shared_network (name) ON DELETE SET NULL ON UPDATE NO ACTION,
  CONSTRAINT fk_ddns_replace_client_name FOREIGN KEY (ddns_replace_client_name)
    REFERENCES ddns_replace_client_name_types (type)
);

CREATE TRIGGER dhcp4_subnet_modification_ts_update
  AFTER UPDATE ON dhcp4_subnet
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();

CREATE INDEX dhcp4_subnet_idx1 ON dhcp4_subnet (modification_ts);
CREATE INDEX dhcp4_subnet_idx2 ON dhcp4_subnet (shared_network_name);



CREATE TABLE dhcp4_subnet_server (
  subnet_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (subnet_id, server_id),
  CONSTRAINT fk_dhcp6_subnet_server_server_id
    FOREIGN KEY (server_id) REFERENCES dhcp6_server (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp6_subnet_server_subnet_id
    FOREIGN KEY (subnet_id) REFERENCES dhcp6_subnet (subnet_id) ON DELETE CASCADE ON UPDATE NO ACTION,
  UNIQUE (subnet_id, server_id)
);
CREATE INDEX dhcp4_subnet_server_idx1 ON dhcp4_subnet_server(server_id);
CREATE INDEX dhcp4_subnet_server_idx2 ON dhcp4_subnet_server(modification_ts);
CREATE TRIGGER dhcp4_subnet_server_modification_ts_update
  AFTER UPDATE ON dhcp4_subnet_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- Create a table that holds all address pools in IPv4.
CREATE TABLE dhcp4_pool (
  id SERIAL PRIMARY KEY NOT NULL,
  start_address inet NOT NULL,
  end_address inet NOT NULL,
  subnet_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  client_class VARCHAR(128) DEFAULT NULL,
  require_client_classes TEXT DEFAULT NULL,
  user_context JSON DEFAULT NULL,
  CONSTRAINT fk_dhcp4_pool_subnet_id FOREIGN KEY (subnet_id) REFERENCES dhcp4_subnet (subnet_id)
);
CREATE INDEX dhcp4_pool_idx1 ON dhcp4_pool (modification_ts);
CREATE INDEX dhcp4_pool_idx2 ON dhcp4_pool (subnet_id);

CREATE TRIGGER dhcp4_pool_modification_ts_update
  AFTER UPDATE ON dhcp4_pool
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- Create a table for storing DHCPv4 options.
ALTER TABLE dhcp4_options
  ADD COLUMN shared_network_name VARCHAR(128) DEFAULT NULL,
  ADD COLUMN pool_id BIGINT DEFAULT NULL,
  ADD COLUMN modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  ADD CONSTRAINT fk_dhcp4_options_pool FOREIGN KEY (pool_id)
    REFERENCES dhcp4_pool (id) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT fk_dhcp4_options_shared_network FOREIGN KEY (shared_network_name)
    REFERENCES dhcp4_shared_network (name) ON DELETE CASCADE ON UPDATE CASCADE;

CREATE TRIGGER dhcp4_options_modification_ts_update
  AFTER UPDATE ON dhcp4_options
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- Now create a table for associating defined v4 options with servers.
CREATE TABLE dhcp4_options_server (
  option_id BIGINT NOT NULL,
  server_id BIGINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (option_id, server_id),
  CONSTRAINT fk_dhcp4_options_server_option_id FOREIGN KEY (option_id)
    REFERENCES dhcp4_options (option_id) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp4_options_server_server_id FOREIGN KEY (server_id)
    REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX dhcp4_options_server_idx1 ON dhcp4_options_server(server_id);
CREATE INDEX dhcp4_options_server_idx2 ON dhcp4_options_server(modification_ts);
CREATE TRIGGER dhcp4_options_server_modification_ts_update
  AFTER UPDATE ON dhcp4_options_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- This table is for storing IPv4 option definitions
CREATE TABLE dhcp4_option_def (
  id SERIAL PRIMARY KEY UNIQUE NOT NULL,
  code SMALLINT NOT NULL,
  name VARCHAR(128) NOT NULL,
  space VARCHAR(128) NOT NULL,
  type SMALLINT NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  is_array BOOLEAN NOT NULL,
  encapsulate VARCHAR(128) NOT NULL,
  record_types VARCHAR DEFAULT NULL,
  user_context JSON DEFAULT NULL
);
CREATE INDEX dhcp4_option_def_idx1 ON dhcp4_option_def(modification_ts);
CREATE INDEX dhcp4_option_def_idx2 ON dhcp4_option_def(code, space);
CREATE TRIGGER dhcp4_option_def_modification_ts_update
  AFTER UPDATE ON dhcp4_option_def
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- and another table for storing relationship between option definitions and servers.
CREATE TABLE dhcp4_option_def_server (
  option_def_id BIGINT NOT NULL REFERENCES dhcp6_option_def (id) ON DELETE CASCADE ON UPDATE NO ACTION,
  server_id BIGINT NOT NULL REFERENCES dhcp4_server (id) ON DELETE CASCADE ON UPDATE NO ACTION,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (option_def_id, server_id)
);
CREATE TRIGGER dhcp4_option_def_server_modification_ts_update
  AFTER UPDATE ON dhcp4_option_def_server
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();



-- Now create two tables for audit revisions...
CREATE TABLE dhcp4_audit_revision (
  id SERIAL PRIMARY KEY NOT NULL,
  modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  log_message TEXT DEFAULT NULL,
  server_id BIGINT DEFAULT NULL
);
CREATE TRIGGER dhcp4_audit_revision_modification_ts_update
  AFTER UPDATE ON dhcp4_audit_revision
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();


-- ... and the DHCPv4 audit itself.
CREATE TABLE dhcp4_audit (
  id SERIAL UNIQUE NOT NULL,
  object_type VARCHAR(256) NOT NULL,
  object_id BIGINT NOT NULL,
  modification_type SMALLINT NOT NULL,
  revision_id BIGINT NOT NULL,
  CONSTRAINT fk_dhcp4_audit_modification_type FOREIGN KEY (modification_type)
    REFERENCES modification (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT fk_dhcp4_audit_revision FOREIGN KEY (revision_id)
    REFERENCES dhcp4_audit_revision (id) ON DELETE NO ACTION ON UPDATE CASCADE
);
CREATE TRIGGER dhcp4_audit_modification_ts_update
  AFTER UPDATE ON dhcp4_audit
  FOR EACH ROW EXECUTE PROCEDURE modification_ts_update();
CREATE INDEX dhcp4_audit_idx1 ON dhcp4_audit (modification_type);
CREATE INDEX dhcp4_audit_idx2 ON dhcp4_audit (revision_id);

-- Stores a TEXT value to a session variable
-- name name of session variable to set
-- value TEXT value to store
CREATE OR REPLACE FUNCTION set_session_value(name text, value TEXT)
RETURNS VOID
AS \$\$
DECLARE
BEGIN
    PERFORM set_config(name, value, false);
    RETURN;

    EXCEPTION
    WHEN OTHERS THEN
        RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate;
END;\$\$
LANGUAGE plpgsql;

-- Stores a BIGINT value to a session variable
-- Note the value converted to TEXT and then stored as Postgresql does
-- not support any other data type in session variables.
-- name name of session variable to set
-- value BIGINT value to store
CREATE OR REPLACE FUNCTION set_session_value(name text, value BIGINT)
RETURNS VOID
AS \$\$
BEGIN
    PERFORM set_config(name, cast(value as text), false);
    RETURN;

    EXCEPTION
    WHEN OTHERS THEN
        RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate;
END;\$\$
LANGUAGE plpgsql;

-- Stores a BOOLEAN value to a session variable
-- Note the value converted to TEXT and then stored as Postgresql does
-- not support any other data type in session variables.
-- name name of session variable to set
-- value BOOLEAN value to store
CREATE OR REPLACE FUNCTION set_session_value(name text, value BOOLEAN)
RETURNS VOID
AS \$\$
BEGIN
    PERFORM set_config(name, cast(value as text), false);
    RETURN;

    EXCEPTION
    WHEN OTHERS THEN
        RAISE EXCEPTION 'set_session_value(%) : value:[%] failed, sqlstate: %', name, value, sqlstate;
END;\$\$
LANGUAGE plpgsql;


-- Fetches a text value from the session configuration.
-- param name name of the session variable to fetch
-- If the name is not found it returns NULL.
-- Postgresql allows you to store custom session values
-- but throws an exception if they have not first been
-- set.  This allows us to be a bit more graceful.
CREATE OR REPLACE FUNCTION get_session_value(name TEXT)
RETURNS TEXT
AS \$\$
DECLARE
    text_value TEXT := '';
BEGIN
    text_value = current_setting(name);
    RETURN(text_value);

    EXCEPTION
    WHEN undefined_object THEN
        -- Variable has not been initialized so return NULL
        RETURN NULL;
    WHEN OTHERS THEN
        RAISE EXCEPTION 'get_session_value(%, TEXT) failed, sqlstate: %', name, sqlstate;
END;\$\$
LANGUAGE plpgsql;

-- Fetches an BIGINT value from the session configuration.
-- param name name of the session variable to fetch
-- If the name is not found it returns zero.
CREATE OR REPLACE FUNCTION get_session_big_int(name text)
RETURNS BIGINT
AS \$\$
DECLARE
    int_value BIGINT := 0;
    text_value TEXT := '';
BEGIN
    text_value = get_session_value(name);
    IF text_value is NULL or text_value = '' THEN
        RETURN(0);
    END IF;

    int_value = cast(text_value as BIGINT);
    RETURN(int_value);

    EXCEPTION
    WHEN OTHERS THEN
        RAISE EXCEPTION 'get_session_big_int(%) failed - text:[%] , sqlstate: %', name, text_value, sqlstate;

END;\$\$
LANGUAGE plpgsql;

-- Fetches an BOOLEAN value from the session configuration.
-- param name name of the session variable to fetch
-- If the name is not found it returns zero.
CREATE OR REPLACE FUNCTION get_session_boolean(name text)
RETURNS BOOLEAN
AS \$\$
DECLARE
    bool_value BOOLEAN := false;
    text_value TEXT := '';
BEGIN
    text_value = get_session_value(name);
    IF text_value is NULL or text_value = '' THEN
        RETURN(false);
    END IF;

    bool_value = cast(text_value as BOOLEAN);
    RETURN(bool_value);

    EXCEPTION
    WHEN OTHERS THEN
        RAISE EXCEPTION 'get_session_boolean(%) failed - text:[%] , sqlstate: %', name, text_value, sqlstate;

END;\$\$
LANGUAGE plpgsql;


-- -----------------------------------------------------
-- Stored procedure which creates a new entry in the
-- dhcp4_audit_revision table and sets appropriate session
-- variables to be used while creating the audit entries
-- by triggers. This procedure should be called at the
-- beginning of a transaction which modifies configuration
-- data in the database, e.g. when new subnet is added.
--
-- Parameters:
-- - audit_ts timestamp to be associated with the audit
--   revision.
-- - server_tag is used to retrieve the server_id which
--   associates the changes applied with the particular
--   server or all servers.
-- - audit_log_message is a log message associates with
--   the audit revision.
-- - cascade_transaction is assigned to a session
--   variable which is used in some triggers to determine
--   if the audit entry should be created for them or
--   not. Specifically, this is used when DHCP options
--   are inserted, updated or deleted. If such modification
--   is a part of the larger change (e.g. change in the
--   subnet the options belong to) the dedicated audit
--   entry for options must not be created. On the other
--   hand, if the global option is being added, the
--   audit entry for the option must be created because
--   it is the sole object modified in that case.
--   Session variable disable_audit is used to disable
--   the procedure when wiping the database during
--   unit tests.  This avoids issues with revision_id
--   being null.
-- -----------------------------------------------------
CREATE OR REPLACE FUNCTION createAuditRevisionDHCP4(audit_ts TIMESTAMP WITH TIME ZONE,
                                                    server_tag VARCHAR(64),
                                                    audit_log_message TEXT,
                                                    cascade_transaction BOOLEAN)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    disable_audit BOOLEAN := false;
    audit_revision_id BIGINT;
    srv_id BIGINT;
BEGIN
    -- Fetch session value for disable_audit.
    disable_audit := get_session_boolean('kea.disable_audit');
    IF disable_audit = false THEN
        SELECT id INTO srv_id FROM dhcp4_server WHERE tag = server_tag;
        INSERT INTO dhcp4_audit_revision (modification_ts, server_id, log_message)
            VALUES (audit_ts, srv_id, audit_log_message) returning id INTO audit_revision_id;

        -- Update pertinent session variables.
        PERFORM set_session_value('kea.audit_revision_id', audit_revision_id);
        PERFORM set_session_value('kea.cascade_transaction', cascade_transaction);
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------
-- Stored procedure which creates a new entry in the
-- dhcp4_audit table. It should be called from the
-- triggers of the tables where the config modifications
-- are applied. The audit_revision_id variable contains
-- the revision id to be placed in the audit entries.
--
-- The following parameters are passed to this procedure:
-- - object_type_val: name of the table to be associated
--   with the applied changes.
-- - object_id_val: identifier of the modified object in
--   that table.
-- - modification_type_val: string value indicating the
--   type of the change, i.e. 'create', 'update' or
--   'delete'.
--   Session variable disable_audit is used to disable
--   the procedure when wiping the database during
--   unit tests.  This avoids issues with revision_id
--   being null.
-- ----------------------------------------------------
CREATE OR REPLACE FUNCTION createAuditEntryDHCP4(object_type_val VARCHAR(256),
                                                 object_id_val BIGINT,
                                                 modification_type_val VARCHAR(32))
RETURNS VOID
LANGUAGE plpgsql
as \$\$
DECLARE
    audit_revision_id BIGINT;
    disable_audit BOOLEAN := false;
BEGIN
    -- Fetch session value for disable_audit.
    disable_audit := get_session_boolean('kea.disable_audit');

    IF disable_audit IS NULL OR disable_audit = false THEN
        -- Fetch session value most recently created audit_revision_id.
        audit_revision_id := get_session_big_int('kea.audit_revision_id');
        INSERT INTO dhcp4_audit (object_type, object_id, modification_type, revision_id)
            VALUES (object_type_val, object_id_val,
                (SELECT id FROM modification WHERE modification_type = modification_type_val),
                 audit_revision_id);
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Create a table holding the DHCPv4 client classes. Most table
-- columns map directly to respective client class properties in
-- Kea configuration. The depend_on_known_directly column is
-- explicitly set in an insert or update statement to indicate
-- if the client class directly depends on KNOWN or UNKNOWN
-- built-in classes. A caller should determine it by evaluating
-- a test expression before inserting or updating the client
-- class in the database. The nullable follow_class_name column
-- can be used for positioning the inserted or updated client
-- class within the class hierarchy. Set this column value to
-- an existing class name, after which this class should be
-- placed in the class hierarchy. See dhcp4_client_class_order
-- description for the details of how classes are ordered.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp4_client_class (
    id SERIAL PRIMARY KEY NOT NULL,
    name VARCHAR(128) UNIQUE NOT NULL,
    test TEXT,
    next_server INET DEFAULT NULL,
    server_hostname VARCHAR(128) DEFAULT NULL,
    boot_file_name VARCHAR(512) DEFAULT NULL,
    only_if_required BOOLEAN NOT NULL DEFAULT false,
    valid_lifetime BIGINT DEFAULT NULL,
    min_valid_lifetime BIGINT DEFAULT NULL,
    max_valid_lifetime BIGINT DEFAULT NULL,
    depend_on_known_directly BOOLEAN NOT NULL DEFAULT false,
    follow_class_name VARCHAR(128) DEFAULT NULL,
    modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX key_dhcp4_client_class_modification_ts on dhcp4_client_class (modification_ts);

-- -----------------------------------------------------------------------
-- Create a table for ordering client classes and holding information
-- about indirect dependencies on KNOWN/UKNOWN built-in client classes.
-- Each class in the dhcp4_client_class table has a corresponding row
-- in the dhcp4_client_class_order table. A caller should not modify
-- the contents of this table. Its entries are automatically created
-- upon inserting or updating client classes in the dhcp4_client_classes
-- using triggers. The order_index designates the position of the client
-- class within the class hierarchy. If the follow_class_name value of
-- the dhcp4_client_class table is set to NULL, the client class is
-- appended at the end of the hierarchy. The assigned order_index
-- value for that class is set to a maximum current value + 1.
-- If the follow_client_class specifies a name of an existing class,
-- the generated order_index is set to an id of that class + 1, and
-- the order_index values of the later classes are incremented by 1.
-- The depend_on_known_indirectly column holds a boolean value indicating
-- whether the given class depends on KNOWN/UKNOWN built-in classes
-- via other classes, i.e. it depends on classes that directly or
-- indirectly depend on these built-ins. This value is auto-generated
-- by a trigger on the dhcp4_client_class_dependency table.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp4_client_class_order (
    class_id BIGINT PRIMARY KEY NOT NULL,
    order_index BIGINT NOT NULL,
    depend_on_known_indirectly BOOLEAN NOT NULL DEFAULT false,
    CONSTRAINT fk_dhcp4_client_class_order_class_id FOREIGN KEY (class_id)
        REFERENCES dhcp4_client_class (id) ON DELETE CASCADE
);

CREATE INDEX key_dhcp4_client_class_order_index on dhcp4_client_class_order (order_index);


-- -----------------------------------------------------------------------
-- Stored procedure positioning an inserted or updated client class
-- within the class hierarchy, depending on the value of the
-- follow_class_name parameter.
--
-- Parameters:
-- - id id of the positioned class,
-- - follow_class_name name of the class after which this class should be
--   positioned within the class hierarchy.
-- - old_follow_class_name previous name of the class after which this
--   class was positioned within the class hierarchy.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION setClientClass4Order(id BIGINT,
                                                new_follow_class_name VARCHAR(128),
                                                old_follow_class_name VARCHAR(128))
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    -- Used to fetch class's current value for depend_on_known_indirectly
    l_depend_on_known_indirectly BIGINT := 0;

    -- Optionally set if the follow_class_name column value is specified.
    follow_class_index BIGINT;
BEGIN
    -- Fetch the class's current value of depend_on_known_indirectly.
    SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly
        FROM dhcp4_client_class_order WHERE id = class_id;

    -- Save it to the current session for use elsewhere during this transaction.
    -- Note this does not work prior to Postgres 9.2 unless the variables are
    -- defined in postgresql.conf. I think for now we put up with CB not supported
    -- prior to 9.2 or we tell people how to edit the conf file.
    PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly);

    -- Bail if the class is updated without re-positioning.
    IF(
       l_depend_on_known_indirectly IS NOT NULL AND
       ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR
        (new_follow_class_name = old_follow_class_name))
    ) THEN
        -- The depend_on_known_indirectly is set to 0 because this procedure is invoked
        -- whenever the dhcp4_client_class record is updated. Such update may include
        -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes.
        -- This value will be later adjusted when dependencies are inserted.
        -- TKM should we update the session value also or is it moot?
        UPDATE dhcp4_client_class_order SET depend_on_known_indirectly = false
            WHERE class_id = id;
        RETURN;
    END IF;

    IF new_follow_class_name IS NOT NULL THEN
        -- Get the position of the class after which the new class should be added.
        SELECT o.order_index INTO follow_class_index
            FROM dhcp4_client_class AS c
            INNER JOIN dhcp4_client_class_order AS o
                ON c.id = o.class_id
            WHERE c.name = new_follow_class_name;

        IF follow_class_index IS NULL THEN
            -- The class with a name specified with new_follow_class_name does
            -- not exist.
            RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name
                USING ERRCODE = 'sql_routine_exception';
        END IF;

        -- We need to place the new class at the position of follow_class_index + 1.
        -- There may be a class at this position already.
        IF EXISTS(SELECT * FROM dhcp4_client_class_order WHERE order_index = follow_class_index + 1) THEN
            -- There is a class at this position already. Let's move all classes
            -- starting from this position by one to create a spot for the new
            -- class.
            UPDATE dhcp4_client_class_order
                SET order_index = order_index + 1
            WHERE order_index >= follow_class_index + 1;
            -- TKM postgresql doesn't like order by here, does it matter?
            -- ORDER BY order_index DESC;
        END IF;

    ELSE
        -- A caller did not specify the new_follow_class_name value. Let's append the
        -- new class at the end of the hierarchy.
        SELECT MAX(order_index) INTO follow_class_index FROM dhcp4_client_class_order;
        IF follow_class_index IS NULL THEN
            -- Apparently, there are no classes. Let's start from 0.
            follow_class_index = 0;
        END IF;
    END IF;

    -- Check if moving the class doesn't break dependent classes.
    IF EXISTS(
        SELECT 1 FROM dhcp4_client_class_dependency AS d
            INNER JOIN dhcp4_client_class_order AS o
                ON d.class_id = o.class_id
            WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1
        LIMIT 1
    ) THEN
        RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- The depend_on_known_indirectly is set to 0 because this procedure is invoked
    -- whenever the dhcp4_client_class record is updated. Such update may include
    -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes.
    -- This value will be later adjusted when dependencies are inserted.
    -- ON CONFLICT required 9.5 or later
    UPDATE dhcp4_client_class_order
        SET order_index = follow_class_index + 1,
            depend_on_known_indirectly = l_depend_on_known_indirectly
        WHERE class_id = id;
    IF FOUND THEN
        RETURN;
    END IF;

    INSERT INTO  dhcp4_client_class_order(class_id, order_index, depend_on_known_indirectly)
        VALUES (id, follow_class_index + 1, 0);
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Trigger procedure to position an inserted class within the class hierarchy
-- and create audit.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp4_client_class_AINS() RETURNS trigger AS \$dhcp4_client_class_AINS\$
BEGIN
    PERFORM setClientClass4Order(NEW.id, NEW.follow_class_name, NULL);
    PERFORM createAuditEntryDHCP4('dhcp4_client_class', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp4_client_class_AINS\$
LANGUAGE plpgsql;

-- Create dhcp4_client_class insert trigger
CREATE TRIGGER dhcp4_client_class_AINS
    AFTER INSERT ON dhcp4_client_class
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_AINS();

-- -----------------------------------------------------------------------
-- Trigger to position an updated class within the class hierarchy,
-- create audit and remember the direct dependency on the
-- KNOWN/UNKNOWN built-in classes before the class update.
-- When updating a client class, it is very important to ensure that
-- its dependency on KNOWN or UNKNOWN built-in client classes is not
-- changed. It is because there may be other classes that depend on
-- these built-ins via this class. Changing the dependency would break
-- the chain of dependencies for other classes. Here, we store the
-- information about the dependency in the session variables. Their
-- values will be compared with the new dependencies after an update.
-- If they change, an error will be signaled.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp4_client_class_AUPD() RETURNS trigger AS \$dhcp4_client_class_AUPD\$
BEGIN
    PERFORM set_session_value('kea.depend_on_known_directly', OLD.depend_on_known_directly);
    PERFORM set_session_value('kea.client_class_id', NEW.id);
    PERFORM setClientClass4Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name);
    PERFORM createAuditEntryDHCP4('dhcp4_client_class', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp4_client_class_AUPD\$
LANGUAGE plpgsql;

-- Create dhcp4_client_class update insert trigger
CREATE TRIGGER dhcp4_client_class_AUPD
    AFTER UPDATE ON dhcp4_client_class
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_AUPD();

-- -----------------------------------------------------------------------
-- Trigger procedure to create the audit entry for client class delete.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp4_client_class_ADEL() RETURNS trigger AS \$dhcp4_client_class_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_client_class', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp4_client_class_ADEL\$
LANGUAGE plpgsql;

-- Create dhcp4_client_class delete trigger
CREATE TRIGGER dhcp4_client_class_ADEL
    AFTER DELETE ON dhcp4_client_class
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_ADEL();

-- -----------------------------------------------------------------------
-- Create a table associating client classes stored in the
-- dhcp4_client_class table with their dependencies. There is
-- an M:N relationship between these tables. Each class may have
-- many dependencies (created using member operator in test expression),
-- and each class may be a dependency for many other classes. A caller
-- is responsible for inserting dependencies for a class after inserting
-- or updating it in the dhcp4_client_class table. A caller should
-- delete all existing dependencies for an updated client class, evaluate
-- test expression to discover new dependencies (in case test expression
-- has changed), and insert new dependencies to this table.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp4_client_class_dependency (
    class_id BIGINT PRIMARY KEY NOT NULL,
    dependency_id BIGINT NOT NULL,

    CONSTRAINT dhcp4_client_class_class_id FOREIGN KEY (class_id)
        REFERENCES dhcp4_client_class (id) ON DELETE CASCADE,
    CONSTRAINT dhcp4_client_class_dependency_id FOREIGN KEY (dependency_id)
        REFERENCES dhcp4_client_class (id)
);

CREATE INDEX dhcp4_client_class_dependency_id_idx on dhcp4_client_class_dependency (dependency_id);

-- -----------------------------------------------------------------------
-- Stored procedure verifying if class dependency is met. It includes
-- checking if referenced classes exist, are associated with the same
-- server or all servers, and are defined before the class specified with
-- class_id.
--
-- Parameters:
-- - p_class_id id client class,
-- - p_dependency_id id of the dependency.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION checkDHCPv4ClientClassDependency(p_class_id BIGINT,
                                                            p_dependency_id BIGINT)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    class_index BIGINT;
    dependency_index BIGINT;
BEGIN
    -- We could check the same with a constraint but later in this
    -- trigger we use this value to verify if the dependencies are
    -- met.
    IF p_class_id IS NULL THEN
        RAISE EXCEPTION 'Client class id must not be NULL.'
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    IF p_dependency_id IS NULL THEN
        RAISE EXCEPTION 'Class dependency id must not be NULL.'
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Dependencies on self make no sense.
    IF p_class_id = p_dependency_id THEN
        RAISE EXCEPTION 'Client class must not have dependency on self.'
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Check position of our class in the hierarchy.
    SELECT o.order_index INTO class_index FROM dhcp4_client_class AS c
        INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id
        WHERE c.id = p_class_id;

    IF class_index IS NULL THEN
        RAISE EXCEPTION 'Client class with id % does not exist.', p_class_id
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Check position of the dependency.
    SELECT o.order_index INTO dependency_index FROM dhcp4_client_class AS c
        INNER JOIN dhcp4_client_class_order AS o ON c.id = o.class_id
        WHERE c.id = p_dependency_id;

    IF dependency_index IS NULL THEN
        RAISE EXCEPTION 'Dependency class with id % does not exist.', p_dependency_id
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- The dependency must not be later than our class.
    IF dependency_index > class_index THEN
        RAISE EXCEPTION
            'Client class with id % must not depend on class defined later with id %',
            p_class_id, p_dependency_id USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Check if all servers associated with the new class have dependent
    -- classes configured. This catches the cases that class A belongs to
    -- server1 and depends on class B which belongs only to server 2.
    -- It is fine if the class B belongs to all servers in this case.
    -- Make a SELECT on the dhcp4_client_class_server table to gather
    -- all servers to which the class belongs. LEFT JOIN it with the
    -- same table, selecting all records matching the dependency class
    -- and the servers to which the new class belongs. If there are
    -- any NULL records joined it implies that some dependencies are
    -- not met (didn't find a dependency for at least one server).
    IF EXISTS(
        SELECT 1 FROM dhcp4_client_class_server AS t1
            LEFT JOIN dhcp4_client_class_server AS t2
                ON t2.class_id = p_dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id)
        WHERE t1.class_id = p_class_id AND t2.server_id IS NULL
        LIMIT 1
    ) THEN
        RAISE EXCEPTION 'Unmet dependencies for client class with id %', class_id
            USING ERRCODE = 'sql_routine_exception';
    END IF;
    RETURN;
END;\$\$;


-- -----------------------------------------------------------------------
-- Trigger verifying if class dependency is met. It includes checking
-- if referenced classes exist, are associated with the same server
-- or all servers, and are defined before the class specified with
-- class_id.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp4_client_class_check_dependency_BINS()
    RETURNS trigger AS \$dhcp4_client_class_check_dependency_BINS\$
BEGIN
    PERFORM checkDHCPv4ClientClassDependency(NEW.class_id, NEW.dependency_id);
    RETURN NULL;
END;
\$dhcp4_client_class_check_dependency_BINS\$
LANGUAGE plpgsql;

-- Create dhcp4_client_class_check_dependency_BINS before insert trigger.
CREATE TRIGGER dhcp4_client_class_check_dependency_BINS
    BEFORE INSERT ON dhcp4_client_class_dependency
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_check_dependency_BINS();

-- -----------------------------------------------------------------------
-- Stored procedure setting client class indirect dependency on KNOWN or
-- UNKNOWN built-in classes by checking this flag for the client classes
-- on which it depends.
--
-- Parameters:
-- - client_class_id id of the client class which dependency is set,
-- - dependency_id id of the client class on which the given class depends.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION updateDHCPv4ClientClassKnownDependency(client_class_id BIGINT,
                                                                  dependency_id BIGINT)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    dependency BOOLEAN;
BEGIN
    -- Check if the dependency class references KNOWN/UNKNOWN.
    SELECT depend_on_known_directly INTO dependency FROM dhcp4_client_class
        WHERE id = dependency_id;

    -- If it doesn't, check if the dependency references KNOWN/UNKNOWN
    -- indirectly (via other classes).
    IF dependency = false THEN
        SELECT depend_on_known_indirectly INTO dependency FROM dhcp4_client_class_order
            WHERE class_id = dependency_id;
    END IF;

    IF dependency = true THEN
        UPDATE dhcp4_client_class_order
            SET depend_on_known_indirectly = true
        WHERE class_id = client_class_id;
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN
-- built-in classes by checking this flag for the client classes on which
-- it depends.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp4_client_class_dependency_AINS()
    RETURNS TRIGGER AS \$dhcp4_client_class_dependency_AINS\$
BEGIN
    PERFORM updateDHCPv4ClientClassKnownDependency(NEW.class_id, NEW.dependency_id);
    RETURN NULL;
END;
\$dhcp4_client_class_dependency_AINS\$
LANGUAGE plpgsql;

-- Create dhcp4_client_class_check_dependency_AINS after insert trigger.
CREATE TRIGGER dhcp4_client_class_dependency_AINS
    AFTER INSERT ON dhcp4_client_class_dependency
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_client_class_dependency_AINS();

-- -----------------------------------------------------------------------
-- Stored procedure to be executed before committing a transaction
-- updating a DHCPv4 client class. It verifies if the class dependency on
-- KNOWN or UNKNOWN built-in classes has changed as a result of the
-- update. It signals an error if it has changed and there is at least
-- one class depending on this class.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION checkDHCPv4ClientClassKnownDependencyChange()
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    depended BOOLEAN := false;
    depends BOOLEAN := false;
    client_class_id BIGINT;
    depend_on_known_directly BOOLEAN;
    depend_on_known_indirectly BOOLEAN;
BEGIN

    -- Session variables are set upon a client class update.
    client_class_id := get_session_big_int('kea.client_class_id');
    IF client_class_id IS NOT NULL THEN
        -- Check if any of the classes depend on this class. If not,
        -- it is ok to change the dependency on KNOWN/UNKNOWN.
        IF EXISTS(
            SELECT 1 FROM dhcp4_client_class_dependency
            WHERE dependency_id = client_class_id LIMIT 1
        ) THEN
            -- Using the session variables, determine whether the client class
            -- depended on KNOWN/UNKNOWN before the update.
            depend_on_known_directly := get_session_boolean('kea.depend_on_known_directly');
            depend_on_known_indirectly := get_session_boolean('kea.depend_on_known_indirectly');
            IF depend_on_known_directly = true OR depend_on_known_indirectly = true THEN
                SET depended = true;
            END IF;

            -- Check if the client class depends on KNOWN/UNKNOWN after the update.
            SELECT depend_on_known_directly INTO depends FROM dhcp4_client_class
                WHERE id = client_class_id;

            -- If it doesn't depend directly, check indirect dependencies.
            IF depends = false THEN
                SELECT depend_on_known_indirectly INTO depends FROM dhcp4_client_class_order
                    WHERE class_id = client_class_id;
            END IF;

            -- The resulting dependency on KNOWN/UNKNOWN must not change.
            IF depended <> depends THEN
                RAISE EXCEPTION 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.'
                    USING ERRCODE = 'sql_routine_exception';
            END IF;
        END IF;
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Create table matching DHCPv4 classes with the servers.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp4_client_class_server (
    class_id BIGINT NOT NULL,
    server_id BIGINT NOT NULL,
    modification_ts  TIMESTAMP WITH TIME ZONE NULL DEFAULT NULL,
    PRIMARY KEY (class_id,server_id),
    CONSTRAINT fk_dhcp4_client_class_class_id FOREIGN KEY (class_id)
        REFERENCES dhcp4_client_class (id)
        ON DELETE CASCADE,
    CONSTRAINT fk_dhcp4_client_class_server_id FOREIGN KEY (server_id)
        REFERENCES dhcp4_server (id)
);

CREATE INDEX fk_dhcp4_client_class_server_id ON dhcp4_client_class_server (server_id);

-- -----------------------------------------------------
-- Stored procedure which creates a new entry in the
-- dhcp6_audit_revision table and sets appropriate session
-- variables to be used while creating the audit entries
-- by triggers. This procedure should be called at the
-- beginning of a transaction which modifies configuration
-- data in the database, e.g. when new subnet is added.
--
-- Parameters:
-- - audit_ts timestamp to be associated with the audit
--   revision.
-- - server_tag is used to retrieve the server_id which
--   associates the changes applied with the particular
--   server or all servers.
-- - audit_log_message is a log message associates with
--   the audit revision.
-- - cascade_transaction is assigned to a session
--   variable which is used in some triggers to determine
--   if the audit entry should be created for them or
--   not. Specifically, this is used when DHCP options
--   are inserted, updated or deleted. If such modification
--   is a part of the larger change (e.g. change in the
--   subnet the options belong to) the dedicated audit
--   entry for options must not be created. On the other
--   hand, if the global option is being added, the
--   audit entry for the option must be created because
--   it is the sole object modified in that case.
--   Session variable disable_audit is used to disable
--   the procedure when wiping the database during
--   unit tests.  This avoids issues with revision_id
--   being null.
-- -----------------------------------------------------
CREATE OR REPLACE FUNCTION createAuditRevisionDHCP6(audit_ts TIMESTAMP WITH TIME ZONE,
                                                    server_tag VARCHAR(64),
                                                    audit_log_message TEXT,
                                                    cascade_transaction BOOLEAN)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    disable_audit BOOLEAN := false;
    audit_revision_id BIGINT;
    srv_id BIGINT;
BEGIN
    -- Fetch session value for disable_audit.
    disable_audit := get_session_boolean('kea.disable_audit');
    IF disable_audit = false THEN
        SELECT id INTO srv_id FROM dhcp6_server WHERE tag = server_tag;
        INSERT INTO dhcp6_audit_revision (modification_ts, server_id, log_message)
            VALUES (audit_ts, srv_id, audit_log_message) returning id INTO audit_revision_id;

        -- Update pertinent session variables.
        PERFORM set_session_value('kea.audit_revision_id', audit_revision_id);
        PERFORM set_session_value('kea.cascade_transaction', cascade_transaction);
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------
-- Stored procedure which creates a new entry in the
-- dhcp6_audit table. It should be called from the
-- triggers of the tables where the config modifications
-- are applied. The audit_revision_id variable contains
-- the revision id to be placed in the audit entries.
--
-- The following parameters are passed to this procedure:
-- - object_type_val: name of the table to be associated
--   with the applied changes.
-- - object_id_val: identifier of the modified object in
--   that table.
-- - modification_type_val: string value indicating the
--   type of the change, i.e. 'create', 'update' or
--   'delete'.
--   Session variable disable_audit is used to disable
--   the procedure when wiping the database during
--   unit tests.  This avoids issues with revision_id
--   being null.
-- ----------------------------------------------------
CREATE OR REPLACE FUNCTION createAuditEntryDHCP6(object_type_val VARCHAR(256),
                                                 object_id_val BIGINT,
                                                 modification_type_val VARCHAR(32))
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    audit_revision_id BIGINT;
    disable_audit BOOLEAN := false;
BEGIN
    -- Fetch session value for disable_audit.
    disable_audit := get_session_boolean('kea.disable_audit');
    IF disable_audit = false THEN
        -- Fetch session value most recently created audit_revision_id.
        audit_revision_id := get_session_big_int('kea.audit_revision_id');
        INSERT INTO dhcp6_audit (object_type, object_id, modification_type, revision_id)
            VALUES (object_type_val, object_id_val,
                (SELECT id FROM modification WHERE modification_type = modification_type_val),
                 audit_revision_id);
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Create a table holding the DHCPv6 client classes. Most table
-- columns map directly to respective client class properties in
-- Kea configuration. The depend_on_known_directly column is
-- explicitly set in an insert or update statement to indicate
-- if the client class directly depends on KNOWN or UNKNOWN
-- built-in classes. A caller should determine it by evaluating
-- a test expression before inserting or updating the client
-- class in the database. The nullable follow_class_name column
-- can be used for positioning the inserted or updated client
-- class within the class hierarchy. Set this column value to
-- an existing class name, after which this class should be
-- placed in the class hierarchy. See dhcp6_client_class_order
-- description for the details of how classes are ordered.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp6_client_class (
    id SERIAL PRIMARY KEY NOT NULL,
    name VARCHAR(128) UNIQUE NOT NULL,
    test TEXT,
    only_if_required BOOLEAN NOT NULL DEFAULT false,
    valid_lifetime BIGINT DEFAULT NULL,
    min_valid_lifetime BIGINT DEFAULT NULL,
    max_valid_lifetime BIGINT DEFAULT NULL,
    depend_on_known_directly BOOLEAN NOT NULL DEFAULT false,
    follow_class_name VARCHAR(128) DEFAULT NULL,
    modification_ts TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX key_dhcp6_client_class_modification_ts on dhcp6_client_class (modification_ts);

-- -----------------------------------------------------------------------
-- Create a table for ordering client classes and holding information
-- about indirect dependencies on KNOWN/UKNOWN built-in client classes.
-- Each class in the dhcp6_client_class table has a corresponding row
-- in the dhcp6_client_class_order table. A caller should not modify
-- the contents of this table. Its entries are automatically created
-- upon inserting or updating client classes in the dhcp6_client_classes
-- using triggers. The order_index designates the position of the client
-- class within the class hierarchy. If the follow_class_name value of
-- the dhcp6_client_class table is set to NULL, the client class is
-- appended at the end of the hierarchy. The assigned order_index
-- value for that class is set to a maximum current value + 1.
-- If the follow_client_class specifies a name of an existing class,
-- the generated order_index is set to an id of that class + 1, and
-- the order_index values of the later classes are incremented by 1.
-- The depend_on_known_indirectly column holds a boolean value indicating
-- whether the given class depends on KNOWN/UKNOWN built-in classes
-- via other classes, i.e. it depends on classes that directly or
-- indirectly depend on these built-ins. This value is auto-generated
-- by a trigger on the dhcp6_client_class_dependency table.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp6_client_class_order (
    class_id BIGINT PRIMARY KEY NOT NULL,
    order_index BIGINT NOT NULL,
    depend_on_known_indirectly BOOLEAN NOT NULL DEFAULT false,
    CONSTRAINT fk_dhcp6_client_class_order_class_id FOREIGN KEY (class_id)
        REFERENCES dhcp6_client_class (id) ON DELETE CASCADE
);

CREATE INDEX key_dhcp6_client_class_order_index on dhcp6_client_class_order (order_index);

-- -----------------------------------------------------------------------
-- Stored procedure positioning an inserted or updated client class
-- within the class hierarchy, depending on the value of the
-- new_follow_class_name parameter.
--
-- Parameters:
-- - id id of the positioned class,
-- - new_follow_class_name name of the class after which this class should be
--   positioned within the class hierarchy.
-- - old_follow_class_name previous name of the class after which this
--   class was positioned within the class hierarchy.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION setClientClass6Order(id BIGINT,
                                                new_follow_class_name VARCHAR(128),
                                                old_follow_class_name VARCHAR(128))
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    -- Used to fetch class's current value for depend_on_known_indirectly
    l_depend_on_known_indirectly BIGINT := 0;

    -- Optionally set if the follow_class_name column value is specified.
    follow_class_index BIGINT;
BEGIN
    -- Fetch the class's current value of depend_on_known_indirectly.
    SELECT depend_on_known_indirectly INTO l_depend_on_known_indirectly
        FROM dhcp6_client_class_order WHERE id = class_id;

    -- Save it to the current session for use elsewhere during this transaction.
    -- Note this does not work prior to Postgres 9.2 unless the variables are
    -- defined in postgresql.conf. I think for now we put up with CB not supported
    -- prior to 9.2 or we tell people how to edit the conf file.
    PERFORM set_session_value('kea.depend_on_known_indirectly', l_depend_on_known_indirectly);

    -- Bail if the class is updated without re-positioning.
    IF(
       l_depend_on_known_indirectly IS NOT NULL AND
       ((new_follow_class_name IS NULL AND old_follow_class_name IS NULL) OR
        (new_follow_class_name = old_follow_class_name))
    ) THEN
        -- The depend_on_known_indirectly is set to 0 because this procedure is invoked
        -- whenever the dhcp6_client_class record is updated. Such update may include
        -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes.
        -- This value will be later adjusted when dependencies are inserted.
        -- TKM should we update the session value also or is it moot?
        UPDATE dhcp6_client_class_order SET depend_on_known_indirectly = false
            WHERE class_id = id;
        RETURN;
    END IF;

    IF new_follow_class_name IS NOT NULL THEN
        -- Get the position of the class after which the new class should be added.
        SELECT o.order_index INTO follow_class_index
            FROM dhcp6_client_class AS c
            INNER JOIN dhcp6_client_class_order AS o
                ON c.id = o.class_id
            WHERE c.name = new_follow_class_name;

        IF follow_class_index IS NULL THEN
            -- The class with a name specified with new_follow_class_name does
            -- not exist.
            RAISE EXCEPTION 'Class %s does not exist.', new_follow_class_name
                USING ERRCODE = 'sql_routine_exception';
        END IF;

        -- We need to place the new class at the position of follow_class_index + 1.
        -- There may be a class at this position already.
        IF EXISTS(SELECT * FROM dhcp6_client_class_order WHERE order_index = follow_class_index + 1) THEN
            -- There is a class at this position already. Let's move all classes
            -- starting from this position by one to create a spot for the new
            -- class.
            UPDATE dhcp6_client_class_order
                SET order_index = order_index + 1
            WHERE order_index >= follow_class_index + 1;
            -- TKM postgresql doesn't like order by here, does it matter?
            -- ORDER BY order_index DESC;
        END IF;

    ELSE
        -- A caller did not specify the new_follow_class_name value. Let's append the
        -- new class at the end of the hierarchy.
        SELECT MAX(order_index) INTO follow_class_index FROM dhcp6_client_class_order;
        IF follow_class_index IS NULL THEN
            -- Apparently, there are no classes. Let's start from 0.
            follow_class_index = 0;
        END IF;
    END IF;

    -- Check if moving the class doesn't break dependent classes.
    IF EXISTS(
        SELECT 1 FROM dhcp6_client_class_dependency AS d
            INNER JOIN dhcp6_client_class_order AS o
                ON d.class_id = o.class_id
            WHERE d.dependency_id = id AND o.order_index < follow_class_index + 1
        LIMIT 1
    ) THEN
        RAISE EXCEPTION 'Unable to move class with id %s because it would break its dependencies', id
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- The depend_on_known_indirectly is set to 0 because this procedure is invoked
    -- whenever the dhcp6_client_class record is updated. Such update may include
    -- test expression changes impacting the dependency on KNOWN/UNKNOWN classes.
    -- This value will be later adjusted when dependencies are inserted.
    -- TKM - note that ON CONFLICT requires PostgreSQL 9.5 or later.
    UPDATE dhcp6_client_class_order
        SET order_index = follow_class_index + 1,
            depend_on_known_indirectly = l_depend_on_known_indirectly
        WHERE class_id = id;
    IF FOUND THEN
        RETURN;
    END IF;

    INSERT INTO  dhcp6_client_class_order(class_id, order_index, depend_on_known_indirectly)
        VALUES (id, follow_class_index + 1, 0);
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Trigger procedure to position an inserted class within the class hierarchy
-- and create audit.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp6_client_class_AINS() RETURNS trigger AS \$dhcp6_client_class_AINS\$
BEGIN
    PERFORM setClientClass6Order(NEW.id, NEW.follow_class_name, NULL);
    PERFORM createAuditEntryDHCP6('dhcp6_client_class', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp6_client_class_AINS\$
LANGUAGE plpgsql;

-- Create dhcp6_client_class insert trigger
CREATE TRIGGER dhcp6_client_class_AINS
    AFTER INSERT ON dhcp6_client_class
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_AINS();

-- -----------------------------------------------------------------------
-- Trigger to position an updated class within the class hierarchy,
-- create audit and remember the direct dependency on the
-- KNOWN/UNKNOWN built-in classes before the class update.
-- When updating a client class, it is very important to ensure that
-- its dependency on KNOWN or UNKNOWN built-in client classes is not
-- changed. It is because there may be other classes that depend on
-- these built-ins via this class. Changing the dependency would break
-- the chain of dependencies for other classes. Here, we store the
-- information about the dependency in the session variables. Their
-- values will be compared with the new dependencies after an update.
-- If they change, an error will be signaled.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp6_client_class_AUPD() RETURNS trigger AS \$dhcp6_client_class_AUPD\$
BEGIN
    PERFORM set_session_value('kea.depend_on_known_directly', OLD.depend_on_known_directly);
    PERFORM set_session_value('kea.client_class_id', NEW.id);
    PERFORM setClientClass6Order(NEW.id, NEW.follow_class_name, OLD.follow_class_name);
    PERFORM createAuditEntryDHCP6('dhcp6_client_class', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp6_client_class_AUPD\$
LANGUAGE plpgsql;

-- Create dhcp6_client_class update insert trigger
CREATE TRIGGER dhcp6_client_class_AUPD
    AFTER UPDATE ON dhcp6_client_class
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_AUPD();

-- -----------------------------------------------------------------------
-- Trigger procedure to create the audit entry for client class delete.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp6_client_class_ADEL() RETURNS trigger AS \$dhcp6_client_class_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_client_class', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp6_client_class_ADEL\$
LANGUAGE plpgsql;

-- Create dhcp6_client_class delete trigger
CREATE TRIGGER dhcp6_client_class_ADEL
    AFTER DELETE ON dhcp6_client_class
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_ADEL();

-- -----------------------------------------------------------------------
-- Create a table associating client classes stored in the
-- dhcp6_client_class table with their dependencies. There is
-- an M:N relationship between these tables. Each class may have
-- many dependencies (created using member operator in test expression),
-- and each class may be a dependency for many other classes. A caller
-- is responsible for inserting dependencies for a class after inserting
-- or updating it in the dhcp6_client_class table. A caller should
-- delete all existing dependencies for an updated client class, evaluate
-- test expression to discover new dependencies (in case test expression
-- has changed), and insert new dependencies to this table.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp6_client_class_dependency (
    class_id BIGINT PRIMARY KEY NOT NULL,
    dependency_id BIGINT NOT NULL,

    CONSTRAINT dhcp6_client_class_class_id FOREIGN KEY (class_id)
        REFERENCES dhcp6_client_class (id) ON DELETE CASCADE,
    CONSTRAINT dhcp6_client_class_dependency_id FOREIGN KEY (dependency_id)
        REFERENCES dhcp6_client_class (id)
);

CREATE INDEX dhcp6_client_class_dependency_id_idx on dhcp6_client_class_dependency (dependency_id);

-- -----------------------------------------------------------------------
-- Stored procedure verifying if class dependency is met. It includes
-- checking if referenced classes exist, are associated with the same
-- server or all servers, and are defined before the class specified with
-- class_id.
--
-- Parameters:
-- - p_class_id id client class,
-- - p_dependency_id id of the dependency.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION checkDHCPv6ClientClassDependency(p_class_id BIGINT,
                                                            p_dependency_id BIGINT)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    class_index BIGINT;
    dependency_index BIGINT;
BEGIN
    -- We could check the same with a constraint but later in this
    -- trigger we use this value to verify if the dependencies are
    -- met.
    IF p_class_id IS NULL THEN
        RAISE EXCEPTION 'Client class id must not be NULL.'
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    IF p_dependency_id IS NULL THEN
        RAISE EXCEPTION 'Class dependency id must not be NULL.'
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Dependencies on self make no sense.
    IF p_class_id = p_dependency_id THEN
        RAISE EXCEPTION 'Client class must not have dependency on self.'
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Check position of our class in the hierarchy.
    SELECT o.order_index INTO class_index FROM dhcp6_client_class AS c
        INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id
        WHERE c.id = p_class_id;

    IF class_index IS NULL THEN
        RAISE EXCEPTION 'Client class with id % does not exist.', p_class_id
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Check position of the dependency.
    SELECT o.order_index INTO dependency_index FROM dhcp6_client_class AS c
        INNER JOIN dhcp6_client_class_order AS o ON c.id = o.class_id
        WHERE c.id = p_dependency_id;

    IF dependency_index IS NULL THEN
        RAISE EXCEPTION 'Dependency class with id % does not exist.', p_dependency_id
            USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- The dependency must not be later than our class.
    IF dependency_index > class_index THEN
        RAISE EXCEPTION
            'Client class with id % must not depend on class defined later with id %',
            p_class_id, p_dependency_id USING ERRCODE = 'sql_routine_exception';
    END IF;

    -- Check if all servers associated with the new class have dependent
    -- classes configured. This catches the cases that class A belongs to
    -- server1 and depends on class B which belongs only to server 2.
    -- It is fine if the class B belongs to all servers in this case.
    -- Make a SELECT on the dhcp6_client_class_server table to gather
    -- all servers to which the class belongs. LEFT JOIN it with the
    -- same table, selecting all records matching the dependency class
    -- and the servers to which the new class belongs. If there are
    -- any NULL records joined it implies that some dependencies are
    -- not met (didn't find a dependency for at least one server).
    IF EXISTS(
        SELECT 1 FROM dhcp6_client_class_server AS t1
            LEFT JOIN dhcp6_client_class_server AS t2
                ON t2.class_id = p_dependency_id AND (t2.server_id = 1 OR t2.server_id = t1.server_id)
        WHERE t1.class_id = p_class_id AND t2.server_id IS NULL
        LIMIT 1
    ) THEN
        RAISE EXCEPTION 'Unmet dependencies for client class with id %', p_class_id
            USING ERRCODE = 'sql_routine_exception';
    END IF;
    RETURN;
END;\$\$;


-- -----------------------------------------------------------------------
-- Trigger verifying if class dependency is met. It includes checking
-- if referenced classes exist, are associated with the same server
-- or all servers, and are defined before the class specified with
-- class_id.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp6_client_class_check_dependency_BINS()
    RETURNS trigger AS \$dhcp6_client_class_check_dependency_BINS\$
BEGIN
    PERFORM checkDHCPv6ClientClassDependency(NEW.class_id, NEW.dependency_id);
    RETURN NULL;
END;
\$dhcp6_client_class_check_dependency_BINS\$
LANGUAGE plpgsql;

-- Create dhcp6_client_class_check_dependency_BINS before insert trigger.
CREATE TRIGGER dhcp6_client_class_check_dependency_BINS
    BEFORE INSERT ON dhcp6_client_class_dependency
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_check_dependency_BINS();

-- -----------------------------------------------------------------------
-- Stored procedure setting client class indirect dependency on KNOWN or
-- UNKNOWN built-in classes by checking this flag for the client classes
-- on which it depends.
--
-- Parameters:
-- - client_class_id id of the client class which dependency is set,
-- - dependency_id id of the client class on which the given class depends.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION updateDHCPv6ClientClassKnownDependency(client_class_id BIGINT,
                                                                  dependency_id BIGINT)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    dependency BOOLEAN;
BEGIN
    -- Check if the dependency class references KNOWN/UNKNOWN.
    SELECT depend_on_known_directly INTO dependency FROM dhcp6_client_class
        WHERE id = dependency_id;

    -- If it doesn't, check if the dependency references KNOWN/UNKNOWN
    -- indirectly (via other classes).
    IF dependency = false THEN
        SELECT depend_on_known_indirectly INTO dependency FROM dhcp6_client_class_order
            WHERE class_id = dependency_id;
    END IF;

    IF dependency = true THEN
        UPDATE dhcp6_client_class_order
            SET depend_on_known_indirectly = true
        WHERE class_id = client_class_id;
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Trigger setting client class indirect dependency on KNOWN or UNKNOWN
-- built-in classes by checking this flag for the client classes on which
-- it depends.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION func_dhcp6_client_class_dependency_AINS()
    RETURNS TRIGGER AS \$dhcp6_client_class_dependency_AINS\$
BEGIN
    PERFORM updateDHCPv6ClientClassKnownDependency(NEW.class_id, NEW.dependency_id);
    RETURN NULL;
END;
\$dhcp6_client_class_dependency_AINS\$
LANGUAGE plpgsql;

-- Create dhcp6_client_class_check_dependency_AINS after insert trigger.
CREATE TRIGGER dhcp6_client_class_dependency_AINS
    AFTER INSERT ON dhcp6_client_class_dependency
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_client_class_dependency_AINS();

-- -----------------------------------------------------------------------
-- Stored procedure to be executed before committing a transaction
-- updating a DHCPv6 client class. It verifies if the class dependency on
-- KNOWN or UNKNOWN built-in classes has changed as a result of the
-- update. It signals an error if it has changed and there is at least
-- one class depending on this class.
-- -----------------------------------------------------------------------
CREATE OR REPLACE FUNCTION checkDHCPv6ClientClassKnownDependencyChange()
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    depended BOOLEAN := false;
    depends BOOLEAN := false;
    client_class_id BIGINT;
    depend_on_known_directly BOOLEAN;
    depend_on_known_indirectly BOOLEAN;
BEGIN

    -- Session variables are set upon a client class update.
    client_class_id := get_session_big_int('kea.client_class_id');
    IF client_class_id IS NOT NULL THEN
        -- Check if any of the classes depend on this class. If not,
        -- it is ok to change the dependency on KNOWN/UNKNOWN.
        IF EXISTS(
            SELECT 1 FROM dhcp6_client_class_dependency
            WHERE dependency_id = client_class_id LIMIT 1
        ) THEN
            -- Using the session variables, determine whether the client class
            -- depended on KNOWN/UNKNOWN before the update.
            depend_on_known_directly := get_session_boolean('kea.depend_on_known_directly');
            depend_on_known_indirectly := get_session_boolean('kea.depend_on_known_indirectly');
            IF depend_on_known_directly = true OR depend_on_known_indirectly = true THEN
                SET depended = true;
            END IF;

            -- Check if the client class depends on KNOWN/UNKNOWN after the update.
            SELECT depend_on_known_directly INTO depends FROM dhcp6_client_class
                WHERE id = client_class_id;

            -- If it doesn't depend directly, check indirect dependencies.
            IF depends = false THEN
                SELECT depend_on_known_indirectly INTO depends FROM dhcp6_client_class_order
                    WHERE class_id = client_class_id;
            END IF;

            -- The resulting dependency on KNOWN/UNKNOWN must not change.
            IF depended <> depends THEN
                RAISE EXCEPTION 'Class dependency on KNOWN/UNKNOWN built-in classes must not change.'
                    USING ERRCODE = 'sql_routine_exception';
            END IF;
        END IF;
    END IF;
    RETURN;
END;\$\$;

-- -----------------------------------------------------------------------
-- Create table matching DHCPv6 classes with the servers.
-- -----------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS dhcp6_client_class_server (
    class_id BIGINT NOT NULL,
    server_id BIGINT NOT NULL,
    modification_ts  TIMESTAMP WITH TIME ZONE NULL DEFAULT NULL,
    PRIMARY KEY (class_id,server_id),
    CONSTRAINT fk_dhcp6_client_class_class_id FOREIGN KEY (class_id)
        REFERENCES dhcp6_client_class (id)
        ON DELETE CASCADE,
    CONSTRAINT fk_dhcp6_client_class_server_id FOREIGN KEY (server_id)
        REFERENCES dhcp6_server (id)
);

CREATE INDEX fk_dhcp6_client_class_server_id ON dhcp6_client_class_server (server_id);

-- Trigger function for dhcp4_pool_BDEL called BEFORE DELETE on dhcp4_pool
-- It removes pool specific options upon removal of the pool.
CREATE OR REPLACE FUNCTION func_dhcp4_pool_BDEL() RETURNS TRIGGER AS \$dhcp4_pool_BDEL\$
BEGIN
    DELETE FROM dhcp4_options WHERE scope_id = 5 AND pool_id = OLD.id;
    RETURN OLD;
END;
\$dhcp4_pool_BDEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_pool_BDEL
    BEFORE DELETE ON dhcp4_pool
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_pool_BDEL();

-- Trigger function for dhcp6_pool_BDEL called BEFORE DELETE on dhcp6_pool
-- It removes pool specific options upon removal of the pool.
CREATE OR REPLACE FUNCTION func_dhcp6_pool_BDEL() RETURNS TRIGGER AS \$dhcp6_pool_BDEL\$
BEGIN
    DELETE FROM dhcp6_options WHERE scope_id = 5 AND pool_id = OLD.id;
    RETURN OLD;
END;
\$dhcp6_pool_BDEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_pool_BDEL
    BEFORE DELETE ON dhcp6_pool
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_pool_BDEL();

-- Trigger function for dhcp4_global_parameter_AINS called AFTER INSERT on dhcp4_global_parameter
CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_AINS() RETURNS TRIGGER AS \$dhcp4_global_parameter_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp4_global_parameter_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_global_parameter_AINS
    AFTER INSERT ON dhcp4_global_parameter
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_AINS();


-- Trigger function for dhcp4_global_parameter_AUPD called AFTER UPDATE on dhcp4_global_parameter
CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_AUPD() RETURNS TRIGGER AS \$dhcp4_global_parameter_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp4_global_parameter_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_global_parameter_AUPD
    AFTER UPDATE ON dhcp4_global_parameter
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_AUPD();


-- Trigger function for dhcp4_global_parameter_ADEL called AFTER DELETE on dhcp4_global_parameter
CREATE OR REPLACE FUNCTION func_dhcp4_global_parameter_ADEL() RETURNS TRIGGER AS \$dhcp4_global_parameter_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_global_parameter', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp4_global_parameter_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_global_parameter_ADEL
    AFTER DELETE ON dhcp4_global_parameter
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_global_parameter_ADEL();

-- Trigger function for dhcp4_subnet_AINS called AFTER INSERT on dhcp4_subnet
CREATE OR REPLACE FUNCTION func_dhcp4_subnet_AINS() RETURNS TRIGGER AS \$dhcp4_subnet_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, 'create');
    RETURN NULL;
END;
\$dhcp4_subnet_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_subnet_AINS
    AFTER INSERT ON dhcp4_subnet
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_AINS();


-- Trigger function for dhcp4_subnet_AUPD called AFTER UPDATE on dhcp4_subnet
CREATE OR REPLACE FUNCTION func_dhcp4_subnet_AUPD() RETURNS TRIGGER AS \$dhcp4_subnet_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_subnet', NEW.subnet_id, 'update');
    RETURN NULL;
END;
\$dhcp4_subnet_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_subnet_AUPD
    AFTER UPDATE ON dhcp4_subnet
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_AUPD();


-- Trigger function for dhcp4_shared_network_AINS called AFTER INSERT on dhcp4_shared_network
CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_AINS() RETURNS TRIGGER AS \$dhcp4_shared_network_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp4_shared_network_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_shared_network_AINS
    AFTER INSERT ON dhcp4_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_AINS();

-- Trigger function for dhcp4_shared_network_AUPD called AFTER UPDATE on dhcp4_shared_network
CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_AUPD() RETURNS TRIGGER AS \$dhcp4_shared_network_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_shared_network', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp4_shared_network_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_shared_network_AUPD
    AFTER UPDATE ON dhcp4_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_AUPD();

-- Trigger function for dhcp4_shared_network_ADEL called AFTER DELETE on dhcp4_shared_network
CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_ADEL() RETURNS TRIGGER AS \$dhcp4_shared_network_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp4_shared_network_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_shared_network_ADEL
    AFTER DELETE ON dhcp4_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_ADEL();

-- Trigger function for dhcp4_option_def_AINS called AFTER INSERT on dhcp4_option_def
CREATE OR REPLACE FUNCTION func_dhcp4_option_def_AINS() RETURNS TRIGGER AS \$dhcp4_option_def_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_option_def', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp4_option_def_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_option_def_AINS
    AFTER INSERT ON dhcp4_option_def
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_AINS();

-- Trigger function for dhcp4_option_def_AUPD called AFTER UPDATE on dhcp4_option_def
CREATE OR REPLACE FUNCTION func_dhcp4_option_def_AUPD() RETURNS TRIGGER AS \$dhcp4_option_def_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_option_def', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp4_option_def_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_option_def_AUPD
    AFTER UPDATE ON dhcp4_option_def
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_AUPD();

-- Trigger function for dhcp4_option_def_ADEL called AFTER DELETE on dhcp4_option_def
CREATE OR REPLACE FUNCTION func_dhcp4_option_def_ADEL() RETURNS TRIGGER AS \$dhcp4_option_def_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_option_def', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp4_option_def_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_option_def_ADEL
    AFTER DELETE ON dhcp4_option_def
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_option_def_ADEL();

-- -----------------------------------------------------
--
-- Stored procedure which updates modification timestamp of
-- a parent object when an option is modified.
--
-- The following parameters are passed to the procedure:
-- - modification_type: 'create', 'update' or 'delete'
-- - scope_id: identifier of the option scope, e.g.
--   global, subnet specific etc.
-- - option_id: identifier of the option.
-- - p_subnet_id: identifier of the subnet if the option
--   belongs to the subnet.
-- - host_id: identifier of the host if the option
-- - belongs to the host.
-- - network_name: shared network name if the option
--   belongs to the shared network.
-- - pool_id: identifier of the pool if the option
--   belongs to the pool.
-- - p_modification_ts: modification timestamp of the
--   option.
--   Some arguments are prefixed with "p_" to avoid ambiguity
--   with column names in SQL statements. PostgreSQL does not
--   allow table aliases to be used with column names in update
--   set expressions.
-- -----------------------------------------------------
CREATE OR REPLACE FUNCTION createOptionAuditDHCP4(modification_type VARCHAR,
                                                  scope_id SMALLINT,
                                                  option_id INT,
                                                  p_subnet_id BIGINT,
                                                  host_id INT,
                                                  network_name VARCHAR,
                                                  pool_id BIGINT,
                                                  p_modification_ts TIMESTAMP WITH TIME ZONE)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    -- These variables will hold shared network id and subnet id that
    -- we will select.
    snid VARCHAR(128);
    sid BIGINT;
    cascade_transaction BOOLEAN := true;
    ct TEXT;
BEGIN
    -- Cascade transaction flag is set to true to prevent creation of
    -- the audit entries for the options when the options are
    -- created as part of the parent object creation or update.
    -- For example: when the option is added as part of the subnet
    -- addition, the cascade transaction flag is equal to true. If
    -- the option is added into the existing subnet the cascade
    -- transaction is equal to false. Note that depending on the option
    -- scope the audit entry will contain the object_type value
    -- of the parent object to cause the server to replace the
    -- entire subnet. The only case when the object_type will be
    -- set to 'dhcp4_options' is when a global option is added.
    -- Global options do not have the owner.

    cascade_transaction := get_session_boolean('kea.cascade_transaction');
    IF cascade_transaction = false THEN
        -- todo: host manager hasn't been updated to use audit
        -- mechanisms so ignore host specific options for now.
        IF scope_id = 0 THEN
            -- If a global option is added or modified, create audit
            -- entry for the 'dhcp4_options' table.
            PERFORM createAuditEntryDHCP4('dhcp4_options', option_id, modification_type);
        ELSEIF scope_id = 1 THEN
            -- If subnet specific option is added or modified, update
            -- the modification timestamp of this subnet to allow the
            -- servers to refresh the subnet information. This will
            -- also result in creating an audit entry for this subnet.
            UPDATE dhcp4_subnet SET modification_ts = p_modification_ts
                WHERE subnet_id = p_subnet_id;
        ELSEIF scope_id = 4 THEN
            -- If shared network specific option is added or modified,
            -- update the modification timestamp of this shared network
            -- to allow the servers to refresh the shared network
            -- information. This will also result in creating an
            -- audit entry for this shared network.
           SELECT id INTO snid FROM dhcp4_shared_network WHERE name = network_name LIMIT 1;
           UPDATE dhcp4_shared_network SET modification_ts = p_modification_ts
                WHERE id = snid;
        ELSEIF scope_id = 5 THEN
            -- If pool specific option is added or modified, update
            -- the modification timestamp of the owning subnet.
            SELECT dhcp4_pool.subnet_id INTO sid FROM dhcp4_pool WHERE id = pool_id;
            UPDATE dhcp4_subnet SET modification_ts = p_modification_ts
                WHERE subnet_id = sid;
        END IF;
    END IF;
    RETURN;
END;\$\$;

-- Trigger function for dhcp4_options_AINS called AFTER INSERT on dhcp4_options
CREATE OR REPLACE FUNCTION func_dhcp4_options_AINS() RETURNS TRIGGER AS \$dhcp4_options_AINS\$
BEGIN
    PERFORM createOptionAuditDHCP4('create', NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id,
                                   NEW.host_id, NEW.shared_network_name, NEW.pool_id,
                                   NEW.modification_ts);
    RETURN NULL;
END;
\$dhcp4_options_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_options_AINS
    AFTER INSERT ON dhcp4_options
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_AINS();


-- Trigger function for dhcp4_options_AUPD called AFTER UPDATE on dhcp4_options
CREATE OR REPLACE FUNCTION func_dhcp4_options_AUPD() RETURNS TRIGGER AS \$dhcp4_options_AUPD\$
BEGIN
    PERFORM createOptionAuditDHCP4('update', NEW.scope_id, NEW.option_id, NEW.dhcp4_subnet_id,
                                   NEW.host_id, NEW.shared_network_name, NEW.pool_id,
                                   NEW.modification_ts);
    RETURN NULL;
END;
\$dhcp4_options_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_options_AUPD
    AFTER UPDATE ON dhcp4_options
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_AUPD();

-- Trigger function for dhcp4_options_ADEL called AFTER DELETE on dhcp4_options
CREATE OR REPLACE FUNCTION func_dhcp4_options_ADEL() RETURNS TRIGGER AS \$dhcp4_options_ADEL\$
BEGIN
    PERFORM createOptionAuditDHCP4('delete', OLD.scope_id, OLD.option_id, OLD.dhcp4_subnet_id,
                                   OLD.host_id, OLD.shared_network_name, OLD.pool_id,
                                   NOW());
    RETURN NULL;
END;
\$dhcp4_options_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_options_ADEL
    AFTER DELETE ON dhcp4_options
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_options_ADEL();

-- Trigger function for dhcp6_global_parameter_AINS called AFTER INSERT on dhcp6_global_parameter
CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_AINS() RETURNS TRIGGER AS \$dhcp6_global_parameter_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp6_global_parameter_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_global_parameter_AINS
    AFTER INSERT ON dhcp6_global_parameter
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_AINS();

-- Trigger function for dhcp6_global_parameter_AUPD called AFTER UPDATE on dhcp6_global_parameter
CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_AUPD() RETURNS TRIGGER AS \$dhcp6_global_parameter_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp6_global_parameter_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_global_parameter_AUPD
    AFTER UPDATE ON dhcp6_global_parameter
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_AUPD();

-- Trigger function for dhcp6_global_parameter_ADEL called AFTER DELETE on dhcp6_global_parameter
CREATE OR REPLACE FUNCTION func_dhcp6_global_parameter_ADEL() RETURNS TRIGGER AS \$dhcp6_global_parameter_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_global_parameter', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp6_global_parameter_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_global_parameter_ADEL
    AFTER DELETE ON dhcp6_global_parameter
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_global_parameter_ADEL();

-- Trigger function for dhcp6_subnet_AINS called AFTER INSERT on dhcp6_subnet
CREATE OR REPLACE FUNCTION func_dhcp6_subnet_AINS() RETURNS TRIGGER AS \$dhcp6_subnet_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, 'create');
    RETURN NULL;
END;
\$dhcp6_subnet_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_subnet_AINS
    AFTER INSERT ON dhcp6_subnet
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_AINS();

-- Trigger function for dhcp6_subnet_AUPD called AFTER UPDATE on dhcp6_subnet
CREATE OR REPLACE FUNCTION func_dhcp6_subnet_AUPD() RETURNS TRIGGER AS \$dhcp6_subnet_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_subnet', NEW.subnet_id, 'update');
    RETURN NULL;
END;
\$dhcp6_subnet_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_subnet_AUPD
    AFTER UPDATE ON dhcp6_subnet
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_AUPD();

-- Trigger function for dhcp6_shared_network_AINS called AFTER INSERT on dhcp6_shared_network
CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_AINS() RETURNS TRIGGER AS \$dhcp6_shared_network_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp6_shared_network_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_shared_network_AINS
    AFTER INSERT ON dhcp6_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_AINS();

-- Trigger function for dhcp6_shared_network_AUPD called AFTER UPDATE on dhcp6_shared_network
CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_AUPD() RETURNS TRIGGER AS \$dhcp6_shared_network_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_shared_network', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp6_shared_network_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_shared_network_AUPD
    AFTER UPDATE ON dhcp6_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_AUPD();

-- Trigger function for dhcp6_shared_network_ADEL called AFTER DELETE on dhcp6_shared_network
CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_ADEL() RETURNS TRIGGER AS \$dhcp6_shared_network_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp6_shared_network_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_shared_network_ADEL
    AFTER DELETE ON dhcp6_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_ADEL();

-- Trigger function for dhcp6_option_def_AINS called AFTER INSERT on dhcp6_option_def
CREATE OR REPLACE FUNCTION func_dhcp6_option_def_AINS() RETURNS TRIGGER AS \$dhcp6_option_def_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_option_def', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp6_option_def_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_option_def_AINS
    AFTER INSERT ON dhcp6_option_def
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_AINS();

-- Trigger function for dhcp6_option_def_AUPD called AFTER UPDATE on dhcp6_option_def
CREATE OR REPLACE FUNCTION func_dhcp6_option_def_AUPD() RETURNS TRIGGER AS \$dhcp6_option_def_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_option_def', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp6_option_def_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_option_def_AUPD
    AFTER UPDATE ON dhcp6_option_def
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_AUPD();

-- Trigger function for dhcp6_option_def_ADEL called AFTER DELETE on dhcp6_option_def
CREATE OR REPLACE FUNCTION func_dhcp6_option_def_ADEL() RETURNS TRIGGER AS \$dhcp6_option_def_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_option_def', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp6_option_def_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_option_def_ADEL
    AFTER DELETE ON dhcp6_option_def
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_option_def_ADEL();

-- - pool_id: identifier of the pool if the option
--   belongs to the pool.
-- - pd_pool_id: identifier of the pool if the option
--   belongs to the pd pool.
-- - modification_ts: modification timestamp of the
--   option.
-- -----------------------------------------------------
CREATE OR REPLACE FUNCTION createOptionAuditDHCP6(modification_type VARCHAR(32),
                                                  scope_id SMALLINT,
                                                  option_id INT,
                                                  subnet_id BIGINT,
                                                  host_id INT,
                                                  network_name VARCHAR(128),
                                                  pool_id BIGINT,
                                                  pd_pool_id BIGINT,
                                                  modification_ts TIMESTAMP WITH TIME ZONE)
RETURNS VOID
LANGUAGE plpgsql
AS \$\$
DECLARE
    -- These variables will hold shared network id and subnet id that
    -- we will select.
    snid VARCHAR(128);
    sid BIGINT;
    cascade_transaction BOOLEAN := false;

BEGIN
    -- Cascade transaction flag is set to true to prevent creation of
    -- the audit entries for the options when the options are
    -- created as part of the parent object creation or update.
    -- For example: when the option is added as part of the subnet
    -- addition, the cascade transaction flag is equal to true. If
    -- the option is added into the existing subnet the cascade
    -- transaction is equal to false. Note that depending on the option
    -- scope the audit entry will contain the object_type value
    -- of the parent object to cause the server to replace the
    -- entire subnet. The only case when the object_type will be
    -- set to 'dhcp6_options' is when a global option is added.
    -- Global options do not have the owner.
    cascade_transaction := get_session_boolean('kea.cascade_transaction');
    IF cascade_transaction = false THEN
        -- todo: host manager hasn't been updated to use audit
        -- mechanisms so ignore host specific options for now.
        IF scope_id = 0 THEN
            -- If a global option is added or modified, create audit
            -- entry for the 'dhcp6_options' table.
            PERFORM createAuditEntryDHCP6('dhcp6_options', option_id, modification_type);
        ELSEIF scope_id = 1 THEN
            -- If subnet specific option is added or modified, create
            -- audit entry for the entire subnet, which indicates that
            -- it should be treated as the subnet update.
            PERFORM createAuditEntryDHCP6('dhcp6_subnet', subnet_id, 'update');
        ELSEIF scope_id = 4 THEN
            -- If shared network specific option is added or modified,
            -- create audit entry for the shared network which
            -- indicates that it should be treated as the shared
            -- network update.
           SELECT id INTO snid FROM dhcp6_shared_network
                WHERE name = network_name LIMIT 1;
           PERFORM createAuditEntryDHCP6('dhcp6_shared_network', snid, 'update');
        ELSEIF scope_id = 5 THEN
            -- If pool specific option is added or modified, create
            -- audit entry for the subnet which this pool belongs to.
            SELECT dhcp6_pool.subnet_id INTO sid FROM dhcp6_pool WHERE id = pool_id;
            PERFORM createAuditEntryDHCP6('dhcp6_subnet', sid, 'update');
        ELSEIF scope_id = 6 THEN
            -- If pd pool specific option is added or modified, create
            -- audit entry for the subnet which this pd pool belongs to.
            SELECT dhcp6_pd_pool.subnet_id INTO sid FROM dhcp6_pd_pool
                WHERE id = pd_pool_id;
            PERFORM createAuditEntryDHCP6('dhcp6_subnet', sid, 'update');
        END IF;
    END IF;
    RETURN;
END;\$\$;

-- Trigger function for dhcp6_options_AINS called AFTER INSERT on dhcp6_options
CREATE OR REPLACE FUNCTION func_dhcp6_options_AINS() RETURNS TRIGGER AS \$dhcp6_options_AINS\$
BEGIN
    PERFORM createOptionAuditDHCP6('create', NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id,
                                   NEW.host_id, NEW.shared_network_name, NEW.pool_id,
                                   NEW.pd_pool_id, NEW.modification_ts);
    RETURN NULL;
END;
\$dhcp6_options_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_options_AINS
    AFTER INSERT ON dhcp6_options
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_AINS();

-- Trigger function for dhcp6_options_AUPD called AFTER UPDATE on dhcp6_options
CREATE OR REPLACE FUNCTION func_dhcp6_options_AUPD() RETURNS TRIGGER AS \$dhcp6_options_AUPD\$
BEGIN
    PERFORM createOptionAuditDHCP6('update', NEW.scope_id, NEW.option_id, NEW.dhcp6_subnet_id,
                                   NEW.host_id, NEW.shared_network_name, NEW.pool_id,
                                   NEW.pd_pool_id, NEW.modification_ts);
    RETURN NULL;
END;
\$dhcp6_options_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_options_AUPD
    AFTER UPDATE ON dhcp6_options
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_AUPD();


-- Trigger function for dhcp6_options_ADEL called AFTER DELETE on dhcp6_options
CREATE OR REPLACE FUNCTION func_dhcp6_options_ADEL() RETURNS TRIGGER AS \$dhcp6_options_ADEL\$
BEGIN
    PERFORM createOptionAuditDHCP6('delete', OLD.scope_id, OLD.option_id, OLD.dhcp6_subnet_id,
                                   OLD.host_id, OLD.shared_network_name, OLD.pool_id,
                                   OLD.pd_pool_id, NOW());
    RETURN NULL;
END;
\$dhcp6_options_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_options_ADEL
    AFTER DELETE ON dhcp6_options
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_options_ADEL();


-- Trigger function for dhcp4_server_AINS called AFTER INSERT on dhcp4_server
CREATE OR REPLACE FUNCTION func_dhcp4_server_AINS() RETURNS TRIGGER AS \$dhcp4_server_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_server', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp4_server_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_server_AINS
    AFTER INSERT ON dhcp4_server
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_AINS();


-- Trigger function for dhcp4_server_AUPD called AFTER UPDATE on dhcp4_server
CREATE OR REPLACE FUNCTION func_dhcp4_server_AUPD() RETURNS TRIGGER AS \$dhcp4_server_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_server', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp4_server_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_server_AUPD
    AFTER UPDATE ON dhcp4_server
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_AUPD();


-- Trigger function for dhcp4_server_ADEL called AFTER DELETE on dhcp4_server
CREATE OR REPLACE FUNCTION func_dhcp4_server_ADEL() RETURNS TRIGGER AS \$dhcp4_server_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_server', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp4_server_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_server_ADEL
    AFTER DELETE ON dhcp4_server
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_server_ADEL();


-- Trigger function for dhcp6_server_AINS called AFTER INSERT on dhcp6_server
CREATE OR REPLACE FUNCTION func_dhcp6_server_AINS() RETURNS TRIGGER AS \$dhcp6_server_AINS\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_server', NEW.id, 'create');
    RETURN NULL;
END;
\$dhcp6_server_AINS\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_server_AINS
    AFTER INSERT ON dhcp6_server
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_AINS();


-- Trigger function for dhcp6_server_AUPD called AFTER UPDATE on dhcp6_server
CREATE OR REPLACE FUNCTION func_dhcp6_server_AUPD() RETURNS TRIGGER AS \$dhcp6_server_AUPD\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_server', NEW.id, 'update');
    RETURN NULL;
END;
\$dhcp6_server_AUPD\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_server_AUPD
    AFTER UPDATE ON dhcp6_server
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_AUPD();


-- Trigger function for dhcp6_server_ADEL called AFTER DELETE on dhcp6_server
CREATE OR REPLACE FUNCTION func_dhcp6_server_ADEL() RETURNS TRIGGER AS \$dhcp6_server_ADEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_server', OLD.id, 'delete');
    RETURN NULL;
END;
\$dhcp6_server_ADEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_server_ADEL
    AFTER DELETE ON dhcp6_server
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_server_ADEL();


-- Trigger function for dhcp4_shared_network_BDEL called BEFORE DELETE on dhcp4_shared_network
CREATE OR REPLACE FUNCTION func_dhcp4_shared_network_BDEL() RETURNS TRIGGER AS \$dhcp4_shared_network_BDEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_shared_network', OLD.id, 'delete');
    DELETE FROM dhcp4_options WHERE shared_network_name = OLD.name;
    RETURN OLD;
END;
\$dhcp4_shared_network_BDEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_shared_network_BDEL
    BEFORE DELETE ON dhcp4_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_shared_network_BDEL();

-- Trigger function for dhcp4_subnet_BDEL called BEFORE DELETE on dhcp4_subnet
CREATE OR REPLACE FUNCTION func_dhcp4_subnet_BDEL() RETURNS TRIGGER AS \$dhcp4_subnet_BDEL\$
BEGIN
    PERFORM createAuditEntryDHCP4('dhcp4_subnet', OLD.subnet_id, 'delete');
    DELETE FROM dhcp4_pool WHERE subnet_id = OLD.subnet_id;
    DELETE FROM dhcp4_options WHERE dhcp4_subnet_id = OLD.subnet_id;
    RETURN OLD;
END;
\$dhcp4_subnet_BDEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp4_subnet_BDEL
    BEFORE DELETE ON dhcp4_subnet
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp4_subnet_BDEL();

-- Trigger function for dhcp6_shared_network_BDEL called BEFORE DELETE on dhcp6_shared_network
CREATE OR REPLACE FUNCTION func_dhcp6_shared_network_BDEL() RETURNS TRIGGER AS \$dhcp6_shared_network_BDEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_shared_network', OLD.id, 'delete');
    DELETE FROM dhcp6_options WHERE shared_network_name = OLD.name;
    RETURN OLD;
END;
\$dhcp6_shared_network_BDEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_shared_network_BDEL
    BEFORE DELETE ON dhcp6_shared_network
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_shared_network_BDEL();

-- Trigger function for dhcp6_subnet_BDEL called BEFORE DELETE on dhcp6_subnet
CREATE OR REPLACE FUNCTION func_dhcp6_subnet_BDEL() RETURNS TRIGGER AS \$dhcp6_subnet_BDEL\$
BEGIN
    PERFORM createAuditEntryDHCP6('dhcp6_subnet', OLD.subnet_id, 'delete');
    DELETE FROM dhcp6_pool WHERE subnet_id = OLD.subnet_id;
    DELETE FROM dhcp6_pd_pool WHERE subnet_id = OLD.subnet_id;
    DELETE FROM dhcp6_options WHERE dhcp6_subnet_id = OLD.subnet_id;
    RETURN OLD;
END;
\$dhcp6_subnet_BDEL\$
LANGUAGE plpgsql;

CREATE TRIGGER dhcp6_subnet_BDEL
    BEFORE DELETE ON dhcp6_subnet
        FOR EACH ROW EXECUTE PROCEDURE func_dhcp6_subnet_BDEL();

-- Trigger function for dhcp6_pd_pool_BDEL called BEFORE DELETE on dhcp6_pd_pool
CREATE OR REPLACE FUNCTION func_dhcp6_pd_pool_BDEL() RETURNS TRIGGER AS \$dhcp6_pd_pool_BDEL\$
BEGIN
    DELETE FROM dhcp6_options WHERE scope_id = 6 AND pd_pool_id = OLD.id;
    RETURN OLD;
END;
\$dhcp6_pd_pool_BDEL\$
LANGUAGE plpgsql;

-- Update the schema version number
UPDATE schema_version
    SET version = '7', minor = '0';

-- Schema 7.0 specification ends here.

-- Commit the script transaction
COMMIT;

EOF