heliosdb-nano 4.7.0

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
//! System Views Registry
//!
//! Provides schemas and execution for Phase 3 system views:
//! - pg_database_branches() - List all database branches
//! - pg_mv_staleness() - Materialized view staleness info
//! - pg_mv_cpu_usage() - MV refresh CPU usage
//! - pg_vector_index_stats() - Vector index statistics
//! - pg_current_scn() - Current System Change Number
//! - pg_compare_branches() - Compare two branches

use crate::storage::{art_index::ArtIndexType, StorageEngine};
use crate::{Column, ColumnStorageMode, DataType, Error, Result, Schema, Tuple, Value};
use std::collections::{HashMap, HashSet};

/// System view registry
pub struct SystemViewRegistry {
    views: HashMap<String, SystemViewSchema>,
}

/// System view schema definition
pub struct SystemViewSchema {
    pub name: String,
    pub schema: Schema,
    pub description: String,
}

impl SystemViewRegistry {
    /// Create a new system view registry with Phase 3 views
    pub fn new() -> Self {
        let mut registry = Self { views: HashMap::new() };

        registry.register_phase3_views();
        registry
    }

    /// Borrow the process-global registry, built exactly once.
    ///
    /// The Phase-3 system-view set is static — `register_phase3_views` consumes
    /// no runtime/storage state, it only allocates string/enum literals — so a
    /// fresh `new()` produces a byte-identical 48-view, hundreds-of-`Column`
    /// HashMap every time. Table resolution (`Planner::table_factor_to_plan`
    /// and the executor scan twins) rebuilt it per query just to answer one
    /// `is_system_view()` membership test, which the profile showed hotter than
    /// the actual index lookup. Sharing one immutable `&'static` removes that
    /// per-query rebuild at no behavioral cost (only `&self` accessors are used
    /// after construction).
    pub fn shared() -> &'static Self {
        static SHARED: std::sync::LazyLock<SystemViewRegistry> = std::sync::LazyLock::new(SystemViewRegistry::new);
        &SHARED
    }

    /// Register all Phase 3 system views
    fn register_phase3_views(&mut self) {
        // pg_database_branches()
        self.register_view(SystemViewSchema {
            name: "pg_database_branches".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "branch_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "branch_id".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "parent_id".to_string(),
                        data_type: DataType::Int8,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "created_at".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "fork_point_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "size_mb".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "status".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Lists all database branches with metadata".to_string(),
        });

        // pg_mv_staleness()
        self.register_view(SystemViewSchema {
            name: "pg_mv_staleness".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "view_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "base_tables".to_string(),
                        data_type: DataType::Text, // JSON array
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "last_update".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "pending_changes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "staleness_sec".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "status".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows staleness info for all materialized views".to_string(),
        });

        // pg_vector_index_stats()
        self.register_view(SystemViewSchema {
            name: "pg_vector_index_stats".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "index_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "num_vectors".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "dimensions".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "quantization".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "memory_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "recall_at_10".to_string(),
                        data_type: DataType::Float8,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Vector index statistics including PQ compression ratios".to_string(),
        });

        // pg_compare_branches()
        self.register_view(SystemViewSchema {
            name: "pg_compare_branches".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "key".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "source_value".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "target_value".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "difference_type".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "source_timestamp".to_string(),
                        data_type: DataType::Int8,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "target_timestamp".to_string(),
                        data_type: DataType::Int8,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Compare differences between two branches".to_string(),
        });

        // pg_branch_stats()
        self.register_view(SystemViewSchema {
            name: "pg_branch_stats".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "branch_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "modified_keys".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "storage_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "commit_count".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "last_modified".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "compression_ratio".to_string(),
                        data_type: DataType::Float8,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Statistics for database branches".to_string(),
        });

        // pg_class - Tables, indexes, sequences, views
        self.register_view(SystemViewSchema {
            name: "pg_class".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "oid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "relname".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "relnamespace".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "reltype".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "relkind".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "relfilenode".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    // KanttBan v3.31.0 release-gate: drizzle-kit's
                    // tables-list query (bin.cjs:19810) reads
                    // `c.relrowsecurity AS rls_enabled`. Nano doesn't
                    // expose pg_catalog-level RLS — RLS lives in the
                    // TenantManager — so report `false` for every
                    // row. Pre-v3.31.0 the catalog short-circuit
                    // hid this; now that pg_class flows through the
                    // planner, the column needs to actually exist.
                    sv_col("relrowsecurity", DataType::Boolean),
                    // Round-3 PARTITION BY Stage-0: partition-bound text for a
                    // partition child. The pgrust corpus reads
                    // `SELECT relname, relpartbound FROM pg_class WHERE …`. At
                    // Stage 0 the flatten keeps no typed bound, so every row
                    // reports NULL (nullable text, exactly what PostgreSQL
                    // returns for a non-partition relation); Stage 1 fills real
                    // `pg_get_expr`-style bounds for partition children.
                    sv_col("relpartbound", DataType::Text),
                ],
            },
            description: "Catalog of tables, indexes, sequences, and views".to_string(),
        });

        // pg_attribute - Column metadata
        self.register_view(SystemViewSchema {
            name: "pg_attribute".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "attrelid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "attname".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "atttypid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "attlen".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "attnotnull".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "attnum".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "atttypmod".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    // KanttBan #23 phase 2.4: drizzle-kit reads these
                    // four per-column attributes. attisdropped is the
                    // most critical — drizzle filters on
                    // `NOT a.attisdropped` and would error out
                    // without it. attndims tracks array nesting (0
                    // for scalars). attidentity / attgenerated are
                    // CHAR(1) PG codes — '' (empty) when neither, 'd'
                    // for IDENTITY BY DEFAULT, 'a' for ALWAYS, 's' /
                    // 'v' for STORED / VIRTUAL generated columns.
                    sv_col("attisdropped", DataType::Boolean),
                    sv_col("attndims", DataType::Int4),
                    sv_col("attidentity", DataType::Text),
                    sv_col("attgenerated", DataType::Text),
                    sv_col("atthasdef", DataType::Boolean),
                    sv_col("attcollation", DataType::Int4),
                ],
            },
            description: "Catalog of table columns and their attributes".to_string(),
        });

        // pg_type - Data type definitions
        self.register_view(SystemViewSchema {
            name: "pg_type".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "oid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "typname".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "typlen".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "typbyval".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "typcategory".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "typnotnull".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    // KanttBan #23 phase 2.6: drizzle's
                    // getColumnsInfoQuery LEFT-JOINs pg_type and then
                    // pg_namespace on `enum_t.typnamespace`. Add the
                    // column (every built-in lives in pg_catalog OID
                    // 11) so the join resolves.
                    sv_col("typnamespace", DataType::Int4),
                    sv_col("typtype", DataType::Text),
                    sv_col("typowner", DataType::Int4),
                    sv_col("typrelid", DataType::Int4),
                    sv_col("typbasetype", DataType::Int4),
                ],
            },
            description: "Catalog of data types".to_string(),
        });

        // sqlite_master - SQLite-shaped catalog for sqlite3-driven Python apps.
        // Only the columns sqlite3 callers actually inspect.
        self.register_view(SystemViewSchema {
            name: "sqlite_master".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "type".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "tbl_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "rootpage".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "sql".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "SQLite-compatible catalog (drop-in for sqlite3 apps)".to_string(),
        });

        // pg_namespace - Schemas
        self.register_view(SystemViewSchema {
            name: "pg_namespace".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "oid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "nspname".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "nspowner".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Catalog of schemas (namespaces)".to_string(),
        });

        // pg_index - Indexes
        self.register_view(SystemViewSchema {
            name: "pg_index".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "indexrelid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "indrelid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "indisprimary".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "indisunique".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "indisexclusion".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "indkey".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    sv_col("indnatts", DataType::Int2),
                    sv_col("indnkeyatts", DataType::Int2),
                    sv_col("indisclustered", DataType::Boolean),
                    sv_col("indisvalid", DataType::Boolean),
                    sv_col("indisready", DataType::Boolean),
                    sv_col("indisreplident", DataType::Boolean),
                    sv_col("indexprs", DataType::Text),
                    sv_col("indpred", DataType::Text),
                ],
            },
            description: "Catalog of indexes".to_string(),
        });

        // pg_constraint - Constraints
        self.register_view(SystemViewSchema {
            name: "pg_constraint".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "oid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "conname".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "connamespace".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "contype".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "conrelid".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "confrelid".to_string(),
                        data_type: DataType::Int4,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    sv_col("conindid", DataType::Int4),
                    sv_col("conkey", DataType::Text),
                    sv_col("confkey", DataType::Text),
                    sv_col("confupdtype", DataType::Text),
                    sv_col("confdeltype", DataType::Text),
                    sv_col("confmatchtype", DataType::Text),
                    sv_col("condeferrable", DataType::Boolean),
                    sv_col("condeferred", DataType::Boolean),
                    sv_col("convalidated", DataType::Boolean),
                ],
            },
            description: "Catalog of constraints (primary key, foreign key, unique, check)".to_string(),
        });

        // information_schema.columns - Standard SQL
        self.register_view(SystemViewSchema {
            name: "information_schema.columns".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "table_schema".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "table_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "column_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "ordinal_position".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "column_default".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "is_nullable".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "data_type".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    // KanttBan #23 (v3.31.1 phase 2): identity /
                    // generated-column fields that drizzle-kit's
                    // getColumnsInfoQuery reads.
                    sv_col("udt_name", DataType::Text),
                    sv_col("is_generated", DataType::Text), // 'NEVER' or 'ALWAYS'
                    sv_col("generation_expression", DataType::Text),
                    sv_col("is_identity", DataType::Text),         // 'YES' or 'NO'
                    sv_col("identity_generation", DataType::Text), // 'ALWAYS' or 'BY DEFAULT' or NULL
                    sv_col("identity_start", DataType::Text),
                    sv_col("identity_increment", DataType::Text),
                    sv_col("identity_maximum", DataType::Text),
                    sv_col("identity_minimum", DataType::Text),
                    sv_col("identity_cycle", DataType::Text), // 'YES' or 'NO'
                ],
            },
            description: "Information schema view of all table columns (ANSI SQL standard)".to_string(),
        });

        // heliosdb_compression_stats - Compression statistics by algorithm
        self.register_view(SystemViewSchema {
            name: "heliosdb_compression_stats".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "algorithm".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "uses".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "avg_ratio".to_string(),
                        data_type: DataType::Float8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "avg_compress_us".to_string(),
                        data_type: DataType::Float8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "avg_decompress_us".to_string(),
                        data_type: DataType::Float8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "total_bytes_in".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "total_bytes_out".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows compression statistics grouped by algorithm".to_string(),
        });

        // heliosdb_pattern_stats - Pattern detection statistics
        self.register_view(SystemViewSchema {
            name: "heliosdb_pattern_stats".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "pattern".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "detections".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "best_algorithm".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "avg_ratio".to_string(),
                        data_type: DataType::Float8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows pattern detection statistics".to_string(),
        });

        // heliosdb_compression_events - Recent compression events
        self.register_view(SystemViewSchema {
            name: "heliosdb_compression_events".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "timestamp".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "table_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "column_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "algorithm".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "ratio".to_string(),
                        data_type: DataType::Float8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "input_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "output_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "duration_us".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows recent compression events per table/column".to_string(),
        });

        // heliosdb_config - Configuration settings
        self.register_view(SystemViewSchema {
            name: "heliosdb_config".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "key".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "value".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "description".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows compression-related configuration settings".to_string(),
        });

        // ========== HA Replication System Views ==========

        // pg_replication_status - Current node's HA configuration and role
        self.register_view(SystemViewSchema {
            name: "pg_replication_status".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "node_id".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "role".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "sync_mode".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "is_read_only".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "current_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "standby_count".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "primary_host".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "listen_addr".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "replication_port".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "started_at".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows current node's HA replication status and configuration".to_string(),
        });

        // pg_replication_standbys - Connected standbys (on primary)
        self.register_view(SystemViewSchema {
            name: "pg_replication_standbys".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "node_id".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "address".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "state".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "sync_mode".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "current_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "flush_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "apply_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "lag_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "lag_ms".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "connected_at".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "last_heartbeat".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows connected standby nodes (run on primary)".to_string(),
        });

        // pg_replication_primary - Primary connection status (on standby)
        self.register_view(SystemViewSchema {
            name: "pg_replication_primary".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "primary_node_id".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "primary_address".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "connection_state".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "primary_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "local_lsn".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "lag_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "lag_ms".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "fencing_token".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "connected_at".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "last_heartbeat".to_string(),
                        data_type: DataType::Timestamp,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows primary connection status (run on standby)".to_string(),
        });

        // pg_replication_metrics - Replication performance metrics
        self.register_view(SystemViewSchema {
            name: "pg_replication_metrics".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "metric_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "metric_value".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "description".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows replication performance metrics".to_string(),
        });

        // heliosdb_art_indexes - ART index information
        self.register_view(SystemViewSchema {
            name: "heliosdb_art_indexes".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "index_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "table_name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "columns".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "index_type".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "key_count".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "memory_bytes".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "node_count".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "lookup_count".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows ART (Adaptive Radix Tree) index information".to_string(),
        });

        // heliosdb_simd_capabilities - SIMD CPU feature detection
        self.register_view(SystemViewSchema {
            name: "heliosdb_simd_capabilities".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "feature".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "available".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "vector_width".to_string(),
                        data_type: DataType::Int4,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "description".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows CPU SIMD capabilities for query acceleration".to_string(),
        });

        // heliosdb_row_cache_stats - Row cache statistics
        self.register_view(SystemViewSchema {
            name: "heliosdb_row_cache_stats".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "metric".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "value".to_string(),
                        data_type: DataType::Int8,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "description".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Shows row cache statistics and hit rates".to_string(),
        });

        // heliosdb_lock_census - Read-hot-path lock-contention counters (W3.1).
        // Empty unless built with the `lock-census` feature AND enabled via
        // `[performance] lock_census`. One row per instrumented lock site.
        self.register_view(SystemViewSchema {
            name: "heliosdb_lock_census".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("lock_site", DataType::Text),
                    sv_col("acquisitions", DataType::Int8),
                    sv_col("contended", DataType::Int8),
                    sv_col("contended_wait_nanos", DataType::Int8),
                ],
            },
            description: "Read-hot-path lock-contention census (W3.1 plateau attribution)".to_string(),
        });

        // heliosdb_write_volume - Per-statement-class write-volume census (W3.2).
        // Zero unless `[performance] write_volume_stats` is enabled. One row per
        // statement class: data:/version/index-key byte totals + a row count.
        self.register_view(SystemViewSchema {
            name: "heliosdb_write_volume".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("stmt_class", DataType::Text),
                    sv_col("data_bytes", DataType::Int8),
                    sv_col("version_bytes", DataType::Int8),
                    sv_col("index_key_bytes", DataType::Int8),
                    sv_col("rows", DataType::Int8),
                ],
            },
            description: "Per-statement-class write-volume census (W3.2 version-format quantification)".to_string(),
        });

        // heliosdb_copy_phase_stats - COPY fast-path phase-timing census (W3.4).
        // Zero unless `[performance] copy_phase_stats` is enabled. One row per
        // funnel phase: cumulative wall nanos, a call count, and a row count.
        self.register_view(SystemViewSchema {
            name: "heliosdb_copy_phase_stats".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("phase", DataType::Text),
                    sv_col("total_nanos", DataType::Int8),
                    sv_col("calls", DataType::Int8),
                    sv_col("rows", DataType::Int8),
                ],
            },
            description: "COPY fast-path phase-timing census (W3.4 ART-maintenance attribution)".to_string(),
        });

        // pg_tables — make the basic catalog query work over SQL.
        // The legacy SystemViewRegistry in sql/system_views.rs has
        // a richer implementation we delegate to at execute time.
        self.register_view(SystemViewSchema {
            name: "pg_tables".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "schemaname".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "tablename".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "tableowner".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "tablespace".to_string(),
                        data_type: DataType::Text,
                        nullable: true,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "hasindexes".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "hasrules".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "hastriggers".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "rowsecurity".to_string(),
                        data_type: DataType::Boolean,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Lists all user tables (schemaname split honours #188 namespacing)".to_string(),
        });

        // hdb_code_languages — code-graph track grammar inventory.
        // Always registered so the view is discoverable; the
        // executor returns an empty result when the code-graph
        // feature isn't compiled in.
        // ---- KanttBan #22 (v3.31.0) — pg_user for catalog JOINs ----
        // drizzle-kit / Postgres ORMs JOIN pg_namespace ⨝ pg_user on
        // `u.usesysid = n.nspowner` to attribute schemas to owners.
        // Pre-v3.31.0 the substring-routed short-circuit in
        // protocol/postgres/catalog.rs picked the first matching branch
        // (pg_roles) and discarded the pg_namespace side of the JOIN,
        // returning bogus rows. Now JOINs flow through the regular
        // operator pipeline; pg_user just needs to exist as a scannable
        // source with the standard shape.
        self.register_view(SystemViewSchema {
            name: "pg_user".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("usename", DataType::Text),
                    sv_col("usesysid", DataType::Int4),
                    sv_col("usecreatedb", DataType::Boolean),
                    sv_col("usesuper", DataType::Boolean),
                    sv_col("userepl", DataType::Boolean),
                    sv_col("usebypassrls", DataType::Boolean),
                    sv_col("passwd", DataType::Text),
                    sv_col("valuntil", DataType::Text),
                    sv_col("useconfig", DataType::Text),
                ],
            },
            description: "Built-in PG-compat view over pg_authid (read-only stub)".to_string(),
        });

        // pg_roles — PG's authoritative role list (different shape from
        // pg_user, includes rolinherit / rolreplication / rolconnlimit /
        // rolvaliduntil etc.). drizzle-kit queries this directly during
        // introspection. Same two hard-coded roles.
        self.register_view(SystemViewSchema {
            name: "pg_roles".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("rolname", DataType::Text),
                    sv_col("rolsuper", DataType::Boolean),
                    sv_col("rolinherit", DataType::Boolean),
                    sv_col("rolcreaterole", DataType::Boolean),
                    sv_col("rolcreatedb", DataType::Boolean),
                    sv_col("rolcanlogin", DataType::Boolean),
                    sv_col("rolreplication", DataType::Boolean),
                    sv_col("rolconnlimit", DataType::Int4),
                    sv_col("rolpassword", DataType::Text),
                    sv_col("rolvaliduntil", DataType::Text),
                    sv_col("rolbypassrls", DataType::Boolean),
                ],
            },
            description: "Built-in PG-compat view over pg_authid (read-only stub)".to_string(),
        });

        // information_schema.table_constraints — drizzle reads this for
        // PK/UNIQUE/FK constraint info. 5-col PG-standard shape.
        self.register_view(SystemViewSchema {
            name: "information_schema.table_constraints".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("constraint_catalog", DataType::Text),
                    sv_col("constraint_schema", DataType::Text),
                    sv_col("constraint_name", DataType::Text),
                    sv_col("table_name", DataType::Text),
                    sv_col("constraint_type", DataType::Text),
                ],
            },
            description: "Standard SQL info_schema.table_constraints (PK/UNIQUE/FK)".to_string(),
        });

        // information_schema.key_column_usage — column-to-constraint
        // mapping. drizzle joins this with table_constraints to map
        // FK columns to their referenced table/column.
        self.register_view(SystemViewSchema {
            name: "information_schema.key_column_usage".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("constraint_catalog", DataType::Text),
                    sv_col("constraint_schema", DataType::Text),
                    sv_col("constraint_name", DataType::Text),
                    sv_col("table_name", DataType::Text),
                    sv_col("column_name", DataType::Text),
                    sv_col("ordinal_position", DataType::Int4),
                ],
            },
            description: "Standard SQL info_schema.key_column_usage".to_string(),
        });

        // information_schema.constraint_column_usage — columns used
        // BY a constraint (the target side for FKs; same as KCU for
        // PK/UNIQUE). drizzle reads this for FK target resolution.
        self.register_view(SystemViewSchema {
            name: "information_schema.constraint_column_usage".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("table_catalog", DataType::Text),
                    sv_col("table_schema", DataType::Text),
                    sv_col("table_name", DataType::Text),
                    sv_col("column_name", DataType::Text),
                    sv_col("constraint_catalog", DataType::Text),
                    sv_col("constraint_schema", DataType::Text),
                    sv_col("constraint_name", DataType::Text),
                ],
            },
            description: "Standard SQL info_schema.constraint_column_usage".to_string(),
        });

        // information_schema.referential_constraints — FK referential
        // actions (ON UPDATE / ON DELETE) per constraint.
        self.register_view(SystemViewSchema {
            name: "information_schema.referential_constraints".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("constraint_catalog", DataType::Text),
                    sv_col("constraint_schema", DataType::Text),
                    sv_col("constraint_name", DataType::Text),
                    sv_col("unique_constraint_catalog", DataType::Text),
                    sv_col("unique_constraint_schema", DataType::Text),
                    sv_col("unique_constraint_name", DataType::Text),
                    sv_col("match_option", DataType::Text),
                    sv_col("update_rule", DataType::Text),
                    sv_col("delete_rule", DataType::Text),
                ],
            },
            description: "Standard SQL info_schema.referential_constraints (FK actions)".to_string(),
        });

        // information_schema.tables — drizzle-kit / Prisma / Knex /
        // postgres-js all introspect through this. Same 4-column shape
        // as the catalog handler's query_information_schema_tables.
        self.register_view(SystemViewSchema {
            name: "information_schema.tables".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("table_catalog", DataType::Text),
                    sv_col("table_schema", DataType::Text),
                    sv_col("table_name", DataType::Text),
                    sv_col("table_type", DataType::Text),
                ],
            },
            description: "SQL-standard table catalogue, sourced from storage::catalog::list_tables".to_string(),
        });

        // ---- Empty-stub catalogue/view tables (KanttBan #22 v3.31.0 slice 5)
        // Nano doesn't implement these features (sequences as objects,
        // logical replication, RLS policies, extended stats, mat-view
        // catalogue, inheritance, server functions/procedures). Every
        // entry registers the standard PG-shape so introspection tools
        // see the expected column names through the planner pipeline.
        // execute returns vec![] — empty rowset.

        self.register_view(SystemViewSchema {
            name: "pg_sequences".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("schemaname", DataType::Text),
                    sv_col("sequencename", DataType::Text),
                    sv_col("sequenceowner", DataType::Text),
                    sv_col("data_type", DataType::Text),
                    sv_col("start_value", DataType::Int8),
                    sv_col("min_value", DataType::Int8),
                    sv_col("max_value", DataType::Int8),
                    sv_col("increment_by", DataType::Int8),
                    sv_col("cycle", DataType::Boolean),
                    sv_col("cache_size", DataType::Int8),
                    sv_col("last_value", DataType::Int8),
                ],
            },
            description: "PG-compat sequences view (real CREATE SEQUENCE defs + SERIAL/IDENTITY synthetics)"
                .to_string(),
        });

        // information_schema.sequences — SQL-standard 12-col shape. Lists REAL
        // CREATE SEQUENCE definitions only (PG excludes SERIAL/IDENTITY-owned
        // sequences from this view). a2h / ORMs / pg_dump discover sequences
        // through this surface; the prior count=0 break is fixed.
        self.register_view(SystemViewSchema {
            name: "information_schema.sequences".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("sequence_catalog", DataType::Text),
                    sv_col("sequence_schema", DataType::Text),
                    sv_col("sequence_name", DataType::Text),
                    sv_col("data_type", DataType::Text),
                    sv_col("numeric_precision", DataType::Int4),
                    sv_col("numeric_precision_radix", DataType::Int4),
                    sv_col("numeric_scale", DataType::Int4),
                    sv_col("start_value", DataType::Text),
                    sv_col("minimum_value", DataType::Text),
                    sv_col("maximum_value", DataType::Text),
                    sv_col("increment", DataType::Text),
                    sv_col("cycle_option", DataType::Text),
                ],
            },
            description: "SQL-standard sequences catalogue, sourced from storage::catalog::list_sequences".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_proc".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("proname", DataType::Text),
                    sv_col("pronamespace", DataType::Int4),
                    sv_col("proowner", DataType::Int4),
                    sv_col("prolang", DataType::Int4),
                    sv_col("prorettype", DataType::Int4),
                    sv_col("proargtypes", DataType::Text),
                    sv_col("prosrc", DataType::Text),
                ],
            },
            description: "PG-compat procedures catalogue (empty stub)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_description".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("objoid", DataType::Int4),
                    sv_col("classoid", DataType::Int4),
                    sv_col("objsubid", DataType::Int4),
                    sv_col("description", DataType::Text),
                ],
            },
            description: "PG-compat object descriptions (empty — Nano doesn't store COMMENT ON)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_policies".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("schemaname", DataType::Text),
                    sv_col("tablename", DataType::Text),
                    sv_col("policyname", DataType::Text),
                    sv_col("permissive", DataType::Text),
                    sv_col("roles", DataType::Text),
                    sv_col("cmd", DataType::Text),
                    sv_col("qual", DataType::Text),
                    sv_col("with_check", DataType::Text),
                ],
            },
            description: "PG-compat RLS policies view (empty — Nano RLS via TenantManager)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_policy".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("polname", DataType::Text),
                    sv_col("polrelid", DataType::Int4),
                    sv_col("polcmd", DataType::Char(1)),
                    sv_col("polpermissive", DataType::Boolean),
                    sv_col("polroles", DataType::Text),
                    sv_col("polqual", DataType::Text),
                    sv_col("polwithcheck", DataType::Text),
                ],
            },
            description: "PG-compat RLS policy catalogue (empty stub)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_matviews".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("schemaname", DataType::Text),
                    sv_col("matviewname", DataType::Text),
                    sv_col("matviewowner", DataType::Text),
                    sv_col("tablespace", DataType::Text),
                    sv_col("hasindexes", DataType::Boolean),
                    sv_col("ispopulated", DataType::Boolean),
                    sv_col("definition", DataType::Text),
                ],
            },
            description: "PG-compat matview view (empty — use pg_mv_staleness instead)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_inherits".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("inhrelid", DataType::Int4),
                    sv_col("inhparent", DataType::Int4),
                    sv_col("inhseqno", DataType::Int4),
                ],
            },
            description: "PG-compat inheritance catalogue (empty — Nano has no inheritance)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_publication".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("pubname", DataType::Text),
                    sv_col("pubowner", DataType::Int4),
                    sv_col("puballtables", DataType::Boolean),
                    sv_col("pubinsert", DataType::Boolean),
                    sv_col("pubupdate", DataType::Boolean),
                    sv_col("pubdelete", DataType::Boolean),
                    sv_col("pubtruncate", DataType::Boolean),
                ],
            },
            description: "PG-compat logical replication publications (empty stub)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "pg_statistic_ext".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("stxrelid", DataType::Int4),
                    sv_col("stxnamespace", DataType::Int4),
                    sv_col("stxname", DataType::Text),
                    sv_col("stxkeys", DataType::Text),
                    sv_col("stxkind", DataType::Text),
                    sv_col("stxstattarget", DataType::Int4),
                ],
            },
            description: "PG-compat extended stats catalogue (empty stub)".to_string(),
        });

        // pg_attrdef — column-default catalogue. KanttBan #23
        // (v3.31.1 phase 1): drizzle-kit's getColumnsInfoQuery joins
        // here in an EXISTS subquery to detect SERIAL columns. Empty
        // stub means the EXISTS is false → drizzle's SERIAL-detection
        // CASE falls through to format_type, which is what we want.
        // Phase 2 populates from real column defaults to make the
        // SERIAL/IDENTITY detection accurate.
        self.register_view(SystemViewSchema {
            name: "pg_attrdef".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("adrelid", DataType::Int4),
                    sv_col("adnum", DataType::Int2),
                    sv_col("adbin", DataType::Text),
                    sv_col("adsrc", DataType::Text),
                ],
            },
            description: "PG-compat column-default catalogue (empty stub; phase-2 will populate)".to_string(),
        });

        // pg_database — \l, ORM connection introspection. Minimal
        // implementation returns only the implicit 'heliosdb' row;
        // tenant enumeration (the v3.25 CREATE DATABASE wrap) needs
        // EmbeddedDatabase access which the registry execute()
        // signature doesn't expose today — flag for v3.31.x follow-up.
        self.register_view(SystemViewSchema {
            name: "pg_database".to_string(),
            schema: Schema {
                columns: vec![
                    sv_col("oid", DataType::Int4),
                    sv_col("datname", DataType::Text),
                    sv_col("datdba", DataType::Int4),
                    sv_col("encoding", DataType::Int4),
                    sv_col("datcollate", DataType::Text),
                    sv_col("datctype", DataType::Text),
                    sv_col("datistemplate", DataType::Boolean),
                    sv_col("datallowconn", DataType::Boolean),
                    sv_col("datconnlimit", DataType::Int4),
                    sv_col("dattablespace", DataType::Int4),
                ],
            },
            description: "PG-compat database list (registry-stub; tenant enumeration deferred)".to_string(),
        });

        self.register_view(SystemViewSchema {
            name: "hdb_code_languages".to_string(),
            schema: Schema {
                columns: vec![
                    Column {
                        name: "name".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                    Column {
                        name: "source".to_string(),
                        data_type: DataType::Text,
                        nullable: false,
                        primary_key: false,
                        source_table: None,
                        source_table_name: None,
                        default_expr: None,
                        unique: false,
                        storage_mode: ColumnStorageMode::Default,
                    },
                ],
            },
            description: "Lists every tree-sitter grammar the indexer can parse".to_string(),
        });
    }

    /// Register a system view
    fn register_view(&mut self, view: SystemViewSchema) {
        self.views.insert(view.name.clone(), view);
    }
}

