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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! The current types used by the in-memory Catalog. Many of the objects in this module are
//! extremely similar to the objects found in [`crate::durable::objects`] but in a format that is
//! easier consumed by higher layers.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, LazyLock};

use chrono::{DateTime, Utc};
use mz_adapter_types::compaction::CompactionWindow;
use mz_adapter_types::connection::ConnectionId;
use mz_compute_client::logging::LogVariant;
use mz_controller::clusters::{ClusterRole, ClusterStatus, ReplicaConfig, ReplicaLogging};
use mz_controller_types::{ClusterId, ReplicaId};
use mz_expr::{MirScalarExpr, OptimizedMirRelationExpr};
use mz_ore::collections::CollectionExt;
use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem, PrivilegeMap};
use mz_repr::network_policy_id::NetworkPolicyId;
use mz_repr::optimize::OptimizerFeatureOverrides;
use mz_repr::refresh_schedule::RefreshSchedule;
use mz_repr::role_id::RoleId;
use mz_repr::{
    CatalogItemId, Diff, GlobalId, RelationDesc, RelationVersion, RelationVersionSelector,
    Timestamp,
};
use mz_sql::ast::display::AstDisplay;
use mz_sql::ast::{Expr, Raw, Statement, UnresolvedItemName, Value, WithOptionValue};
use mz_sql::catalog::{
    CatalogClusterReplica, CatalogError as SqlCatalogError, CatalogItem as SqlCatalogItem,
    CatalogItemType as SqlCatalogItemType, CatalogItemType, CatalogSchema, CatalogTypeDetails,
    DefaultPrivilegeAclItem, DefaultPrivilegeObject, IdReference, RoleAttributes, RoleMembership,
    RoleVars, SystemObjectType,
};
use mz_sql::names::{
    Aug, CommentObjectId, DatabaseId, DependencyIds, FullItemName, QualifiedItemName,
    QualifiedSchemaName, ResolvedDatabaseSpecifier, ResolvedIds, SchemaId, SchemaSpecifier,
};
use mz_sql::plan::{
    ClusterSchedule, ComputeReplicaConfig, ComputeReplicaIntrospectionConfig, ConnectionDetails,
    CreateClusterManagedPlan, CreateClusterPlan, CreateClusterVariant, CreateSourcePlan,
    HirRelationExpr, Ingestion as PlanIngestion, NetworkPolicyRule, PlanError, WebhookBodyFormat,
    WebhookHeaders, WebhookValidation,
};
use mz_sql::rbac;
use mz_sql::session::vars::OwnedVarInput;
use mz_storage_client::controller::IntrospectionType;
use mz_storage_types::connections::inline::ReferencedConnection;
use mz_storage_types::sinks::{SinkEnvelope, SinkPartitionStrategy, StorageSinkConnection};
use mz_storage_types::sources::{
    GenericSourceConnection, SourceConnection, SourceDesc, SourceEnvelope, SourceExportDataConfig,
    SourceExportDetails, Timeline,
};
use serde::ser::SerializeSeq;
use serde::{Deserialize, Serialize};
use timely::progress::Antichain;
use tracing::debug;

use crate::builtin::{MZ_CATALOG_SERVER_CLUSTER, MZ_SYSTEM_CLUSTER};
use crate::durable;

/// Used to update `self` from the input value while consuming the input value.
pub trait UpdateFrom<T>: From<T> {
    fn update_from(&mut self, from: T);
}

#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct Database {
    pub name: String,
    pub id: DatabaseId,
    pub oid: u32,
    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
    pub schemas_by_id: BTreeMap<SchemaId, Schema>,
    pub schemas_by_name: BTreeMap<String, SchemaId>,
    pub owner_id: RoleId,
    pub privileges: PrivilegeMap,
}

impl From<Database> for durable::Database {
    fn from(database: Database) -> durable::Database {
        durable::Database {
            id: database.id,
            oid: database.oid,
            name: database.name,
            owner_id: database.owner_id,
            privileges: database.privileges.into_all_values().collect(),
        }
    }
}

impl From<durable::Database> for Database {
    fn from(
        durable::Database {
            id,
            oid,
            name,
            owner_id,
            privileges,
        }: durable::Database,
    ) -> Database {
        Database {
            id,
            oid,
            schemas_by_id: BTreeMap::new(),
            schemas_by_name: BTreeMap::new(),
            name,
            owner_id,
            privileges: PrivilegeMap::from_mz_acl_items(privileges),
        }
    }
}

impl UpdateFrom<durable::Database> for Database {
    fn update_from(
        &mut self,
        durable::Database {
            id,
            oid,
            name,
            owner_id,
            privileges,
        }: durable::Database,
    ) {
        self.id = id;
        self.oid = oid;
        self.name = name;
        self.owner_id = owner_id;
        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
    }
}

#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct Schema {
    pub name: QualifiedSchemaName,
    pub id: SchemaSpecifier,
    pub oid: u32,
    pub items: BTreeMap<String, CatalogItemId>,
    pub functions: BTreeMap<String, CatalogItemId>,
    pub types: BTreeMap<String, CatalogItemId>,
    pub owner_id: RoleId,
    pub privileges: PrivilegeMap,
}

impl From<Schema> for durable::Schema {
    fn from(schema: Schema) -> durable::Schema {
        durable::Schema {
            id: schema.id.into(),
            oid: schema.oid,
            name: schema.name.schema,
            database_id: schema.name.database.id(),
            owner_id: schema.owner_id,
            privileges: schema.privileges.into_all_values().collect(),
        }
    }
}

impl From<durable::Schema> for Schema {
    fn from(
        durable::Schema {
            id,
            oid,
            name,
            database_id,
            owner_id,
            privileges,
        }: durable::Schema,
    ) -> Schema {
        Schema {
            name: QualifiedSchemaName {
                database: database_id.into(),
                schema: name,
            },
            id: id.into(),
            oid,
            items: BTreeMap::new(),
            functions: BTreeMap::new(),
            types: BTreeMap::new(),
            owner_id,
            privileges: PrivilegeMap::from_mz_acl_items(privileges),
        }
    }
}

impl UpdateFrom<durable::Schema> for Schema {
    fn update_from(
        &mut self,
        durable::Schema {
            id,
            oid,
            name,
            database_id,
            owner_id,
            privileges,
        }: durable::Schema,
    ) {
        self.name = QualifiedSchemaName {
            database: database_id.into(),
            schema: name,
        };
        self.id = id.into();
        self.oid = oid;
        self.owner_id = owner_id;
        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
    }
}

#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct Role {
    pub name: String,
    pub id: RoleId,
    pub oid: u32,
    pub attributes: RoleAttributes,
    pub membership: RoleMembership,
    pub vars: RoleVars,
}

impl Role {
    pub fn is_user(&self) -> bool {
        self.id.is_user()
    }

    pub fn vars<'a>(&'a self) -> impl Iterator<Item = (&'a str, &'a OwnedVarInput)> {
        self.vars.map.iter().map(|(name, val)| (name.as_str(), val))
    }
}

impl From<Role> for durable::Role {
    fn from(role: Role) -> durable::Role {
        durable::Role {
            id: role.id,
            oid: role.oid,
            name: role.name,
            attributes: role.attributes,
            membership: role.membership,
            vars: role.vars,
        }
    }
}

impl From<durable::Role> for Role {
    fn from(
        durable::Role {
            id,
            oid,
            name,
            attributes,
            membership,
            vars,
        }: durable::Role,
    ) -> Self {
        Role {
            name,
            id,
            oid,
            attributes,
            membership,
            vars,
        }
    }
}

impl UpdateFrom<durable::Role> for Role {
    fn update_from(
        &mut self,
        durable::Role {
            id,
            oid,
            name,
            attributes,
            membership,
            vars,
        }: durable::Role,
    ) {
        self.id = id;
        self.oid = oid;
        self.name = name;
        self.attributes = attributes;
        self.membership = membership;
        self.vars = vars;
    }
}

#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct Cluster {
    pub name: String,
    pub id: ClusterId,
    pub config: ClusterConfig,
    #[serde(skip)]
    pub log_indexes: BTreeMap<LogVariant, GlobalId>,
    /// Objects bound to this cluster. Does not include introspection source
    /// indexes.
    pub bound_objects: BTreeSet<CatalogItemId>,
    pub replica_id_by_name_: BTreeMap<String, ReplicaId>,
    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
    pub replicas_by_id_: BTreeMap<ReplicaId, ClusterReplica>,
    pub owner_id: RoleId,
    pub privileges: PrivilegeMap,
}

impl Cluster {
    /// The role of the cluster. Currently used to set alert severity.
    pub fn role(&self) -> ClusterRole {
        // NOTE - These roles power monitoring systems. Do not change
        // them without talking to the cloud or observability groups.
        if self.name == MZ_SYSTEM_CLUSTER.name {
            ClusterRole::SystemCritical
        } else if self.name == MZ_CATALOG_SERVER_CLUSTER.name {
            ClusterRole::System
        } else {
            ClusterRole::User
        }
    }

    /// Returns `true` if the cluster is a managed cluster.
    pub fn is_managed(&self) -> bool {
        matches!(self.config.variant, ClusterVariant::Managed { .. })
    }

    /// Lists the user replicas, which are those that do not have the internal flag set.
    pub fn user_replicas(&self) -> impl Iterator<Item = &ClusterReplica> {
        self.replicas().filter(|r| !r.config.location.internal())
    }

    /// Lists all replicas in the cluster
    pub fn replicas(&self) -> impl Iterator<Item = &ClusterReplica> {
        self.replicas_by_id_.values()
    }

    /// Lookup a replica by ID.
    pub fn replica(&self, replica_id: ReplicaId) -> Option<&ClusterReplica> {
        self.replicas_by_id_.get(&replica_id)
    }

    /// Lookup a replica ID by name.
    pub fn replica_id(&self, name: &str) -> Option<ReplicaId> {
        self.replica_id_by_name_.get(name).copied()
    }

    /// Returns the availability zones of this cluster, if they exist.
    pub fn availability_zones(&self) -> Option<&[String]> {
        match &self.config.variant {
            ClusterVariant::Managed(managed) => Some(&managed.availability_zones),
            ClusterVariant::Unmanaged => None,
        }
    }

    pub fn try_to_plan(&self) -> Result<CreateClusterPlan, PlanError> {
        let name = self.name.clone();
        let variant = match &self.config.variant {
            ClusterVariant::Managed(ClusterVariantManaged {
                size,
                availability_zones,
                logging,
                replication_factor,
                disk,
                optimizer_feature_overrides,
                schedule,
            }) => {
                let introspection = match logging {
                    ReplicaLogging {
                        log_logging,
                        interval: Some(interval),
                    } => Some(ComputeReplicaIntrospectionConfig {
                        debugging: *log_logging,
                        interval: interval.clone(),
                    }),
                    ReplicaLogging {
                        log_logging: _,
                        interval: None,
                    } => None,
                };
                let compute = ComputeReplicaConfig { introspection };
                CreateClusterVariant::Managed(CreateClusterManagedPlan {
                    replication_factor: replication_factor.clone(),
                    size: size.clone(),
                    availability_zones: availability_zones.clone(),
                    compute,
                    disk: disk.clone(),
                    optimizer_feature_overrides: optimizer_feature_overrides.clone(),
                    schedule: schedule.clone(),
                })
            }
            ClusterVariant::Unmanaged => {
                // Unmanaged clusters are deprecated, so hopefully we can remove
                // them before we have to implement this.
                return Err(PlanError::Unsupported {
                    feature: "SHOW CREATE for unmanaged clusters".to_string(),
                    discussion_no: None,
                });
            }
        };
        let workload_class = self.config.workload_class.clone();
        Ok(CreateClusterPlan {
            name,
            variant,
            workload_class,
        })
    }
}

impl From<Cluster> for durable::Cluster {
    fn from(cluster: Cluster) -> durable::Cluster {
        durable::Cluster {
            id: cluster.id,
            name: cluster.name,
            owner_id: cluster.owner_id,
            privileges: cluster.privileges.into_all_values().collect(),
            config: cluster.config.into(),
        }
    }
}

impl From<durable::Cluster> for Cluster {
    fn from(
        durable::Cluster {
            id,
            name,
            owner_id,
            privileges,
            config,
        }: durable::Cluster,
    ) -> Self {
        Cluster {
            name: name.clone(),
            id,
            bound_objects: BTreeSet::new(),
            log_indexes: BTreeMap::new(),
            replica_id_by_name_: BTreeMap::new(),
            replicas_by_id_: BTreeMap::new(),
            owner_id,
            privileges: PrivilegeMap::from_mz_acl_items(privileges),
            config: config.into(),
        }
    }
}

impl UpdateFrom<durable::Cluster> for Cluster {
    fn update_from(
        &mut self,
        durable::Cluster {
            id,
            name,
            owner_id,
            privileges,
            config,
        }: durable::Cluster,
    ) {
        self.id = id;
        self.name = name;
        self.owner_id = owner_id;
        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
        self.config = config.into();
    }
}

#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct ClusterReplica {
    pub name: String,
    pub cluster_id: ClusterId,
    pub replica_id: ReplicaId,
    pub config: ReplicaConfig,
    pub owner_id: RoleId,
}

impl From<ClusterReplica> for durable::ClusterReplica {
    fn from(replica: ClusterReplica) -> durable::ClusterReplica {
        durable::ClusterReplica {
            cluster_id: replica.cluster_id,
            replica_id: replica.replica_id,
            name: replica.name,
            config: replica.config.into(),
            owner_id: replica.owner_id,
        }
    }
}