/// KanttBan #23 (v3.31.1 phase 2): map a Nano DataType to the
/// canonical PG udt_name string. Matches `format_pg_type_oid` in
/// `src/sql/evaluator.rs` (different surface, same OID-to-name
/// table) — kept in sync by convention.
fn format_pg_type_name(dt: &DataType) -> String {
    match dt {
        DataType::Boolean => "bool".into(),
        DataType::Int2 => "int2".into(),
        DataType::Int4 => "int4".into(),
        DataType::Int8 => "int8".into(),
        DataType::Float4 => "float4".into(),
        DataType::Float8 => "float8".into(),
        DataType::Numeric => "numeric".into(),
        DataType::Varchar(_) => "varchar".into(),
        DataType::Text => "text".into(),
        DataType::Char(_) => "bpchar".into(),
        DataType::Bytea => "bytea".into(),
        DataType::Date => "date".into(),
        DataType::Time => "time".into(),
        DataType::Timestamp => "timestamp".into(),
        DataType::Timestamptz => "timestamptz".into(),
        DataType::Interval => "interval".into(),
        DataType::Uuid => "uuid".into(),
        DataType::Json => "json".into(),
        DataType::Jsonb => "jsonb".into(),
        DataType::Array(inner) => format!("_{}", format_pg_type_name(inner)),
        DataType::Vector(_) => "vector".into(),
    }
}