#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct ClusterReplicaProcessStatus {
    pub status: ClusterStatus,
    pub time: DateTime<Utc>,
}

#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct SourceReferences {
    pub updated_at: u64,
    pub references: Vec<SourceReference>,
}

#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct SourceReference {
    pub name: String,
    pub namespace: Option<String>,
    pub columns: Vec<String>,
}

impl From<SourceReference> for durable::SourceReference {
    fn from(source_reference: SourceReference) -> durable::SourceReference {
        durable::SourceReference {
            name: source_reference.name,
            namespace: source_reference.namespace,
            columns: source_reference.columns,
        }
    }
}

impl SourceReferences {
    pub fn to_durable(self, source_id: CatalogItemId) -> durable::SourceReferences {
        durable::SourceReferences {
            source_id,
            updated_at: self.updated_at,
            references: self.references.into_iter().map(Into::into).collect(),
        }
    }
}

impl From<durable::SourceReference> for SourceReference {
    fn from(source_reference: durable::SourceReference) -> SourceReference {
        SourceReference {
            name: source_reference.name,
            namespace: source_reference.namespace,
            columns: source_reference.columns,
        }
    }
}

impl From<durable::SourceReferences> for SourceReferences {
    fn from(source_references: durable::SourceReferences) -> SourceReferences {
        SourceReferences {
            updated_at: source_references.updated_at,
            references: source_references
                .references
                .into_iter()
                .map(|source_reference| source_reference.into())
                .collect(),
        }
    }
}

impl From<mz_sql::plan::SourceReference> for SourceReference {
    fn from(source_reference: mz_sql::plan::SourceReference) -> SourceReference {
        SourceReference {
            name: source_reference.name,
            namespace: source_reference.namespace,
            columns: source_reference.columns,
        }
    }
}

impl From<mz_sql::plan::SourceReferences> for SourceReferences {
    fn from(source_references: mz_sql::plan::SourceReferences) -> SourceReferences {
        SourceReferences {
            updated_at: source_references.updated_at,
            references: source_references
                .references
                .into_iter()
                .map(|source_reference| source_reference.into())
                .collect(),
        }
    }
}

impl From<SourceReferences> for mz_sql::plan::SourceReferences {
    fn from(source_references: SourceReferences) -> mz_sql::plan::SourceReferences {
        mz_sql::plan::SourceReferences {
            updated_at: source_references.updated_at,
            references: source_references
                .references
                .into_iter()
                .map(|source_reference| source_reference.into())
                .collect(),
        }
    }
}

impl From<SourceReference> for mz_sql::plan::SourceReference {
    fn from(source_reference: SourceReference) -> mz_sql::plan::SourceReference {
        mz_sql::plan::SourceReference {
            name: source_reference.name,
            namespace: source_reference.namespace,
            columns: source_reference.columns,
        }
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct CatalogEntry {
    pub item: CatalogItem,
    #[serde(skip)]
    pub referenced_by: Vec<CatalogItemId>,
    // TODO(database-issues#7922)––this should have an invariant tied to it that all
    // dependents (i.e. entries in this field) have IDs greater than this
    // entry's ID.
    #[serde(skip)]
    pub used_by: Vec<CatalogItemId>,
    pub id: CatalogItemId,
    pub oid: u32,
    pub name: QualifiedItemName,
    pub owner_id: RoleId,
    pub privileges: PrivilegeMap,
}

/// A [`CatalogEntry`] that is associated with a specific "collection" of data.
/// A single item in the catalog may be associated with multiple "collections".
///
/// Here "collection" generally means a pTVC, e.g. a Persist Shard, an Index, a
/// currently running dataflow, etc.
///
/// Items in the Catalog have a stable name -> ID mapping, in other words for
/// the entire lifetime of an object its [`CatalogItemId`] will _never_ change.
/// Similarly, we need to maintain a stable mapping from [`GlobalId`] to pTVC.
/// This presents a challenge when `ALTER`-ing an object, e.g. adding columns
/// to a table. We can't just change the schema of the underlying Persist Shard
/// because that would be rebinding the [`GlobalId`] of the pTVC. Instead we
/// allocate a new [`GlobalId`] to refer to the new version of the table, and
/// then the [`CatalogEntry`] tracks the [`GlobalId`] for each version.
///
/// TODO(ct): Add a note here if we end up using this for associating continual
/// tasks with a single catalog item.
#[derive(Clone, Debug)]
pub struct CatalogCollectionEntry {
    entry: CatalogEntry,
    #[allow(dead_code)]
    version: RelationVersionSelector,
}

impl mz_sql::catalog::CatalogCollectionItem for CatalogCollectionEntry {
    fn desc(&self, name: &FullItemName) -> Result<Cow<RelationDesc>, SqlCatalogError> {
        // TODO(alter_table): Versioned Relation Desc
        self.entry.desc(name)
    }

    fn global_id(&self) -> GlobalId {
        match self.entry.item() {
            CatalogItem::Source(source) => source.global_id,
            CatalogItem::Log(log) => log.global_id,
            CatalogItem::View(view) => view.global_id,
            CatalogItem::MaterializedView(mv) => mv.global_id,
            CatalogItem::Sink(sink) => sink.global_id,
            CatalogItem::Index(index) => index.global_id,
            CatalogItem::Type(ty) => ty.global_id,
            CatalogItem::Func(func) => func.global_id,
            CatalogItem::Secret(secret) => secret.global_id,
            CatalogItem::Connection(conn) => conn.global_id,
            CatalogItem::ContinualTask(ct) => ct.global_id,
            CatalogItem::Table(table) => match self.version {
                RelationVersionSelector::Latest => {
                    let (_version, gid) = table
                        .collections
                        .last_key_value()
                        .expect("at least one version");
                    *gid
                }
                RelationVersionSelector::Specific(version) => table
                    .collections
                    .get(&version)
                    .expect("catalog corruption, missing version!")
                    .clone(),
            },
        }
    }
}

impl mz_sql::catalog::CatalogItem for CatalogCollectionEntry {
    fn name(&self) -> &QualifiedItemName {
        self.entry.name()
    }

    fn id(&self) -> CatalogItemId {
        self.entry.id()
    }

    fn global_ids(&self) -> Box<dyn Iterator<Item = GlobalId> + '_> {
        Box::new(self.entry.global_ids())
    }

    fn oid(&self) -> u32 {
        self.entry.oid()
    }

    fn func(&self) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
        self.entry.func()
    }

    fn source_desc(&self) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
        self.entry.source_desc()
    }

    fn connection(
        &self,
    ) -> Result<mz_storage_types::connections::Connection<ReferencedConnection>, SqlCatalogError>
    {
        mz_sql::catalog::CatalogItem::connection(&self.entry)
    }

    fn create_sql(&self) -> &str {
        self.entry.create_sql()
    }

    fn item_type(&self) -> SqlCatalogItemType {
        self.entry.item_type()
    }

    fn index_details(&self) -> Option<(&[MirScalarExpr], GlobalId)> {
        self.entry.index_details()
    }

    fn writable_table_details(&self) -> Option<&[Expr<Aug>]> {
        self.entry.writable_table_details()
    }

    fn type_details(&self) -> Option<&CatalogTypeDetails<IdReference>> {
        self.entry.type_details()
    }

    fn references(&self) -> &ResolvedIds {
        self.entry.references()
    }

    fn uses(&self) -> BTreeSet<CatalogItemId> {
        self.entry.uses()
    }

    fn referenced_by(&self) -> &[CatalogItemId] {
        self.entry.referenced_by()
    }

    fn used_by(&self) -> &[CatalogItemId] {
        self.entry.used_by()
    }

    fn subsource_details(
        &self,
    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)> {
        self.entry.subsource_details()
    }

    fn source_export_details(
        &self,
    ) -> Option<(
        CatalogItemId,
        &UnresolvedItemName,
        &SourceExportDetails,
        &SourceExportDataConfig<ReferencedConnection>,
    )> {
        self.entry.source_export_details()
    }

    fn is_progress_source(&self) -> bool {
        self.entry.is_progress_source()
    }

    fn progress_id(&self) -> Option<CatalogItemId> {
        self.entry.progress_id()
    }

    fn owner_id(&self) -> RoleId {
        *self.entry.owner_id()
    }

    fn privileges(&self) -> &PrivilegeMap {
        self.entry.privileges()
    }

    fn cluster_id(&self) -> Option<ClusterId> {
        self.entry.item().cluster_id()
    }

    fn at_version(
        &self,
        version: RelationVersionSelector,
    ) -> Box<dyn mz_sql::catalog::CatalogCollectionItem> {
        self.entry.at_version(version)
    }
}

#[derive(Debug, Clone, Serialize)]
pub enum CatalogItem {
    Table(Table),
    Source(Source),
    Log(Log),
    View(View),
    MaterializedView(MaterializedView),
    Sink(Sink),
    Index(Index),
    Type(Type),
    Func(Func),
    Secret(Secret),
    Connection(Connection),
    ContinualTask(ContinualTask),
}

impl From<CatalogEntry> for durable::Item {
    fn from(entry: CatalogEntry) -> durable::Item {
        let (create_sql, global_id, extra_versions) = entry.item.into_serialized();
        durable::Item {
            id: entry.id,
            oid: entry.oid,
            global_id,
            schema_id: entry.name.qualifiers.schema_spec.into(),
            name: entry.name.item,
            create_sql,
            owner_id: entry.owner_id,
            privileges: entry.privileges.into_all_values().collect(),
            extra_versions,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Table {
    /// Parse-able SQL that defines this table.
    pub create_sql: Option<String>,
    /// [`RelationDesc`] of this table, derived from the `create_sql`.
    pub desc: RelationDesc,
    /// Versions of this table, and the [`GlobalId`]s that refer to them.
    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
    pub collections: BTreeMap<RelationVersion, GlobalId>,
    /// If created in the `TEMPORARY` schema, the [`ConnectionId`] for that session.
    #[serde(skip)]
    pub conn_id: Option<ConnectionId>,
    /// Other catalog objects referenced by this table, e.g. custom types.
    pub resolved_ids: ResolvedIds,
    /// Custom compaction window, e.g. set via `ALTER RETAIN HISTORY`.
    pub custom_logical_compaction_window: Option<CompactionWindow>,
    /// Whether the table's logical compaction window is controlled by the ['metrics_retention']
    /// session variable.
    ///
    /// ['metrics_retention']: mz_sql::session::vars::METRICS_RETENTION
    pub is_retained_metrics_object: bool,
    /// Where data for this table comes from, e.g. `INSERT` statements or an upstream source.
    pub data_source: TableDataSource,
}

impl Table {
    pub fn timeline(&self) -> Timeline {
        match &self.data_source {
            // The Coordinator controls insertions for writable tables
            // (including system tables), so they are realtime.
            TableDataSource::TableWrites { .. } => Timeline::EpochMilliseconds,
            TableDataSource::DataSource { timeline, .. } => timeline.clone(),
        }
    }

    /// Returns all of the [`GlobalId`]s that this [`Table`] can be referenced by.
    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
        self.collections.values().copied()
    }

    /// Returns the latest [`GlobalId`] for this [`Table`] which should be used for writes.
    pub fn global_id_writes(&self) -> GlobalId {
        self.collections
            .last_key_value()
            .expect("at least one version of a table")
            .1
            .clone()
    }

    /// Returns all of the collections and their [`RelationDesc`]s associated with this [`Table`].
    pub fn collection_descs(&self) -> impl Iterator<Item = (GlobalId, RelationDesc)> + '_ {
        // TODO(alter_table): Support multiple versions of the table.
        assert_eq!(self.collections.len(), 1);
        self.collections
            .values()
            .map(|gid| (*gid, self.desc.clone()))
    }
}

#[derive(Clone, Debug, Serialize)]
pub enum TableDataSource {
    /// The table owns data created via INSERT/UPDATE/DELETE statements.
    TableWrites {
        #[serde(skip)]
        defaults: Vec<Expr<Aug>>,
    },

    /// The table receives its data from the identified `DataSourceDesc`.
    /// This table type does not support INSERT/UPDATE/DELETE statements.
    DataSource {
        desc: DataSourceDesc,
        timeline: Timeline,
    },
}

#[derive(Debug, Clone, Serialize)]
pub enum DataSourceDesc {
    /// Receives data from an external system
    Ingestion {
        ingestion_desc: PlanIngestion,
        cluster_id: ClusterId,
    },
    /// This source receives its data from the identified ingestion,
    /// specifically the output identified by `external_reference`.
    /// N.B. that `external_reference` should not be used to identify
    /// anything downstream of purification, as the purification process
    /// encodes source-specific identifiers into the `details` struct.
    /// The `external_reference` field is only used here for displaying
    /// human-readable names in system tables.
    IngestionExport {
        ingestion_id: CatalogItemId,
        external_reference: UnresolvedItemName,
        details: SourceExportDetails,
        data_config: SourceExportDataConfig<ReferencedConnection>,
    },
    /// Receives introspection data from an internal system
    Introspection(IntrospectionType),
    /// Receives data from the source's reclocking/remapping operations.
    Progress,
    /// Receives data from HTTP requests.
    Webhook {
        /// Optional components used to validation a webhook request.
        validate_using: Option<WebhookValidation>,
        /// Describes how we deserialize the body of a webhook request.
        body_format: WebhookBodyFormat,
        /// Describes whether or not to include headers and how to map them.
        headers: WebhookHeaders,
        /// The cluster which this source is associated with.
        cluster_id: ClusterId,
    },
}

impl DataSourceDesc {
    /// The key and value formats of the data source.
    pub fn formats(&self) -> (Option<&str>, Option<&str>) {
        match &self {
            DataSourceDesc::Ingestion { ingestion_desc, .. } => {
                match &ingestion_desc.desc.primary_export {
                    Some(export) => match export.encoding.as_ref() {
                        Some(encoding) => match &encoding.key {
                            Some(key) => (Some(key.type_()), Some(encoding.value.type_())),
                            None => (None, Some(encoding.value.type_())),
                        },
                        None => (None, None),
                    },
                    None => (None, None),
                }
            }
            DataSourceDesc::IngestionExport { data_config, .. } => match &data_config.encoding {
                Some(encoding) => match &encoding.key {
                    Some(key) => (Some(key.type_()), Some(encoding.value.type_())),
                    None => (None, Some(encoding.value.type_())),
                },
                None => (None, None),
            },
            DataSourceDesc::Introspection(_)
            | DataSourceDesc::Webhook { .. }
            | DataSourceDesc::Progress => (None, None),
        }
    }

    /// Envelope of the data source.
    pub fn envelope(&self) -> Option<&str> {
        // Note how "none"/"append-only" is different from `None`. Source
        // sources don't have an envelope (internal logs, for example), while
        // other sources have an envelope that we call the "NONE"-envelope.

        fn envelope_string(envelope: &SourceEnvelope) -> &str {
            match envelope {
                SourceEnvelope::None(_) => "none",
                SourceEnvelope::Upsert(upsert_envelope) => match upsert_envelope.style {
                    mz_storage_types::sources::envelope::UpsertStyle::Default(_) => "upsert",
                    mz_storage_types::sources::envelope::UpsertStyle::Debezium { .. } => {
                        // NOTE(aljoscha): Should we somehow mark that this is
                        // using upsert internally? See note above about
                        // DEBEZIUM.
                        "debezium"
                    }
                    mz_storage_types::sources::envelope::UpsertStyle::ValueErrInline { .. } => {
                        "upsert-value-err-inline"
                    }
                },
                SourceEnvelope::CdcV2 => {
                    // TODO(aljoscha): Should we even report this? It's
                    // currently not exposed.
                    "materialize"
                }
            }
        }

        match self {
            // NOTE(aljoscha): We could move the block for ingestions into
            // `SourceEnvelope` itself, but that one feels more like an internal
            // thing and adapter should own how we represent envelopes as a
            // string? It would not be hard to convince me otherwise, though.
            DataSourceDesc::Ingestion { ingestion_desc, .. } => ingestion_desc
                .desc
                .primary_export
                .as_ref()
                .map(|export| envelope_string(&export.envelope)),
            DataSourceDesc::IngestionExport { data_config, .. } => {
                Some(envelope_string(&data_config.envelope))
            }
            DataSourceDesc::Introspection(_)
            | DataSourceDesc::Webhook { .. }
            | DataSourceDesc::Progress => None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Source {
    /// Parse-able SQL that defines this table.
    pub create_sql: Option<String>,
    /// [`GlobalId`] used to reference this source from outside the catalog.
    pub global_id: GlobalId,
    // TODO: Unskip: currently blocked on some inner BTreeMap<X, _> problems.
    #[serde(skip)]
    pub data_source: DataSourceDesc,
    /// [`RelationDesc`] of this source, derived from the `create_sql`.
    pub desc: RelationDesc,
    /// The timeline this source exists on.
    pub timeline: Timeline,
    /// Other catalog objects referenced by this table, e.g. custom types.
    pub resolved_ids: ResolvedIds,
    /// This value is ignored for subsources, i.e. for
    /// [`DataSourceDesc::IngestionExport`]. Instead, it uses the primary
    /// sources logical compaction window.
    pub custom_logical_compaction_window: Option<CompactionWindow>,
    /// Whether the source's logical compaction window is controlled by
    /// METRICS_RETENTION
    pub is_retained_metrics_object: bool,
}

impl Source {
    /// Creates a new `Source`.
    ///
    /// # Panics
    /// - If an ingestion-based plan is not given a cluster_id.
    /// - If a non-ingestion-based source has a defined cluster config in its plan.
    /// - If a non-ingestion-based source is given a cluster_id.
    pub fn new(
        plan: CreateSourcePlan,
        global_id: GlobalId,
        resolved_ids: ResolvedIds,
        custom_logical_compaction_window: Option<CompactionWindow>,
        is_retained_metrics_object: bool,
    ) -> Source {
        Source {
            create_sql: Some(plan.source.create_sql),
            data_source: match plan.source.data_source {
                mz_sql::plan::DataSourceDesc::Ingestion(ingestion_desc) => {
                    DataSourceDesc::Ingestion {
                        ingestion_desc,
                        cluster_id: plan
                            .in_cluster
                            .expect("ingestion-based sources must be given a cluster ID"),
                    }
                }
                mz_sql::plan::DataSourceDesc::Progress => {
                    assert!(
                        plan.in_cluster.is_none(),
                        "subsources must not have a host config or cluster_id defined"
                    );
                    DataSourceDesc::Progress
                }
                mz_sql::plan::DataSourceDesc::IngestionExport {
                    ingestion_id,
                    external_reference,
                    details,
                    data_config,
                } => {
                    assert!(
                        plan.in_cluster.is_none(),
                        "subsources must not have a host config or cluster_id defined"
                    );
                    DataSourceDesc::IngestionExport {
                        ingestion_id,
                        external_reference,
                        details,
                        data_config,
                    }
                }
                mz_sql::plan::DataSourceDesc::Webhook {
                    validate_using,
                    body_format,
                    headers,
                } => DataSourceDesc::Webhook {
                    validate_using,
                    body_format,
                    headers,
                    cluster_id: plan
                        .in_cluster
                        .expect("webhook sources must be given a cluster ID"),
                },
            },
            desc: plan.source.desc,
            global_id,
            timeline: plan.timeline,
            resolved_ids,
            custom_logical_compaction_window: plan
                .source
                .compaction_window
                .or(custom_logical_compaction_window),
            is_retained_metrics_object,
        }
    }

    /// Type of the source.
    pub fn source_type(&self) -> &str {
        match &self.data_source {
            DataSourceDesc::Ingestion { ingestion_desc, .. } => {
                ingestion_desc.desc.connection.name()
            }
            DataSourceDesc::Progress => "progress",
            DataSourceDesc::IngestionExport { .. } => "subsource",
            DataSourceDesc::Introspection(_) => "source",
            DataSourceDesc::Webhook { .. } => "webhook",
        }
    }

    /// Connection ID of the source, if one exists.
    pub fn connection_id(&self) -> Option<CatalogItemId> {
        match &self.data_source {
            DataSourceDesc::Ingestion { ingestion_desc, .. } => {
                ingestion_desc.desc.connection.connection_id()
            }
            DataSourceDesc::IngestionExport { .. }
            | DataSourceDesc::Introspection(_)
            | DataSourceDesc::Webhook { .. }
            | DataSourceDesc::Progress => None,
        }
    }

    /// The single [`GlobalId`] that refers to this Source.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }

    /// The expensive resource that each source consumes is persist shards. To
    /// prevent abuse, we want to prevent users from creating sources that use an
    /// unbounded number of persist shards. But we also don't want to count
    /// persist shards that are mandated by teh system (e.g., the progress
    /// shard) so that future versions of Materialize can introduce additional
    /// per-source shards (e.g., a per-source status shard) without impacting
    /// the limit calculation.
    pub fn user_controllable_persist_shard_count(&self) -> i64 {
        match &self.data_source {
            DataSourceDesc::Ingestion { ingestion_desc, .. } => {
                match &ingestion_desc.desc.connection {
                    // These multi-output sources do not use their primary
                    // source's data shard, so we don't include it in accounting
                    // for users.
                    GenericSourceConnection::Postgres(_) | GenericSourceConnection::MySql(_) => 0,
                    GenericSourceConnection::LoadGenerator(lg) => {
                        // TODO: make this a method on the load generator.
                        if lg.load_generator.views().is_empty() {
                            // Load generator writes directly to its persist shard
                            1
                        } else {
                            // Load generator has 1 persist shard per output,
                            // which will be accounted for by `SourceExport`.
                            0
                        }
                    }
                    GenericSourceConnection::Kafka(_) => 1,
                }
            }
            //  DataSourceDesc::IngestionExport represents a subsource, which
            //  use a data shard.
            DataSourceDesc::IngestionExport { .. } => 1,
            DataSourceDesc::Webhook { .. } => 1,
            // Introspection and progress subsources are not under the user's control, so shouldn't
            // count toward their quota.
            DataSourceDesc::Introspection(_) | DataSourceDesc::Progress => 0,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Log {
    /// The category of data this log stores.
    pub variant: LogVariant,
    /// [`GlobalId`] used to reference this log from outside the catalog.
    pub global_id: GlobalId,
}

impl Log {
    /// The single [`GlobalId`] that refers to this Log.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Sink {
    /// Parse-able SQL that defines this sink.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this sink from outside the catalog, e.g storage.
    pub global_id: GlobalId,
    /// Collection we read into this sink.
    pub from: GlobalId,
    /// Connection to the external service we're sinking into, e.g. Kafka.
    pub connection: StorageSinkConnection<ReferencedConnection>,
    /// Envelope we use to sink into the external system.
    ///
    /// TODO(guswynn): this probably should just be in the `connection`.
    pub envelope: SinkEnvelope,
    /// Strategy used to partition rows.
    pub partition_strategy: SinkPartitionStrategy,
    /// Emit an initial snapshot into the sink.
    pub with_snapshot: bool,
    /// Used to fence other writes into this sink as we evolve the upstream materialized view.
    pub version: u64,
    /// Other catalog objects this sink references.
    pub resolved_ids: ResolvedIds,
    /// Cluster this sink runs on.
    pub cluster_id: ClusterId,
}

impl Sink {
    pub fn sink_type(&self) -> &str {
        self.connection.name()
    }

    /// Envelope of the sink.
    pub fn envelope(&self) -> Option<&str> {
        match &self.envelope {
            SinkEnvelope::Debezium => Some("debezium"),
            SinkEnvelope::Upsert => Some("upsert"),
        }
    }

    /// Output a combined format string of the sink. For legacy reasons
    /// if the key-format is none or the key & value formats are
    /// both the same (either avro or json), we return the value format name,
    /// otherwise we return a composite name.
    pub fn combined_format(&self) -> Cow<'_, str> {
        let StorageSinkConnection::Kafka(connection) = &self.connection;
        connection.format.get_format_name()
    }

    /// Output distinct key_format and value_format of the sink.
    pub fn formats(&self) -> (Option<&str>, &str) {
        let StorageSinkConnection::Kafka(connection) = &self.connection;
        let key_format = connection
            .format
            .key_format
            .as_ref()
            .map(|format| format.get_format_name());
        let value_format = connection.format.value_format.get_format_name();
        (key_format, value_format)
    }

    pub fn connection_id(&self) -> Option<CatalogItemId> {
        self.connection.connection_id()
    }

    /// The single [`GlobalId`] that this Sink can be referenced by.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct View {
    /// Parse-able SQL that defines this view.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this view from outside the catalog, e.g. compute.
    pub global_id: GlobalId,
    /// Unoptimized high-level expression from parsing the `create_sql`.
    pub raw_expr: Arc<HirRelationExpr>,
    /// Optimized mid-level expression from optimizing the `raw_expr`.
    pub optimized_expr: Arc<OptimizedMirRelationExpr>,
    /// Columns of this view.
    pub desc: RelationDesc,
    /// If created in the `TEMPORARY` schema, the [`ConnectionId`] for that session.
    pub conn_id: Option<ConnectionId>,
    /// Other catalog objects that are referenced by this view, determined at name resolution.
    pub resolved_ids: ResolvedIds,
    /// All of the catalog objects that are referenced by this view.
    pub dependencies: DependencyIds,
}

impl View {
    /// The single [`GlobalId`] this [`View`] can be referenced by.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct MaterializedView {
    /// Parse-able SQL that defines this materialized view.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this materialized view from outside the catalog.
    pub global_id: GlobalId,
    /// Raw high-level expression from planning, derived from the `create_sql`.
    pub raw_expr: Arc<HirRelationExpr>,
    /// Optimized mid-level expression, derived from the `raw_expr`.
    pub optimized_expr: Arc<OptimizedMirRelationExpr>,
    /// Columns for this materialized view.
    pub desc: RelationDesc,
    /// Other catalog items that this materialized view references, determined at name resolution.
    pub resolved_ids: ResolvedIds,
    /// All of the catalog objects that are referenced by this view.
    pub dependencies: DependencyIds,
    /// Cluster that this materialized view runs on.
    pub cluster_id: ClusterId,
    /// Column indexes that we assert are not `NULL`.
    ///
    /// TODO(parkmycar): Switch this to use the `ColumnIdx` type.
    pub non_null_assertions: Vec<usize>,
    /// Custom compaction window, e.g. set via `ALTER RETAIN HISTORY`.
    pub custom_logical_compaction_window: Option<CompactionWindow>,
    /// Schedule to refresh this materialized view, e.g. set via `REFRESH EVERY` option.
    pub refresh_schedule: Option<RefreshSchedule>,
    /// The initial `as_of` of the storage collection associated with the materialized view.
    ///
    /// Note: This doesn't change upon restarts.
    /// (The dataflow's initial `as_of` can be different.)
    pub initial_as_of: Option<Antichain<mz_repr::Timestamp>>,
}

impl MaterializedView {
    /// The single [`GlobalId`] this [`MaterializedView`] can be referenced by.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Index {
    /// Parse-able SQL that defines this table.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this index from outside the catalog, e.g. compute.
    pub global_id: GlobalId,
    /// The [`GlobalId`] this Index is on.
    pub on: GlobalId,
    /// Keys of the index.
    pub keys: Arc<[MirScalarExpr]>,
    /// If created in the `TEMPORARY` schema, the [`ConnectionId`] for that session.
    pub conn_id: Option<ConnectionId>,
    /// Other catalog objects referenced by this index, e.g. the object we're indexing.
    pub resolved_ids: ResolvedIds,
    /// Cluster this index is installed on.
    pub cluster_id: ClusterId,
    /// Custom compaction window, e.g. set via `ALTER RETAIN HISTORY`.
    pub custom_logical_compaction_window: Option<CompactionWindow>,
    /// Whether the table's logical compaction window is controlled by the ['metrics_retention']
    /// session variable.
    ///
    /// ['metrics_retention']: mz_sql::session::vars::METRICS_RETENTION
    pub is_retained_metrics_object: bool,
}

impl Index {
    /// The [`GlobalId`] that refers to this Index.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Type {
    /// Parse-able SQL that defines this type.
    pub create_sql: Option<String>,
    /// [`GlobalId`] used to reference this type from outside the catalog.
    pub global_id: GlobalId,
    #[serde(skip)]
    pub details: CatalogTypeDetails<IdReference>,
    pub desc: Option<RelationDesc>,
    /// Other catalog objects referenced by this type.
    pub resolved_ids: ResolvedIds,
}

#[derive(Debug, Clone, Serialize)]
pub struct Func {
    /// Static definition of the function.
    #[serde(skip)]
    pub inner: &'static mz_sql::func::Func,
    /// [`GlobalId`] used to reference this function from outside the catalog.
    pub global_id: GlobalId,
}

#[derive(Debug, Clone, Serialize)]
pub struct Secret {
    /// Parse-able SQL that defines this secret.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this secret from outside the catalog.
    pub global_id: GlobalId,
}

#[derive(Debug, Clone, Serialize)]
pub struct Connection {
    /// Parse-able SQL that defines this connection.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this connection from the storage layer.
    pub global_id: GlobalId,
    /// The kind of connection.
    pub details: ConnectionDetails,
    /// Other objects this connection depends on.
    pub resolved_ids: ResolvedIds,
}

impl Connection {
    /// The single [`GlobalId`] used to reference this connection.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ContinualTask {
    /// Parse-able SQL that defines this continual task.
    pub create_sql: String,
    /// [`GlobalId`] used to reference this continual task from outside the catalog.
    pub global_id: GlobalId,
    /// [`GlobalId`] of the collection that we read into this continual task.
    pub input_id: GlobalId,
    pub with_snapshot: bool,
    /// ContinualTasks are self-referential. We make this work by using a
    /// placeholder `LocalId` for the CT itself through name resolution and
    /// planning. Then we fill in the real `GlobalId` before constructing this
    /// catalog item.
    pub raw_expr: Arc<HirRelationExpr>,
    /// Columns for this continual task.
    pub desc: RelationDesc,
    /// Other catalog items that this continual task references, determined at name resolution.
    pub resolved_ids: ResolvedIds,
    /// All of the catalog objects that are referenced by this continual task.
    pub dependencies: DependencyIds,
    /// Cluster that this continual task runs on.
    pub cluster_id: ClusterId,
    /// See the comment on [MaterializedView::initial_as_of].
    pub initial_as_of: Option<Antichain<mz_repr::Timestamp>>,
}

impl ContinualTask {
    /// The single [`GlobalId`] used to reference this continual task.
    pub fn global_id(&self) -> GlobalId {
        self.global_id
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct NetworkPolicy {
    pub name: String,
    pub id: NetworkPolicyId,
    pub oid: u32,
    pub rules: Vec<NetworkPolicyRule>,
    pub owner_id: RoleId,
    pub privileges: PrivilegeMap,
}

impl From<NetworkPolicy> for durable::NetworkPolicy {
    fn from(policy: NetworkPolicy) -> durable::NetworkPolicy {
        durable::NetworkPolicy {
            id: policy.id,
            oid: policy.oid,
            name: policy.name,
            rules: policy.rules,
            owner_id: policy.owner_id,
            privileges: policy.privileges.into_all_values().collect(),
        }
    }
}

impl From<durable::NetworkPolicy> for NetworkPolicy {
    fn from(
        durable::NetworkPolicy {
            id,
            oid,
            name,
            rules,
            owner_id,
            privileges,
        }: durable::NetworkPolicy,
    ) -> Self {
        NetworkPolicy {
            id,
            oid,
            name,
            rules,
            owner_id,
            privileges: PrivilegeMap::from_mz_acl_items(privileges),
        }
    }
}

impl UpdateFrom<durable::NetworkPolicy> for NetworkPolicy {
    fn update_from(
        &mut self,
        durable::NetworkPolicy {
            id,
            oid,
            name,
            rules,
            owner_id,
            privileges,
        }: durable::NetworkPolicy,
    ) {
        self.id = id;
        self.oid = oid;
        self.name = name;
        self.rules = rules;
        self.owner_id = owner_id;
        self.privileges = PrivilegeMap::from_mz_acl_items(privileges);
    }
}

impl CatalogItem {
    /// Returns a string indicating the type of this catalog entry.
    pub fn typ(&self) -> mz_sql::catalog::CatalogItemType {
        match self {
            CatalogItem::Table(_) => mz_sql::catalog::CatalogItemType::Table,
            CatalogItem::Source(_) => mz_sql::catalog::CatalogItemType::Source,
            CatalogItem::Log(_) => mz_sql::catalog::CatalogItemType::Source,
            CatalogItem::Sink(_) => mz_sql::catalog::CatalogItemType::Sink,
            CatalogItem::View(_) => mz_sql::catalog::CatalogItemType::View,
            CatalogItem::MaterializedView(_) => mz_sql::catalog::CatalogItemType::MaterializedView,
            CatalogItem::Index(_) => mz_sql::catalog::CatalogItemType::Index,
            CatalogItem::Type(_) => mz_sql::catalog::CatalogItemType::Type,
            CatalogItem::Func(_) => mz_sql::catalog::CatalogItemType::Func,
            CatalogItem::Secret(_) => mz_sql::catalog::CatalogItemType::Secret,
            CatalogItem::Connection(_) => mz_sql::catalog::CatalogItemType::Connection,
            CatalogItem::ContinualTask(_) => mz_sql::catalog::CatalogItemType::ContinualTask,
        }
    }

    /// Returns the [`GlobalId`]s that reference this item, if any.
    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
        let gid = match self {
            CatalogItem::Source(source) => source.global_id,
            CatalogItem::Log(log) => log.global_id,
            CatalogItem::Sink(sink) => sink.global_id,
            CatalogItem::View(view) => view.global_id,
            CatalogItem::MaterializedView(mv) => mv.global_id,
            CatalogItem::ContinualTask(ct) => ct.global_id,
            CatalogItem::Index(index) => index.global_id,
            CatalogItem::Func(func) => func.global_id,
            CatalogItem::Type(ty) => ty.global_id,
            CatalogItem::Secret(secret) => secret.global_id,
            CatalogItem::Connection(conn) => conn.global_id,
            CatalogItem::Table(table) => {
                return itertools::Either::Left(table.collections.values().copied());
            }
        };
        itertools::Either::Right(std::iter::once(gid))
    }

    /// Returns the most up-to-date [`GlobalId`] for this item.
    ///
    /// Note: The only type of object that can have multiple [`GlobalId`]s are tables.
    pub fn latest_global_id(&self) -> GlobalId {
        match self {
            CatalogItem::Source(source) => source.global_id,
            CatalogItem::Log(log) => log.global_id,
            CatalogItem::Sink(sink) => sink.global_id,
            CatalogItem::View(view) => view.global_id,
            CatalogItem::MaterializedView(mv) => mv.global_id,
            CatalogItem::ContinualTask(ct) => ct.global_id,
            CatalogItem::Index(index) => index.global_id,
            CatalogItem::Func(func) => func.global_id,
            CatalogItem::Type(ty) => ty.global_id,
            CatalogItem::Secret(secret) => secret.global_id,
            CatalogItem::Connection(conn) => conn.global_id,
            CatalogItem::Table(table) => table.global_id_writes(),
        }
    }

    /// Whether this item represents a storage collection.
    pub fn is_storage_collection(&self) -> bool {
        match self {
            CatalogItem::Table(_)
            | CatalogItem::Source(_)
            | CatalogItem::MaterializedView(_)
            | CatalogItem::ContinualTask(_) => true,
            CatalogItem::Log(_)
            | CatalogItem::Sink(_)
            | CatalogItem::View(_)
            | CatalogItem::Index(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => false,
        }
    }

    pub fn desc(&self, name: &FullItemName) -> Result<Cow<RelationDesc>, SqlCatalogError> {
        self.desc_opt().ok_or(SqlCatalogError::InvalidDependency {
            name: name.to_string(),
            typ: self.typ(),
        })
    }

    pub fn desc_opt(&self) -> Option<Cow<RelationDesc>> {
        match &self {
            CatalogItem::Source(src) => Some(Cow::Borrowed(&src.desc)),
            CatalogItem::Log(log) => Some(Cow::Owned(log.variant.desc())),
            CatalogItem::Table(tbl) => Some(Cow::Borrowed(&tbl.desc)),
            CatalogItem::View(view) => Some(Cow::Borrowed(&view.desc)),
            CatalogItem::MaterializedView(mview) => Some(Cow::Borrowed(&mview.desc)),
            CatalogItem::Type(typ) => typ.desc.as_ref().map(Cow::Borrowed),
            CatalogItem::ContinualTask(ct) => Some(Cow::Borrowed(&ct.desc)),
            CatalogItem::Func(_)
            | CatalogItem::Index(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => None,
        }
    }

    pub fn func(
        &self,
        entry: &CatalogEntry,
    ) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
        match &self {
            CatalogItem::Func(func) => Ok(func.inner),
            _ => Err(SqlCatalogError::UnexpectedType {
                name: entry.name().item.to_string(),
                actual_type: entry.item_type(),
                expected_type: CatalogItemType::Func,
            }),
        }
    }

    pub fn source_desc(
        &self,
        entry: &CatalogEntry,
    ) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
        match &self {
            CatalogItem::Source(source) => match &source.data_source {
                DataSourceDesc::Ingestion { ingestion_desc, .. } => Ok(Some(&ingestion_desc.desc)),
                DataSourceDesc::IngestionExport { .. }
                | DataSourceDesc::Introspection(_)
                | DataSourceDesc::Webhook { .. }
                | DataSourceDesc::Progress => Ok(None),
            },
            _ => Err(SqlCatalogError::UnexpectedType {
                name: entry.name().item.to_string(),
                actual_type: entry.item_type(),
                expected_type: CatalogItemType::Source,
            }),
        }
    }

    /// Reports whether this catalog entry is a progress source.
    pub fn is_progress_source(&self) -> bool {
        matches!(
            self,
            CatalogItem::Source(Source {
                data_source: DataSourceDesc::Progress,
                ..
            })
        )
    }

    /// Collects the identifiers of the objects that were encountered when resolving names in the
    /// item's DDL statement.
    pub fn references(&self) -> &ResolvedIds {
        static EMPTY: LazyLock<ResolvedIds> = LazyLock::new(ResolvedIds::empty);
        match self {
            CatalogItem::Func(_) => &*EMPTY,
            CatalogItem::Index(idx) => &idx.resolved_ids,
            CatalogItem::Sink(sink) => &sink.resolved_ids,
            CatalogItem::Source(source) => &source.resolved_ids,
            CatalogItem::Log(_) => &*EMPTY,
            CatalogItem::Table(table) => &table.resolved_ids,
            CatalogItem::Type(typ) => &typ.resolved_ids,
            CatalogItem::View(view) => &view.resolved_ids,
            CatalogItem::MaterializedView(mview) => &mview.resolved_ids,
            CatalogItem::Secret(_) => &*EMPTY,
            CatalogItem::Connection(connection) => &connection.resolved_ids,
            CatalogItem::ContinualTask(ct) => &ct.resolved_ids,
        }
    }

    /// Collects the identifiers of the objects used by this [`CatalogItem`].
    ///
    /// Like [`CatalogItem::references()`] but also includes objects that are not directly
    /// referenced. For example this will include any catalog objects used to implement functions
    /// and casts in the item.
    pub fn uses(&self) -> BTreeSet<CatalogItemId> {
        let mut uses: BTreeSet<_> = self.references().items().copied().collect();
        match self {
            // TODO(jkosh44) This isn't really correct for functions. They may use other objects in
            // their implementation. However, currently there's no way to get that information.
            CatalogItem::Func(_) => {}
            CatalogItem::Index(_) => {}
            CatalogItem::Sink(_) => {}
            CatalogItem::Source(_) => {}
            CatalogItem::Log(_) => {}
            CatalogItem::Table(_) => {}
            CatalogItem::Type(_) => {}
            CatalogItem::View(view) => uses.extend(view.dependencies.0.iter().copied()),
            CatalogItem::MaterializedView(mview) => {
                uses.extend(mview.dependencies.0.iter().copied())
            }
            CatalogItem::ContinualTask(ct) => uses.extend(ct.dependencies.0.iter().copied()),
            CatalogItem::Secret(_) => {}
            CatalogItem::Connection(_) => {}
        }
        uses
    }

    /// Returns the connection ID that this item belongs to, if this item is
    /// temporary.
    pub fn conn_id(&self) -> Option<&ConnectionId> {
        match self {
            CatalogItem::View(view) => view.conn_id.as_ref(),
            CatalogItem::Index(index) => index.conn_id.as_ref(),
            CatalogItem::Table(table) => table.conn_id.as_ref(),
            CatalogItem::Log(_)
            | CatalogItem::Source(_)
            | CatalogItem::Sink(_)
            | CatalogItem::MaterializedView(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Connection(_)
            | CatalogItem::ContinualTask(_) => None,
        }
    }

    /// Indicates whether this item is temporary or not.
    pub fn is_temporary(&self) -> bool {
        self.conn_id().is_some()
    }

    pub fn rename_schema_refs(
        &self,
        database_name: &str,
        cur_schema_name: &str,
        new_schema_name: &str,
    ) -> Result<CatalogItem, (String, String)> {
        let do_rewrite = |create_sql: String| -> Result<String, (String, String)> {
            let mut create_stmt = mz_sql::parse::parse(&create_sql)
                .expect("invalid create sql persisted to catalog")
                .into_element()
                .ast;

            // Rename all references to cur_schema_name.
            mz_sql::ast::transform::create_stmt_rename_schema_refs(
                &mut create_stmt,
                database_name,
                cur_schema_name,
                new_schema_name,
            )?;

            Ok(create_stmt.to_ast_string_stable())
        };

        match self {
            CatalogItem::Table(i) => {
                let mut i = i.clone();
                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
                Ok(CatalogItem::Table(i))
            }
            CatalogItem::Log(i) => Ok(CatalogItem::Log(i.clone())),
            CatalogItem::Source(i) => {
                let mut i = i.clone();
                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
                Ok(CatalogItem::Source(i))
            }
            CatalogItem::Sink(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Sink(i))
            }
            CatalogItem::View(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::View(i))
            }
            CatalogItem::MaterializedView(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::MaterializedView(i))
            }
            CatalogItem::Index(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Index(i))
            }
            CatalogItem::Secret(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Secret(i))
            }
            CatalogItem::Connection(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Connection(i))
            }
            CatalogItem::Type(i) => {
                let mut i = i.clone();
                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
                Ok(CatalogItem::Type(i))
            }
            CatalogItem::Func(i) => Ok(CatalogItem::Func(i.clone())),
            CatalogItem::ContinualTask(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::ContinualTask(i))
            }
        }
    }