/// Build a non-PK, non-unique nullable column with default storage —
/// the shape system-view columns take. Reduces the per-column boilerplate
/// from 9 fields to 2.
#[inline]
fn sv_col(name: &str, data_type: DataType) -> Column {
    Column {
        name: name.to_string(),
        data_type,
        nullable: true,
        primary_key: false,
        source_table: None,
        source_table_name: None,
        default_expr: None,
        unique: false,
        storage_mode: ColumnStorageMode::Default,
    }
}

const PG_TABLE_OID_BASE: i32 = 1000;
const PG_INDEX_OID_BASE: i32 = 5000;
const PG_CONSTRAINT_OID_BASE: i32 = 4000;
/// Distinct OID base for sequence relations (pg_class relkind='S'). Kept clear
/// of the table (1000) and index (5000) bases so sequence OIDs never collide.
const PG_SEQ_OID_BASE: i32 = 6000;
const PG_PUBLIC_NAMESPACE_OID: i32 = 2200;

fn pg_table_oid(table_idx: usize) -> i32 {
    PG_TABLE_OID_BASE + table_idx as i32
}

fn pg_table_oid_by_name(tables: &[String], table_name: &str) -> Option<i32> {
    tables
        .iter()
        .position(|name| name.eq_ignore_ascii_case(table_name))
        .map(pg_table_oid)
}

fn sorted_art_indexes(storage: &StorageEngine) -> Vec<(String, String, ArtIndexType, Vec<String>)> {
    let mut indexes = storage.art_indexes().list_indexes();
    indexes.sort_by(|left, right| left.1.cmp(&right.1).then(left.0.cmp(&right.0)));
    indexes
}

fn pg_index_oid(index_idx: usize) -> i32 {
    PG_INDEX_OID_BASE + index_idx as i32
}

fn pg_index_oid_by_name(indexes: &[(String, String, ArtIndexType, Vec<String>)], index_name: &str) -> i32 {
    indexes
        .iter()
        .position(|(name, _, _, _)| name.eq_ignore_ascii_case(index_name))
        .map(pg_index_oid)
        .unwrap_or(0)
}

fn pg_sequence_oid(seq_idx: usize) -> i32 {
    PG_SEQ_OID_BASE + seq_idx as i32
}

/// Map a SERIAL/IDENTITY column's integer type to its synthetic
/// owned-sequence `(data_type, max_value)`. Non-integer columns (shouldn't
/// happen for an identity column) fall back to bigint.
fn serial_type_bounds(dt: &DataType) -> (&'static str, i64) {
    match dt {
        DataType::Int2 => ("smallint", i16::MAX as i64),
        DataType::Int4 => ("integer", i32::MAX as i64),
        _ => ("bigint", i64::MAX),
    }
}

fn pg_attnums(schema: &Schema, columns: &[String]) -> Vec<i32> {
    columns
        .iter()
        .filter_map(|wanted| {
            schema
                .columns
                .iter()
                .position(|col| col.name.eq_ignore_ascii_case(wanted))
                .map(|idx| idx as i32 + 1)
        })
        .collect()
}

fn pg_indkey(schema: &Schema, columns: &[String]) -> String {
    pg_attnums(schema, columns)
        .into_iter()
        .map(|attnum| attnum.to_string())
        .collect::<Vec<_>>()
        .join(" ")
}

fn pg_conkey(schema: &Schema, columns: &[String]) -> Value {
    let attnums = pg_attnums(schema, columns);
    if attnums.is_empty() {
        Value::Null
    } else {
        Value::String(format!(
            "{{{}}}",
            attnums
                .into_iter()
                .map(|attnum| attnum.to_string())
                .collect::<Vec<_>>()
                .join(",")
        ))
    }
}

fn pg_fk_action_code(action: crate::sql::ReferentialAction) -> &'static str {
    match action {
        crate::sql::ReferentialAction::NoAction => "a",
        crate::sql::ReferentialAction::Restrict => "r",
        crate::sql::ReferentialAction::Cascade => "c",
        crate::sql::ReferentialAction::SetNull => "n",
        crate::sql::ReferentialAction::SetDefault => "d",
    }
}

#[allow(clippy::too_many_arguments)]
fn push_pg_constraint_row(
    rows: &mut Vec<Tuple>,
    next_oid: &mut i32,
    seen: &mut HashSet<String>,
    name: String,
    contype: &str,
    conrelid: i32,
    confrelid: Option<i32>,
    conindid: i32,
    conkey: Value,
    confkey: Value,
    on_update: Option<crate::sql::ReferentialAction>,
    on_delete: Option<crate::sql::ReferentialAction>,
    deferrable: bool,
    deferred: bool,
    validated: bool,
) {
    let seen_key = format!("{conrelid}:{name}");
    if !seen.insert(seen_key) {
        return;
    }

    rows.push(Tuple::new(vec![
        Value::Int4(*next_oid),
        Value::String(name),
        Value::Int4(PG_PUBLIC_NAMESPACE_OID),
        Value::String(contype.to_string()),
        Value::Int4(conrelid),
        confrelid.map(Value::Int4).unwrap_or(Value::Null),
        Value::Int4(conindid),
        conkey,
        confkey,
        on_update
            .map(pg_fk_action_code)
            .map(|code| Value::String(code.to_string()))
            .unwrap_or(Value::Null),
        on_delete
            .map(pg_fk_action_code)
            .map(|code| Value::String(code.to_string()))
            .unwrap_or(Value::Null),
        if contype == "f" {
            Value::String("s".to_string())
        } else {
            Value::Null
        },
        Value::Boolean(deferrable),
        Value::Boolean(deferred),
        Value::Boolean(validated),
    ]));
    *next_oid += 1;
}

impl SystemViewRegistry {
    /// Get system view schema
    pub fn get_schema(&self, view_name: &str) -> Option<&Schema> {
        self.views.get(view_name).map(|v| &v.schema)
    }

    /// Check if a view is a system view
    pub fn is_system_view(&self, view_name: &str) -> bool {
        self.views.contains_key(view_name)
    }

    /// List all system views
    pub fn list_views(&self) -> Vec<&str> {
        self.views.keys().map(|s| s.as_str()).collect()
    }

    /// Execute a system view query
    ///
    /// Queries storage metadata and returns results based on the view type
    pub fn execute(&self, view_name: &str, storage: &StorageEngine) -> Result<Vec<Tuple>> {
        if !self.is_system_view(view_name) {
            return Err(Error::query_execution(format!("Unknown system view: {}", view_name)));
        }

        match view_name {
            "pg_database_branches" => Self::execute_pg_database_branches(storage),
            "pg_mv_staleness" => Self::execute_pg_mv_staleness(storage),
            "pg_vector_index_stats" => Self::execute_pg_vector_index_stats(storage),
            "pg_compare_branches" => {
                // This view requires parameters (source and target branch names)
                // For now, return error indicating parameters are needed
                Err(Error::query_execution(
                    "pg_compare_branches requires parameters: SELECT * FROM pg_compare_branches('source_branch', 'target_branch')"
                ))
            }
            "pg_branch_stats" => Self::execute_pg_branch_stats(storage),
            "pg_class" => Self::execute_pg_class(storage),
            "pg_attribute" => Self::execute_pg_attribute(storage),
            "pg_type" => Self::execute_pg_type(storage),
            "pg_namespace" => Self::execute_pg_namespace(storage),
            "pg_user" => Self::execute_pg_user(),
            "pg_roles" => Self::execute_pg_roles(),
            "information_schema.tables" => Self::execute_information_schema_tables(storage),
            "information_schema.sequences" => Self::execute_information_schema_sequences(storage),
            "information_schema.table_constraints" => Self::execute_information_schema_table_constraints(storage),
            "information_schema.key_column_usage" => Self::execute_information_schema_key_column_usage(storage),
            "information_schema.constraint_column_usage" => {
                Self::execute_information_schema_constraint_column_usage(storage)
            }
            "information_schema.referential_constraints" => {
                Self::execute_information_schema_referential_constraints(storage)
            }
            "pg_database" => Self::execute_pg_database(),
            // Empty-stub catalogue tables (v3.31.0 slice 5). Schema
            // already registered; rows are always empty because Nano
            // doesn't model these concepts.
            "pg_sequences" => Self::execute_pg_sequences(storage),
            "pg_attrdef" => Self::execute_pg_attrdef(storage),
            "pg_proc" | "pg_description" | "pg_policies" | "pg_policy" | "pg_matviews" | "pg_inherits"
            | "pg_publication" | "pg_statistic_ext" => Ok(vec![]),
            "sqlite_master" => Self::execute_sqlite_master(storage),
            "pg_index" => Self::execute_pg_index(storage),
            "pg_constraint" => Self::execute_pg_constraint(storage),
            "information_schema.columns" => Self::execute_information_schema_columns(storage),
            // Compression monitoring views
            "heliosdb_compression_stats" => Self::execute_heliosdb_compression_stats(storage),
            "heliosdb_pattern_stats" => Self::execute_heliosdb_pattern_stats(storage),
            "heliosdb_compression_events" => Self::execute_heliosdb_compression_events(storage),
            "heliosdb_config" => Self::execute_heliosdb_config(storage),
            // HA Replication monitoring views
            "pg_replication_status" => Self::execute_pg_replication_status(),
            "pg_replication_standbys" => Self::execute_pg_replication_standbys(),
            "pg_replication_primary" => Self::execute_pg_replication_primary(),
            "pg_replication_metrics" => Self::execute_pg_replication_metrics(),
            // ART index monitoring
            "heliosdb_art_indexes" => Self::execute_heliosdb_art_indexes(storage),
            // SIMD capabilities
            "heliosdb_simd_capabilities" => Self::execute_heliosdb_simd_capabilities(),
            // Row cache stats
            "heliosdb_row_cache_stats" => Self::execute_heliosdb_row_cache_stats(storage),
            // Read-hot-path lock-contention census (W3.1)
            "heliosdb_lock_census" => Self::execute_heliosdb_lock_census(),
            // Per-statement-class write-volume census (W3.2)
            "heliosdb_write_volume" => Self::execute_heliosdb_write_volume(),
            // COPY fast-path phase-timing census (W3.4)
            "heliosdb_copy_phase_stats" => Self::execute_heliosdb_copy_phase_stats(),
            // Code-graph track grammar inventory.
            "hdb_code_languages" => Self::execute_hdb_code_languages(),
            // pg_tables — delegate to the legacy SystemViewRegistry
            // which has the schema-namespacing split we want.
            "pg_tables" => Self::execute_pg_tables_compat(storage),
            _ => {
                // Other system views not yet implemented
                Ok(vec![])
            }
        }
    }