    /// Returns a clone of `self` with all instances of `from` renamed to `to`
    /// (with the option of including the item's own name) or errors if request
    /// is ambiguous.
    pub fn rename_item_refs(
        &self,
        from: FullItemName,
        to_item_name: String,
        rename_self: bool,
    ) -> Result<CatalogItem, String> {
        let do_rewrite = |create_sql: String| -> Result<String, String> {
            let mut create_stmt = mz_sql::parse::parse(&create_sql)
                .expect("invalid create sql persisted to catalog")
                .into_element()
                .ast;
            if rename_self {
                mz_sql::ast::transform::create_stmt_rename(&mut create_stmt, to_item_name.clone());
            }
            // Determination of what constitutes an ambiguous request is done here.
            mz_sql::ast::transform::create_stmt_rename_refs(&mut create_stmt, from, to_item_name)?;
            Ok(create_stmt.to_ast_string_stable())
        };

        match self {
            CatalogItem::Table(i) => {
                let mut i = i.clone();
                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
                Ok(CatalogItem::Table(i))
            }
            CatalogItem::Log(i) => Ok(CatalogItem::Log(i.clone())),
            CatalogItem::Source(i) => {
                let mut i = i.clone();
                i.create_sql = i.create_sql.map(do_rewrite).transpose()?;
                Ok(CatalogItem::Source(i))
            }
            CatalogItem::Sink(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Sink(i))
            }
            CatalogItem::View(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::View(i))
            }
            CatalogItem::MaterializedView(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::MaterializedView(i))
            }
            CatalogItem::Index(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Index(i))
            }
            CatalogItem::Secret(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Secret(i))
            }
            CatalogItem::Func(_) | CatalogItem::Type(_) => {
                unreachable!("{}s cannot be renamed", self.typ())
            }
            CatalogItem::Connection(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Connection(i))
            }
            CatalogItem::ContinualTask(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::ContinualTask(i))
            }
        }
    }

    /// Updates the retain history for an item. Returns the previous retain history value. Returns
    /// an error if this item does not support retain history.
    pub fn update_retain_history(
        &mut self,
        value: Option<Value>,
        window: CompactionWindow,
    ) -> Result<Option<WithOptionValue<Raw>>, ()> {
        let update = |ast: &mut Statement<Raw>| {
            // Each statement type has unique option types. This macro handles them commonly.
            macro_rules! update_retain_history {
                ( $stmt:ident, $opt:ident, $name:ident ) => {{
                    // Replace or add the option.
                    let pos = $stmt
                        .with_options
                        .iter()
                        // In case there are ever multiple, look for the last one.
                        .rposition(|o| o.name == mz_sql_parser::ast::$name::RetainHistory);
                    if let Some(value) = value {
                        let next = mz_sql_parser::ast::$opt {
                            name: mz_sql_parser::ast::$name::RetainHistory,
                            value: Some(WithOptionValue::RetainHistoryFor(value)),
                        };
                        if let Some(idx) = pos {
                            let previous = $stmt.with_options[idx].clone();
                            $stmt.with_options[idx] = next;
                            previous.value
                        } else {
                            $stmt.with_options.push(next);
                            None
                        }
                    } else {
                        if let Some(idx) = pos {
                            $stmt.with_options.swap_remove(idx).value
                        } else {
                            None
                        }
                    }
                }};
            }
            let previous = match ast {
                Statement::CreateTable(ref mut stmt) => {
                    update_retain_history!(stmt, TableOption, TableOptionName)
                }
                Statement::CreateIndex(ref mut stmt) => {
                    update_retain_history!(stmt, IndexOption, IndexOptionName)
                }
                Statement::CreateSource(ref mut stmt) => {
                    update_retain_history!(stmt, CreateSourceOption, CreateSourceOptionName)
                }
                Statement::CreateMaterializedView(ref mut stmt) => {
                    update_retain_history!(stmt, MaterializedViewOption, MaterializedViewOptionName)
                }
                _ => {
                    return Err(());
                }
            };
            Ok(previous)
        };

        let res = self.update_sql(update)?;
        let cw = self
            .custom_logical_compaction_window_mut()
            .expect("item must have compaction window");
        *cw = Some(window);
        Ok(res)
    }

    /// Updates the create_sql field of this item. Returns an error if this is a builtin item,
    /// otherwise returns f's result.
    pub fn update_sql<F, T>(&mut self, f: F) -> Result<T, ()>
    where
        F: FnOnce(&mut Statement<Raw>) -> Result<T, ()>,
    {
        let create_sql = match self {
            CatalogItem::Table(Table { create_sql, .. })
            | CatalogItem::Type(Type { create_sql, .. })
            | CatalogItem::Source(Source { create_sql, .. }) => create_sql.as_mut(),
            CatalogItem::Sink(Sink { create_sql, .. })
            | CatalogItem::View(View { create_sql, .. })
            | CatalogItem::MaterializedView(MaterializedView { create_sql, .. })
            | CatalogItem::Index(Index { create_sql, .. })
            | CatalogItem::Secret(Secret { create_sql, .. })
            | CatalogItem::Connection(Connection { create_sql, .. })
            | CatalogItem::ContinualTask(ContinualTask { create_sql, .. }) => Some(create_sql),
            CatalogItem::Func(_) | CatalogItem::Log(_) => None,
        };
        let Some(create_sql) = create_sql else {
            return Err(());
        };
        let mut ast = mz_sql_parser::parser::parse_statements(create_sql)
            .expect("non-system items must be parseable")
            .into_element()
            .ast;
        debug!("rewrite: {}", ast.to_ast_string_redacted());
        let t = f(&mut ast)?;
        *create_sql = ast.to_ast_string_stable();
        debug!("rewrote: {}", ast.to_ast_string_redacted());
        Ok(t)
    }

    /// If the object is considered a "compute object"
    /// (i.e., it is managed by the compute controller),
    /// this function returns its cluster ID. Otherwise, it returns nothing.
    ///
    /// This function differs from `cluster_id` because while all
    /// compute objects run on a cluster, the converse is not true.
    pub fn is_compute_object_on_cluster(&self) -> Option<ClusterId> {
        match self {
            CatalogItem::Index(index) => Some(index.cluster_id),
            CatalogItem::Table(_)
            | CatalogItem::Source(_)
            | CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::MaterializedView(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_)
            | CatalogItem::ContinualTask(_) => None,
        }
    }

    pub fn cluster_id(&self) -> Option<ClusterId> {
        match self {
            CatalogItem::MaterializedView(mv) => Some(mv.cluster_id),
            CatalogItem::Index(index) => Some(index.cluster_id),
            CatalogItem::Source(source) => match &source.data_source {
                DataSourceDesc::Ingestion { cluster_id, .. } => Some(*cluster_id),
                // This is somewhat of a lie because the export runs on the same
                // cluster as its ingestion but we don't yet have a way of
                // cross-referencing the items
                DataSourceDesc::IngestionExport { .. } => None,
                DataSourceDesc::Webhook { cluster_id, .. } => Some(*cluster_id),
                DataSourceDesc::Introspection(_) | DataSourceDesc::Progress => None,
            },
            CatalogItem::Sink(sink) => Some(sink.cluster_id),
            CatalogItem::ContinualTask(ct) => Some(ct.cluster_id),
            CatalogItem::Table(_)
            | CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => None,
        }
    }

    /// The custom compaction window, if any has been set. This does not reflect any propagated
    /// compaction window (i.e., source -> subsource).
    pub fn custom_logical_compaction_window(&self) -> Option<CompactionWindow> {
        match self {
            CatalogItem::Table(table) => table.custom_logical_compaction_window,
            CatalogItem::Source(source) => source.custom_logical_compaction_window,
            CatalogItem::Index(index) => index.custom_logical_compaction_window,
            CatalogItem::MaterializedView(mview) => mview.custom_logical_compaction_window,
            CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_)
            | CatalogItem::ContinualTask(_) => None,
        }
    }

    /// Mutable access to the custom compaction window, or None if this type does not support custom
    /// compaction windows. This does not reflect any propagated compaction window (i.e., source ->
    /// subsource).
    pub fn custom_logical_compaction_window_mut(
        &mut self,
    ) -> Option<&mut Option<CompactionWindow>> {
        let cw = match self {
            CatalogItem::Table(table) => &mut table.custom_logical_compaction_window,
            CatalogItem::Source(source) => &mut source.custom_logical_compaction_window,
            CatalogItem::Index(index) => &mut index.custom_logical_compaction_window,
            CatalogItem::MaterializedView(mview) => &mut mview.custom_logical_compaction_window,
            CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_)
            | CatalogItem::ContinualTask(_) => return None,
        };
        Some(cw)
    }

    /// The initial compaction window, for objects that have one; that is, tables, sources, indexes,
    /// and MVs. This does not reflect any propagated compaction window (i.e., source -> subsource).
    ///
    /// If `custom_logical_compaction_window()` returns something, use that.  Otherwise, use a
    /// sensible default (currently 1s).
    ///
    /// For objects that do not have the concept of compaction window, return None.
    pub fn initial_logical_compaction_window(&self) -> Option<CompactionWindow> {
        let custom_logical_compaction_window = match self {
            CatalogItem::Table(_)
            | CatalogItem::Source(_)
            | CatalogItem::Index(_)
            | CatalogItem::MaterializedView(_)
            | CatalogItem::ContinualTask(_) => self.custom_logical_compaction_window(),
            CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => return None,
        };
        Some(custom_logical_compaction_window.unwrap_or(CompactionWindow::Default))
    }

    /// Whether the item's logical compaction window
    /// is controlled by the METRICS_RETENTION
    /// system var.
    pub fn is_retained_metrics_object(&self) -> bool {
        match self {
            CatalogItem::Table(table) => table.is_retained_metrics_object,
            CatalogItem::Source(source) => source.is_retained_metrics_object,
            CatalogItem::Index(index) => index.is_retained_metrics_object,
            CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::MaterializedView(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_)
            | CatalogItem::ContinualTask(_) => false,
        }
    }

    pub fn to_serialized(&self) -> (String, GlobalId, BTreeMap<RelationVersion, GlobalId>) {
        match self {
            CatalogItem::Table(table) => {
                let create_sql = table
                    .create_sql
                    .clone()
                    .expect("builtin tables cannot be serialized");
                let mut collections = table.collections.clone();
                let global_id = collections
                    .remove(&RelationVersion::root())
                    .expect("at least one version");
                (create_sql, global_id, collections)
            }
            CatalogItem::Log(_) => unreachable!("builtin logs cannot be serialized"),
            CatalogItem::Source(source) => {
                assert!(
                    !matches!(source.data_source, DataSourceDesc::Introspection(_)),
                    "cannot serialize introspection/builtin sources",
                );
                let create_sql = source
                    .create_sql
                    .clone()
                    .expect("builtin sources cannot be serialized");
                (create_sql, source.global_id, BTreeMap::new())
            }
            CatalogItem::View(view) => (view.create_sql.clone(), view.global_id, BTreeMap::new()),
            CatalogItem::MaterializedView(mview) => {
                (mview.create_sql.clone(), mview.global_id, BTreeMap::new())
            }
            CatalogItem::Index(index) => {
                (index.create_sql.clone(), index.global_id, BTreeMap::new())
            }
            CatalogItem::Sink(sink) => (sink.create_sql.clone(), sink.global_id, BTreeMap::new()),
            CatalogItem::Type(typ) => {
                let create_sql = typ
                    .create_sql
                    .clone()
                    .expect("builtin types cannot be serialized");
                (create_sql, typ.global_id, BTreeMap::new())
            }
            CatalogItem::Secret(secret) => {
                (secret.create_sql.clone(), secret.global_id, BTreeMap::new())
            }
            CatalogItem::Connection(connection) => (
                connection.create_sql.clone(),
                connection.global_id,
                BTreeMap::new(),
            ),
            CatalogItem::Func(_) => unreachable!("cannot serialize functions yet"),
            CatalogItem::ContinualTask(ct) => {
                (ct.create_sql.clone(), ct.global_id, BTreeMap::new())
            }
        }
    }

    pub fn into_serialized(self) -> (String, GlobalId, BTreeMap<RelationVersion, GlobalId>) {
        match self {
            CatalogItem::Table(mut table) => {
                let create_sql = table
                    .create_sql
                    .expect("builtin tables cannot be serialized");
                let global_id = table
                    .collections
                    .remove(&RelationVersion::root())
                    .expect("at least one version");
                (create_sql, global_id, table.collections)
            }
            CatalogItem::Log(_) => unreachable!("builtin logs cannot be serialized"),
            CatalogItem::Source(source) => {
                assert!(
                    !matches!(source.data_source, DataSourceDesc::Introspection(_)),
                    "cannot serialize introspection/builtin sources",
                );
                let create_sql = source
                    .create_sql
                    .expect("builtin sources cannot be serialized");
                (create_sql, source.global_id, BTreeMap::new())
            }
            CatalogItem::View(view) => (view.create_sql, view.global_id, BTreeMap::new()),
            CatalogItem::MaterializedView(mview) => {
                (mview.create_sql, mview.global_id, BTreeMap::new())
            }
            CatalogItem::Index(index) => (index.create_sql, index.global_id, BTreeMap::new()),
            CatalogItem::Sink(sink) => (sink.create_sql, sink.global_id, BTreeMap::new()),
            CatalogItem::Type(typ) => {
                let create_sql = typ.create_sql.expect("builtin types cannot be serialized");
                (create_sql, typ.global_id, BTreeMap::new())
            }
            CatalogItem::Secret(secret) => (secret.create_sql, secret.global_id, BTreeMap::new()),
            CatalogItem::Connection(connection) => {
                (connection.create_sql, connection.global_id, BTreeMap::new())
            }
            CatalogItem::Func(_) => unreachable!("cannot serialize functions yet"),
            CatalogItem::ContinualTask(ct) => (ct.create_sql, ct.global_id, BTreeMap::new()),
        }
    }
}

impl CatalogEntry {
    /// Like [`CatalogEntry::desc_opt`], but returns an error if the catalog
    /// entry is not of a type that has a description.
    pub fn desc(&self, name: &FullItemName) -> Result<Cow<RelationDesc>, SqlCatalogError> {
        self.item.desc(name)
    }

    /// Reports the description of the rows produced by this catalog entry, if
    /// this catalog entry produces rows.
    pub fn desc_opt(&self) -> Option<Cow<RelationDesc>> {
        self.item.desc_opt()
    }

    /// Reports if the item has columns.
    pub fn has_columns(&self) -> bool {
        self.item.desc_opt().is_some()
    }

    /// Returns the [`mz_sql::func::Func`] associated with this `CatalogEntry`.
    pub fn func(&self) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
        self.item.func(self)
    }

    /// Returns the inner [`Index`] if this entry is an index, else `None`.
    pub fn index(&self) -> Option<&Index> {
        match self.item() {
            CatalogItem::Index(idx) => Some(idx),
            _ => None,
        }
    }

    /// Returns the inner [`MaterializedView`] if this entry is a materialized view, else `None`.
    pub fn materialized_view(&self) -> Option<&MaterializedView> {
        match self.item() {
            CatalogItem::MaterializedView(mv) => Some(mv),
            _ => None,
        }
    }

    /// Returns the inner [`Table`] if this entry is a table, else `None`.
    pub fn table(&self) -> Option<&Table> {
        match self.item() {
            CatalogItem::Table(tbl) => Some(tbl),
            _ => None,
        }
    }

    /// Returns the inner [`Source`] if this entry is a source, else `None`.
    pub fn source(&self) -> Option<&Source> {
        match self.item() {
            CatalogItem::Source(src) => Some(src),
            _ => None,
        }
    }

    /// Returns the inner [`Sink`] if this entry is a sink, else `None`.
    pub fn sink(&self) -> Option<&Sink> {
        match self.item() {
            CatalogItem::Sink(sink) => Some(sink),
            _ => None,
        }
    }

    /// Returns the inner [`Secret`] if this entry is a secret, else `None`.
    pub fn secret(&self) -> Option<&Secret> {
        match self.item() {
            CatalogItem::Secret(secret) => Some(secret),
            _ => None,
        }
    }

    pub fn connection(&self) -> Result<&Connection, SqlCatalogError> {
        match self.item() {
            CatalogItem::Connection(connection) => Ok(connection),
            _ => {
                let db_name = match self.name().qualifiers.database_spec {
                    ResolvedDatabaseSpecifier::Ambient => "".to_string(),
                    ResolvedDatabaseSpecifier::Id(id) => format!("{id}."),
                };
                Err(SqlCatalogError::UnknownConnection(format!(
                    "{}{}.{}",
                    db_name,
                    self.name().qualifiers.schema_spec,
                    self.name().item
                )))
            }
        }
    }

    /// Returns the [`mz_storage_types::sources::SourceDesc`] associated with
    /// this `CatalogEntry`, if any.
    pub fn source_desc(
        &self,
    ) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
        self.item.source_desc(self)
    }

    /// Reports whether this catalog entry is a connection.
    pub fn is_connection(&self) -> bool {
        matches!(self.item(), CatalogItem::Connection(_))
    }

    /// Reports whether this catalog entry is a table.
    pub fn is_table(&self) -> bool {
        matches!(self.item(), CatalogItem::Table(_))
    }

    /// Reports whether this catalog entry is a source. Note that this includes
    /// subsources.
    pub fn is_source(&self) -> bool {
        matches!(self.item(), CatalogItem::Source(_))
    }

    /// Reports whether this catalog entry is a subsource and, if it is, the
    /// ingestion it is an export of, as well as the item it exports.
    pub fn subsource_details(
        &self,
    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)> {
        match &self.item() {
            CatalogItem::Source(source) => match &source.data_source {
                DataSourceDesc::IngestionExport {
                    ingestion_id,
                    external_reference,
                    details,
                    data_config: _,
                } => Some((*ingestion_id, external_reference, details)),
                _ => None,
            },
            _ => None,
        }
    }

    /// Reports whether this catalog entry is a source export and, if it is, the
    /// ingestion it is an export of, as well as the item it exports.
    pub fn source_export_details(
        &self,
    ) -> Option<(
        CatalogItemId,
        &UnresolvedItemName,
        &SourceExportDetails,
        &SourceExportDataConfig<ReferencedConnection>,
    )> {
        match &self.item() {
            CatalogItem::Source(source) => match &source.data_source {
                DataSourceDesc::IngestionExport {
                    ingestion_id,
                    external_reference,
                    details,
                    data_config,
                } => Some((*ingestion_id, external_reference, details, data_config)),
                _ => None,
            },
            CatalogItem::Table(table) => match &table.data_source {
                TableDataSource::DataSource {
                    desc:
                        DataSourceDesc::IngestionExport {
                            ingestion_id,
                            external_reference,
                            details,
                            data_config,
                        },
                    timeline: _,
                } => Some((*ingestion_id, external_reference, details, data_config)),
                _ => None,
            },
            _ => None,
        }
    }

    /// Reports whether this catalog entry is a progress source.
    pub fn is_progress_source(&self) -> bool {
        self.item().is_progress_source()
    }

    /// Returns the `GlobalId` of all of this entry's progress ID.
    pub fn progress_id(&self) -> Option<CatalogItemId> {
        match &self.item() {
            CatalogItem::Source(source) => match &source.data_source {
                DataSourceDesc::Ingestion { ingestion_desc, .. } => {
                    Some(ingestion_desc.progress_subsource)
                }
                DataSourceDesc::IngestionExport { .. }
                | DataSourceDesc::Introspection(_)
                | DataSourceDesc::Progress
                | DataSourceDesc::Webhook { .. } => None,
            },
            CatalogItem::Table(_)
            | CatalogItem::Log(_)
            | CatalogItem::View(_)
            | CatalogItem::MaterializedView(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Index(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_)
            | CatalogItem::ContinualTask(_) => None,
        }
    }

    /// Reports whether this catalog entry is a sink.
    pub fn is_sink(&self) -> bool {
        matches!(self.item(), CatalogItem::Sink(_))
    }

    /// Reports whether this catalog entry is a materialized view.
    pub fn is_materialized_view(&self) -> bool {
        matches!(self.item(), CatalogItem::MaterializedView(_))
    }

    /// Reports whether this catalog entry is a view.
    pub fn is_view(&self) -> bool {
        matches!(self.item(), CatalogItem::View(_))
    }

    /// Reports whether this catalog entry is a secret.
    pub fn is_secret(&self) -> bool {
        matches!(self.item(), CatalogItem::Secret(_))
    }

    /// Reports whether this catalog entry is an introspection source.
    pub fn is_introspection_source(&self) -> bool {
        matches!(self.item(), CatalogItem::Log(_))
    }

    /// Reports whether this catalog entry is an index.
    pub fn is_index(&self) -> bool {
        matches!(self.item(), CatalogItem::Index(_))
    }

    /// Reports whether this catalog entry is a continual task.
    pub fn is_continual_task(&self) -> bool {
        matches!(self.item(), CatalogItem::ContinualTask(_))
    }

    /// Reports whether this catalog entry can be treated as a relation, it can produce rows.
    pub fn is_relation(&self) -> bool {
        mz_sql::catalog::ObjectType::from(self.item_type()).is_relation()
    }

    /// Collects the identifiers of the objects that were encountered when
    /// resolving names in the item's DDL statement.
    pub fn references(&self) -> &ResolvedIds {
        self.item.references()
    }

    /// Collects the identifiers of the objects used by this [`CatalogEntry`].
    ///
    /// Like [`CatalogEntry::references()`] but also includes objects that are not directly
    /// referenced. For example this will include any catalog objects used to implement functions
    /// and casts in the item.
    pub fn uses(&self) -> BTreeSet<CatalogItemId> {
        self.item.uses()
    }

    /// Returns the `CatalogItem` associated with this catalog entry.
    pub fn item(&self) -> &CatalogItem {
        &self.item
    }

    /// Returns the [`CatalogItemId`] of this catalog entry.
    pub fn id(&self) -> CatalogItemId {
        self.id
    }

    /// Returns all of the [`GlobalId`]s associated with this item.
    pub fn global_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
        self.item().global_ids()
    }

    pub fn latest_global_id(&self) -> GlobalId {
        self.item().latest_global_id()
    }

    /// Returns the OID of this catalog entry.
    pub fn oid(&self) -> u32 {
        self.oid
    }

    /// Returns the fully qualified name of this catalog entry.
    pub fn name(&self) -> &QualifiedItemName {
        &self.name
    }

    /// Returns the identifiers of the dataflows that are directly referenced by this dataflow.
    pub fn referenced_by(&self) -> &[CatalogItemId] {
        &self.referenced_by
    }

    /// Returns the identifiers of the dataflows that depend upon this dataflow.
    pub fn used_by(&self) -> &[CatalogItemId] {
        &self.used_by
    }

    /// Returns the connection ID that this item belongs to, if this item is
    /// temporary.
    pub fn conn_id(&self) -> Option<&ConnectionId> {
        self.item.conn_id()
    }

    /// Returns the role ID of the entry owner.
    pub fn owner_id(&self) -> &RoleId {
        &self.owner_id
    }

    /// Returns the privileges of the entry.
    pub fn privileges(&self) -> &PrivilegeMap {
        &self.privileges
    }
}