    /// Bridge to the legacy SystemViewRegistry's pg_tables
    /// implementation so SELECT * FROM pg_tables works over SQL
    /// (the planner only consults the phase-3 registry).
    fn execute_pg_tables_compat(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let legacy = crate::sql::SystemViewRegistry::new();
        legacy.execute("pg_tables", storage)
    }

    /// Materialise `hdb_code_languages`: one row per static
    /// `SupportedLanguage` variant + one row per
    /// runtime-registered grammar.  Sorted by name for stable
    /// output. Returns an empty set when the `code-graph` feature
    /// isn't compiled in.
    fn execute_hdb_code_languages() -> Result<Vec<Tuple>> {
        #[cfg(feature = "code-graph")]
        {
            use crate::code_graph::{parse, SupportedLanguage};
            let mut rows: Vec<(String, &'static str)> = SupportedLanguage::all()
                .iter()
                .map(|l| (l.as_str().to_string(), "static"))
                .collect();
            for name in parse::registered_grammars() {
                if let Some(idx) = rows.iter().position(|(n, _)| n == &name) {
                    rows[idx].1 = "runtime";
                } else {
                    rows.push((name, "runtime"));
                }
            }
            rows.sort_by(|a, b| a.0.cmp(&b.0));
            Ok(rows
                .into_iter()
                .map(|(n, s)| Tuple::new(vec![Value::String(n), Value::String(s.to_string())]))
                .collect())
        }
        #[cfg(not(feature = "code-graph"))]
        {
            Ok(vec![])
        }
    }

    /// Execute pg_database_branches() system view
    ///
    /// Returns information about all database branches
    fn execute_pg_database_branches(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let branches = storage.list_branches()?;
        let mut results = Vec::new();

        for branch in branches {
            let tuple = Tuple::new(vec![
                Value::String(branch.name.clone()),
                Value::Int8(branch.branch_id as i64),
                Value::Int8(branch.parent_id.map(|id| id as i64).unwrap_or(0)),
                Value::Timestamp(chrono::DateTime::from_timestamp(branch.created_at as i64, 0).unwrap_or_default()),
                Value::Int8(branch.created_from_snapshot as i64),
                Value::Int8((branch.stats.storage_bytes / (1024 * 1024)) as i64), // Convert to MB
                Value::String(format!("{:?}", branch.state)),
            ]);
            results.push(tuple);
        }

        Ok(results)
    }

    /// Execute pg_mv_staleness() system view
    ///
    /// Returns staleness information for all materialized views
    fn execute_pg_mv_staleness(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let mv_catalog = storage.mv_catalog();
        let view_names = mv_catalog.list_views()?;
        let mut results = Vec::new();

        for view_name in view_names {
            match mv_catalog.get_view(&view_name) {
                Ok(metadata) => {
                    // Format base tables as JSON array string
                    let base_tables = format!(
                        "[{}]",
                        metadata
                            .base_tables
                            .iter()
                            .map(|t| format!("\"{}\"", t))
                            .collect::<Vec<_>>()
                            .join(", ")
                    );

                    // Calculate staleness
                    let last_update = metadata.last_refresh.map(|dt| dt.timestamp()).unwrap_or(0);

                    let staleness_sec = metadata.staleness_seconds().unwrap_or(0);

                    // Estimate pending changes (0 for now - would need change tracking)
                    let pending_changes = 0i64;

                    // Determine status
                    let status = if metadata.is_stale() {
                        "STALE"
                    } else if staleness_sec > 3600 {
                        "OUTDATED"
                    } else {
                        "FRESH"
                    };

                    let tuple = Tuple::new(vec![
                        Value::String(metadata.view_name.clone()),
                        Value::String(base_tables),
                        Value::Timestamp(chrono::DateTime::from_timestamp(last_update, 0).unwrap_or_default()),
                        Value::Int8(pending_changes),
                        Value::Int8(staleness_sec),
                        Value::String(status.to_string()),
                    ]);
                    results.push(tuple);
                }
                Err(e) => {
                    tracing::warn!("Failed to get metadata for view '{}': {}", view_name, e);
                    continue;
                }
            }
        }

        Ok(results)
    }

    /// Execute pg_vector_index_stats() system view
    ///
    /// Returns statistics for all vector indexes
    fn execute_pg_vector_index_stats(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let vector_indexes = storage.vector_indexes();
        let all_metadata = vector_indexes.list_all_metadata();
        let mut results = Vec::new();

        for metadata in all_metadata {
            // Get statistics for this index
            match vector_indexes.get_index_stats(&metadata.name) {
                Ok(stats) => {
                    let tuple = Tuple::new(vec![
                        Value::String(stats.index_name),
                        Value::Int8(stats.num_vectors),
                        Value::Int4(stats.dimensions),
                        Value::String(stats.quantization),
                        Value::Int8(stats.memory_bytes),
                        stats.recall_at_10.map(Value::Float8).unwrap_or(Value::Null),
                    ]);
                    results.push(tuple);
                }
                Err(e) => {
                    tracing::warn!("Failed to get stats for index '{}': {}", metadata.name, e);
                    continue;
                }
            }
        }

        Ok(results)
    }

    /// Execute pg_branch_stats() system view
    ///
    /// Returns detailed statistics for all database branches
    fn execute_pg_branch_stats(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let branches = storage.list_branches()?;
        let mut results = Vec::new();

        for branch in branches {
            // Calculate compression ratio (storage vs uncompressed estimate)
            // Simple heuristic: assume typical compression of 2:1
            let compression_ratio = if branch.stats.storage_bytes > 0 {
                Some(2.0) // Placeholder - would need actual compression tracking
            } else {
                None
            };

            let last_modified_ts = if branch.stats.last_modified > 0 {
                chrono::DateTime::from_timestamp(branch.stats.last_modified as i64, 0).unwrap_or_default()
            } else {
                chrono::DateTime::from_timestamp(branch.created_at as i64, 0).unwrap_or_default()
            };

            let tuple = Tuple::new(vec![
                Value::String(branch.name.clone()),
                Value::Int8(branch.stats.modified_keys as i64),
                Value::Int8(branch.stats.storage_bytes as i64),
                Value::Int8(branch.stats.commit_count as i64),
                Value::Timestamp(last_modified_ts),
                compression_ratio.map(Value::Float8).unwrap_or(Value::Null),
            ]);
            results.push(tuple);
        }

        Ok(results)
    }

    /// Execute pg_class() system view
    ///
    /// Returns information about all tables, indexes, sequences, and views
    fn execute_pg_class(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();

        for (idx, table_name) in tables.iter().enumerate() {
            let oid = pg_table_oid(idx);
            // Schema namespacing: the storage key is `schema.table` for a
            // non-`public` table; `relname` is the BARE table (PostgreSQL keeps
            // the schema in `relnamespace`, not `relname`), so two coexisting
            // `a.t` / `b.t` both surface as `relname = 't'`.
            let (relschema, relname) = crate::sql::Planner::split_schema_key(table_name);
            let tuple = Tuple::new(vec![
                Value::Int4(oid),       // oid
                Value::String(relname), // relname
                // relnamespace = the table's REAL schema oid (public tables map
                // to 2200; a `s.t` key maps to s's oid), via the shared map that
                // also fills pg_namespace.oid so JOINs line up.
                Value::Int4(crate::sql::Planner::schema_name_to_oid(&relschema)),
                Value::Int4(oid + 1000),        // reltype
                Value::String("r".to_string()), // relkind (r = relation/table)
                Value::Int4(oid),               // relfilenode
                Value::Boolean(false),          // relrowsecurity (Nano RLS is via TenantManager, not pg_catalog)
                Value::Null,                    // relpartbound (Stage-0 flatten keeps no typed bound)
            ]);
            results.push(tuple);
        }

        for (idx, (index_name, _table_name, _index_type, _columns)) in sorted_art_indexes(storage).iter().enumerate() {
            let oid = pg_index_oid(idx);
            results.push(Tuple::new(vec![
                Value::Int4(oid),
                Value::String(index_name.clone()),
                Value::Int4(PG_PUBLIC_NAMESPACE_OID),
                Value::Int4(0),
                Value::String("i".to_string()),
                Value::Int4(oid),
                Value::Boolean(false),
                Value::Null, // relpartbound
            ]));
        }

        // Sequences (relkind='S'): real CREATE SEQUENCE defs first, then
        // SERIAL/IDENTITY synthetic owned-sequence names, deduped by name so
        // pg_class never reports a sequence twice. A monotonic `seq_idx` keeps
        // OIDs stable for a given catalog ordering.
        let mut seq_idx = 0usize;
        let mut seen_seq: HashSet<String> = HashSet::new();
        for def in catalog.list_sequences()? {
            if !seen_seq.insert(def.name.to_lowercase()) {
                continue;
            }
            let oid = pg_sequence_oid(seq_idx);
            seq_idx += 1;
            results.push(Tuple::new(vec![
                Value::Int4(oid),                     // oid
                Value::String(def.name.clone()),      // relname
                Value::Int4(PG_PUBLIC_NAMESPACE_OID), // relnamespace
                Value::Int4(oid),                     // reltype
                Value::String("S".to_string()),       // relkind (S = sequence)
                Value::Int4(oid),                     // relfilenode
                Value::Boolean(false),                // relrowsecurity
                Value::Null,                          // relpartbound
            ]));
        }
        for table_name in &tables {
            for col_name in catalog.list_identity_columns(table_name)? {
                let seq_name = format!("{table_name}_{col_name}_seq");
                if !seen_seq.insert(seq_name.to_lowercase()) {
                    continue;
                }
                let oid = pg_sequence_oid(seq_idx);
                seq_idx += 1;
                results.push(Tuple::new(vec![
                    Value::Int4(oid),
                    Value::String(seq_name),
                    Value::Int4(PG_PUBLIC_NAMESPACE_OID),
                    Value::Int4(oid),
                    Value::String("S".to_string()),
                    Value::Int4(oid),
                    Value::Boolean(false),
                    Value::Null, // relpartbound
                ]));
            }
        }

        Ok(results)
    }

    /// Execute sqlite_master view — SQLite-shaped catalog rows for each
    /// user table / materialised view. The `sql` column is best-effort:
    /// most sqlite3 callers only filter on `type` and `name`.
    fn execute_sqlite_master(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();
        for table_name in tables {
            // Skip internal helios_* bookkeeping tables — sqlite3 apps don't expect them.
            if table_name.starts_with("helios_") || table_name.starts_with("_hdb_") {
                continue;
            }
            let (kind, sql_decl) = if let Some(rest) = table_name.strip_prefix("mv_") {
                ("view", format!("CREATE MATERIALIZED VIEW {rest} AS ..."))
            } else {
                ("table", format!("CREATE TABLE {table_name} (...)"))
            };
            results.push(Tuple::new(vec![
                Value::String(kind.to_string()),
                Value::String(table_name.clone()),
                Value::String(table_name),
                Value::Int4(0),
                Value::String(sql_decl),
            ]));
        }
        Ok(results)
    }

    /// Execute pg_attribute() system view
    ///
    /// Returns information about all table columns and their attributes
    fn execute_pg_attribute(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();
        let oid_counter = 1000i32;

        for (table_idx, table_name) in tables.iter().enumerate() {
            let table_oid = oid_counter + (table_idx as i32);
            // KanttBan #23 phase 2.4: cache the IDENTITY column list
            // for this table so we can set attidentity = 'd' on the
            // right rows. Empty / missing record → no identity cols
            // → every column gets attidentity = ''.
            let identity_cols = catalog.list_identity_columns(table_name).unwrap_or_default();

            match catalog.get_table_schema(table_name) {
                Ok(schema) => {
                    for (col_idx, column) in schema.columns.iter().enumerate() {
                        let type_oid = Self::get_type_oid(&column.data_type);
                        let is_identity_col = identity_cols.iter().any(|c| c.eq_ignore_ascii_case(&column.name));
                        let ndims: i32 = match &column.data_type {
                            DataType::Array(_) => 1,
                            _ => 0,
                        };
                        let has_default = column.default_expr.is_some() || is_identity_col;
                        let tuple = Tuple::new(vec![
                            Value::Int4(table_oid),                                                  // attrelid
                            Value::String(column.name.clone()),                                      // attname
                            Value::Int4(type_oid),                                                   // atttypid
                            Value::Int4(-1),                                                         // attlen
                            Value::Boolean(!column.nullable),                                        // attnotnull
                            Value::Int4((col_idx + 1) as i32),                                       // attnum
                            Value::Int4(-1),                                                         // atttypmod
                            Value::Boolean(false),                                                   // attisdropped
                            Value::Int4(ndims),                                                      // attndims
                            Value::String(if is_identity_col { "d".into() } else { String::new() }), // attidentity
                            Value::String(String::new()),                                            // attgenerated
                            Value::Boolean(has_default),                                             // atthasdef
                            Value::Int4(0), // attcollation (default)
                        ]);
                        results.push(tuple);
                    }
                }
                Err(_) => {
                    // Skip tables we can't read schema for
                    continue;
                }
            }
        }

        Ok(results)
    }

    /// Execute pg_type() system view
    ///
    /// Returns information about all data types
    fn execute_pg_type(_storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let mut results = Vec::new();
        let types = vec![
            ("int4", 23, 4, true, "N", false),
            ("int8", 20, 8, true, "N", false),
            ("text", 25, -1, false, "S", false),
            ("boolean", 16, 1, true, "B", false),
            ("timestamp", 1114, 8, true, "D", false),
            ("float8", 701, 8, true, "N", false),
            ("vector", 3614, -1, false, "U", false),
        ];

        for (type_name, oid, len, byval, category, notnull) in types {
            let tuple = Tuple::new(vec![
                Value::Int4(oid),                     // oid
                Value::String(type_name.to_string()), // typname
                Value::Int4(len),                     // typlen
                Value::Boolean(byval),                // typbyval
                Value::String(category.to_string()),  // typcategory
                Value::Boolean(notnull),              // typnotnull
                // KanttBan #23 phase 2.6: typnamespace + 4 more
                // columns drizzle joins / reads. Every built-in
                // type lives in pg_catalog (OID 11). typtype 'b' =
                // base type. typowner = postgres (10). typrelid /
                // typbasetype = 0 for non-composite/non-domain.
                Value::Int4(11),           // typnamespace
                Value::String("b".into()), // typtype
                Value::Int4(10),           // typowner
                Value::Int4(0),            // typrelid
                Value::Int4(0),            // typbasetype
            ]);
            results.push(tuple);
        }

        Ok(results)
    }

    /// Execute pg_namespace() system view
    ///
    /// Returns information about all schemas (namespaces).
    /// Always exposes `public` + `information_schema`; other
    /// schemas (`_hdb_code` / `_hdb_graph` / user-created) come
    /// from the catalog's `list_schemas()` materialisation.
    /// KanttBan #23 (v3.31.1 phase 2): synthesise pg_sequences rows
    /// for every IDENTITY / SERIAL column registered in the catalog.
    /// Nano doesn't model sequences as separate objects (synthetic
    /// row counters on the column), so we project one synthetic
    /// sequence per identity column with name `<table>_<col>_seq`.
    /// drizzle-kit's sequence-diff path treats these as existing
    /// objects → no spurious "missing sequence" diffs.
    fn execute_pg_sequences(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        // Track the names we've already emitted so a real CREATE SEQUENCE and a
        // SERIAL/IDENTITY synthetic row never both surface the same name —
        // pg_dump would otherwise see doubles.
        let mut seen: HashSet<String> = HashSet::new();

        // (1) REAL sequences from the durable catalog: full fidelity from each
        // PersistedSequence + its high-water state.
        for def in catalog.list_sequences()? {
            // PostgreSQL's `last_value` is the value last OBTAINED, not the
            // reserved CACHE-block end. The durable state stores the block end
            // (`last_reserved`), which would overstate by up to `cache - 1` and,
            // worse, move BACKWARD after a CYCLE wrap. So prefer the exact
            // value this session actually served (tracked in the live runtime);
            // fall back to the durable high-water only when this session has not
            // advanced the sequence (e.g. just after a reopen) — the documented
            // cached-sequence gap. NULL until the first nextval (is_called).
            let last_value = match crate::sql::sequences::peek_last_served(&def.name) {
                Some(v) => Value::Int8(v),
                None => match catalog.get_sequence_state(&def.name)? {
                    Some(st) if st.is_called => Value::Int8(st.last_reserved),
                    _ => Value::Null, // never advanced yet (is_called == false)
                },
            };
            seen.insert(def.name.to_lowercase());
            rows.push(Tuple::new(vec![
                Value::String("public".into()),       // schemaname
                Value::String(def.name.clone()),      // sequencename
                Value::String("postgres".into()),     // sequenceowner
                Value::String(def.data_type.clone()), // data_type
                Value::Int8(def.start_value),         // start_value
                Value::Int8(def.min_value),           // min_value
                Value::Int8(def.max_value),           // max_value
                Value::Int8(def.increment_by),        // increment_by
                Value::Boolean(def.cycle),            // cycle
                Value::Int8(def.cache),               // cache_size
                last_value,                           // last_value
            ]));
        }

        // (2) SYNTHETIC owned sequences for SERIAL / IDENTITY columns, named
        // `<table>_<col>_seq`. Type/start/max reflect the column's real integer
        // type (next_row_id-backed, so last_value is NULL). Skip any name a real
        // sequence already owns.
        for table_name in catalog.list_tables()? {
            let schema = catalog.get_table_schema(&table_name).ok();
            for col_name in catalog.list_identity_columns(&table_name)? {
                let seq_name = format!("{table_name}_{col_name}_seq");
                if !seen.insert(seq_name.to_lowercase()) {
                    continue;
                }
                let (data_type, max_value) = schema
                    .as_ref()
                    .and_then(|s| s.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&col_name)))
                    .map(|c| serial_type_bounds(&c.data_type))
                    .unwrap_or(("bigint", i64::MAX));
                rows.push(Tuple::new(vec![
                    Value::String("public".into()),   // schemaname
                    Value::String(seq_name),          // sequencename
                    Value::String("postgres".into()), // sequenceowner
                    Value::String(data_type.into()),  // data_type
                    Value::Int8(1),                   // start_value
                    Value::Int8(1),                   // min_value
                    Value::Int8(max_value),           // max_value
                    Value::Int8(1),                   // increment_by
                    Value::Boolean(false),            // cycle
                    Value::Int8(1),                   // cache_size
                    Value::Null,                      // last_value (synthetic counter)
                ]));
            }
        }
        Ok(rows)
    }

    /// information_schema.sequences (SQL-standard, 12 cols). PG excludes
    /// SERIAL/IDENTITY-owned sequences here, so this lists REAL CREATE SEQUENCE
    /// definitions only. Numeric metadata + the value columns are decimal
    /// STRINGS per the standard.
    fn execute_information_schema_sequences(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        for def in catalog.list_sequences()? {
            let precision = match def.data_type.as_str() {
                "smallint" => 16,
                "integer" => 32,
                _ => 64, // bigint (default)
            };
            rows.push(Tuple::new(vec![
                Value::String("heliosdb".into()),                           // sequence_catalog
                Value::String("public".into()),                             // sequence_schema
                Value::String(def.name.clone()),                            // sequence_name
                Value::String(def.data_type.clone()),                       // data_type
                Value::Int4(precision),                                     // numeric_precision
                Value::Int4(2),                                             // numeric_precision_radix
                Value::Int4(0),                                             // numeric_scale
                Value::String(def.start_value.to_string()),                 // start_value
                Value::String(def.min_value.to_string()),                   // minimum_value
                Value::String(def.max_value.to_string()),                   // maximum_value
                Value::String(def.increment_by.to_string()),                // increment
                Value::String(if def.cycle { "YES" } else { "NO" }.into()), // cycle_option
            ]));
        }
        Ok(rows)
    }

    /// KanttBan #23 (v3.31.1 phase 2): synthesise pg_attrdef rows for
    /// every IDENTITY / SERIAL column so drizzle's EXISTS subquery
    /// (joins pg_attrdef ON ad.adrelid + ad.adnum, filters where
    /// pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''<seq>''::regclass)')
    /// resolves to TRUE for those columns. The literal `adsrc` string
    /// matches the format drizzle's CASE arm looks for.
    fn execute_pg_attrdef(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        let mut oid_counter: i32 = 7000;
        for (table_idx, table_name) in catalog.list_tables()?.iter().enumerate() {
            let adrelid = 1000_i32 + table_idx as i32;
            if let Ok(schema) = catalog.get_table_schema(table_name) {
                let identity_cols = catalog.list_identity_columns(table_name)?;
                for (col_idx, col) in schema.columns.iter().enumerate() {
                    // Emit a row for every column that HAS a default: an IDENTITY
                    // column (synthetic owned sequence) OR a column with an
                    // explicit `DEFAULT` expression (e.g. `DEFAULT nextval('seq')`,
                    // which is NOT an identity column). Previously only identity
                    // columns appeared, so pg_get_expr over an explicit-default
                    // column returned nothing.
                    let is_identity = identity_cols.iter().any(|c| c.eq_ignore_ascii_case(&col.name));
                    let adsrc = if is_identity {
                        format!("nextval('{table_name}_{}_seq'::regclass)", col.name)
                    } else if let Some(def) = &col.default_expr {
                        crate::sql::logical_plan::default_expr_json_to_sql(def).unwrap_or_else(|| def.clone())
                    } else {
                        continue;
                    };
                    rows.push(Tuple::new(vec![
                        Value::Int4(oid_counter),          // oid
                        Value::Int4(adrelid),              // adrelid
                        Value::Int2((col_idx + 1) as i16), // adnum (1-indexed)
                        Value::String(adsrc.clone()),      // adbin (node-tree text; same as adsrc for our purposes)
                        Value::String(adsrc),              // adsrc
                    ]));
                    oid_counter += 1;
                }
            }
        }
        Ok(rows)
    }

    /// pg_roles companion to pg_user — different shape (12 cols vs 9)
    /// but same two synthetic roles. drizzle-kit's introspection
    /// queries pg_roles directly during pull.
    fn execute_pg_roles() -> Result<Vec<Tuple>> {
        let role = |oid: i32, name: &str| {
            Tuple::new(vec![
                Value::Int4(oid),           // oid
                Value::String(name.into()), // rolname
                Value::Boolean(true),       // rolsuper
                Value::Boolean(true),       // rolinherit
                Value::Boolean(true),       // rolcreaterole
                Value::Boolean(true),       // rolcreatedb
                Value::Boolean(true),       // rolcanlogin
                Value::Boolean(true),       // rolreplication
                Value::Int4(-1),            // rolconnlimit
                Value::Null,                // rolpassword
                Value::Null,                // rolvaliduntil
                Value::Boolean(true),       // rolbypassrls
            ])
        };
        Ok(vec![role(10, "postgres"), role(11, "helios")])
    }

    /// KanttBan #23 phase 2.8: information_schema.table_constraints —
    /// PK + UNIQUE per table. Mirrors the legacy
    /// `query_information_schema_table_constraints` in
    /// protocol/postgres/catalog.rs.
    fn execute_information_schema_table_constraints(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        for name in catalog.list_tables()? {
            let mut emitted = HashSet::new();
            if let Ok(tschema) = catalog.get_table_schema(&name) {
                if tschema.columns.iter().any(|c| c.primary_key) {
                    let constraint_name = format!("{}_pkey", name);
                    emitted.insert(constraint_name.clone());
                    rows.push(Tuple::new(vec![
                        Value::String("heliosdb".into()),
                        Value::String("public".into()),
                        Value::String(constraint_name),
                        Value::String(name.clone()),
                        Value::String("PRIMARY KEY".into()),
                    ]));
                }
                for col in &tschema.columns {
                    if col.unique && !col.primary_key {
                        let constraint_name = format!("{}_{}_key", name, col.name);
                        emitted.insert(constraint_name.clone());
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(constraint_name),
                            Value::String(name.clone()),
                            Value::String("UNIQUE".into()),
                        ]));
                    }
                }
            }
            if let Ok(constraints) = catalog.load_table_constraints(&name) {
                for unique in constraints.unique_constraints {
                    if emitted.insert(unique.name.clone()) {
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(unique.name),
                            Value::String(name.clone()),
                            Value::String(if unique.is_primary_key {
                                "PRIMARY KEY".into()
                            } else {
                                "UNIQUE".into()
                            }),
                        ]));
                    }
                }
                for fk in constraints.foreign_keys {
                    if emitted.insert(fk.name.clone()) {
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(fk.name),
                            Value::String(name.clone()),
                            Value::String("FOREIGN KEY".into()),
                        ]));
                    }
                }
                for check in constraints.check_constraints {
                    if emitted.insert(check.name.clone()) {
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(check.name),
                            Value::String(name.clone()),
                            Value::String("CHECK".into()),
                        ]));
                    }
                }
            }
        }
        Ok(rows)
    }

    /// KanttBan #23 phase 2.9: information_schema.constraint_column_usage.
    /// For PK/UNIQUE constraints, lists the same columns that form the
    /// constraint (same as KCU). For FK constraints, lists the
    /// REFERENCED (target) columns on the parent table. drizzle reads
    /// this to map FK definitions to their target table+column.
    fn execute_information_schema_constraint_column_usage(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        for name in catalog.list_tables()? {
            // PK + UNIQUE columns (same shape as KCU)
            if let Ok(tschema) = catalog.get_table_schema(&name) {
                for col in &tschema.columns {
                    if col.primary_key {
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(name.clone()),
                            Value::String(col.name.clone()),
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(format!("{}_pkey", name)),
                        ]));
                    } else if col.unique {
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(name.clone()),
                            Value::String(col.name.clone()),
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(format!("{}_{}_key", name, col.name)),
                        ]));
                    }
                }
            }
            // FK target columns (references_table + references_columns)
            if let Ok(constraints) = catalog.load_table_constraints(&name) {
                for fk in &constraints.foreign_keys {
                    for refcol in &fk.references_columns {
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(fk.references_table.clone()),
                            Value::String(refcol.clone()),
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(fk.name.clone()),
                        ]));
                    }
                }
            }
        }
        Ok(rows)
    }

    /// KanttBan #23 phase 2.8: information_schema.key_column_usage.
    fn execute_information_schema_key_column_usage(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        for name in catalog.list_tables()? {
            let mut emitted = HashSet::new();
            if let Ok(tschema) = catalog.get_table_schema(&name) {
                let mut pos: i32 = 1;
                for col in &tschema.columns {
                    if col.primary_key {
                        emitted.insert((format!("{}_pkey", name), col.name.clone()));
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(format!("{}_pkey", name)),
                            Value::String(name.clone()),
                            Value::String(col.name.clone()),
                            Value::Int4(pos),
                        ]));
                        pos += 1;
                    } else if col.unique {
                        emitted.insert((format!("{}_{}_key", name, col.name), col.name.clone()));
                        rows.push(Tuple::new(vec![
                            Value::String("heliosdb".into()),
                            Value::String("public".into()),
                            Value::String(format!("{}_{}_key", name, col.name)),
                            Value::String(name.clone()),
                            Value::String(col.name.clone()),
                            Value::Int4(1),
                        ]));
                    }
                }
            }
            if let Ok(constraints) = catalog.load_table_constraints(&name) {
                for unique in constraints.unique_constraints {
                    for (idx, col) in unique.columns.iter().enumerate() {
                        if emitted.insert((unique.name.clone(), col.clone())) {
                            rows.push(Tuple::new(vec![
                                Value::String("heliosdb".into()),
                                Value::String("public".into()),
                                Value::String(unique.name.clone()),
                                Value::String(name.clone()),
                                Value::String(col.clone()),
                                Value::Int4((idx + 1) as i32),
                            ]));
                        }
                    }
                }
                for fk in constraints.foreign_keys {
                    for (idx, col) in fk.columns.iter().enumerate() {
                        if emitted.insert((fk.name.clone(), col.clone())) {
                            rows.push(Tuple::new(vec![
                                Value::String("heliosdb".into()),
                                Value::String("public".into()),
                                Value::String(fk.name.clone()),
                                Value::String(name.clone()),
                                Value::String(col.clone()),
                                Value::Int4((idx + 1) as i32),
                            ]));
                        }
                    }
                }
            }
        }
        Ok(rows)
    }

    /// KanttBan #23 phase 2.8: information_schema.referential_constraints
    /// — FK ON UPDATE / ON DELETE rules per constraint.
    fn execute_information_schema_referential_constraints(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let mut rows = Vec::new();
        for table in catalog.list_tables()? {
            let constraints = match catalog.load_table_constraints(&table) {
                Ok(c) => c,
                Err(_) => continue,
            };
            for fk in &constraints.foreign_keys {
                rows.push(Tuple::new(vec![
                    Value::String("heliosdb".into()),
                    Value::String("public".into()),
                    Value::String(fk.name.clone()),
                    Value::String("heliosdb".into()),
                    Value::String("public".into()),
                    Value::String(format!("{}_pkey", fk.references_table)),
                    Value::String("NONE".into()),
                    Value::String(fk.on_update.to_string()),
                    Value::String(fk.on_delete.to_string()),
                ]));
            }
        }
        Ok(rows)
    }

    /// KanttBan #22 (v3.31.0): information_schema.tables backed by
    /// the storage catalogue. Mirrors the legacy
    /// `protocol/postgres/catalog.rs::query_information_schema_tables`
    /// (sans the substring LIKE filter — the planner handles WHERE
    /// LIKE natively now).
    fn execute_information_schema_tables(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let table_names = storage.catalog().list_tables()?;
        let mut rows = Vec::with_capacity(table_names.len());
        for name in &table_names {
            // Schema namespacing: `table_schema` is the real schema and
            // `table_name` the bare table (split the `schema.table` key).
            let (table_schema, table_name) = crate::sql::Planner::split_schema_key(name);
            rows.push(Tuple::new(vec![
                Value::String("heliosdb".into()),
                Value::String(table_schema),
                Value::String(table_name),
                Value::String("BASE TABLE".into()),
            ]));
        }
        Ok(rows)
    }

    /// KanttBan #22 (v3.31.0): pg_database minimal stub. Only the
    /// implicit `heliosdb` system database is enumerated — surfacing
    /// tenant databases registered via `CREATE DATABASE` needs
    /// `EmbeddedDatabase::tenant_manager` access, which the registry's
    /// `execute(&StorageEngine)` signature doesn't carry. Deferred to
    /// a follow-up that widens the executor context. `\l` already
    /// renders only `heliosdb` (via try_psql_metacommand's own
    /// matcher), so there's no current-behaviour regression.
    fn execute_pg_database() -> Result<Vec<Tuple>> {
        Ok(vec![Tuple::new(vec![
            Value::Int4(1),                   // oid
            Value::String("heliosdb".into()), // datname
            Value::Int4(10),                  // datdba
            Value::Int4(6),                   // encoding = UTF8
            Value::String("C.UTF-8".into()),  // datcollate
            Value::String("C.UTF-8".into()),  // datctype
            Value::Boolean(false),            // datistemplate
            Value::Boolean(true),             // datallowconn
            Value::Int4(-1),                  // datconnlimit
            Value::Int4(1663),                // dattablespace = pg_default
        ])])
    }

    /// KanttBan #22 (v3.31.0): pg_user as a read-only stub. Mirrors
    /// the two hard-coded roles the legacy substring router exposed
    /// via query_pg_roles in `protocol/postgres/catalog.rs`.
    /// usesysid is the value drivers JOIN to nspowner / relowner /
    /// proowner; keep it stable at 10 (postgres) and 11 (helios) so
    /// existing introspection sees the schemas / tables as owned by
    /// the postgres super-user.
    fn execute_pg_user() -> Result<Vec<Tuple>> {
        let role = |name: &str, uid: i32| {
            Tuple::new(vec![
                Value::String(name.into()), // usename
                Value::Int4(uid),           // usesysid
                Value::Boolean(true),       // usecreatedb
                Value::Boolean(true),       // usesuper
                Value::Boolean(true),       // userepl
                Value::Boolean(true),       // usebypassrls
                Value::Null,                // passwd
                Value::Null,                // valuntil
                Value::Null,                // useconfig
            ])
        };
        Ok(vec![role("postgres", 10), role("helios", 11)])
    }

    fn execute_pg_namespace(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        use std::collections::BTreeSet;
        // The namespaces PostgreSQL always exposes, plus every user schema —
        // whether implied by a `schema.table` key or DECLARED empty via
        // `CREATE SCHEMA` (`list_schemas` now unions the `meta:schema:` markers).
        let mut all: BTreeSet<String> = BTreeSet::new();
        all.insert("pg_catalog".to_string());
        all.insert("information_schema".to_string());
        all.insert("public".to_string());
        if let Ok(catalog_schemas) = storage.catalog().list_schemas() {
            for s in catalog_schemas {
                all.insert(s);
            }
        }

        let mut results = Vec::new();
        for nspname in all {
            // Shared schema→oid map (also drives `pg_class.relnamespace`), so a
            // relation's relnamespace always matches its schema's oid here.
            let oid = crate::sql::Planner::schema_name_to_oid(&nspname);
            results.push(Tuple::new(vec![
                Value::Int4(oid),       // oid
                Value::String(nspname), // nspname
                Value::Int4(10),        // nspowner (postgres super-user)
            ]));
        }
        Ok(results)
    }

    /// Execute pg_index() system view
    ///
    /// Returns information about all indexes
    fn execute_pg_index(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();

        for (idx, (_index_name, table_name, index_type, columns)) in sorted_art_indexes(storage).iter().enumerate() {
            let Some(table_oid) = pg_table_oid_by_name(&tables, table_name) else {
                continue;
            };
            let schema = match catalog.get_table_schema(table_name) {
                Ok(schema) => schema,
                Err(_) => continue,
            };
            let indkey = pg_indkey(&schema, columns);
            let column_count = columns.len() as i16;
            results.push(Tuple::new(vec![
                Value::Int4(pg_index_oid(idx)),                          // indexrelid
                Value::Int4(table_oid),                                  // indrelid
                Value::Boolean(*index_type == ArtIndexType::PrimaryKey), // indisprimary
                Value::Boolean(matches!(*index_type, ArtIndexType::PrimaryKey | ArtIndexType::Unique)), // indisunique
                Value::Boolean(false),                                   // indisexclusion
                Value::String(indkey),                                   // indkey (space-separated attnums)
                Value::Int2(column_count),                               // indnatts
                Value::Int2(column_count),                               // indnkeyatts
                Value::Boolean(false),                                   // indisclustered
                Value::Boolean(true),                                    // indisvalid
                Value::Boolean(true),                                    // indisready
                Value::Boolean(false),                                   // indisreplident
                Value::Null,                                             // indexprs
                Value::Null,                                             // indpred
            ]));
        }

        Ok(results)
    }

    /// Execute pg_constraint() system view
    ///
    /// Returns information about all constraints
    fn execute_pg_constraint(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let indexes = sorted_art_indexes(storage);
        let mut results = Vec::new();
        let mut constraint_oid = PG_CONSTRAINT_OID_BASE;
        let mut seen = HashSet::new();

        for (table_idx, table_name) in tables.iter().enumerate() {
            let table_oid = pg_table_oid(table_idx);
            let schema = match catalog.get_table_schema(table_name) {
                Ok(schema) => schema,
                Err(_) => continue,
            };

            let pk_columns: Vec<String> = schema
                .columns
                .iter()
                .filter(|col| col.primary_key)
                .map(|col| col.name.clone())
                .collect();
            if !pk_columns.is_empty() {
                let constraint_name = format!("{}_pkey", table_name);
                push_pg_constraint_row(
                    &mut results,
                    &mut constraint_oid,
                    &mut seen,
                    constraint_name.clone(),
                    "p",
                    table_oid,
                    None,
                    pg_index_oid_by_name(&indexes, &constraint_name),
                    pg_conkey(&schema, &pk_columns),
                    Value::Null,
                    None,
                    None,
                    false,
                    false,
                    true,
                );
            }

            for col in &schema.columns {
                if col.unique && !col.primary_key {
                    let constraint_name = format!("{}_{}_key", table_name, col.name);
                    push_pg_constraint_row(
                        &mut results,
                        &mut constraint_oid,
                        &mut seen,
                        constraint_name.clone(),
                        "u",
                        table_oid,
                        None,
                        pg_index_oid_by_name(&indexes, &constraint_name),
                        pg_conkey(&schema, std::slice::from_ref(&col.name)),
                        Value::Null,
                        None,
                        None,
                        false,
                        false,
                        true,
                    );
                }
            }

            let constraints = match catalog.load_table_constraints(table_name) {
                Ok(constraints) => constraints,
                Err(_) => continue,
            };

            for unique in constraints.unique_constraints {
                push_pg_constraint_row(
                    &mut results,
                    &mut constraint_oid,
                    &mut seen,
                    unique.name.clone(),
                    if unique.is_primary_key { "p" } else { "u" },
                    table_oid,
                    None,
                    pg_index_oid_by_name(&indexes, &unique.name),
                    pg_conkey(&schema, &unique.columns),
                    Value::Null,
                    None,
                    None,
                    false,
                    false,
                    true,
                );
            }

            for check in constraints.check_constraints {
                push_pg_constraint_row(
                    &mut results,
                    &mut constraint_oid,
                    &mut seen,
                    check.name,
                    "c",
                    table_oid,
                    None,
                    0,
                    Value::Null,
                    Value::Null,
                    None,
                    None,
                    false,
                    false,
                    true,
                );
            }

            for fk in constraints.foreign_keys {
                let ref_oid = pg_table_oid_by_name(&tables, &fk.references_table);
                let ref_key = match catalog.get_table_schema(&fk.references_table) {
                    Ok(ref_schema) => pg_conkey(&ref_schema, &fk.references_columns),
                    Err(_) => Value::Null,
                };
                push_pg_constraint_row(
                    &mut results,
                    &mut constraint_oid,
                    &mut seen,
                    fk.name.clone(),
                    "f",
                    table_oid,
                    ref_oid,
                    0,
                    pg_conkey(&schema, &fk.columns),
                    ref_key,
                    Some(fk.on_update),
                    Some(fk.on_delete),
                    fk.deferrable,
                    fk.initially_deferred,
                    !matches!(fk.enforcement, crate::sql::ConstraintEnforcement::NotEnforced),
                );
            }
        }

        Ok(results)
    }

    /// Execute information_schema.columns() system view
    ///
    /// Returns ANSI SQL standard view of all table columns
    fn execute_information_schema_columns(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();

        for table_name in tables.iter() {
            // Schema namespacing: `table_name` is the raw storage key (used for
            // the schema/identity lookups below); the introspection ROW shows
            // the real schema and the bare table name.
            let (disp_schema, disp_table) = crate::sql::Planner::split_schema_key(table_name);
            let identity_cols = catalog.list_identity_columns(table_name).unwrap_or_default();
            match catalog.get_table_schema(table_name) {
                Ok(schema) => {
                    for (col_idx, column) in schema.columns.iter().enumerate() {
                        let is_nullable = if column.nullable { "YES" } else { "NO" };
                        let data_type = format!("{:?}", column.data_type);
                        let pg_type_name = format_pg_type_name(&column.data_type);
                        let is_identity_col = identity_cols.iter().any(|c| c.eq_ignore_ascii_case(&column.name));
                        // KanttBan #23 (v3.31.1 phase 2): identity
                        // metadata. We always report BY DEFAULT — we
                        // don't track GENERATED ALWAYS separately
                        // (SERIAL maps to BY DEFAULT, IDENTITY can be
                        // either; defaulting to the user-friendly
                        // form). identity_start / identity_increment
                        // / identity_maximum / identity_minimum
                        // match the bigint defaults (1 / 1 / max /
                        // 1). identity_cycle = NO.
                        let (is_identity_str, id_gen, id_start, id_incr, id_max, id_min, id_cycle) = if is_identity_col
                        {
                            (
                                Value::String("YES".into()),
                                Value::String("BY DEFAULT".into()),
                                Value::String("1".into()),
                                Value::String("1".into()),
                                Value::String(i64::MAX.to_string()),
                                Value::String("1".into()),
                                Value::String("NO".into()),
                            )
                        } else {
                            (
                                Value::Null,
                                Value::Null,
                                Value::Null,
                                Value::Null,
                                Value::Null,
                                Value::Null,
                                Value::Null,
                            )
                        };
                        let column_default = if is_identity_col {
                            Value::String(format!("nextval('{table_name}_{}_seq'::regclass)", column.name,))
                        } else {
                            column
                                .default_expr
                                .as_ref()
                                .map(|s| {
                                    Value::String(
                                        crate::sql::logical_plan::default_expr_json_to_sql(s)
                                            .unwrap_or_else(|| s.clone()),
                                    )
                                })
                                .unwrap_or(Value::Null)
                        };

                        let tuple = Tuple::new(vec![
                            Value::String(disp_schema.clone()),     // table_schema
                            Value::String(disp_table.clone()),      // table_name
                            Value::String(column.name.clone()),     // column_name
                            Value::Int4((col_idx + 1) as i32),      // ordinal_position
                            column_default,                         // column_default
                            Value::String(is_nullable.to_string()), // is_nullable
                            Value::String(data_type),               // data_type
                            Value::String(pg_type_name),            // udt_name
                            Value::String("NEVER".into()),          // is_generated
                            Value::Null,                            // generation_expression
                            is_identity_str,                        // is_identity
                            id_gen,                                 // identity_generation
                            id_start,                               // identity_start
                            id_incr,                                // identity_increment
                            id_max,                                 // identity_maximum
                            id_min,                                 // identity_minimum
                            id_cycle,                               // identity_cycle
                        ]);
                        results.push(tuple);
                    }
                }
                Err(_) => {
                    // Skip tables we can't read schema for
                    continue;
                }
            }
        }

        Ok(results)
    }

    /// Helper function to get PostgreSQL type OID for HeliosDB data types
    fn get_type_oid(data_type: &DataType) -> i32 {
        match data_type {
            DataType::Boolean => 16,
            DataType::Int2 => 21,
            DataType::Int4 => 23,
            DataType::Int8 => 20,
            DataType::Float4 => 700,
            DataType::Float8 => 701,
            DataType::Numeric => 1700,
            DataType::Varchar(_) => 1043,
            DataType::Text => 25,
            DataType::Char(_) => 1042,
            DataType::Bytea => 17,
            DataType::Date => 1082,
            DataType::Time => 1083,
            DataType::Timestamp => 1114,
            DataType::Timestamptz => 1184,
            DataType::Interval => 1186,
            DataType::Uuid => 2950,
            DataType::Json => 114,
            DataType::Jsonb => 3802,
            DataType::Array(_) => 2277,
            DataType::Vector(_) => 3614,
        }
    }

    // === Compression Monitoring View Executors ===

    /// Execute heliosdb_compression_stats view
    fn execute_heliosdb_compression_stats(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();

        // Aggregate stats by codec
        let mut alp_stats = (0i64, 0i64, 0i64, 0.0f64); // (uses, bytes_in, bytes_out, total_ratio)
        let mut fsst_stats = (0i64, 0i64, 0i64, 0.0f64);
        let mut none_stats = (0i64, 0i64, 0i64, 0.0f64);

        for table_name in &tables {
            if let Some(stats) = catalog.get_compression_stats(table_name)? {
                for col_stats in stats.column_stats.values() {
                    let codec_name = format!("{:?}", col_stats.codec);
                    match codec_name.as_str() {
                        "ALP" => {
                            alp_stats.0 += col_stats.value_count as i64;
                            alp_stats.1 += col_stats.original_size as i64;
                            alp_stats.2 += col_stats.compressed_size as i64;
                            alp_stats.3 += col_stats.compression_ratio;
                        }
                        "FSST" => {
                            fsst_stats.0 += col_stats.value_count as i64;
                            fsst_stats.1 += col_stats.original_size as i64;
                            fsst_stats.2 += col_stats.compressed_size as i64;
                            fsst_stats.3 += col_stats.compression_ratio;
                        }
                        _ => {
                            none_stats.0 += col_stats.value_count as i64;
                            none_stats.1 += col_stats.original_size as i64;
                            none_stats.2 += col_stats.compressed_size as i64;
                        }
                    }
                }
            }
        }

        // Add ALP row if used
        if alp_stats.0 > 0 {
            results.push(Tuple::new(vec![
                Value::String("ALP".to_string()),
                Value::Int8(alp_stats.0),
                Value::Float8(if alp_stats.2 > 0 {
                    alp_stats.1 as f64 / alp_stats.2 as f64
                } else {
                    1.0
                }),
                Value::Float8(0.0), // avg_compress_us (not tracked yet)
                Value::Float8(0.0), // avg_decompress_us
                Value::Int8(alp_stats.1),
                Value::Int8(alp_stats.2),
            ]));
        }

        // Add FSST row if used
        if fsst_stats.0 > 0 {
            results.push(Tuple::new(vec![
                Value::String("FSST".to_string()),
                Value::Int8(fsst_stats.0),
                Value::Float8(if fsst_stats.2 > 0 {
                    fsst_stats.1 as f64 / fsst_stats.2 as f64
                } else {
                    1.0
                }),
                Value::Float8(0.0),
                Value::Float8(0.0),
                Value::Int8(fsst_stats.1),
                Value::Int8(fsst_stats.2),
            ]));
        }

        // Add None row if exists
        if none_stats.0 > 0 {
            results.push(Tuple::new(vec![
                Value::String("None".to_string()),
                Value::Int8(none_stats.0),
                Value::Float8(1.0),
                Value::Float8(0.0),
                Value::Float8(0.0),
                Value::Int8(none_stats.1),
                Value::Int8(none_stats.2),
            ]));
        }

        Ok(results)
    }

    /// Execute heliosdb_pattern_stats view
    fn execute_heliosdb_pattern_stats(_storage: &StorageEngine) -> Result<Vec<Tuple>> {
        // Pattern detection statistics - returns predefined patterns based on data type affinity
        let results = vec![
            Tuple::new(vec![
                Value::String("FloatingPointData".to_string()),
                Value::Int8(0), // Will be populated when pattern detection is tracked
                Value::String("ALP".to_string()),
                Value::Float8(3.8),
            ]),
            Tuple::new(vec![
                Value::String("StringData".to_string()),
                Value::Int8(0),
                Value::String("FSST".to_string()),
                Value::Float8(6.2),
            ]),
        ];
        Ok(results)
    }

    /// Execute heliosdb_compression_events view
    fn execute_heliosdb_compression_events(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();
        let now = chrono::Utc::now();

        for table_name in &tables {
            if table_name.starts_with("helios_") || table_name.starts_with("mv_") {
                continue;
            }

            if let Some(stats) = catalog.get_compression_stats(table_name)? {
                for (col_name, col_stats) in &stats.column_stats {
                    let tuple = Tuple::new(vec![
                        Value::Timestamp(now),
                        Value::String(table_name.clone()),
                        Value::String(col_name.clone()),
                        Value::String(format!("{:?}", col_stats.codec)),
                        Value::Float8(col_stats.compression_ratio),
                        Value::Int8(col_stats.original_size as i64),
                        Value::Int8(col_stats.compressed_size as i64),
                        Value::Int8(0), // duration_us (not tracked)
                    ]);
                    results.push(tuple);
                }
            }
        }

        Ok(results)
    }

    /// Execute heliosdb_config view
    fn execute_heliosdb_config(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let catalog = storage.catalog();
        let tables = catalog.list_tables()?;
        let mut results = Vec::new();

        // Global compression settings
        results.push(Tuple::new(vec![
            Value::String("compression.enabled".to_string()),
            Value::String("true".to_string()),
            Value::String("Enable automatic compression".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("compression.algorithm".to_string()),
            Value::String("auto".to_string()),
            Value::String("Default compression algorithm (auto selects best)".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("compression.auto.min_rows".to_string()),
            Value::String("1000".to_string()),
            Value::String("Minimum rows before compression is applied".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("compression.auto.min_data_size".to_string()),
            Value::String("1024".to_string()),
            Value::String("Minimum data size in bytes for compression".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("compression.level".to_string()),
            Value::String("6".to_string()),
            Value::String("Compression level (1-9, higher = better ratio)".to_string()),
        ]));

        // Add per-table compression configs
        for table_name in &tables {
            if table_name.starts_with("helios_") || table_name.starts_with("mv_") {
                continue;
            }

            if let Some(config) = catalog.get_compression_config(table_name)? {
                results.push(Tuple::new(vec![
                    Value::String(format!("compression.table.{}.enabled", table_name)),
                    Value::String(config.enabled.to_string()),
                    Value::String(format!("Compression enabled for table {}", table_name)),
                ]));

                results.push(Tuple::new(vec![
                    Value::String(format!("compression.table.{}.level", table_name)),
                    Value::String(config.compression_level.to_string()),
                    Value::String(format!("Compression level for table {}", table_name)),
                ]));
            }
        }

        Ok(results)
    }

    // ========== HA Replication System View Execution ==========

    /// Execute pg_replication_status() system view
    ///
    /// Returns current node's HA replication status and configuration
    #[cfg(feature = "ha-tier1")]
    fn execute_pg_replication_status() -> Result<Vec<Tuple>> {
        use crate::replication::ha_state;
        use chrono::{TimeZone, Utc};

        let state = ha_state();
        let config = state.get_config().unwrap_or_default();
        let lsn = state.get_lsn();
        let standby_count = state.standby_count();
        let is_read_only = state.is_read_only();

        let started_at = Utc
            .timestamp_opt(config.started_at, 0)
            .single()
            .map(|dt| Value::Timestamp(dt))
            .unwrap_or(Value::Null);

        Ok(vec![Tuple::new(vec![
            Value::String(config.node_id.to_string()),
            Value::String(config.role.as_str().to_string()),
            Value::String(config.sync_mode.as_str().to_string()),
            Value::Boolean(is_read_only),
            Value::Int8(lsn as i64),
            Value::Int4(standby_count as i32),
            config.primary_host.map(Value::String).unwrap_or(Value::Null),
            Value::String(format!("{}:{}", config.listen_addr, config.port)),
            Value::Int4(config.replication_port as i32),
            started_at,
        ])])
    }

    #[cfg(not(feature = "ha-tier1"))]
    fn execute_pg_replication_status() -> Result<Vec<Tuple>> {
        Ok(vec![Tuple::new(vec![
            Value::String("N/A".to_string()),
            Value::String("standalone".to_string()),
            Value::String("N/A".to_string()),
            Value::Boolean(false),
            Value::Int8(0),
            Value::Int4(0),
            Value::Null,
            Value::String("N/A".to_string()),
            Value::Int4(0),
            Value::Null,
        ])])
    }

    /// Execute pg_replication_standbys() system view
    ///
    /// Returns connected standby nodes (run on primary)
    #[cfg(feature = "ha-tier1")]
    fn execute_pg_replication_standbys() -> Result<Vec<Tuple>> {
        use crate::replication::ha_state;
        use chrono::{TimeZone, Utc};

        let state = ha_state();
        let standbys = state.get_standbys();

        let mut results = Vec::new();
        for standby in standbys {
            let connected_at = Utc
                .timestamp_opt(standby.connected_at, 0)
                .single()
                .map(|dt| Value::Timestamp(dt))
                .unwrap_or(Value::Null);
            let last_heartbeat = Utc
                .timestamp_opt(standby.last_heartbeat, 0)
                .single()
                .map(|dt| Value::Timestamp(dt))
                .unwrap_or(Value::Null);

            results.push(Tuple::new(vec![
                Value::String(standby.node_id.to_string()),
                Value::String(standby.address.clone()),
                Value::String(standby.state.as_str().to_string()),
                Value::String(standby.sync_mode.as_str().to_string()),
                Value::Int8(standby.current_lsn as i64),
                Value::Int8(standby.flush_lsn as i64),
                Value::Int8(standby.apply_lsn as i64),
                Value::Int8(standby.lag_bytes as i64),
                Value::Int8(standby.lag_ms as i64),
                connected_at,
                last_heartbeat,
            ]));
        }

        Ok(results)
    }

    #[cfg(not(feature = "ha-tier1"))]
    fn execute_pg_replication_standbys() -> Result<Vec<Tuple>> {
        Ok(vec![])
    }

    /// Execute pg_replication_primary() system view
    ///
    /// Returns primary connection status (run on standby)
    #[cfg(feature = "ha-tier1")]
    fn execute_pg_replication_primary() -> Result<Vec<Tuple>> {
        use crate::replication::ha_state;
        use chrono::{TimeZone, Utc};

        let state = ha_state();

        if let Some(primary) = state.get_primary() {
            let connected_at = Utc
                .timestamp_opt(primary.connected_at, 0)
                .single()
                .map(|dt| Value::Timestamp(dt))
                .unwrap_or(Value::Null);
            let last_heartbeat = Utc
                .timestamp_opt(primary.last_heartbeat, 0)
                .single()
                .map(|dt| Value::Timestamp(dt))
                .unwrap_or(Value::Null);

            Ok(vec![Tuple::new(vec![
                Value::String(primary.node_id.to_string()),
                Value::String(primary.address.clone()),
                Value::String(primary.state.as_str().to_string()),
                Value::Int8(primary.primary_lsn as i64),
                Value::Int8(primary.local_lsn as i64),
                Value::Int8(primary.lag_bytes as i64),
                Value::Int8(primary.lag_ms as i64),
                Value::Int8(primary.fencing_token as i64),
                connected_at,
                last_heartbeat,
            ])])
        } else {
            // No primary connection - return a row indicating disconnected state
            Ok(vec![Tuple::new(vec![
                Value::Null,
                Value::Null,
                Value::String("disconnected".to_string()),
                Value::Int8(0),
                Value::Int8(state.get_lsn() as i64),
                Value::Int8(0),
                Value::Int8(0),
                Value::Int8(0),
                Value::Null,
                Value::Null,
            ])])
        }
    }

    #[cfg(not(feature = "ha-tier1"))]
    fn execute_pg_replication_primary() -> Result<Vec<Tuple>> {
        Ok(vec![Tuple::new(vec![
            Value::Null,
            Value::Null,
            Value::String("N/A".to_string()),
            Value::Int8(0),
            Value::Int8(0),
            Value::Int8(0),
            Value::Int8(0),
            Value::Int8(0),
            Value::Null,
            Value::Null,
        ])])
    }

    /// Execute pg_replication_metrics() system view
    ///
    /// Returns replication performance metrics
    #[cfg(feature = "ha-tier1")]
    fn execute_pg_replication_metrics() -> Result<Vec<Tuple>> {
        use crate::replication::ha_state;

        let state = ha_state();
        let metrics = state.get_metrics();

        let mut results = Vec::new();

        // Add each metric as a row
        let metrics_data = vec![
            ("wal_writes", metrics.wal_writes, "Total WAL write operations"),
            (
                "wal_bytes_written",
                metrics.wal_bytes_written,
                "Total bytes written to WAL",
            ),
            (
                "records_replicated",
                metrics.records_replicated,
                "Total records replicated to standbys",
            ),
            (
                "bytes_replicated",
                metrics.bytes_replicated,
                "Total bytes replicated to standbys",
            ),
            ("heartbeats_sent", metrics.heartbeats_sent, "Total heartbeats sent"),
            (
                "heartbeats_received",
                metrics.heartbeats_received,
                "Total heartbeats received",
            ),
            (
                "reconnect_count",
                metrics.reconnect_count,
                "Number of reconnection attempts",
            ),
            ("current_lsn", state.get_lsn(), "Current Log Sequence Number"),
            (
                "standby_count",
                state.standby_count() as u64,
                "Number of connected standbys",
            ),
        ];

        for (name, value, description) in metrics_data {
            results.push(Tuple::new(vec![
                Value::String(name.to_string()),
                Value::Int8(value as i64),
                Value::String(description.to_string()),
            ]));
        }

        // Add timestamp metrics
        if let Some(last_write) = metrics.last_wal_write {
            results.push(Tuple::new(vec![
                Value::String("last_wal_write_epoch".to_string()),
                Value::Int8(last_write),
                Value::String("Unix timestamp of last WAL write".to_string()),
            ]));
        }

        if let Some(last_repl) = metrics.last_replication {
            results.push(Tuple::new(vec![
                Value::String("last_replication_epoch".to_string()),
                Value::Int8(last_repl),
                Value::String("Unix timestamp of last replication".to_string()),
            ]));
        }

        Ok(results)
    }

    #[cfg(not(feature = "ha-tier1"))]
    fn execute_pg_replication_metrics() -> Result<Vec<Tuple>> {
        Ok(vec![Tuple::new(vec![
            Value::String("ha_enabled".to_string()),
            Value::Int8(0),
            Value::String("HA feature not enabled".to_string()),
        ])])
    }

    /// Execute heliosdb_art_indexes view
    ///
    /// Returns information about all ART indexes
    fn execute_heliosdb_art_indexes(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let art_manager = storage.art_indexes();
        let indexes = art_manager.list_indexes();
        let mut results = Vec::new();

        for (name, table, index_type, columns) in indexes {
            // Get stats without cloning the entire tree
            if let Some(stats) = art_manager.index_stats(&name) {
                let columns_str = columns.join(", ");
                let node_count = stats.node4_count + stats.node16_count + stats.node48_count + stats.node256_count;

                results.push(Tuple::new(vec![
                    Value::String(name),
                    Value::String(table),
                    Value::String(columns_str),
                    Value::String(index_type.to_string()),
                    Value::Int8(stats.key_count as i64),
                    Value::Int8(stats.memory_bytes as i64),
                    Value::Int8(node_count as i64),
                    Value::Int8(stats.lookup_count as i64),
                ]));
            }
        }

        Ok(results)
    }

    /// Execute heliosdb_simd_capabilities view
    ///
    /// Returns information about CPU SIMD capabilities
    fn execute_heliosdb_simd_capabilities() -> Result<Vec<Tuple>> {
        use crate::storage::simd_filter::simd_capabilities;
        let caps = simd_capabilities();
        let mut results = Vec::new();

        // AVX-512
        results.push(Tuple::new(vec![
            Value::String("AVX-512".to_string()),
            Value::Boolean(caps.avx512f),
            Value::Int4(if caps.avx512f { 16 } else { 0 }),
            Value::String("512-bit SIMD (16 x i32/f32)".to_string()),
        ]));

        // AVX2
        results.push(Tuple::new(vec![
            Value::String("AVX2".to_string()),
            Value::Boolean(caps.avx2),
            Value::Int4(if caps.avx2 { 8 } else { 0 }),
            Value::String("256-bit SIMD (8 x i32/f32)".to_string()),
        ]));

        // SSE4.1
        results.push(Tuple::new(vec![
            Value::String("SSE4.1".to_string()),
            Value::Boolean(caps.sse41),
            Value::Int4(if caps.sse41 { 4 } else { 0 }),
            Value::String("128-bit SIMD (4 x i32/f32)".to_string()),
        ]));

        // Best available
        let best_level = caps.best_level();
        results.push(Tuple::new(vec![
            Value::String("BEST_AVAILABLE".to_string()),
            Value::Boolean(true),
            Value::Int4(best_level.i32_width() as i32),
            Value::String(caps.description()),
        ]));

        Ok(results)
    }

    /// Execute heliosdb_row_cache_stats view
    ///
    /// Returns row cache statistics
    fn execute_heliosdb_row_cache_stats(storage: &StorageEngine) -> Result<Vec<Tuple>> {
        let row_cache = storage.row_cache();
        let stats = row_cache.stats();
        let mut results = Vec::new();

        results.push(Tuple::new(vec![
            Value::String("lookups".to_string()),
            Value::Int8(stats.lookups as i64),
            Value::String("Total cache lookups".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("hits".to_string()),
            Value::Int8(stats.hits as i64),
            Value::String("Cache hits (found and not expired)".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("misses".to_string()),
            Value::Int8(stats.misses as i64),
            Value::String("Cache misses".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("expirations".to_string()),
            Value::Int8(stats.expirations as i64),
            Value::String("Expired entries encountered".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("evictions".to_string()),
            Value::Int8(stats.evictions as i64),
            Value::String("Entries evicted due to capacity".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("inserts".to_string()),
            Value::Int8(stats.inserts as i64),
            Value::String("Total entries inserted".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("current_entries".to_string()),
            Value::Int8(stats.current_entries as i64),
            Value::String("Current entry count".to_string()),
        ]));

        results.push(Tuple::new(vec![
            Value::String("hit_rate_pct".to_string()),
            Value::Int8((stats.hit_rate() * 100.0) as i64),
            Value::String("Cache hit rate percentage".to_string()),
        ]));

        Ok(results)
    }

    /// Execute heliosdb_lock_census view (W3.1 plateau attribution).
    ///
    /// One row per instrumented read-hot-path lock site: acquisitions,
    /// try-lock-contended count, and cumulative contended-wait nanos. Always
    /// empty unless the binary was built with the `lock-census` feature and
    /// `[performance] lock_census` is enabled — the counters are process-global
    /// (see `crate::lock_census`).
    fn execute_heliosdb_lock_census() -> Result<Vec<Tuple>> {
        let results = crate::lock_census::snapshot()
            .into_iter()
            .map(|site| {
                Tuple::new(vec![
                    Value::String(site.name.to_string()),
                    Value::Int8(site.acquisitions as i64),
                    Value::Int8(site.contended as i64),
                    Value::Int8(site.contended_wait_nanos as i64),
                ])
            })
            .collect();
        Ok(results)
    }

    /// Execute heliosdb_write_volume view (W3.2 version-format quantification).
    ///
    /// One row per statement class: bytes written to `data:`, to the
    /// `v:`/`v_idx:` version chain, and to secondary-index keys, plus a written-
    /// row count. All zero unless `[performance] write_volume_stats` is enabled;
    /// the counters are process-global (see `crate::write_volume`).
    fn execute_heliosdb_write_volume() -> Result<Vec<Tuple>> {
        let results = crate::write_volume::snapshot()
            .into_iter()
            .map(|stat| {
                Tuple::new(vec![
                    Value::String(stat.class.to_string()),
                    Value::Int8(stat.data_bytes as i64),
                    Value::Int8(stat.version_bytes as i64),
                    Value::Int8(stat.index_key_bytes as i64),
                    Value::Int8(stat.rows as i64),
                ])
            })
            .collect();
        Ok(results)
    }

    /// Execute heliosdb_copy_phase_stats view (W3.4 ART-maintenance attribution).
    ///
    /// One row per COPY fast-path funnel phase: cumulative wall nanos, a call
    /// count (COPY batches through the phase), and a processed-row count. All
    /// zero unless `[performance] copy_phase_stats` is enabled; the counters are
    /// process-global (see `crate::copy_phase_stats`).
    fn execute_heliosdb_copy_phase_stats() -> Result<Vec<Tuple>> {
        let results = crate::copy_phase_stats::snapshot()
            .into_iter()
            .map(|stat| {
                Tuple::new(vec![
                    Value::String(stat.phase.to_string()),
                    Value::Int8(stat.total_nanos as i64),
                    Value::Int8(stat.calls as i64),
                    Value::Int8(stat.rows as i64),
                ])
            })
            .collect();
        Ok(results)
    }
}

impl Default for SystemViewRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::Config;

    #[test]
    fn test_registry_creation() {
        let registry = SystemViewRegistry::new();
        assert!(registry.is_system_view("pg_database_branches"));
        assert!(registry.is_system_view("pg_mv_staleness"));
        assert!(registry.is_system_view("pg_vector_index_stats"));
        assert!(!registry.is_system_view("nonexistent_view"));
    }

    #[test]
    fn test_get_schema() {
        let registry = SystemViewRegistry::new();
        let schema = registry.get_schema("pg_database_branches").unwrap();
        assert_eq!(schema.columns.len(), 7);
        assert_eq!(schema.columns[0].name, "branch_name");
    }

    #[test]
    fn test_list_views() {
        let registry = SystemViewRegistry::new();
        let views = registry.list_views();
        assert!(views.len() >= 3);
        assert!(views.contains(&"pg_database_branches"));
    }

    #[test]
    fn test_execute_pg_database_branches() {
        let config = Config::in_memory();
        let storage = StorageEngine::open_in_memory(&config).expect("Failed to create storage");

        // Create a test branch
        storage
            .create_branch("test_branch", Some("main"), crate::storage::BranchOptions::default())
            .expect("Failed to create branch");

        let registry = SystemViewRegistry::new();
        let results = registry
            .execute("pg_database_branches", &storage)
            .expect("Failed to execute pg_database_branches");

        // Should have at least 2 branches (main + test_branch)
        assert!(results.len() >= 2);

        // Verify first result has correct number of columns
        assert_eq!(results[0].values.len(), 7);
    }

    #[test]
    fn test_execute_pg_mv_staleness() {
        let config = Config::in_memory();
        let storage = StorageEngine::open_in_memory(&config).expect("Failed to create storage");

        let registry = SystemViewRegistry::new();
        let results = registry
            .execute("pg_mv_staleness", &storage)
            .expect("Failed to execute pg_mv_staleness");

        // Should return empty results if no materialized views exist
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_execute_pg_vector_index_stats() {
        let config = Config::in_memory();
        let storage = StorageEngine::open_in_memory(&config).expect("Failed to create storage");

        let registry = SystemViewRegistry::new();
        let results = registry
            .execute("pg_vector_index_stats", &storage)
            .expect("Failed to execute pg_vector_index_stats");

        // Should return empty results if no vector indexes exist
        assert_eq!(results.len(), 0);
    }
}