#[derive(Debug, Clone, Default)]
pub struct CommentsMap {
    map: BTreeMap<CommentObjectId, BTreeMap<Option<usize>, String>>,
}

impl CommentsMap {
    pub fn update_comment(
        &mut self,
        object_id: CommentObjectId,
        sub_component: Option<usize>,
        comment: Option<String>,
    ) -> Option<String> {
        let object_comments = self.map.entry(object_id).or_default();

        // Either replace the existing comment, or remove it if comment is None/NULL.
        let (empty, prev) = if let Some(comment) = comment {
            let prev = object_comments.insert(sub_component, comment);
            (false, prev)
        } else {
            let prev = object_comments.remove(&sub_component);
            (object_comments.is_empty(), prev)
        };

        // Cleanup entries that are now empty.
        if empty {
            self.map.remove(&object_id);
        }

        // Return the previous comment, if there was one, for easy removal.
        prev
    }

    /// Remove all comments for `object_id` from the map.
    ///
    /// Generally there is one comment for a given [`CommentObjectId`], but in the case of
    /// relations you can also have comments on the individual columns. Dropping the comments for a
    /// relation will also drop all of the comments on any columns.
    pub fn drop_comments(
        &mut self,
        object_ids: &BTreeSet<CommentObjectId>,
    ) -> Vec<(CommentObjectId, Option<usize>, String)> {
        let mut removed_comments = Vec::new();

        for object_id in object_ids {
            if let Some(comments) = self.map.remove(object_id) {
                let removed = comments
                    .into_iter()
                    .map(|(sub_comp, comment)| (object_id.clone(), sub_comp, comment));
                removed_comments.extend(removed);
            }
        }

        removed_comments
    }

    pub fn iter(&self) -> impl Iterator<Item = (CommentObjectId, Option<usize>, &str)> {
        self.map
            .iter()
            .map(|(id, comments)| {
                comments
                    .iter()
                    .map(|(pos, comment)| (*id, *pos, comment.as_str()))
            })
            .flatten()
    }

    pub fn get_object_comments(
        &self,
        object_id: CommentObjectId,
    ) -> Option<&BTreeMap<Option<usize>, String>> {
        self.map.get(&object_id)
    }
}

impl Serialize for CommentsMap {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let comment_count = self
            .map
            .iter()
            .map(|(_object_id, comments)| comments.len())
            .sum();

        let mut seq = serializer.serialize_seq(Some(comment_count))?;
        for (object_id, sub) in &self.map {
            for (sub_component, comment) in sub {
                seq.serialize_element(&(
                    format!("{object_id:?}"),
                    format!("{sub_component:?}"),
                    comment,
                ))?;
            }
        }
        seq.end()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Default)]
pub struct DefaultPrivileges {
    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
    privileges: BTreeMap<DefaultPrivilegeObject, RoleDefaultPrivileges>,
}

// Use a new type here because otherwise we have two levels of BTreeMap, both needing
// map_key_to_string.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Default)]
struct RoleDefaultPrivileges(
    /// Denormalized, the key is the grantee Role.
    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
    BTreeMap<RoleId, DefaultPrivilegeAclItem>,
);

impl Deref for RoleDefaultPrivileges {
    type Target = BTreeMap<RoleId, DefaultPrivilegeAclItem>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for RoleDefaultPrivileges {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl DefaultPrivileges {
    /// Add a new default privilege into the set of all default privileges.
    pub fn grant(&mut self, object: DefaultPrivilegeObject, privilege: DefaultPrivilegeAclItem) {
        if privilege.acl_mode.is_empty() {
            return;
        }

        let privileges = self.privileges.entry(object).or_default();
        if let Some(default_privilege) = privileges.get_mut(&privilege.grantee) {
            default_privilege.acl_mode |= privilege.acl_mode;
        } else {
            privileges.insert(privilege.grantee, privilege);
        }
    }

    /// Revoke a default privilege from the set of all default privileges.
    pub fn revoke(&mut self, object: &DefaultPrivilegeObject, privilege: &DefaultPrivilegeAclItem) {
        if let Some(privileges) = self.privileges.get_mut(object) {
            if let Some(default_privilege) = privileges.get_mut(&privilege.grantee) {
                default_privilege.acl_mode =
                    default_privilege.acl_mode.difference(privilege.acl_mode);
                if default_privilege.acl_mode.is_empty() {
                    privileges.remove(&privilege.grantee);
                }
            }
            if privileges.is_empty() {
                self.privileges.remove(object);
            }
        }
    }

    /// Get the privileges that will be granted on all objects matching `object` to `grantee`, if
    /// any exist.
    pub fn get_privileges_for_grantee(
        &self,
        object: &DefaultPrivilegeObject,
        grantee: &RoleId,
    ) -> Option<&AclMode> {
        self.privileges
            .get(object)
            .and_then(|privileges| privileges.get(grantee))
            .map(|privilege| &privilege.acl_mode)
    }

    /// Get all default privileges that apply to the provided object details.
    pub fn get_applicable_privileges(
        &self,
        role_id: RoleId,
        database_id: Option<DatabaseId>,
        schema_id: Option<SchemaId>,
        object_type: mz_sql::catalog::ObjectType,
    ) -> impl Iterator<Item = DefaultPrivilegeAclItem> + '_ {
        // Privileges consider all relations to be of type table due to PostgreSQL compatibility. We
        // don't require the caller to worry about that and we will map their `object_type` to the
        // correct type for privileges.
        let privilege_object_type = if object_type.is_relation() {
            mz_sql::catalog::ObjectType::Table
        } else {
            object_type
        };
        let valid_acl_mode = rbac::all_object_privileges(SystemObjectType::Object(object_type));

        // Collect all entries that apply to the provided object details.
        // If either `database_id` or `schema_id` are `None`, then we might end up with duplicate
        // entries in the vec below. That's OK because we consolidate the results after.
        [
            DefaultPrivilegeObject {
                role_id,
                database_id,
                schema_id,
                object_type: privilege_object_type,
            },
            DefaultPrivilegeObject {
                role_id,
                database_id,
                schema_id: None,
                object_type: privilege_object_type,
            },
            DefaultPrivilegeObject {
                role_id,
                database_id: None,
                schema_id: None,
                object_type: privilege_object_type,
            },
            DefaultPrivilegeObject {
                role_id: RoleId::Public,
                database_id,
                schema_id,
                object_type: privilege_object_type,
            },
            DefaultPrivilegeObject {
                role_id: RoleId::Public,
                database_id,
                schema_id: None,
                object_type: privilege_object_type,
            },
            DefaultPrivilegeObject {
                role_id: RoleId::Public,
                database_id: None,
                schema_id: None,
                object_type: privilege_object_type,
            },
        ]
        .into_iter()
        .filter_map(|object| self.privileges.get(&object))
        .flat_map(|acl_map| acl_map.values())
        // Consolidate privileges with a common grantee.
        .fold(
            BTreeMap::new(),
            |mut accum, DefaultPrivilegeAclItem { grantee, acl_mode }| {
                let accum_acl_mode = accum.entry(grantee).or_insert_with(AclMode::empty);
                *accum_acl_mode |= *acl_mode;
                accum
            },
        )
        .into_iter()
        // Restrict the acl_mode to only privileges valid for the provided object type. If the
        // default privilege has an object type of Table, then it may contain privileges valid for
        // tables but not other relations. If the passed in object type is another relation, then
        // we need to remove any privilege that is not valid for the specified relation.
        .map(move |(grantee, acl_mode)| (grantee, acl_mode & valid_acl_mode))
        // Filter out empty privileges.
        .filter(|(_, acl_mode)| !acl_mode.is_empty())
        .map(|(grantee, acl_mode)| DefaultPrivilegeAclItem {
            grantee: *grantee,
            acl_mode,
        })
    }

    pub fn iter(
        &self,
    ) -> impl Iterator<
        Item = (
            &DefaultPrivilegeObject,
            impl Iterator<Item = &DefaultPrivilegeAclItem>,
        ),
    > {
        self.privileges
            .iter()
            .map(|(object, acl_map)| (object, acl_map.values()))
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
pub struct ClusterConfig {
    pub variant: ClusterVariant,
    pub workload_class: Option<String>,
}

impl ClusterConfig {
    pub fn features(&self) -> Option<&OptimizerFeatureOverrides> {
        match &self.variant {
            ClusterVariant::Managed(managed) => Some(&managed.optimizer_feature_overrides),
            ClusterVariant::Unmanaged => None,
        }
    }
}

impl From<ClusterConfig> for durable::ClusterConfig {
    fn from(config: ClusterConfig) -> Self {
        Self {
            variant: config.variant.into(),
            workload_class: config.workload_class,
        }
    }
}

impl From<durable::ClusterConfig> for ClusterConfig {
    fn from(config: durable::ClusterConfig) -> Self {
        Self {
            variant: config.variant.into(),
            workload_class: config.workload_class,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
pub struct ClusterVariantManaged {
    pub size: String,
    pub availability_zones: Vec<String>,
    pub logging: ReplicaLogging,
    pub replication_factor: u32,
    pub disk: bool,
    pub optimizer_feature_overrides: OptimizerFeatureOverrides,
    pub schedule: ClusterSchedule,
}

impl From<ClusterVariantManaged> for durable::ClusterVariantManaged {
    fn from(managed: ClusterVariantManaged) -> Self {
        Self {
            size: managed.size,
            availability_zones: managed.availability_zones,
            logging: managed.logging,
            replication_factor: managed.replication_factor,
            disk: managed.disk,
            optimizer_feature_overrides: managed.optimizer_feature_overrides.into(),
            schedule: managed.schedule,
        }
    }
}

impl From<durable::ClusterVariantManaged> for ClusterVariantManaged {
    fn from(managed: durable::ClusterVariantManaged) -> Self {
        Self {
            size: managed.size,
            availability_zones: managed.availability_zones,
            logging: managed.logging,
            replication_factor: managed.replication_factor,
            disk: managed.disk,
            optimizer_feature_overrides: managed.optimizer_feature_overrides.into(),
            schedule: managed.schedule,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialOrd, PartialEq, Eq, Ord)]
pub enum ClusterVariant {
    Managed(ClusterVariantManaged),
    Unmanaged,
}

impl From<ClusterVariant> for durable::ClusterVariant {
    fn from(variant: ClusterVariant) -> Self {
        match variant {
            ClusterVariant::Managed(managed) => Self::Managed(managed.into()),
            ClusterVariant::Unmanaged => Self::Unmanaged,
        }
    }
}

impl From<durable::ClusterVariant> for ClusterVariant {
    fn from(variant: durable::ClusterVariant) -> Self {
        match variant {
            durable::ClusterVariant::Managed(managed) => Self::Managed(managed.into()),
            durable::ClusterVariant::Unmanaged => Self::Unmanaged,
        }
    }
}

impl mz_sql::catalog::CatalogDatabase for Database {
    fn name(&self) -> &str {
        &self.name
    }

    fn id(&self) -> DatabaseId {
        self.id
    }

    fn has_schemas(&self) -> bool {
        !self.schemas_by_name.is_empty()
    }

    fn schema_ids(&self) -> &BTreeMap<String, SchemaId> {
        &self.schemas_by_name
    }

    // `as` is ok to use to cast to a trait object.
    #[allow(clippy::as_conversions)]
    fn schemas(&self) -> Vec<&dyn CatalogSchema> {
        self.schemas_by_id
            .values()
            .map(|schema| schema as &dyn CatalogSchema)
            .collect()
    }

    fn owner_id(&self) -> RoleId {
        self.owner_id
    }

    fn privileges(&self) -> &PrivilegeMap {
        &self.privileges
    }
}

impl mz_sql::catalog::CatalogSchema for Schema {
    fn database(&self) -> &ResolvedDatabaseSpecifier {
        &self.name.database
    }

    fn name(&self) -> &QualifiedSchemaName {
        &self.name
    }

    fn id(&self) -> &SchemaSpecifier {
        &self.id
    }

    fn has_items(&self) -> bool {
        !self.items.is_empty()
    }

    fn item_ids(&self) -> Box<dyn Iterator<Item = CatalogItemId> + '_> {
        Box::new(
            self.items
                .values()
                .chain(self.functions.values())
                .chain(self.types.values())
                .copied(),
        )
    }

    fn owner_id(&self) -> RoleId {
        self.owner_id
    }

    fn privileges(&self) -> &PrivilegeMap {
        &self.privileges
    }
}

impl mz_sql::catalog::CatalogRole for Role {
    fn name(&self) -> &str {
        &self.name
    }

    fn id(&self) -> RoleId {
        self.id
    }

    fn membership(&self) -> &BTreeMap<RoleId, RoleId> {
        &self.membership.map
    }

    fn attributes(&self) -> &RoleAttributes {
        &self.attributes
    }

    fn vars(&self) -> &BTreeMap<String, OwnedVarInput> {
        &self.vars.map
    }
}

impl mz_sql::catalog::CatalogNetworkPolicy for NetworkPolicy {
    fn name(&self) -> &str {
        &self.name
    }

    fn id(&self) -> NetworkPolicyId {
        self.id
    }

    fn owner_id(&self) -> RoleId {
        self.owner_id
    }

    fn privileges(&self) -> &PrivilegeMap {
        &self.privileges
    }
}

impl mz_sql::catalog::CatalogCluster<'_> for Cluster {
    fn name(&self) -> &str {
        &self.name
    }

    fn id(&self) -> ClusterId {
        self.id
    }

    fn bound_objects(&self) -> &BTreeSet<CatalogItemId> {
        &self.bound_objects
    }

    fn replica_ids(&self) -> &BTreeMap<String, ReplicaId> {
        &self.replica_id_by_name_
    }

    // `as` is ok to use to cast to a trait object.
    #[allow(clippy::as_conversions)]
    fn replicas(&self) -> Vec<&dyn CatalogClusterReplica> {
        self.replicas()
            .map(|replica| replica as &dyn CatalogClusterReplica)
            .collect()
    }

    fn replica(&self, id: ReplicaId) -> &dyn CatalogClusterReplica {
        self.replica(id).expect("catalog out of sync")
    }

    fn owner_id(&self) -> RoleId {
        self.owner_id
    }

    fn privileges(&self) -> &PrivilegeMap {
        &self.privileges
    }

    fn is_managed(&self) -> bool {
        self.is_managed()
    }

    fn managed_size(&self) -> Option<&str> {
        match &self.config.variant {
            ClusterVariant::Managed(ClusterVariantManaged { size, .. }) => Some(size),
            _ => None,
        }
    }

    fn schedule(&self) -> Option<&ClusterSchedule> {
        match &self.config.variant {
            ClusterVariant::Managed(ClusterVariantManaged { schedule, .. }) => Some(schedule),
            _ => None,
        }
    }

    fn try_to_plan(&self) -> Result<CreateClusterPlan, PlanError> {
        self.try_to_plan()
    }
}

impl mz_sql::catalog::CatalogClusterReplica<'_> for ClusterReplica {
    fn name(&self) -> &str {
        &self.name
    }

    fn cluster_id(&self) -> ClusterId {
        self.cluster_id
    }

    fn replica_id(&self) -> ReplicaId {
        self.replica_id
    }

    fn owner_id(&self) -> RoleId {
        self.owner_id
    }

    fn internal(&self) -> bool {
        self.config.location.internal()
    }
}

impl mz_sql::catalog::CatalogItem for CatalogEntry {
    fn name(&self) -> &QualifiedItemName {
        self.name()
    }

    fn id(&self) -> CatalogItemId {
        self.id()
    }

    fn global_ids(&self) -> Box<dyn Iterator<Item = GlobalId> + '_> {
        Box::new(self.global_ids())
    }

    fn oid(&self) -> u32 {
        self.oid()
    }

    fn func(&self) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
        self.func()
    }

    fn source_desc(&self) -> Result<Option<&SourceDesc<ReferencedConnection>>, SqlCatalogError> {
        self.source_desc()
    }

    fn connection(
        &self,
    ) -> Result<mz_storage_types::connections::Connection<ReferencedConnection>, SqlCatalogError>
    {
        Ok(self.connection()?.details.to_connection())
    }

    fn create_sql(&self) -> &str {
        match self.item() {
            CatalogItem::Table(Table { create_sql, .. }) => {
                create_sql.as_deref().unwrap_or("<builtin>")
            }
            CatalogItem::Source(Source { create_sql, .. }) => {
                create_sql.as_deref().unwrap_or("<builtin>")
            }
            CatalogItem::Sink(Sink { create_sql, .. }) => create_sql,
            CatalogItem::View(View { create_sql, .. }) => create_sql,
            CatalogItem::MaterializedView(MaterializedView { create_sql, .. }) => create_sql,
            CatalogItem::Index(Index { create_sql, .. }) => create_sql,
            CatalogItem::Type(Type { create_sql, .. }) => {
                create_sql.as_deref().unwrap_or("<builtin>")
            }
            CatalogItem::Secret(Secret { create_sql, .. }) => create_sql,
            CatalogItem::Connection(Connection { create_sql, .. }) => create_sql,
            CatalogItem::Func(_) => "<builtin>",
            CatalogItem::Log(_) => "<builtin>",
            CatalogItem::ContinualTask(ContinualTask { create_sql, .. }) => create_sql,
        }
    }

    fn item_type(&self) -> SqlCatalogItemType {
        self.item().typ()
    }

    fn index_details(&self) -> Option<(&[MirScalarExpr], GlobalId)> {
        if let CatalogItem::Index(Index { keys, on, .. }) = self.item() {
            Some((keys, *on))
        } else {
            None
        }
    }

    fn writable_table_details(&self) -> Option<&[Expr<Aug>]> {
        if let CatalogItem::Table(Table {
            data_source: TableDataSource::TableWrites { defaults },
            ..
        }) = self.item()
        {
            Some(defaults.as_slice())
        } else {
            None
        }
    }

    fn type_details(&self) -> Option<&CatalogTypeDetails<IdReference>> {
        if let CatalogItem::Type(Type { details, .. }) = self.item() {
            Some(details)
        } else {
            None
        }
    }

    fn references(&self) -> &ResolvedIds {
        self.references()
    }

    fn uses(&self) -> BTreeSet<CatalogItemId> {
        self.uses()
    }

    fn referenced_by(&self) -> &[CatalogItemId] {
        self.referenced_by()
    }

    fn used_by(&self) -> &[CatalogItemId] {
        self.used_by()
    }

    fn subsource_details(
        &self,
    ) -> Option<(CatalogItemId, &UnresolvedItemName, &SourceExportDetails)> {
        self.subsource_details()
    }

    fn source_export_details(
        &self,
    ) -> Option<(
        CatalogItemId,
        &UnresolvedItemName,
        &SourceExportDetails,
        &SourceExportDataConfig<ReferencedConnection>,
    )> {
        self.source_export_details()
    }

    fn is_progress_source(&self) -> bool {
        self.is_progress_source()
    }

    fn progress_id(&self) -> Option<CatalogItemId> {
        self.progress_id()
    }

    fn owner_id(&self) -> RoleId {
        self.owner_id
    }

    fn privileges(&self) -> &PrivilegeMap {
        &self.privileges
    }

    fn cluster_id(&self) -> Option<ClusterId> {
        self.item().cluster_id()
    }

    fn at_version(
        &self,
        version: RelationVersionSelector,
    ) -> Box<dyn mz_sql::catalog::CatalogCollectionItem> {
        Box::new(CatalogCollectionEntry {
            entry: self.clone(),
            version,
        })
    }
}

/// A single update to the catalog state.
#[derive(Debug)]
pub struct StateUpdate {
    pub kind: StateUpdateKind,
    pub ts: Timestamp,
    pub diff: StateDiff,
}

/// The contents of a single state update.
///
/// Variants are listed in dependency order.
#[derive(Debug, Clone)]
pub enum StateUpdateKind {
    Role(durable::objects::Role),
    Database(durable::objects::Database),
    Schema(durable::objects::Schema),
    DefaultPrivilege(durable::objects::DefaultPrivilege),
    SystemPrivilege(MzAclItem),
    SystemConfiguration(durable::objects::SystemConfiguration),
    Cluster(durable::objects::Cluster),
    NetworkPolicy(durable::objects::NetworkPolicy),
    IntrospectionSourceIndex(durable::objects::IntrospectionSourceIndex),
    ClusterReplica(durable::objects::ClusterReplica),
    SourceReferences(durable::objects::SourceReferences),
    SystemObjectMapping(durable::objects::SystemObjectMapping),
    // Temporary items are not actually updated via the durable catalog, but this allows us to
    // model them the same way as all other items.
    TemporaryItem(TemporaryItem),
    Item(durable::objects::Item),
    Comment(durable::objects::Comment),
    AuditLog(durable::objects::AuditLog),
    // Storage updates.
    StorageCollectionMetadata(durable::objects::StorageCollectionMetadata),
    UnfinalizedShard(durable::objects::UnfinalizedShard),
}

/// Valid diffs for catalog state updates.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum StateDiff {
    Retraction,
    Addition,
}

impl From<StateDiff> for Diff {
    fn from(diff: StateDiff) -> Self {
        match diff {
            StateDiff::Retraction => -1,
            StateDiff::Addition => 1,
        }
    }
}
impl TryFrom<Diff> for StateDiff {
    type Error = String;

    fn try_from(diff: Diff) -> Result<Self, Self::Error> {
        match diff {
            -1 => Ok(Self::Retraction),
            1 => Ok(Self::Addition),
            diff => Err(format!("invalid diff {diff}")),
        }
    }
}

/// Information needed to process an update to a temporary item.
#[derive(Debug, Clone)]
pub struct TemporaryItem {
    pub id: CatalogItemId,
    pub oid: u32,
    pub name: QualifiedItemName,
    pub item: CatalogItem,
    pub owner_id: RoleId,
    pub privileges: PrivilegeMap,
}

impl From<CatalogEntry> for TemporaryItem {
    fn from(entry: CatalogEntry) -> Self {
        TemporaryItem {
            id: entry.id,
            oid: entry.oid,
            name: entry.name,
            item: entry.item,
            owner_id: entry.owner_id,
            privileges: entry.privileges,
        }
    }
}

/// The same as [`StateUpdateKind`], but without `TemporaryItem` so we can derive [`Ord`].
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum BootstrapStateUpdateKind {
    Role(durable::objects::Role),
    Database(durable::objects::Database),
    Schema(durable::objects::Schema),
    DefaultPrivilege(durable::objects::DefaultPrivilege),
    SystemPrivilege(MzAclItem),
    SystemConfiguration(durable::objects::SystemConfiguration),
    Cluster(durable::objects::Cluster),
    NetworkPolicy(durable::objects::NetworkPolicy),
    IntrospectionSourceIndex(durable::objects::IntrospectionSourceIndex),
    ClusterReplica(durable::objects::ClusterReplica),
    SourceReferences(durable::objects::SourceReferences),
    SystemObjectMapping(durable::objects::SystemObjectMapping),
    Item(durable::objects::Item),
    Comment(durable::objects::Comment),
    AuditLog(durable::objects::AuditLog),
    // Storage updates.
    StorageCollectionMetadata(durable::objects::StorageCollectionMetadata),
    UnfinalizedShard(durable::objects::UnfinalizedShard),
}

impl From<BootstrapStateUpdateKind> for StateUpdateKind {
    fn from(value: BootstrapStateUpdateKind) -> Self {
        match value {
            BootstrapStateUpdateKind::Role(kind) => StateUpdateKind::Role(kind),
            BootstrapStateUpdateKind::Database(kind) => StateUpdateKind::Database(kind),
            BootstrapStateUpdateKind::Schema(kind) => StateUpdateKind::Schema(kind),
            BootstrapStateUpdateKind::DefaultPrivilege(kind) => {
                StateUpdateKind::DefaultPrivilege(kind)
            }
            BootstrapStateUpdateKind::SystemPrivilege(kind) => {
                StateUpdateKind::SystemPrivilege(kind)
            }
            BootstrapStateUpdateKind::SystemConfiguration(kind) => {
                StateUpdateKind::SystemConfiguration(kind)
            }
            BootstrapStateUpdateKind::SourceReferences(kind) => {
                StateUpdateKind::SourceReferences(kind)
            }
            BootstrapStateUpdateKind::Cluster(kind) => StateUpdateKind::Cluster(kind),
            BootstrapStateUpdateKind::NetworkPolicy(kind) => StateUpdateKind::NetworkPolicy(kind),
            BootstrapStateUpdateKind::IntrospectionSourceIndex(kind) => {
                StateUpdateKind::IntrospectionSourceIndex(kind)
            }
            BootstrapStateUpdateKind::ClusterReplica(kind) => StateUpdateKind::ClusterReplica(kind),
            BootstrapStateUpdateKind::SystemObjectMapping(kind) => {
                StateUpdateKind::SystemObjectMapping(kind)
            }
            BootstrapStateUpdateKind::Item(kind) => StateUpdateKind::Item(kind),
            BootstrapStateUpdateKind::Comment(kind) => StateUpdateKind::Comment(kind),
            BootstrapStateUpdateKind::AuditLog(kind) => StateUpdateKind::AuditLog(kind),
            BootstrapStateUpdateKind::StorageCollectionMetadata(kind) => {
                StateUpdateKind::StorageCollectionMetadata(kind)
            }
            BootstrapStateUpdateKind::UnfinalizedShard(kind) => {
                StateUpdateKind::UnfinalizedShard(kind)
            }
        }
    }
}

impl TryFrom<StateUpdateKind> for BootstrapStateUpdateKind {
    type Error = TemporaryItem;

    fn try_from(value: StateUpdateKind) -> Result<Self, Self::Error> {
        match value {
            StateUpdateKind::Role(kind) => Ok(BootstrapStateUpdateKind::Role(kind)),
            StateUpdateKind::Database(kind) => Ok(BootstrapStateUpdateKind::Database(kind)),
            StateUpdateKind::Schema(kind) => Ok(BootstrapStateUpdateKind::Schema(kind)),
            StateUpdateKind::DefaultPrivilege(kind) => {
                Ok(BootstrapStateUpdateKind::DefaultPrivilege(kind))
            }
            StateUpdateKind::SystemPrivilege(kind) => {
                Ok(BootstrapStateUpdateKind::SystemPrivilege(kind))
            }
            StateUpdateKind::SystemConfiguration(kind) => {
                Ok(BootstrapStateUpdateKind::SystemConfiguration(kind))
            }
            StateUpdateKind::Cluster(kind) => Ok(BootstrapStateUpdateKind::Cluster(kind)),
            StateUpdateKind::NetworkPolicy(kind) => {
                Ok(BootstrapStateUpdateKind::NetworkPolicy(kind))
            }
            StateUpdateKind::IntrospectionSourceIndex(kind) => {
                Ok(BootstrapStateUpdateKind::IntrospectionSourceIndex(kind))
            }
            StateUpdateKind::ClusterReplica(kind) => {
                Ok(BootstrapStateUpdateKind::ClusterReplica(kind))
            }
            StateUpdateKind::SourceReferences(kind) => {
                Ok(BootstrapStateUpdateKind::SourceReferences(kind))
            }
            StateUpdateKind::SystemObjectMapping(kind) => {
                Ok(BootstrapStateUpdateKind::SystemObjectMapping(kind))
            }
            StateUpdateKind::TemporaryItem(kind) => Err(kind),
            StateUpdateKind::Item(kind) => Ok(BootstrapStateUpdateKind::Item(kind)),
            StateUpdateKind::Comment(kind) => Ok(BootstrapStateUpdateKind::Comment(kind)),
            StateUpdateKind::AuditLog(kind) => Ok(BootstrapStateUpdateKind::AuditLog(kind)),
            StateUpdateKind::StorageCollectionMetadata(kind) => {
                Ok(BootstrapStateUpdateKind::StorageCollectionMetadata(kind))
            }
            StateUpdateKind::UnfinalizedShard(kind) => {
                Ok(BootstrapStateUpdateKind::UnfinalizedShard(kind))
            }
        }
    }
}