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

//! Persistent metadata storage for the coordinator.

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::bail;
use chrono::{DateTime, TimeZone, Utc};
use itertools::Itertools;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, MutexGuard};
use tracing::{info, trace};

use mz_audit_log::{EventDetails, EventType, FullNameV1, ObjectType, VersionedEvent};
use mz_build_info::DUMMY_BUILD_INFO;
use mz_compute_client::command::{ProcessId, ReplicaId};
use mz_compute_client::controller::ComputeInstanceId;
use mz_compute_client::logging::LoggingConfig as DataflowLoggingConfig;
use mz_controller::{ComputeInstanceEvent, ConcreteComputeInstanceReplicaConfig};
use mz_expr::{ExprHumanizer, MirScalarExpr, OptimizedMirRelationExpr};
use mz_ore::collections::CollectionExt;
use mz_ore::metrics::MetricsRegistry;
use mz_ore::now::{to_datetime, EpochMillis, NowFn};
use mz_pgrepr::oid::FIRST_USER_OID;
use mz_repr::{Diff, GlobalId, RelationDesc, ScalarType};
use mz_sql::ast::display::AstDisplay;
use mz_sql::ast::Expr;
use mz_sql::catalog::{
    CatalogDatabase, CatalogError as SqlCatalogError, CatalogItem as SqlCatalogItem,
    CatalogItemType as SqlCatalogItemType, CatalogSchema, CatalogType, CatalogTypeDetails,
    IdReference, NameReference, SessionCatalog, TypeReference,
};
use mz_sql::names::{
    Aug, DatabaseId, FullObjectName, ObjectQualifiers, PartialObjectName, QualifiedObjectName,
    QualifiedSchemaName, RawDatabaseSpecifier, ResolvedDatabaseSpecifier, SchemaId,
    SchemaSpecifier,
};
use mz_sql::plan::{
    ComputeInstanceIntrospectionConfig, CreateConnectionPlan, CreateIndexPlan,
    CreateRecordedViewPlan, CreateSecretPlan, CreateSinkPlan, CreateSourcePlan, CreateTablePlan,
    CreateTypePlan, CreateViewPlan, Params, Plan, PlanContext, StatementDesc,
};
use mz_sql::DEFAULT_SCHEMA;
use mz_stash::{Append, Postgres, Sqlite};
use mz_storage::client::sinks::{SinkConnection, SinkConnectionBuilder, SinkEnvelope};
use mz_storage::client::sources::{SourceDesc, Timeline};
use mz_transform::Optimizer;
use uuid::Uuid;

use crate::catalog::builtin::{
    Builtin, BuiltinLog, BuiltinTable, BuiltinType, Fingerprint, BUILTINS, BUILTIN_ROLES,
    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_TEMP_SCHEMA, PG_CATALOG_SCHEMA,
};
use crate::session::{PreparedStatement, Session, DEFAULT_DATABASE_NAME};
use crate::CoordError;

mod builtin_table_updates;
mod config;
mod error;
mod migrate;

pub mod builtin;
pub mod storage;

pub use crate::catalog::builtin_table_updates::BuiltinTableUpdate;
pub use crate::catalog::config::Config;
pub use crate::catalog::error::AmbiguousRename;
pub use crate::catalog::error::Error;
pub use crate::catalog::error::ErrorKind;
use crate::client::ConnectionId;

pub const SYSTEM_CONN_ID: ConnectionId = 0;
const SYSTEM_USER: &str = "mz_system";

/// A `Catalog` keeps track of the SQL objects known to the planner.
///
/// For each object, it keeps track of both forward and reverse dependencies:
/// i.e., which objects are depended upon by the object, and which objects
/// depend upon the object. It enforces the SQL rules around dropping: an object
/// cannot be dropped until all of the objects that depend upon it are dropped.
/// It also enforces uniqueness of names.
///
/// SQL mandates a hierarchy of exactly three layers. A catalog contains
/// databases, databases contain schemas, and schemas contain catalog items,
/// like sources, sinks, view, and indexes.
///
/// To the outside world, databases, schemas, and items are all identified by
/// name. Items can be referred to by their [`FullObjectName`], which fully and
/// unambiguously specifies the item, or a [`PartialObjectName`], which can omit the
/// database name and/or the schema name. Partial names can be converted into
/// full names via a complicated resolution process documented by the
/// [`CatalogState::resolve`] method.
///
/// The catalog also maintains special "ambient schemas": virtual schemas,
/// implicitly present in all databases, that house various system views.
/// The big examples of ambient schemas are `pg_catalog` and `mz_catalog`.
#[derive(Debug)]
pub struct Catalog<S> {
    state: CatalogState,
    storage: Arc<Mutex<storage::Connection<S>>>,
    transient_revision: u64,
}

// Implement our own Clone because derive can't unless S is Clone, which it's
// not (hence the Arc).
impl<S> Clone for Catalog<S> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            storage: Arc::clone(&self.storage),
            transient_revision: self.transient_revision,
        }
    }
}

#[derive(Debug, Clone)]
pub struct CatalogState {
    database_by_name: BTreeMap<String, DatabaseId>,
    database_by_id: BTreeMap<DatabaseId, Database>,
    entry_by_id: BTreeMap<GlobalId, CatalogEntry>,
    ambient_schemas_by_name: BTreeMap<String, SchemaId>,
    ambient_schemas_by_id: BTreeMap<SchemaId, Schema>,
    temporary_schemas: HashMap<ConnectionId, Schema>,
    compute_instances_by_id: HashMap<ComputeInstanceId, ComputeInstance>,
    compute_instances_by_name: HashMap<String, ComputeInstanceId>,
    roles: HashMap<String, Role>,
    config: mz_sql::catalog::CatalogConfig,
    oid_counter: u32,
}

impl CatalogState {
    pub fn allocate_oid(&mut self) -> Result<u32, Error> {
        let oid = self.oid_counter;
        if oid == u32::max_value() {
            return Err(Error::new(ErrorKind::OidExhaustion));
        }
        self.oid_counter += 1;
        Ok(oid)
    }

    /// Computes the IDs of any indexes that transitively depend on this catalog
    /// entry.
    pub fn dependent_indexes(&self, id: GlobalId) -> Vec<GlobalId> {
        let mut out = Vec::new();
        self.dependent_indexes_inner(id, &mut out);
        out
    }

    fn dependent_indexes_inner(&self, id: GlobalId, out: &mut Vec<GlobalId>) {
        let entry = self.get_entry(&id);
        match entry.item() {
            CatalogItem::Index(_) => out.push(id),
            _ => {
                for id in entry.used_by() {
                    self.dependent_indexes_inner(*id, out)
                }
            }
        }
    }

    /// Computes the IDs of any log sources this catalog entry transitively
    /// depends on.
    pub fn log_dependencies(&self, id: GlobalId) -> Vec<GlobalId> {
        let mut out = Vec::new();
        self.log_dependencies_inner(id, &mut out);
        out
    }

    fn log_dependencies_inner(&self, id: GlobalId, out: &mut Vec<GlobalId>) {
        match self.get_entry(&id).item() {
            CatalogItem::Log(_) => out.push(id),
            CatalogItem::View(view) => {
                for id in view.depends_on.iter() {
                    self.log_dependencies_inner(*id, out);
                }
            }
            CatalogItem::Sink(sink) => self.log_dependencies_inner(sink.from, out),
            CatalogItem::Index(idx) => self.log_dependencies_inner(idx.on, out),
            CatalogItem::Table(_)
            | CatalogItem::Source(_)
            | CatalogItem::Type(_)
            | CatalogItem::Func(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => (),
        }
    }

    pub fn uses_tables(&self, id: GlobalId) -> bool {
        match self.get_entry(&id).item() {
            CatalogItem::Table(_) => true,
            item @ CatalogItem::View(_) => item.uses().iter().any(|id| self.uses_tables(*id)),
            CatalogItem::Index(idx) => self.uses_tables(idx.on),
            CatalogItem::Source(_)
            | CatalogItem::Log(_)
            | CatalogItem::Func(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => false,
        }
    }

    pub fn resolve_full_name(
        &self,
        name: &QualifiedObjectName,
        conn_id: Option<ConnectionId>,
    ) -> FullObjectName {
        let conn_id = conn_id.unwrap_or(SYSTEM_CONN_ID);

        let database = match &name.qualifiers.database_spec {
            ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
            ResolvedDatabaseSpecifier::Id(id) => {
                RawDatabaseSpecifier::Name(self.get_database(id).name().to_string())
            }
        };
        let schema = self
            .get_schema(
                &name.qualifiers.database_spec,
                &name.qualifiers.schema_spec,
                conn_id,
            )
            .name()
            .schema
            .clone();
        FullObjectName {
            database,
            schema,
            item: name.item.clone(),
        }
    }

    pub fn get_entry(&self, id: &GlobalId) -> &CatalogEntry {
        &self.entry_by_id[id]
    }

    pub fn try_get_entry_in_schema(
        &self,
        name: &QualifiedObjectName,
        conn_id: ConnectionId,
    ) -> Option<&CatalogEntry> {
        self.get_schema(
            &name.qualifiers.database_spec,
            &name.qualifiers.schema_spec,
            conn_id,
        )
        .items
        .get(&name.item)
        .and_then(|id| self.try_get_entry(id))
    }

    /// Gets an entry named `item` from exactly one of system schemas.
    ///
    /// # Panics
    /// - If `item` is not an entry in any system schema
    /// - If more than one system schema has an entry named `item`.
    fn get_entry_in_system_schemas(&self, item: &str) -> &CatalogEntry {
        let mut res = None;
        for system_schema in &[
            PG_CATALOG_SCHEMA,
            INFORMATION_SCHEMA,
            MZ_CATALOG_SCHEMA,
            MZ_INTERNAL_SCHEMA,
        ] {
            let schema_id = &self.ambient_schemas_by_name[*system_schema];
            let schema = &self.ambient_schemas_by_id[schema_id];
            if let Some(global_id) = schema.items.get(item) {
                match res {
                    None => res = Some(self.get_entry(global_id)),
                    Some(_) => panic!("only call get_entry_in_system_schemas on objects uniquely identifiable in one system schema"),
                }
            }
        }

        res.unwrap_or_else(|| panic!("cannot find {} in system schema", item))
    }

    pub fn item_exists(&self, name: &QualifiedObjectName, conn_id: ConnectionId) -> bool {
        self.try_get_entry_in_schema(name, conn_id).is_some()
    }

    fn find_available_name(
        &self,
        mut name: QualifiedObjectName,
        conn_id: ConnectionId,
    ) -> QualifiedObjectName {
        let mut i = 0;
        let orig_item_name = name.item.clone();
        while self.item_exists(&name, conn_id) {
            i += 1;
            name.item = format!("{}{}", orig_item_name, i);
        }
        name
    }

    pub fn try_get_entry(&self, id: &GlobalId) -> Option<&CatalogEntry> {
        self.entry_by_id.get(id)
    }

    /// Returns all indexes on the given object and compute instance known in
    /// the catalog.
    pub fn get_indexes_on(
        &self,
        id: GlobalId,
        compute_instance: ComputeInstanceId,
    ) -> impl Iterator<Item = (GlobalId, &Index)> {
        let index_matches =
            move |idx: &Index| idx.on == id && idx.compute_instance == compute_instance;

        self.get_entry(&id)
            .used_by()
            .iter()
            .filter_map(move |uses_id| match self.get_entry(uses_id).item() {
                CatalogItem::Index(index) if index_matches(index) => Some((*uses_id, index)),
                _ => None,
            })
    }

    fn insert_item(
        &mut self,
        id: GlobalId,
        oid: u32,
        name: QualifiedObjectName,
        item: CatalogItem,
    ) {
        if !id.is_system() && !item.is_placeholder() {
            info!(
                "create {} {} ({})",
                item.typ(),
                self.resolve_full_name(&name, None),
                id
            );
        }

        if !id.is_system() {
            if let CatalogItem::Index(Index {
                compute_instance, ..
            })
            | CatalogItem::Sink(Sink {
                compute_instance, ..
            }) = item
            {
                self.compute_instances_by_id
                    .get_mut(&compute_instance)
                    .unwrap()
                    .indexes
                    .insert(id);
            };
        }

        let entry = CatalogEntry {
            item,
            name,
            id,
            oid,
            used_by: Vec::new(),
        };
        for u in entry.uses() {
            match self.entry_by_id.get_mut(&u) {
                Some(metadata) => metadata.used_by.push(entry.id),
                None => panic!(
                    "Catalog: missing dependent catalog item {} while installing {}",
                    &u,
                    self.resolve_full_name(&entry.name, entry.conn_id())
                ),
            }
        }
        let conn_id = entry.item().conn_id().unwrap_or(SYSTEM_CONN_ID);
        let schema = self.get_schema_mut(
            &entry.name().qualifiers.database_spec,
            &entry.name().qualifiers.schema_spec,
            conn_id,
        );
        if let CatalogItem::Func(_) = entry.item() {
            schema.functions.insert(entry.name.item.clone(), entry.id);
        } else {
            schema.items.insert(entry.name.item.clone(), entry.id);
        }

        self.entry_by_id.insert(entry.id, entry.clone());
    }

    fn get_database(&self, database_id: &DatabaseId) -> &Database {
        &self.database_by_id[database_id]
    }

    async fn insert_compute_instance(
        &mut self,
        id: ComputeInstanceId,
        name: String,
        introspection: Option<ComputeInstanceIntrospectionConfig>,
        introspection_sources: Vec<(&'static BuiltinLog, GlobalId)>,
    ) {
        let logging = match introspection {
            None => None,
            Some(introspection) => {
                let mut active_logs = HashMap::new();
                for (log, index_id) in introspection_sources {
                    let source_name = FullObjectName {
                        database: RawDatabaseSpecifier::Ambient,
                        schema: log.schema.into(),
                        item: log.name.into(),
                    };
                    let index_name = format!("{}_{}_primary_idx", log.name, id);
                    let mut index_name = QualifiedObjectName {
                        qualifiers: ObjectQualifiers {
                            database_spec: ResolvedDatabaseSpecifier::Ambient,
                            schema_spec: SchemaSpecifier::Id(
                                self.get_mz_catalog_schema_id().clone(),
                            ),
                        },
                        item: index_name.clone(),
                    };
                    index_name = self.find_available_name(index_name, SYSTEM_CONN_ID);
                    let index_item_name = index_name.item.clone();
                    // TODO(clusters): Avoid panicking here on ID exhaustion
                    // before stabilization.
                    //
                    // The OID counter is an i32, and could plausibly be exhausted.
                    // Preallocating OIDs for each logging index is eminently
                    // doable, but annoying enough that we don't bother now.
                    let oid = self.allocate_oid().expect("cannot return error here");
                    let log_id = self.resolve_builtin_log(&log);
                    self.insert_item(
                        index_id,
                        oid,
                        index_name,
                        CatalogItem::Index(Index {
                            on: log_id,
                            keys: log
                                .variant
                                .index_by()
                                .into_iter()
                                .map(MirScalarExpr::Column)
                                .collect(),
                            create_sql: super::coord::index_sql(
                                index_item_name,
                                id,
                                source_name,
                                &log.variant.desc(),
                                &log.variant.index_by(),
                            ),
                            conn_id: None,
                            depends_on: vec![log_id],
                            compute_instance: id,
                        }),
                    );
                    active_logs.insert(log.variant.clone(), index_id);
                }
                Some(DataflowLoggingConfig {
                    granularity_ns: introspection.granularity.as_nanos(),
                    log_logging: introspection.debugging,
                    active_logs,
                })
            }
        };

        self.compute_instances_by_id.insert(
            id,
            ComputeInstance {
                name: name.clone(),
                id,
                indexes: HashSet::new(),
                logging,
                replica_id_by_name: HashMap::new(),
                replicas_by_id: HashMap::new(),
            },
        );
        assert!(self.compute_instances_by_name.insert(name, id).is_none());
    }

    fn insert_compute_instance_replica(
        &mut self,
        on_instance: ComputeInstanceId,
        replica_name: String,
        replica_id: ReplicaId,
        config: ConcreteComputeInstanceReplicaConfig,
    ) {
        let replica = ComputeInstanceReplica {
            config,
            process_status: HashMap::new(),
        };
        let compute_instance = self.compute_instances_by_id.get_mut(&on_instance).unwrap();
        assert!(compute_instance
            .replica_id_by_name
            .insert(replica_name, replica_id)
            .is_none());
        assert!(compute_instance
            .replicas_by_id
            .insert(replica_id, replica)
            .is_none());
    }

    /// Try inserting/updating the status of a compute instance process as
    /// described by the given event.
    ///
    /// This method returns `true` if the insert was successful. It returns
    /// `false` if the insert was unsuccessful, i.e., the given compute instance
    /// replica is not found.
    ///
    /// This treatment of non-existing replicas allows us to gracefully handle
    /// scenarios where we receive status updates for replicas that we have
    /// already removed from the catalog.
    fn try_insert_compute_instance_status(&mut self, event: ComputeInstanceEvent) -> bool {
        self.compute_instances_by_id
            .get_mut(&event.instance_id)
            .and_then(|instance| instance.replicas_by_id.get_mut(&event.replica_id))
            .map(|replica| replica.process_status.insert(event.process_id, event))
            .is_some()
    }

    /// Try getting the status of the given compute instance process.
    ///
    /// This method returns `None` if no status was found for the given
    /// compute instance process because:
    ///   * The given compute instance replica is not found. This can occur
    ///     if we already dropped the replica from the catalog, but we still
    ///     receive status updates.
    ///   * The given replica process is not found. This is the case when we
    ///     receive the first status update for a new replica process.
    fn try_get_compute_instance_status(
        &self,
        instance_id: ComputeInstanceId,
        replica_id: ReplicaId,
        process_id: ProcessId,
    ) -> Option<ComputeInstanceEvent> {
        self.compute_instances_by_id
            .get(&instance_id)
            .and_then(|instance| instance.replicas_by_id.get(&replica_id))
            .and_then(|replica| replica.process_status.get(&process_id))
            .cloned()
    }

    /// Gets the schema map for the database matching `database_spec`.
    fn resolve_schema_in_database(
        &self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_name: &str,
        conn_id: ConnectionId,
    ) -> Result<&Schema, SqlCatalogError> {
        let schema = match database_spec {
            ResolvedDatabaseSpecifier::Ambient if schema_name == MZ_TEMP_SCHEMA => {
                self.temporary_schemas.get(&conn_id)
            }
            ResolvedDatabaseSpecifier::Ambient => self
                .ambient_schemas_by_name
                .get(schema_name)
                .and_then(|id| self.ambient_schemas_by_id.get(id)),
            ResolvedDatabaseSpecifier::Id(id) => self.database_by_id.get(id).and_then(|db| {
                db.schemas_by_name
                    .get(schema_name)
                    .and_then(|id| db.schemas_by_id.get(id))
            }),
        };
        schema.ok_or_else(|| SqlCatalogError::UnknownSchema(schema_name.into()))
    }

    pub fn get_schema(
        &self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_spec: &SchemaSpecifier,
        conn_id: ConnectionId,
    ) -> &Schema {
        // Keep in sync with `get_schemas_mut`
        match (database_spec, schema_spec) {
            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Temporary) => {
                &self.temporary_schemas[&conn_id]
            }
            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Id(id)) => {
                &self.ambient_schemas_by_id[id]
            }

            (ResolvedDatabaseSpecifier::Id(database_id), SchemaSpecifier::Id(schema_id)) => {
                &self.database_by_id[database_id].schemas_by_id[schema_id]
            }
            (ResolvedDatabaseSpecifier::Id(_), SchemaSpecifier::Temporary) => {
                unreachable!("temporary schemas are in the ambient database")
            }
        }
    }

    fn get_schema_mut(
        &mut self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_spec: &SchemaSpecifier,
        conn_id: ConnectionId,
    ) -> &mut Schema {
        // Keep in sync with `get_schemas`
        match (database_spec, schema_spec) {
            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Temporary) => self
                .temporary_schemas
                .get_mut(&conn_id)
                .expect("catalog out of sync"),
            (ResolvedDatabaseSpecifier::Ambient, SchemaSpecifier::Id(id)) => self
                .ambient_schemas_by_id
                .get_mut(id)
                .expect("catalog out of sync"),
            (ResolvedDatabaseSpecifier::Id(database_id), SchemaSpecifier::Id(schema_id)) => self
                .database_by_id
                .get_mut(database_id)
                .expect("catalog out of sync")
                .schemas_by_id
                .get_mut(schema_id)
                .expect("catalog out of sync"),
            (ResolvedDatabaseSpecifier::Id(_), SchemaSpecifier::Temporary) => {
                unreachable!("temporary schemas are in the ambient database")
            }
        }
    }

    pub fn get_mz_catalog_schema_id(&self) -> &SchemaId {
        &self.ambient_schemas_by_name[MZ_CATALOG_SCHEMA]
    }

    pub fn get_pg_catalog_schema_id(&self) -> &SchemaId {
        &self.ambient_schemas_by_name[PG_CATALOG_SCHEMA]
    }

    pub fn get_information_schema_id(&self) -> &SchemaId {
        &self.ambient_schemas_by_name[INFORMATION_SCHEMA]
    }

    pub fn is_system_schema(&self, schema: &str) -> bool {
        schema == MZ_CATALOG_SCHEMA
            || schema == PG_CATALOG_SCHEMA
            || schema == INFORMATION_SCHEMA
            || schema == MZ_INTERNAL_SCHEMA
    }

    /// Optimized lookup for a builtin table
    ///
    /// Panics if the builtin table doesn't exist in the catalog
    pub fn resolve_builtin_table(&self, builtin: &'static BuiltinTable) -> GlobalId {
        self.resolve_builtin_object(&Builtin::<IdReference>::Table(builtin))
    }

    /// Optimized lookup for a builtin log
    ///
    /// Panics if the builtin log doesn't exist in the catalog
    pub fn resolve_builtin_log(&self, builtin: &'static BuiltinLog) -> GlobalId {
        self.resolve_builtin_object(&Builtin::<IdReference>::Log(builtin))
    }

    /// Optimized lookup for a builtin object
    ///
    /// Panics if the builtin object doesn't exist in the catalog
    pub fn resolve_builtin_object<T: TypeReference>(&self, builtin: &Builtin<T>) -> GlobalId {
        let schema_id = &self.ambient_schemas_by_name[builtin.schema()];
        let schema = &self.ambient_schemas_by_id[schema_id];
        schema.items[builtin.name()].clone()
    }

    pub fn config(&self) -> &mz_sql::catalog::CatalogConfig {
        &self.config
    }

    pub fn resolve_database(&self, database_name: &str) -> Result<&Database, SqlCatalogError> {
        match self.database_by_name.get(database_name) {
            Some(id) => Ok(&self.database_by_id[id]),
            None => Err(SqlCatalogError::UnknownDatabase(database_name.into())),
        }
    }

    pub fn resolve_schema(
        &self,
        current_database: Option<&DatabaseId>,
        database_name: Option<&str>,
        schema_name: &str,
        conn_id: ConnectionId,
    ) -> Result<&Schema, SqlCatalogError> {
        let database_spec = match database_name {
            // If a database is explicitly specified, validate it. Note that we
            // intentionally do not validate `current_database` to permit
            // querying `mz_catalog` with an invalid session database, e.g., so
            // that you can run `SHOW DATABASES` to *find* a valid database.
            Some(database) => Some(ResolvedDatabaseSpecifier::Id(
                self.resolve_database(database)?.id().clone(),
            )),
            None => current_database.map(|id| ResolvedDatabaseSpecifier::Id(id.clone())),
        };

        // First try to find the schema in the named database.
        if let Some(database_spec) = database_spec {
            if let Ok(schema) =
                self.resolve_schema_in_database(&database_spec, schema_name, conn_id)
            {
                return Ok(schema);
            }
        }

        // Then fall back to the ambient database.
        if let Ok(schema) = self.resolve_schema_in_database(
            &ResolvedDatabaseSpecifier::Ambient,
            schema_name,
            conn_id,
        ) {
            return Ok(schema);
        }

        Err(SqlCatalogError::UnknownSchema(schema_name.into()))
    }

    pub fn resolve_compute_instance(
        &self,
        name: &str,
    ) -> Result<&ComputeInstance, SqlCatalogError> {
        let id = self
            .compute_instances_by_name
            .get(name)
            .ok_or_else(|| SqlCatalogError::UnknownComputeInstance(name.to_string()))?;
        Ok(&self.compute_instances_by_id[id])
    }

    /// Resolves [`PartialObjectName`] into a [`CatalogEntry`].
    ///
    /// If `name` does not specify a database, the `current_database` is used.
    /// If `name` does not specify a schema, then the schemas in `search_path`
    /// are searched in order.
    #[allow(clippy::useless_let_if_seq)]
    pub fn resolve(
        &self,
        get_schema_entries: fn(&Schema) -> &BTreeMap<String, GlobalId>,
        current_database: Option<&DatabaseId>,
        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
        name: &PartialObjectName,
        conn_id: ConnectionId,
    ) -> Result<&CatalogEntry, SqlCatalogError> {
        // If a schema name was specified, just try to find the item in that
        // schema. If no schema was specified, try to find the item in the connection's
        // temporary schema. If the item is not found, try to find the item in every
        // schema in the search path.
        let schemas = match &name.schema {
            Some(schema_name) => {
                match self.resolve_schema(
                    current_database,
                    name.database.as_deref(),
                    schema_name,
                    conn_id,
                ) {
                    Ok(schema) => vec![(schema.name.database.clone(), schema.id.clone())],
                    Err(e) => return Err(e),
                }
            }
            None => match self
                .get_schema(
                    &ResolvedDatabaseSpecifier::Ambient,
                    &SchemaSpecifier::Temporary,
                    conn_id,
                )
                .items
                .get(&name.item)
            {
                Some(id) => return Ok(&self.get_entry(id)),
                None => search_path.to_vec(),
            },
        };

        for (database_spec, schema_spec) in schemas {
            let schema = self.get_schema(&database_spec, &schema_spec, conn_id);

            if let Some(id) = get_schema_entries(schema).get(&name.item) {
                return Ok(&self.entry_by_id[id]);
            }
        }
        Err(SqlCatalogError::UnknownItem(name.to_string()))
    }

    /// Resolves `name` to a non-function [`CatalogEntry`].
    pub fn resolve_entry(
        &self,
        current_database: Option<&DatabaseId>,
        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
        name: &PartialObjectName,
        conn_id: ConnectionId,
    ) -> Result<&CatalogEntry, SqlCatalogError> {
        self.resolve(
            |schema| &schema.items,
            current_database,
            search_path,
            name,
            conn_id,
        )
    }

    /// Resolves `name` to a function [`CatalogEntry`].
    pub fn resolve_function(
        &self,
        current_database: Option<&DatabaseId>,
        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
        name: &PartialObjectName,
        conn_id: ConnectionId,
    ) -> Result<&CatalogEntry, SqlCatalogError> {
        self.resolve(
            |schema| &schema.functions,
            current_database,
            search_path,
            name,
            conn_id,
        )
    }

    /// Serializes the catalog's in-memory state.
    ///
    /// There are no guarantees about the format of the serialized state, except
    /// that the serialized state for two identical catalogs will compare
    /// identically.
    pub fn dump(&self) -> String {
        serde_json::to_string(&self.database_by_id).expect("serialization cannot fail")
    }
}

#[derive(Debug)]
pub struct ConnCatalog<'a> {
    state: Cow<'a, CatalogState>,
    //TODO(jkosh44) usages
    conn_id: ConnectionId,
    compute_instance: String,
    database: Option<DatabaseId>,
    search_path: Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
    user: String,
    prepared_statements: Option<Cow<'a, HashMap<String, PreparedStatement>>>,
}

impl ConnCatalog<'_> {
    pub fn conn_id(&self) -> ConnectionId {
        self.conn_id
    }

    pub fn state(&self) -> &CatalogState {
        &*self.state
    }

    pub fn into_owned(self) -> ConnCatalog<'static> {
        ConnCatalog {
            state: Cow::Owned(self.state.into_owned()),
            conn_id: self.conn_id,
            compute_instance: self.compute_instance,
            database: self.database,
            search_path: self.search_path,
            user: self.user,
            prepared_statements: self.prepared_statements.map(|s| Cow::Owned(s.into_owned())),
        }
    }

    fn effective_search_path(
        &self,
        include_temp_schema: bool,
    ) -> Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)> {
        let mut v = Vec::with_capacity(self.search_path.len() + 3);
        // Temp schema is only included for relations and data types, not for functions and operators
        let temp_schema = (
            ResolvedDatabaseSpecifier::Ambient,
            SchemaSpecifier::Temporary,
        );
        if include_temp_schema && !self.search_path.contains(&temp_schema) {
            v.push(temp_schema);
        }
        let default_schemas = [
            (
                ResolvedDatabaseSpecifier::Ambient,
                SchemaSpecifier::Id(self.state.get_mz_catalog_schema_id().clone()),
            ),
            (
                ResolvedDatabaseSpecifier::Ambient,
                SchemaSpecifier::Id(self.state.get_pg_catalog_schema_id().clone()),
            ),
        ];
        for schema in default_schemas.into_iter() {
            if !self.search_path.contains(&schema) {
                v.push(schema);
            }
        }
        v.extend_from_slice(&self.search_path);
        v
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Database {
    pub name: String,
    pub id: DatabaseId,
    #[serde(skip)]
    pub oid: u32,
    pub schemas_by_id: BTreeMap<SchemaId, Schema>,
    pub schemas_by_name: BTreeMap<String, SchemaId>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Schema {
    pub name: QualifiedSchemaName,
    pub id: SchemaSpecifier,
    #[serde(skip)]
    pub oid: u32,
    pub items: BTreeMap<String, GlobalId>,
    pub functions: BTreeMap<String, GlobalId>,
}

#[derive(Debug, Serialize, Clone)]
pub struct Role {
    pub name: String,
    pub id: u64,
    #[serde(skip)]
    pub oid: u32,
}

#[derive(Debug, Serialize, Clone)]
pub struct ComputeInstance {
    pub name: String,
    pub id: ComputeInstanceId,
    pub logging: Option<DataflowLoggingConfig>,
    // does not include introspection source indexes
    pub indexes: HashSet<GlobalId>,
    pub replica_id_by_name: HashMap<String, ReplicaId>,
    pub replicas_by_id: HashMap<ReplicaId, ComputeInstanceReplica>,
}

#[derive(Debug, Serialize, Clone)]
pub struct ComputeInstanceReplica {
    pub config: ConcreteComputeInstanceReplicaConfig,
    pub process_status: HashMap<ProcessId, ComputeInstanceEvent>,
}

#[derive(Clone, Debug)]
pub struct CatalogEntry {
    item: CatalogItem,
    used_by: Vec<GlobalId>,
    id: GlobalId,
    oid: u32,
    name: QualifiedObjectName,
}

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

#[derive(Debug, Clone, Serialize)]
pub struct Table {
    pub create_sql: String,
    pub desc: RelationDesc,
    #[serde(skip)]
    pub defaults: Vec<Expr<Aug>>,
    pub conn_id: Option<ConnectionId>,
    pub depends_on: Vec<GlobalId>,
}

impl Table {
    // The Coordinator controls insertions for tables (including system tables),
    // so they are realtime.
    pub fn timeline(&self) -> Timeline {
        Timeline::EpochMilliseconds
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Source {
    pub create_sql: String,
    pub source_desc: SourceDesc,
    pub desc: RelationDesc,
    pub timeline: Timeline,
    pub depends_on: Vec<GlobalId>,
    pub remote_addr: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Sink {
    pub create_sql: String,
    pub from: GlobalId,
    pub connection: SinkConnectionState,
    pub envelope: SinkEnvelope,
    pub with_snapshot: bool,
    pub depends_on: Vec<GlobalId>,
    pub compute_instance: ComputeInstanceId,
}

#[derive(Debug, Clone, Serialize)]
pub enum SinkConnectionState {
    Pending(SinkConnectionBuilder),
    Ready(SinkConnection),
}

#[derive(Debug, Clone, Serialize)]
pub struct View {
    pub create_sql: String,
    pub optimized_expr: OptimizedMirRelationExpr,
    pub desc: RelationDesc,
    pub conn_id: Option<ConnectionId>,
    pub depends_on: Vec<GlobalId>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Index {
    pub create_sql: String,
    pub on: GlobalId,
    pub keys: Vec<MirScalarExpr>,
    pub conn_id: Option<ConnectionId>,
    pub depends_on: Vec<GlobalId>,
    pub compute_instance: ComputeInstanceId,
}

#[derive(Debug, Clone, Serialize)]
pub struct Type {
    pub create_sql: String,
    #[serde(skip)]
    pub details: CatalogTypeDetails<IdReference>,
    pub depends_on: Vec<GlobalId>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Func {
    #[serde(skip)]
    pub inner: &'static mz_sql::func::Func,
}

#[derive(Debug, Clone, Serialize)]
pub struct Secret {
    pub create_sql: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct Connection {
    pub create_sql: String,
    pub connection: mz_storage::client::connections::Connection,
}

impl CatalogItem {
    /// Returns a string indicating the type of this catalog entry.
    pub(crate) 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::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,
        }
    }

    pub fn desc(&self, name: &FullObjectName) -> Result<Cow<RelationDesc>, SqlCatalogError> {
        match &self {
            CatalogItem::Source(src) => Ok(Cow::Borrowed(&src.desc)),
            CatalogItem::Log(log) => Ok(Cow::Owned(log.variant.desc())),
            CatalogItem::Table(tbl) => Ok(Cow::Borrowed(&tbl.desc)),
            CatalogItem::View(view) => Ok(Cow::Borrowed(&view.desc)),
            CatalogItem::Func(_)
            | CatalogItem::Index(_)
            | CatalogItem::Sink(_)
            | CatalogItem::Type(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => Err(SqlCatalogError::InvalidDependency {
                name: name.to_string(),
                typ: self.typ(),
            }),
        }
    }

    pub fn func(
        &self,
        name: &QualifiedObjectName,
    ) -> Result<&'static mz_sql::func::Func, SqlCatalogError> {
        match &self {
            CatalogItem::Func(func) => Ok(func.inner),
            _ => Err(SqlCatalogError::UnknownFunction(name.item.to_string())),
        }
    }

    pub fn source_desc(&self, name: &QualifiedObjectName) -> Result<&SourceDesc, SqlCatalogError> {
        match &self {
            CatalogItem::Source(source) => Ok(&source.source_desc),
            _ => Err(SqlCatalogError::UnknownSource(name.item.clone())),
        }
    }

    /// Collects the identifiers of the dataflows that this item depends
    /// upon.
    pub fn uses(&self) -> &[GlobalId] {
        match self {
            CatalogItem::Func(_) => &[],
            CatalogItem::Index(idx) => &idx.depends_on,
            CatalogItem::Sink(sink) => &sink.depends_on,
            CatalogItem::Source(source) => &source.depends_on,
            CatalogItem::Log(_) => &[],
            CatalogItem::Table(table) => &table.depends_on,
            CatalogItem::Type(typ) => &typ.depends_on,
            CatalogItem::View(view) => &view.depends_on,
            CatalogItem::Secret(_) => &[],
            CatalogItem::Connection(_) => &[],
        }
    }

    /// Indicates whether this item is a placeholder for a future item
    /// or if it's actually a real item.
    pub fn is_placeholder(&self) -> bool {
        match self {
            CatalogItem::Func(_)
            | CatalogItem::Index(_)
            | CatalogItem::Source(_)
            | CatalogItem::Log(_)
            | CatalogItem::Table(_)
            | CatalogItem::Type(_)
            | CatalogItem::View(_)
            | CatalogItem::Secret(_)
            | CatalogItem::Connection(_) => false,
            CatalogItem::Sink(s) => match s.connection {
                SinkConnectionState::Pending(_) => true,
                SinkConnectionState::Ready(_) => false,
            },
        }
    }

    /// 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,
            CatalogItem::Index(index) => index.conn_id,
            CatalogItem::Table(table) => table.conn_id,
            CatalogItem::Log(_) => None,
            CatalogItem::Source(_) => None,
            CatalogItem::Sink(_) => None,
            CatalogItem::Secret(_) => None,
            CatalogItem::Type(_) => None,
            CatalogItem::Func(_) => None,
            CatalogItem::Connection(_) => None,
        }
    }

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

    /// 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.
    fn rename_item_refs(
        &self,
        from: FullObjectName,
        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).unwrap().into_element();
            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 = do_rewrite(i.create_sql)?;
                Ok(CatalogItem::Table(i))
            }
            CatalogItem::Log(i) => Ok(CatalogItem::Log(i)),
            CatalogItem::Source(i) => {
                let mut i = i.clone();
                i.create_sql = do_rewrite(i.create_sql)?;
                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::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))
            }
        }
    }
}

impl CatalogEntry {
    /// Reports the description of the datums produced by this catalog item.
    pub fn desc(&self, name: &FullObjectName) -> Result<Cow<RelationDesc>, SqlCatalogError> {
        self.item.desc(name)
    }

    /// 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.name())
    }

    /// 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 [`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),
            _ => Err(SqlCatalogError::UnknownConnection(self.name().to_string())),
        }
    }

    /// Returns the [`mz_storage::client::sources::SourceDesc`] associated with
    /// this `CatalogEntry`.
    pub fn source_desc(&self) -> Result<&SourceDesc, SqlCatalogError> {
        self.item.source_desc(self.name())
    }

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

    /// Collects the identifiers of the dataflows that this dataflow depends
    /// upon.
    pub fn uses(&self) -> &[GlobalId] {
        self.item.uses()
    }

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

    /// Returns the global ID of this catalog entry.
    pub fn id(&self) -> GlobalId {
        self.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) -> &QualifiedObjectName {
        &self.name
    }

    /// Returns the identifiers of the dataflows that depend upon this dataflow.
    pub fn used_by(&self) -> &[GlobalId] {
        &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()
    }
}

struct AllocatedBuiltinSystemIds<T> {
    all_builtins: Vec<(T, GlobalId)>,
    new_builtins: Vec<(T, GlobalId)>,
    migrated_builtins: Vec<(T, GlobalId)>,
}

impl Catalog<Sqlite> {
    /// Opens a debug in-memory sqlite catalog.
    ///
    /// See [`Catalog::open_debug`].
    pub async fn open_debug_sqlite(now: NowFn) -> Result<Catalog<Sqlite>, anyhow::Error> {
        let stash = mz_stash::Sqlite::open(None)?;
        Catalog::open_debug(stash, now).await
    }
}

impl Catalog<Postgres> {
    /// Opens a debug postgres catalog at `url`.
    ///
    /// If specified, `schema` will set the connection's `search_path` to `schema`.
    ///
    /// See [`Catalog::open_debug`].
    pub async fn open_debug_postgres(
        url: String,
        schema: Option<String>,
        now: NowFn,
    ) -> Result<Catalog<Postgres>, anyhow::Error> {
        let tls = mz_postgres_util::make_tls(&tokio_postgres::Config::new()).unwrap();
        let stash = mz_stash::Postgres::new(url, schema, tls).await?;
        Catalog::open_debug(stash, now).await
    }
}

impl<S: Append> Catalog<S> {
    /// Opens or creates a catalog that stores data at `path`.
    ///
    /// Returns the catalog and a list of updates to builtin tables that
    /// describe the initial state of the catalog.
    pub async fn open(
        config: Config<'_, S>,
    ) -> Result<(Catalog<S>, Vec<BuiltinTableUpdate>), Error> {
        let mut catalog = Catalog {
            state: CatalogState {
                database_by_name: BTreeMap::new(),
                database_by_id: BTreeMap::new(),
                entry_by_id: BTreeMap::new(),
                ambient_schemas_by_name: BTreeMap::new(),
                ambient_schemas_by_id: BTreeMap::new(),
                temporary_schemas: HashMap::new(),
                compute_instances_by_id: HashMap::new(),
                compute_instances_by_name: HashMap::new(),
                roles: HashMap::new(),
                config: mz_sql::catalog::CatalogConfig {
                    start_time: to_datetime((config.now)()),
                    start_instant: Instant::now(),
                    nonce: rand::random(),
                    unsafe_mode: config.unsafe_mode,
                    cluster_id: config.storage.cluster_id(),
                    session_id: Uuid::new_v4(),
                    build_info: config.build_info,
                    timestamp_frequency: config.timestamp_frequency,
                    now: config.now.clone(),
                },
                oid_counter: FIRST_USER_OID,
            },
            transient_revision: 0,
            storage: Arc::new(Mutex::new(config.storage)),
        };

        catalog.create_temporary_schema(SYSTEM_CONN_ID).await?;

        let databases = catalog.storage().await.load_databases().await?;
        for (id, name) in databases {
            let oid = catalog.allocate_oid().await?;
            catalog.state.database_by_id.insert(
                id.clone(),
                Database {
                    name: name.clone(),
                    id,
                    oid,
                    schemas_by_id: BTreeMap::new(),
                    schemas_by_name: BTreeMap::new(),
                },
            );
            catalog
                .state
                .database_by_name
                .insert(name.clone(), id.clone());
        }

        let schemas = catalog.storage().await.load_schemas().await?;
        for (schema_id, schema_name, database_id) in schemas {
            let oid = catalog.allocate_oid().await?;
            let (schemas_by_id, schemas_by_name, database_spec) = match &database_id {
                Some(database_id) => {
                    let db = catalog
                        .state
                        .database_by_id
                        .get_mut(database_id)
                        .expect("catalog out of sync");
                    (
                        &mut db.schemas_by_id,
                        &mut db.schemas_by_name,
                        ResolvedDatabaseSpecifier::Id(*database_id),
                    )
                }
                None => (
                    &mut catalog.state.ambient_schemas_by_id,
                    &mut catalog.state.ambient_schemas_by_name,
                    ResolvedDatabaseSpecifier::Ambient,
                ),
            };
            schemas_by_id.insert(
                schema_id.clone(),
                Schema {
                    name: QualifiedSchemaName {
                        database: database_spec,
                        schema: schema_name.clone(),
                    },
                    id: SchemaSpecifier::Id(schema_id.clone()),
                    oid,
                    items: BTreeMap::new(),
                    functions: BTreeMap::new(),
                },
            );
            schemas_by_name.insert(schema_name.clone(), schema_id);
        }

        let roles = catalog.storage().await.load_roles().await?;
        let builtin_roles = BUILTIN_ROLES.iter().map(|b| (b.id, b.name.to_owned()));
        for (id, name) in roles.into_iter().chain(builtin_roles) {
            let oid = catalog.allocate_oid().await?;
            catalog.state.roles.insert(
                name.clone(),
                Role {
                    name: name.clone(),
                    id,
                    oid,
                },
            );
        }

        catalog.load_builtin_types().await?;

        let persisted_builtin_ids = catalog.storage().await.load_system_gids().await?;
        let AllocatedBuiltinSystemIds {
            all_builtins,
            new_builtins,
            migrated_builtins,
        } = catalog
            .allocate_system_ids(
                BUILTINS::iter()
                    .filter(|builtin| !matches!(builtin, Builtin::Type(_)))
                    .collect(),
                |builtin| {
                    persisted_builtin_ids
                        .get(&(builtin.schema().to_string(), builtin.name().to_string()))
                        .cloned()
                },
            )
            .await?;

        for (builtin, id) in all_builtins {
            let schema_id = catalog.state.ambient_schemas_by_name[builtin.schema()];
            let name = QualifiedObjectName {
                qualifiers: ObjectQualifiers {
                    database_spec: ResolvedDatabaseSpecifier::Ambient,
                    schema_spec: SchemaSpecifier::Id(schema_id),
                },
                item: builtin.name().into(),
            };
            match builtin {
                Builtin::Log(log) => {
                    let oid = catalog.allocate_oid().await?;
                    catalog
                        .state
                        .insert_item(id, oid, name.clone(), CatalogItem::Log(log));
                }

                Builtin::Table(table) => {
                    let oid = catalog.allocate_oid().await?;
                    catalog.state.insert_item(
                        id,
                        oid,
                        name.clone(),
                        CatalogItem::Table(Table {
                            create_sql: "TODO".to_string(),
                            desc: table.desc.clone(),
                            defaults: vec![Expr::null(); table.desc.arity()],
                            conn_id: None,
                            depends_on: vec![],
                        }),
                    );
                }

                Builtin::View(view) => {
                    let item = catalog
                        .parse_item(
                            view.sql.into(),
                            None,
                        )
                        .unwrap_or_else(|e| {
                            panic!(
                                "internal error: failed to load bootstrap view:\n\
                                    {}\n\
                                    error:\n\
                                    {:?}\n\n\
                                    make sure that the schema name is specified in the builtin view's create sql statement.",
                                view.name, e
                            )
                        });
                    let oid = catalog.allocate_oid().await?;
                    catalog.state.insert_item(id, oid, name, item);
                }

                Builtin::Type(_) => unreachable!("loaded separately"),

                Builtin::Func(func) => {
                    let oid = catalog.allocate_oid().await?;
                    catalog.state.insert_item(
                        id,
                        oid,
                        name.clone(),
                        CatalogItem::Func(Func { inner: func.inner }),
                    );
                }
            }
        }
        let new_system_id_mappings = new_builtins
            .iter()
            .map(|(builtin, id)| (builtin.schema(), builtin.name(), *id, builtin.fingerprint()))
            .collect();
        catalog
            .storage()
            .await
            .set_system_gids(new_system_id_mappings)
            .await?;

        // TODO(jkosh44) actually migrate builtins
        let migrated_system_id_mappings = migrated_builtins
            .iter()
            .map(|(builtin, id)| (builtin.schema(), builtin.name(), *id, builtin.fingerprint()))
            .collect();
        catalog
            .storage()
            .await
            .set_system_gids(migrated_system_id_mappings)
            .await?;

        let compute_instances = catalog.storage().await.load_compute_instances().await?;
        for (id, name, introspection) in compute_instances {
            let introspection_sources = if introspection.is_some() {
                let introspection_source_index_gids = catalog
                    .storage()
                    .await
                    .load_introspection_source_index_gids(id)
                    .await?;

                let AllocatedBuiltinSystemIds {
                    all_builtins: all_indexes,
                    new_builtins: new_indexes,
                    ..
                } = catalog
                    .allocate_system_ids(BUILTINS::logs().collect(), |log| {
                        introspection_source_index_gids
                            .get(log.name)
                            .cloned()
                            // We don't migrate indexes so we can hardcode the fingerprint as 0
                            .map(|id| (id, 0))
                    })
                    .await?;

                catalog
                    .storage()
                    .await
                    .set_introspection_source_index_gids(
                        new_indexes
                            .iter()
                            .map(|(log, index_id)| (id, log.name, *index_id))
                            .collect(),
                    )
                    .await?;

                all_indexes
            } else {
                Vec::new()
            };
            catalog
                .state
                .insert_compute_instance(id, name, introspection, introspection_sources)
                .await;
        }

        let replicas = catalog
            .storage()
            .await
            .load_compute_instance_replicas()
            .await?;
        for (instance_id, replica_id, name, config) in replicas {
            catalog
                .state
                .insert_compute_instance_replica(instance_id, name, replica_id, config);
        }

        if !config.skip_migrations {
            let last_seen_version = catalog
                .storage()
                .await
                .get_catalog_content_version()
                .await?
                // `new` means that it hasn't been initialized
                .unwrap_or_else(|| "new".to_string());

            migrate::migrate(&mut catalog).await.map_err(|e| {
                Error::new(ErrorKind::FailedMigration {
                    last_seen_version,
                    this_version: catalog.config().build_info.version,
                    cause: e.to_string(),
                })
            })?;
            catalog
                .storage()
                .await
                .set_catalog_content_version(catalog.config().build_info.version)
                .await?;
        }

        let mut storage = catalog.storage().await;
        let mut tx = storage.transaction().await?;
        let catalog = Self::load_catalog_items(&mut tx, &catalog).await?;
        tx.commit().await?;

        let mut builtin_table_updates = vec![];
        for (schema_id, schema) in &catalog.state.ambient_schemas_by_id {
            let db_spec = ResolvedDatabaseSpecifier::Ambient;
            builtin_table_updates.push(catalog.state.pack_schema_update(&db_spec, schema_id, 1));
            for (_item_name, item_id) in &schema.items {
                builtin_table_updates.extend(catalog.state.pack_item_update(*item_id, 1));
            }
            for (_item_name, function_id) in &schema.functions {
                builtin_table_updates.extend(catalog.state.pack_item_update(*function_id, 1));
            }
        }
        for (db_id, db) in &catalog.state.database_by_id {
            builtin_table_updates.push(catalog.state.pack_database_update(db_id, 1));
            let db_spec = ResolvedDatabaseSpecifier::Id(db.id.clone());
            for (schema_id, schema) in &db.schemas_by_id {
                builtin_table_updates
                    .push(catalog.state.pack_schema_update(&db_spec, schema_id, 1));
                for (_item_name, item_id) in &schema.items {
                    builtin_table_updates.extend(catalog.state.pack_item_update(*item_id, 1));
                }
                for (_item_name, function_id) in &schema.functions {
                    builtin_table_updates.extend(catalog.state.pack_item_update(*function_id, 1));
                }
            }
        }
        for (role_name, _role) in &catalog.state.roles {
            builtin_table_updates.push(catalog.state.pack_role_update(role_name, 1));
        }
        for (name, id) in &catalog.state.compute_instances_by_name {
            builtin_table_updates.push(catalog.state.pack_compute_instance_update(name, 1));
            let instance = &catalog.state.compute_instances_by_id[id];
            for (replica_name, _replica_id) in &instance.replica_id_by_name {
                builtin_table_updates.push(catalog.state.pack_compute_instance_replica_update(
                    *id,
                    &replica_name,
                    1,
                ));
            }
        }
        let audit_logs = storage.load_audit_log().await?;
        for event in audit_logs {
            let event = VersionedEvent::deserialize(&event).unwrap();
            builtin_table_updates.push(catalog.state.pack_audit_log_update(&event)?);
        }

        Ok((catalog, builtin_table_updates))
    }

    /// Loads built-in system types into the catalog.
    ///
    /// Built-in types sometimes have references to other built-in types, and sometimes these
    /// references are circular. This makes loading built-in types more complicated than other
    /// built-in objects, and requires us to make multiple passes over the types to correctly
    /// resolve all references.
    async fn load_builtin_types(&mut self) -> Result<(), Error> {
        let persisted_builtin_ids = self.storage().await.load_system_gids().await?;

        let AllocatedBuiltinSystemIds {
            all_builtins,
            new_builtins,
            ..
        } = self
            .allocate_system_ids(BUILTINS::types().collect(), |typ| {
                persisted_builtin_ids
                    .get(&(typ.schema.to_string(), typ.name.to_string()))
                    .cloned()
            })
            .await?;
        let name_to_id_map: HashMap<&str, GlobalId> = all_builtins
            .into_iter()
            .map(|(typ, id)| (typ.name, id))
            .collect();

        // Replace named references with id references
        let mut builtin_types: Vec<_> = BUILTINS::types()
            .map(|typ| Self::resolve_builtin_type(typ, &name_to_id_map))
            .collect();

        // Resolve array_id for types
        let mut element_id_to_array_id = HashMap::new();
        for typ in &builtin_types {
            match &typ.details.typ {
                CatalogType::Array { element_reference } => {
                    let array_id = name_to_id_map[typ.name];
                    element_id_to_array_id.insert(*element_reference, array_id);
                }
                _ => {}
            }
        }
        let pg_catalog_schema_id = self.state.get_pg_catalog_schema_id().clone();
        for typ in &mut builtin_types {
            let element_id = name_to_id_map[typ.name];
            typ.details.array_id = element_id_to_array_id.get(&element_id).map(|id| id.clone());
        }

        // Insert into catalog
        for typ in builtin_types {
            let element_id = name_to_id_map[typ.name];
            self.state.insert_item(
                element_id,
                typ.oid,
                QualifiedObjectName {
                    qualifiers: ObjectQualifiers {
                        database_spec: ResolvedDatabaseSpecifier::Ambient,
                        schema_spec: SchemaSpecifier::Id(pg_catalog_schema_id),
                    },
                    item: typ.name.to_owned(),
                },
                CatalogItem::Type(Type {
                    create_sql: format!("CREATE TYPE {}", typ.name),
                    details: typ.details.clone(),
                    depends_on: vec![],
                }),
            );
        }

        let new_system_id_mappings = new_builtins
            .iter()
            .map(|(typ, id)| (typ.schema, typ.name, *id, typ.fingerprint()))
            .collect();
        self.storage()
            .await
            .set_system_gids(new_system_id_mappings)
            .await?;

        Ok(())
    }

    fn resolve_builtin_type(
        builtin: &BuiltinType<NameReference>,
        name_to_id_map: &HashMap<&str, GlobalId>,
    ) -> BuiltinType<IdReference> {
        let typ: CatalogType<IdReference> = match &builtin.details.typ {
            CatalogType::Array { element_reference } => CatalogType::Array {
                element_reference: name_to_id_map[element_reference],
            },
            CatalogType::List { element_reference } => CatalogType::List {
                element_reference: name_to_id_map[element_reference],
            },
            CatalogType::Map {
                key_reference,
                value_reference,
            } => CatalogType::Map {
                key_reference: name_to_id_map[key_reference],
                value_reference: name_to_id_map[value_reference],
            },
            CatalogType::Record { fields } => CatalogType::Record {
                fields: fields
                    .into_iter()
                    .map(|(column_name, reference)| {
                        (column_name.clone(), name_to_id_map[reference])
                    })
                    .collect(),
            },
            CatalogType::Bool => CatalogType::Bool,
            CatalogType::Bytes => CatalogType::Bytes,
            CatalogType::Char => CatalogType::Char,
            CatalogType::Date => CatalogType::Date,
            CatalogType::Float32 => CatalogType::Float32,
            CatalogType::Float64 => CatalogType::Float64,
            CatalogType::Int16 => CatalogType::Int16,
            CatalogType::Int32 => CatalogType::Int32,
            CatalogType::Int64 => CatalogType::Int64,
            CatalogType::Interval => CatalogType::Interval,
            CatalogType::Jsonb => CatalogType::Jsonb,
            CatalogType::Numeric => CatalogType::Numeric,
            CatalogType::Oid => CatalogType::Oid,
            CatalogType::PgLegacyChar => CatalogType::PgLegacyChar,
            CatalogType::Pseudo => CatalogType::Pseudo,
            CatalogType::RegClass => CatalogType::RegClass,
            CatalogType::RegProc => CatalogType::RegProc,
            CatalogType::RegType => CatalogType::RegType,
            CatalogType::String => CatalogType::String,
            CatalogType::Time => CatalogType::Time,
            CatalogType::Timestamp => CatalogType::Timestamp,
            CatalogType::TimestampTz => CatalogType::TimestampTz,
            CatalogType::Uuid => CatalogType::Uuid,
            CatalogType::VarChar => CatalogType::VarChar,
            CatalogType::Int2Vector => CatalogType::Int2Vector,
        };

        BuiltinType {
            name: builtin.name,
            schema: builtin.schema,
            oid: builtin.oid,
            details: CatalogTypeDetails {
                array_id: builtin.details.array_id,
                typ,
            },
        }
    }

    /// Returns the catalog's transient revision, which starts at 1 and is
    /// incremented on every change. This is not persisted to disk, and will
    /// restart on every load.
    pub fn transient_revision(&self) -> u64 {
        self.transient_revision
    }

    /// Takes a catalog which only has items in its on-disk storage ("unloaded")
    /// and cannot yet resolve names, and returns a catalog loaded with those
    /// items.
    ///
    /// This function requires transactions to support loading a catalog with
    /// the transaction's currently in-flight updates to existing catalog
    /// objects, which is necessary for at least one catalog migration.
    ///
    /// TODO(justin): it might be nice if these were two different types.
    pub async fn load_catalog_items<'a>(
        tx: &mut storage::Transaction<'a, S>,
        c: &Catalog<S>,
    ) -> Result<Catalog<S>, Error> {
        let mut c = c.clone();
        let items = tx.loaded_items();
        for (id, name, def) in items {
            // TODO(benesch): a better way of detecting when a view has depended
            // upon a non-existent logging view. This is fine for now because
            // the only goal is to produce a nicer error message; we'll bail out
            // safely even if the error message we're sniffing out changes.
            static LOGGING_ERROR: Lazy<Regex> =
                Lazy::new(|| Regex::new("unknown catalog item 'mz_catalog.[^']*'").unwrap());
            let item = match c.deserialize_item(def) {
                Ok(item) => item,
                Err(e) if LOGGING_ERROR.is_match(&e.to_string()) => {
                    return Err(Error::new(ErrorKind::UnsatisfiableLoggingDependency {
                        depender_name: name.to_string(),
                    }));
                }
                Err(e) => {
                    return Err(Error::new(ErrorKind::Corruption {
                        detail: format!("failed to deserialize item {} ({}): {}", id, name, e),
                    }))
                }
            };
            let oid = c.allocate_oid().await?;
            c.state.insert_item(id, oid, name, item);
        }
        c.transient_revision = 1;
        Ok(c)
    }

    /// Opens the catalog from `stash` with parameters set appropriately for debug
    /// contexts, like in tests.
    ///
    /// WARNING! This function can arbitrarily fail because it does not make any
    /// effort to adjust the catalog's contents' structure or semantics to the
    /// currently running version, i.e. it does not apply any migrations.
    ///
    /// This function should not be called in production contexts. Use
    /// [`Catalog::open`] with appropriately set configuration parameters
    /// instead.
    pub async fn open_debug(stash: S, now: NowFn) -> Result<Catalog<S>, anyhow::Error> {
        let metrics_registry = &MetricsRegistry::new();
        let storage = storage::Connection::open(stash).await?;
        let (catalog, _) = Catalog::open(Config {
            storage,
            unsafe_mode: true,
            build_info: &DUMMY_BUILD_INFO,
            timestamp_frequency: Duration::from_secs(1),
            now,
            skip_migrations: true,
            metrics_registry,
        })
        .await?;
        Ok(catalog)
    }

    pub fn for_session<'a>(&'a self, session: &'a Session) -> ConnCatalog<'a> {
        let database = self
            .state
            .database_by_name
            .get(session.vars().database())
            .map(|id| id.clone());
        let search_path = session
            .vars()
            .search_path()
            .iter()
            .map(|schema| self.resolve_schema(database.as_ref(), None, schema, session.conn_id()))
            .filter_map(|schema| schema.ok())
            .map(|schema| (schema.name().database.clone(), schema.id().clone()))
            .collect();
        ConnCatalog {
            state: Cow::Borrowed(&self.state),
            conn_id: session.conn_id(),
            compute_instance: session.vars().cluster().into(),
            database,
            search_path,
            user: session.user().into(),
            prepared_statements: Some(Cow::Borrowed(session.prepared_statements())),
        }
    }

    pub fn for_sessionless_user(&self, user: String) -> ConnCatalog {
        ConnCatalog {
            state: Cow::Borrowed(&self.state),
            conn_id: SYSTEM_CONN_ID,
            compute_instance: "default".into(),
            database: self
                .resolve_database(DEFAULT_DATABASE_NAME)
                .ok()
                .map(|db| db.id()),
            search_path: Vec::new(),
            user,
            prepared_statements: None,
        }
    }

    // Leaving the system's search path empty allows us to catch issues
    // where catalog object names have not been normalized correctly.
    pub fn for_system_session(&self) -> ConnCatalog {
        self.for_sessionless_user(SYSTEM_USER.into())
    }

    async fn storage<'a>(&'a self) -> MutexGuard<'a, storage::Connection<S>> {
        self.storage.lock().await
    }

    /// Allocate new system ids for any new builtin objects and looks up existing system ids for
    /// existing builtin objects
    async fn allocate_system_ids<T, F>(
        &mut self,
        builtins: Vec<T>,
        builtin_lookup: F,
    ) -> Result<AllocatedBuiltinSystemIds<T>, Error>
    where
        T: Copy + Fingerprint,
        F: Fn(&T) -> Option<(GlobalId, u64)>,
    {
        let new_builtin_amount = builtins
            .iter()
            .filter(|builtin| builtin_lookup(builtin).is_none())
            .count();

        let mut global_ids = self
            .storage()
            .await
            .allocate_system_ids(
                new_builtin_amount
                    .try_into()
                    .expect("builtins should fit into u64"),
            )
            .await?
            .into_iter();

        let mut all_builtins = Vec::new();
        let mut new_builtins = Vec::new();
        let mut migrated_builtins = Vec::new();
        for builtin in &builtins {
            match builtin_lookup(builtin) {
                Some((id, fingerprint)) => {
                    all_builtins.push((*builtin, id));
                    if fingerprint != builtin.fingerprint() {
                        migrated_builtins.push((*builtin, id));
                    }
                }
                None => {
                    let id = global_ids.next().expect("not enough global IDs");
                    all_builtins.push((*builtin, id));
                    new_builtins.push((*builtin, id));
                }
            }
        }

        Ok(AllocatedBuiltinSystemIds {
            all_builtins,
            new_builtins,
            migrated_builtins,
        })
    }

    pub async fn allocate_user_id(&mut self) -> Result<GlobalId, Error> {
        self.storage().await.allocate_user_id().await
    }

    pub async fn allocate_oid(&mut self) -> Result<u32, Error> {
        self.state.allocate_oid()
    }

    pub fn resolve_database(&self, database_name: &str) -> Result<&Database, SqlCatalogError> {
        self.state.resolve_database(database_name)
    }

    pub fn resolve_schema(
        &self,
        current_database: Option<&DatabaseId>,
        database_name: Option<&str>,
        schema_name: &str,
        conn_id: ConnectionId,
    ) -> Result<&Schema, SqlCatalogError> {
        self.state
            .resolve_schema(current_database, database_name, schema_name, conn_id)
    }

    pub fn resolve_schema_in_database(
        &self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_name: &str,
        conn_id: ConnectionId,
    ) -> Result<&Schema, SqlCatalogError> {
        self.state
            .resolve_schema_in_database(database_spec, schema_name, conn_id)
    }

    /// Resolves `name` to a non-function [`CatalogEntry`].
    pub fn resolve_entry(
        &self,
        current_database: Option<&DatabaseId>,
        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
        name: &PartialObjectName,
        conn_id: ConnectionId,
    ) -> Result<&CatalogEntry, SqlCatalogError> {
        self.state
            .resolve_entry(current_database, search_path, name, conn_id)
    }

    /// Resolves a `BuiltinTable`.
    pub fn resolve_builtin_table(&self, builtin: &'static BuiltinTable) -> GlobalId {
        self.state.resolve_builtin_table(builtin)
    }

    /// Resolves a `BuiltinLog`.
    pub fn resolve_builtin_log(&self, builtin: &'static BuiltinLog) -> GlobalId {
        self.state.resolve_builtin_log(builtin)
    }

    /// Resolves `name` to a function [`CatalogEntry`].
    pub fn resolve_function(
        &self,
        current_database: Option<&DatabaseId>,
        search_path: &Vec<(ResolvedDatabaseSpecifier, SchemaSpecifier)>,
        name: &PartialObjectName,
        conn_id: ConnectionId,
    ) -> Result<&CatalogEntry, SqlCatalogError> {
        self.state
            .resolve_function(current_database, search_path, name, conn_id)
    }

    pub fn resolve_compute_instance(
        &self,
        name: &str,
    ) -> Result<&ComputeInstance, SqlCatalogError> {
        self.state.resolve_compute_instance(name)
    }

    pub fn state(&self) -> &CatalogState {
        &self.state
    }

    pub fn resolve_full_name(
        &self,
        name: &QualifiedObjectName,
        conn_id: Option<ConnectionId>,
    ) -> FullObjectName {
        self.state.resolve_full_name(name, conn_id)
    }

    /// Returns the named catalog item, if it exists.
    pub fn try_get_entry_in_schema(
        &self,
        name: &QualifiedObjectName,
        conn_id: ConnectionId,
    ) -> Option<&CatalogEntry> {
        self.state.try_get_entry_in_schema(name, conn_id)
    }

    pub fn item_exists(&self, name: &QualifiedObjectName, conn_id: ConnectionId) -> bool {
        self.state.item_exists(name, conn_id)
    }

    pub fn try_get_entry(&self, id: &GlobalId) -> Option<&CatalogEntry> {
        self.state.try_get_entry(id)
    }

    pub fn get_entry(&self, id: &GlobalId) -> &CatalogEntry {
        self.state.get_entry(id)
    }

    pub fn get_schema(
        &self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_spec: &SchemaSpecifier,
        conn_id: ConnectionId,
    ) -> &Schema {
        self.state.get_schema(database_spec, schema_spec, conn_id)
    }

    pub fn get_mz_catalog_schema_id(&self) -> &SchemaId {
        self.state.get_mz_catalog_schema_id()
    }

    pub fn get_pg_catalog_schema_id(&self) -> &SchemaId {
        self.state.get_pg_catalog_schema_id()
    }

    pub fn get_information_schema_id(&self) -> &SchemaId {
        self.state.get_information_schema_id()
    }

    pub fn get_database(&self, id: &DatabaseId) -> &Database {
        self.state.get_database(id)
    }

    /// Creates a new schema in the `Catalog` for temporary items
    /// indicated by the TEMPORARY or TEMP keywords.
    pub async fn create_temporary_schema(&mut self, conn_id: ConnectionId) -> Result<(), Error> {
        let oid = self.allocate_oid().await?;
        self.state.temporary_schemas.insert(
            conn_id,
            Schema {
                name: QualifiedSchemaName {
                    database: ResolvedDatabaseSpecifier::Ambient,
                    schema: MZ_TEMP_SCHEMA.into(),
                },
                id: SchemaSpecifier::Temporary,
                oid,
                items: BTreeMap::new(),
                functions: BTreeMap::new(),
            },
        );
        Ok(())
    }

    fn item_exists_in_temp_schemas(&self, conn_id: ConnectionId, item_name: &str) -> bool {
        self.state.temporary_schemas[&conn_id]
            .items
            .contains_key(item_name)
    }

    pub fn drop_temp_item_ops(&mut self, conn_id: ConnectionId) -> Vec<Op> {
        let ids: Vec<GlobalId> = self.state.temporary_schemas[&conn_id]
            .items
            .values()
            .cloned()
            .collect();
        self.drop_items_ops(&ids)
    }

    pub fn drop_temporary_schema(&mut self, conn_id: ConnectionId) -> Result<(), Error> {
        if !self.state.temporary_schemas[&conn_id].items.is_empty() {
            return Err(Error::new(ErrorKind::SchemaNotEmpty(MZ_TEMP_SCHEMA.into())));
        }
        self.state.temporary_schemas.remove(&conn_id);
        Ok(())
    }

    pub fn drop_database_ops(&mut self, id: Option<DatabaseId>) -> Vec<Op> {
        let mut ops = vec![];
        let mut seen = HashSet::new();
        if let Some(id) = id {
            let database = self.get_database(&id);
            for (schema_id, schema) in &database.schemas_by_id {
                Self::drop_schema_items(schema, &self.state.entry_by_id, &mut ops, &mut seen);
                ops.push(Op::DropSchema {
                    database_id: id.clone(),
                    schema_id: schema_id.clone(),
                });
            }
            ops.push(Op::DropDatabase { id });
        }
        ops
    }

    pub fn drop_schema_ops(&mut self, id: Option<(DatabaseId, SchemaId)>) -> Vec<Op> {
        let mut ops = vec![];
        let mut seen = HashSet::new();
        if let Some((database_id, schema_id)) = id {
            let database = self.get_database(&database_id);
            let schema = &database.schemas_by_id[&schema_id];
            Self::drop_schema_items(schema, &self.state.entry_by_id, &mut ops, &mut seen);
            ops.push(Op::DropSchema {
                database_id,
                schema_id,
            })
        }
        ops
    }

    pub fn drop_items_ops(&mut self, ids: &[GlobalId]) -> Vec<Op> {
        let mut ops = vec![];
        let mut seen = HashSet::new();
        for &id in ids {
            Self::drop_item_cascade(id, &self.state.entry_by_id, &mut ops, &mut seen);
        }
        ops
    }

    fn drop_schema_items(
        schema: &Schema,
        by_id: &BTreeMap<GlobalId, CatalogEntry>,
        ops: &mut Vec<Op>,
        seen: &mut HashSet<GlobalId>,
    ) {
        for &id in schema.items.values() {
            Self::drop_item_cascade(id, by_id, ops, seen)
        }
    }

    fn drop_item_cascade(
        id: GlobalId,
        by_id: &BTreeMap<GlobalId, CatalogEntry>,
        ops: &mut Vec<Op>,
        seen: &mut HashSet<GlobalId>,
    ) {
        if !seen.contains(&id) {
            seen.insert(id);
            for &u in &by_id[&id].used_by {
                Self::drop_item_cascade(u, by_id, ops, seen)
            }
            ops.push(Op::DropItem(id));
        }
    }

    /// Gets GlobalIds of temporary items to be created, checks for name collisions
    /// within a connection id.
    fn temporary_ids(
        &mut self,
        ops: &[Op],
        temporary_drops: HashSet<(ConnectionId, String)>,
    ) -> Result<Vec<GlobalId>, Error> {
        let mut creating = HashSet::with_capacity(ops.len());
        let mut temporary_ids = Vec::with_capacity(ops.len());
        for op in ops.iter() {
            if let Op::CreateItem {
                id,
                oid: _,
                name,
                item,
            } = op
            {
                if let Some(conn_id) = item.conn_id() {
                    if self.item_exists_in_temp_schemas(conn_id, &name.item)
                        && !temporary_drops.contains(&(conn_id, name.item.clone()))
                        || creating.contains(&(conn_id, &name.item))
                    {
                        return Err(Error::new(ErrorKind::ItemAlreadyExists(name.item.clone())));
                    } else {
                        creating.insert((conn_id, &name.item));
                        temporary_ids.push(id.clone());
                    }
                }
            }
        }
        Ok(temporary_ids)
    }

    // TODO(mjibson): Is there a way to make this a closure to avoid explicitly
    // passing tx, session, and builtin_table_updates?
    fn add_to_audit_log(
        &self,
        session: Option<&Session>,
        tx: &mut storage::Transaction<S>,
        builtin_table_updates: &mut Vec<BuiltinTableUpdate>,
        event_type: EventType,
        object_type: ObjectType,
        event_details: EventDetails,
    ) -> Result<(), Error> {
        let session = match session {
            Some(session) => session,
            None => return Ok(()),
        };
        let user = session.user().to_string();
        let occurred_at = (self.state.config.now)();
        let id = tx.get_and_increment_id(storage::AUDIT_LOG_ID_ALLOC_KEY.to_string())?;
        let event = VersionedEvent::new(
            id,
            event_type,
            object_type,
            event_details,
            user,
            occurred_at,
        );
        builtin_table_updates.push(self.state.pack_audit_log_update(&event)?);
        tx.insert_audit_log_event(event);
        Ok(())
    }

    fn should_audit_log_item(item: &CatalogItem) -> bool {
        !item.is_temporary()
            && matches!(
                item.typ(),
                SqlCatalogItemType::View
                    | SqlCatalogItemType::RecordedView
                    | SqlCatalogItemType::Source
                    | SqlCatalogItemType::Sink
                    | SqlCatalogItemType::Index
            )
    }

    fn resolve_full_name_detail(
        &self,
        name: &QualifiedObjectName,
        session: Option<&Session>,
    ) -> FullNameV1 {
        let name = self
            .state
            .resolve_full_name(name, session.map(|session| session.conn_id()));
        self.full_name_detail(&name)
    }

    fn full_name_detail(&self, name: &FullObjectName) -> FullNameV1 {
        FullNameV1 {
            database: name.database.to_string(),
            schema: name.schema.clone(),
            item: name.item.clone(),
        }
    }

    pub async fn transact<F, T>(
        &mut self,
        session: Option<&Session>,
        ops: Vec<Op>,
        f: F,
    ) -> Result<(Vec<BuiltinTableUpdate>, T), CoordError>
    where
        F: FnOnce(&CatalogState) -> Result<T, CoordError>,
    {
        trace!("transact: {:?}", ops);

        #[derive(Debug, Clone)]
        enum Action {
            CreateDatabase {
                id: DatabaseId,
                oid: u32,
                name: String,
            },
            CreateSchema {
                id: SchemaId,
                oid: u32,
                database_id: DatabaseId,
                schema_name: String,
            },
            CreateRole {
                id: u64,
                oid: u32,
                name: String,
            },
            CreateComputeInstance {
                id: ComputeInstanceId,
                name: String,
                config: Option<ComputeInstanceIntrospectionConfig>,
                introspection_sources: Vec<(&'static BuiltinLog, GlobalId)>,
            },
            CreateComputeInstanceReplica {
                id: ReplicaId,
                name: String,
                on_cluster_name: String,
                config: ConcreteComputeInstanceReplicaConfig,
            },
            CreateItem {
                id: GlobalId,
                oid: u32,
                name: QualifiedObjectName,
                item: CatalogItem,
            },

            DropDatabase {
                id: DatabaseId,
            },
            DropSchema {
                database_id: DatabaseId,
                schema_id: SchemaId,
            },
            DropRole {
                name: String,
            },
            DropComputeInstance {
                name: String,
                introspection_source_index_ids: Vec<GlobalId>,
            },
            DropComputeInstanceReplica {
                name: String,
                compute_id: ComputeInstanceId,
            },
            DropItem(GlobalId),
            UpdateItem {
                id: GlobalId,
                to_name: QualifiedObjectName,
                to_item: CatalogItem,
            },
            UpdateComputeInstanceStatus {
                event: ComputeInstanceEvent,
            },
        }

        let drop_ids: HashSet<_> = ops
            .iter()
            .filter_map(|op| match op {
                Op::DropItem(id) => Some(*id),
                _ => None,
            })
            .collect();
        let temporary_drops = drop_ids
            .iter()
            .filter_map(|id| {
                let entry = self.get_entry(id);
                match entry.item.conn_id() {
                    Some(conn_id) => Some((conn_id, entry.name().item.clone())),
                    None => None,
                }
            })
            .collect();
        let temporary_ids = self.temporary_ids(&ops, temporary_drops)?;
        let mut builtin_table_updates = vec![];
        let mut actions = Vec::with_capacity(ops.len());
        let mut storage = self.storage().await;
        let mut tx = storage.transaction().await?;

        fn sql_type_to_object_type(sql_type: SqlCatalogItemType) -> ObjectType {
            match sql_type {
                SqlCatalogItemType::View => ObjectType::View,
                SqlCatalogItemType::RecordedView => ObjectType::RecordedView,
                SqlCatalogItemType::Source => ObjectType::Source,
                SqlCatalogItemType::Sink => ObjectType::Sink,
                SqlCatalogItemType::Index => ObjectType::Index,
                _ => unreachable!(),
            }
        }

        for op in ops {
            actions.extend(match op {
                Op::CreateDatabase {
                    name,
                    oid,
                    public_schema_oid,
                } => {
                    let database_id = tx.insert_database(&name)?;
                    vec![
                        Action::CreateDatabase {
                            id: database_id,
                            oid,
                            name,
                        },
                        Action::CreateSchema {
                            id: tx.insert_schema(database_id, DEFAULT_SCHEMA)?,
                            oid: public_schema_oid,
                            database_id,
                            schema_name: DEFAULT_SCHEMA.to_string(),
                        },
                    ]
                }
                Op::CreateSchema {
                    database_id,
                    schema_name,
                    oid,
                } => {
                    if is_reserved_name(&schema_name) {
                        return Err(CoordError::Catalog(Error::new(
                            ErrorKind::ReservedSchemaName(schema_name),
                        )));
                    }
                    let database_id = match database_id {
                        ResolvedDatabaseSpecifier::Id(id) => id,
                        ResolvedDatabaseSpecifier::Ambient => {
                            return Err(CoordError::Catalog(Error::new(
                                ErrorKind::ReadOnlySystemSchema(schema_name),
                            )));
                        }
                    };
                    vec![Action::CreateSchema {
                        id: tx.insert_schema(database_id, &schema_name)?,
                        oid,
                        database_id,
                        schema_name,
                    }]
                }
                Op::CreateRole { name, oid } => {
                    if is_reserved_name(&name) {
                        return Err(CoordError::Catalog(Error::new(
                            ErrorKind::ReservedRoleName(name),
                        )));
                    }
                    vec![Action::CreateRole {
                        id: tx.insert_role(&name)?,
                        oid,
                        name,
                    }]
                }
                Op::CreateComputeInstance {
                    name,
                    config,
                    introspection_sources,
                } => {
                    if is_reserved_name(&name) {
                        return Err(CoordError::Catalog(Error::new(
                            ErrorKind::ReservedClusterName(name),
                        )));
                    }
                    let id = tx.insert_compute_instance(&name, &config, &introspection_sources)?;
                    self.add_to_audit_log(
                        session,
                        &mut tx,
                        &mut builtin_table_updates,
                        EventType::Create,
                        ObjectType::Cluster,
                        EventDetails::NameV1(mz_audit_log::NameV1 { name: name.clone() }),
                    )?;
                    vec![Action::CreateComputeInstance {
                        id,
                        name,
                        config,
                        introspection_sources,
                    }]
                }
                Op::CreateComputeInstanceReplica {
                    name,
                    on_cluster_name,
                    config,
                    logical_size,
                } => {
                    if is_reserved_name(&name) {
                        return Err(CoordError::Catalog(Error::new(
                            ErrorKind::ReservedReplicaName(name),
                        )));
                    }
                    if let Some(logical_size) = logical_size {
                        let details = EventDetails::CreateComputeInstanceReplicaV1(
                            mz_audit_log::CreateComputeInstanceReplicaV1 {
                                cluster_name: on_cluster_name.clone(),
                                replica_name: name.clone(),
                                logical_size,
                            },
                        );
                        self.add_to_audit_log(
                            session,
                            &mut tx,
                            &mut builtin_table_updates,
                            EventType::Create,
                            ObjectType::ClusterReplica,
                            details,
                        )?;
                    }
                    vec![Action::CreateComputeInstanceReplica {
                        id: tx.insert_compute_instance_replica(&on_cluster_name, &name, &config)?,
                        name,
                        on_cluster_name,
                        config,
                    }]
                }
                Op::CreateItem {
                    id,
                    oid,
                    name,
                    item,
                } => {
                    if item.is_temporary() {
                        if name.qualifiers.database_spec != ResolvedDatabaseSpecifier::Ambient
                            || name.qualifiers.schema_spec != SchemaSpecifier::Temporary
                        {
                            return Err(CoordError::Catalog(Error::new(
                                ErrorKind::InvalidTemporarySchema,
                            )));
                        }
                    } else {
                        if let Some(temp_id) =
                            item.uses().iter().find(|id| match self.try_get_entry(*id) {
                                Some(entry) => entry.item().is_temporary(),
                                None => temporary_ids.contains(id),
                            })
                        {
                            let temp_item = self.get_entry(temp_id);
                            return Err(CoordError::Catalog(Error::new(
                                ErrorKind::InvalidTemporaryDependency(
                                    temp_item.name().item.clone(),
                                ),
                            )));
                        }
                        if let ResolvedDatabaseSpecifier::Ambient = name.qualifiers.database_spec {
                            return Err(CoordError::Catalog(Error::new(
                                ErrorKind::ReadOnlySystemSchema(name.to_string()),
                            )));
                        }
                        let schema_id = name.qualifiers.schema_spec.clone().into();
                        let serialized_item = self.serialize_item(&item);
                        tx.insert_item(id, schema_id, &name.item, &serialized_item)?;
                    }

                    if Self::should_audit_log_item(&item) {
                        self.add_to_audit_log(
                            session,
                            &mut tx,
                            &mut builtin_table_updates,
                            EventType::Create,
                            sql_type_to_object_type(item.typ()),
                            EventDetails::FullNameV1(self.resolve_full_name_detail(&name, session)),
                        )?;
                    }

                    vec![Action::CreateItem {
                        id,
                        oid,
                        name,
                        item,
                    }]
                }
                Op::DropDatabase { id } => {
                    tx.remove_database(&id)?;
                    builtin_table_updates.push(self.state.pack_database_update(&id, -1));
                    vec![Action::DropDatabase { id }]
                }
                Op::DropSchema {
                    database_id,
                    schema_id,
                } => {
                    tx.remove_schema(&database_id, &schema_id)?;
                    builtin_table_updates.push(self.state.pack_schema_update(
                        &ResolvedDatabaseSpecifier::Id(database_id.clone()),
                        &schema_id,
                        -1,
                    ));
                    vec![Action::DropSchema {
                        database_id,
                        schema_id,
                    }]
                }
                Op::DropRole { name } => {
                    tx.remove_role(&name)?;
                    builtin_table_updates.push(self.state.pack_role_update(&name, -1));
                    vec![Action::DropRole { name }]
                }
                Op::DropComputeInstance { name } => {
                    let introspection_source_index_ids = tx.remove_compute_instance(&name)?;
                    builtin_table_updates.push(self.state.pack_compute_instance_update(&name, -1));
                    for id in &introspection_source_index_ids {
                        builtin_table_updates.extend(self.state.pack_item_update(*id, -1));
                    }
                    self.add_to_audit_log(
                        session,
                        &mut tx,
                        &mut builtin_table_updates,
                        EventType::Drop,
                        ObjectType::Cluster,
                        EventDetails::NameV1(mz_audit_log::NameV1 { name: name.clone() }),
                    )?;
                    vec![Action::DropComputeInstance {
                        name,
                        introspection_source_index_ids,
                    }]
                }
                Op::DropComputeInstanceReplica { name, compute_id } => {
                    tx.remove_compute_instance_replica(&name, compute_id)?;

                    let instance = &self.state.compute_instances_by_id[&compute_id];
                    let replica_id = instance.replica_id_by_name[&name];
                    let replica = &instance.replicas_by_id[&replica_id];
                    for process_id in replica.process_status.keys() {
                        let update = self.state.pack_compute_instance_status_update(
                            compute_id,
                            replica_id,
                            *process_id,
                            -1,
                        );
                        builtin_table_updates.push(update);
                    }

                    builtin_table_updates.push(
                        self.state
                            .pack_compute_instance_replica_update(compute_id, &name, -1),
                    );

                    let details = EventDetails::DropComputeInstanceReplicaV1(
                        mz_audit_log::DropComputeInstanceReplicaV1 {
                            cluster_name: instance.name.clone(),
                            replica_name: name.clone(),
                        },
                    );
                    self.add_to_audit_log(
                        session,
                        &mut tx,
                        &mut builtin_table_updates,
                        EventType::Drop,
                        ObjectType::ClusterReplica,
                        details,
                    )?;

                    vec![Action::DropComputeInstanceReplica { name, compute_id }]
                }
                Op::DropItem(id) => {
                    let entry = self.get_entry(&id);
                    if !entry.item().is_temporary() {
                        tx.remove_item(id)?;
                    }
                    builtin_table_updates.extend(self.state.pack_item_update(id, -1));
                    if Self::should_audit_log_item(&entry.item) {
                        self.add_to_audit_log(
                            session,
                            &mut tx,
                            &mut builtin_table_updates,
                            EventType::Drop,
                            sql_type_to_object_type(entry.item().typ()),
                            EventDetails::FullNameV1(
                                self.resolve_full_name_detail(&entry.name, session),
                            ),
                        )?;
                    }
                    vec![Action::DropItem(id)]
                }
                Op::RenameItem {
                    id,
                    to_name,
                    current_full_name,
                } => {
                    let mut actions = Vec::new();

                    let entry = self.get_entry(&id);
                    if let CatalogItem::Type(_) = entry.item() {
                        return Err(CoordError::Catalog(Error::new(ErrorKind::TypeRename(
                            current_full_name.to_string(),
                        ))));
                    }

                    let details = EventDetails::RenameItemV1(mz_audit_log::RenameItemV1 {
                        previous_name: self.full_name_detail(&current_full_name),
                        new_name: to_name.clone(),
                    });
                    if Self::should_audit_log_item(&entry.item) {
                        self.add_to_audit_log(
                            session,
                            &mut tx,
                            &mut builtin_table_updates,
                            EventType::Alter,
                            sql_type_to_object_type(entry.item().typ()),
                            details,
                        )?;
                    }

                    let mut to_full_name = current_full_name.clone();
                    to_full_name.item = to_name.clone();

                    let mut to_qualified_name = entry.name().clone();
                    to_qualified_name.item = to_name;

                    // Rename item itself.
                    let item = entry
                        .item
                        .rename_item_refs(
                            current_full_name.clone(),
                            to_full_name.item.clone(),
                            true,
                        )
                        .map_err(|e| {
                            Error::new(ErrorKind::from(AmbiguousRename {
                                depender: self
                                    .resolve_full_name(&entry.name, entry.conn_id())
                                    .to_string(),
                                dependee: self
                                    .resolve_full_name(&entry.name, entry.conn_id())
                                    .to_string(),
                                message: e,
                            }))
                        })?;
                    let serialized_item = self.serialize_item(&item);

                    for id in entry.used_by() {
                        let dependent_item = self.get_entry(id);
                        let to_item = dependent_item
                            .item
                            .rename_item_refs(
                                current_full_name.clone(),
                                to_full_name.item.clone(),
                                false,
                            )
                            .map_err(|e| {
                                Error::new(ErrorKind::from(AmbiguousRename {
                                    depender: self
                                        .resolve_full_name(
                                            &dependent_item.name,
                                            dependent_item.conn_id(),
                                        )
                                        .to_string(),
                                    dependee: self
                                        .resolve_full_name(&entry.name, entry.conn_id())
                                        .to_string(),
                                    message: e,
                                }))
                            })?;

                        if !item.is_temporary() {
                            let serialized_item = self.serialize_item(&to_item);
                            tx.update_item(*id, &dependent_item.name().item, &serialized_item)?;
                        }
                        builtin_table_updates.extend(self.state.pack_item_update(*id, -1));

                        actions.push(Action::UpdateItem {
                            id: id.clone(),
                            to_name: dependent_item.name().clone(),
                            to_item,
                        });
                    }
                    if !item.is_temporary() {
                        tx.update_item(id, &to_full_name.item, &serialized_item)?;
                    }
                    builtin_table_updates.extend(self.state.pack_item_update(id, -1));
                    actions.push(Action::UpdateItem {
                        id,
                        to_name: to_qualified_name,
                        to_item: item,
                    });
                    actions
                }
                Op::UpdateComputeInstanceStatus { event } => {
                    // When we receive the first status update for a given
                    // replica process, there is no entry in the builtin table
                    // yet, so we must make sure to not try to delete one.
                    let status_known = self
                        .state
                        .try_get_compute_instance_status(
                            event.instance_id,
                            event.replica_id,
                            event.process_id,
                        )
                        .is_some();
                    if status_known {
                        let update = self.state.pack_compute_instance_status_update(
                            event.instance_id,
                            event.replica_id,
                            event.process_id,
                            -1,
                        );
                        builtin_table_updates.push(update);
                    }

                    vec![Action::UpdateComputeInstanceStatus { event }]
                }
            });
        }

        // Prepare a candidate catalog state.
        let mut state = self.state.clone();

        for action in actions {
            match action {
                Action::CreateDatabase { id, oid, name } => {
                    info!("create database {}", name);
                    state.database_by_id.insert(
                        id.clone(),
                        Database {
                            name: name.clone(),
                            id: id.clone(),
                            oid,
                            schemas_by_id: BTreeMap::new(),
                            schemas_by_name: BTreeMap::new(),
                        },
                    );
                    state.database_by_name.insert(name.clone(), id.clone());
                    builtin_table_updates.push(state.pack_database_update(&id, 1));
                }

                Action::CreateSchema {
                    id,
                    oid,
                    database_id,
                    schema_name,
                } => {
                    info!(
                        "create schema {}.{}",
                        state.get_database(&database_id).name,
                        schema_name
                    );
                    let db = state.database_by_id.get_mut(&database_id).unwrap();
                    db.schemas_by_id.insert(
                        id.clone(),
                        Schema {
                            name: QualifiedSchemaName {
                                database: ResolvedDatabaseSpecifier::Id(database_id.clone()),
                                schema: schema_name.clone(),
                            },
                            id: SchemaSpecifier::Id(id.clone()),
                            oid,
                            items: BTreeMap::new(),
                            functions: BTreeMap::new(),
                        },
                    );
                    db.schemas_by_name.insert(schema_name.clone(), id.clone());
                    builtin_table_updates.push(state.pack_schema_update(
                        &ResolvedDatabaseSpecifier::Id(database_id.clone()),
                        &id,
                        1,
                    ));
                }

                Action::CreateRole { id, oid, name } => {
                    info!("create role {}", name);
                    state.roles.insert(
                        name.clone(),
                        Role {
                            name: name.clone(),
                            id,
                            oid,
                        },
                    );
                    builtin_table_updates.push(state.pack_role_update(&name, 1));
                }

                Action::CreateComputeInstance {
                    id,
                    name,
                    config,
                    introspection_sources,
                } => {
                    info!("create cluster {}", name);
                    let introspection_source_index_ids: Vec<GlobalId> =
                        introspection_sources.iter().map(|(_, id)| *id).collect();
                    state
                        .insert_compute_instance(id, name.clone(), config, introspection_sources)
                        .await;
                    builtin_table_updates.push(state.pack_compute_instance_update(&name, 1));
                    for id in introspection_source_index_ids {
                        builtin_table_updates.extend(state.pack_item_update(id, 1));
                    }
                }

                Action::CreateComputeInstanceReplica {
                    id,
                    name,
                    on_cluster_name,
                    config,
                } => {
                    info!("create replica {} of instance {}", name, on_cluster_name);
                    let compute_instance_id = state.compute_instances_by_name[&on_cluster_name];
                    state.insert_compute_instance_replica(
                        compute_instance_id,
                        name.clone(),
                        id,
                        config,
                    );
                    builtin_table_updates.push(state.pack_compute_instance_replica_update(
                        compute_instance_id,
                        &name,
                        1,
                    ));
                }

                Action::CreateItem {
                    id,
                    oid,
                    name,
                    item,
                } => {
                    state.insert_item(id, oid, name, item);
                    builtin_table_updates.extend(state.pack_item_update(id, 1));
                }

                Action::DropDatabase { id } => {
                    let db = state.database_by_id.get(&id).unwrap();
                    state.database_by_name.remove(db.name());
                    state.database_by_id.remove(&id);
                }

                Action::DropSchema {
                    database_id,
                    schema_id,
                } => {
                    let db = state.database_by_id.get_mut(&database_id).unwrap();
                    let schema = db.schemas_by_id.get(&schema_id).unwrap();
                    db.schemas_by_name.remove(&schema.name.schema);
                    db.schemas_by_id.remove(&schema_id);
                }

                Action::DropRole { name } => {
                    if state.roles.remove(&name).is_some() {
                        info!("drop role {}", name);
                    }
                }

                Action::DropComputeInstance {
                    name,
                    introspection_source_index_ids,
                } => {
                    for id in introspection_source_index_ids {
                        state
                            .entry_by_id
                            .remove(&id)
                            .expect("introspection source index does not exist");
                    }

                    let id = state
                        .compute_instances_by_name
                        .remove(&name)
                        .expect("can only drop known instances");

                    let instance = state
                        .compute_instances_by_id
                        .remove(&id)
                        .expect("can only drop known instances");

                    assert!(
                        instance.indexes.is_empty() && instance.replicas_by_id.is_empty(),
                        "not all items dropped before compute instance"
                    );
                }

                Action::DropComputeInstanceReplica { name, compute_id } => {
                    let instance = state
                        .compute_instances_by_id
                        .get_mut(&compute_id)
                        .expect("can only drop replicas from known instances");
                    let replica_id = instance.replica_id_by_name.remove(&name).unwrap();
                    assert!(instance.replicas_by_id.remove(&replica_id).is_some());
                    assert!(instance.replica_id_by_name.len() == instance.replicas_by_id.len());
                }

                Action::DropItem(id) => {
                    let metadata = state.entry_by_id.remove(&id).unwrap();
                    if !metadata.item.is_placeholder() {
                        info!(
                            "drop {} {} ({})",
                            metadata.item_type(),
                            state.resolve_full_name(&metadata.name, metadata.conn_id()),
                            id
                        );
                    }
                    for u in metadata.uses() {
                        if let Some(dep_metadata) = state.entry_by_id.get_mut(&u) {
                            dep_metadata.used_by.retain(|u| *u != metadata.id)
                        }
                    }

                    let conn_id = metadata.item.conn_id().unwrap_or(SYSTEM_CONN_ID);
                    let schema = state.get_schema_mut(
                        &metadata.name().qualifiers.database_spec,
                        &metadata.name().qualifiers.schema_spec,
                        conn_id,
                    );
                    schema
                        .items
                        .remove(&metadata.name().item)
                        .expect("catalog out of sync");

                    if let CatalogItem::Index(Index {
                        compute_instance, ..
                    })
                    | CatalogItem::Sink(Sink {
                        compute_instance, ..
                    }) = metadata.item
                    {
                        assert!(
                            state
                                .compute_instances_by_id
                                .get_mut(&compute_instance)
                                .unwrap()
                                .indexes
                                .remove(&id),
                            "catalog out of sync"
                        );
                    };
                }

                Action::UpdateItem {
                    id,
                    to_name,
                    to_item,
                } => {
                    let old_entry = state.entry_by_id.remove(&id).unwrap();
                    info!(
                        "update {} {} ({})",
                        old_entry.item_type(),
                        state.resolve_full_name(&old_entry.name, old_entry.conn_id()),
                        id
                    );
                    assert_eq!(old_entry.uses(), to_item.uses());
                    let conn_id = old_entry.item().conn_id().unwrap_or(SYSTEM_CONN_ID);
                    let schema = &mut state.get_schema_mut(
                        &old_entry.name().qualifiers.database_spec,
                        &old_entry.name().qualifiers.schema_spec,
                        conn_id,
                    );
                    schema.items.remove(&old_entry.name().item);
                    let mut new_entry = old_entry.clone();
                    new_entry.name = to_name;
                    new_entry.item = to_item;
                    schema.items.insert(new_entry.name().item.clone(), id);
                    state.entry_by_id.insert(id, new_entry.clone());
                    builtin_table_updates.extend(state.pack_item_update(id, 1));
                }

                Action::UpdateComputeInstanceStatus { event } => {
                    // It is possible that we receive a status update for a
                    // replica that has already been dropped from the catalog.
                    // In this case, `try_insert_compute_instance_status`
                    // returns `false` and we ignore the event.
                    if state.try_insert_compute_instance_status(event.clone()) {
                        let update = state.pack_compute_instance_status_update(
                            event.instance_id,
                            event.replica_id,
                            event.process_id,
                            1,
                        );
                        builtin_table_updates.push(update);
                    }
                }
            }
        }

        let result = f(&state)?;

        // The user closure was successful, apply the updates.
        tx.commit().await?;
        // Dropping here keeps the mutable borrow on self, preventing us accidentally
        // mutating anything until after f is executed.
        drop(storage);
        self.state = state;
        self.transient_revision += 1;

        Ok((builtin_table_updates, result))
    }

    fn serialize_item(&self, item: &CatalogItem) -> Vec<u8> {
        let item = match item {
            CatalogItem::Table(table) => SerializedCatalogItem::V1 {
                create_sql: table.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Log(_) => unreachable!("builtin logs cannot be serialized"),
            CatalogItem::Source(source) => SerializedCatalogItem::V1 {
                create_sql: source.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::View(view) => SerializedCatalogItem::V1 {
                create_sql: view.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Index(index) => SerializedCatalogItem::V1 {
                create_sql: index.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Sink(sink) => SerializedCatalogItem::V1 {
                create_sql: sink.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Type(typ) => SerializedCatalogItem::V1 {
                create_sql: typ.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Secret(secret) => SerializedCatalogItem::V1 {
                create_sql: secret.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Connection(connection) => SerializedCatalogItem::V1 {
                create_sql: connection.create_sql.clone(),
                eval_env: None,
            },
            CatalogItem::Func(_) => unreachable!("cannot serialize functions yet"),
        };
        serde_json::to_vec(&item).expect("catalog serialization cannot fail")
    }

    fn deserialize_item(&self, bytes: Vec<u8>) -> Result<CatalogItem, anyhow::Error> {
        let SerializedCatalogItem::V1 {
            create_sql,
            eval_env: _,
        } = serde_json::from_slice(&bytes)?;
        self.parse_item(create_sql, Some(&PlanContext::zero()))
    }

    // Parses the given SQL string into a `CatalogItem`.
    fn parse_item(
        &self,
        create_sql: String,
        pcx: Option<&PlanContext>,
    ) -> Result<CatalogItem, anyhow::Error> {
        let session_catalog = self.for_system_session();
        let stmt = mz_sql::parse::parse(&create_sql)?.into_element();
        let (stmt, depends_on) = mz_sql::names::resolve(&session_catalog, stmt)?;
        let depends_on = depends_on.into_iter().collect();
        let plan = mz_sql::plan::plan(pcx, &session_catalog, stmt, &Params::empty())?;
        Ok(match plan {
            Plan::CreateTable(CreateTablePlan { table, .. }) => CatalogItem::Table(Table {
                create_sql: table.create_sql,
                desc: table.desc,
                defaults: table.defaults,
                conn_id: None,
                depends_on,
            }),
            Plan::CreateSource(CreateSourcePlan {
                source,
                remote,
                timeline,
                ..
            }) => CatalogItem::Source(Source {
                create_sql: source.create_sql,
                source_desc: source.source_desc,
                desc: source.desc,
                timeline,
                depends_on,
                remote_addr: remote,
            }),
            Plan::CreateView(CreateViewPlan { view, .. }) => {
                let mut optimizer = Optimizer::logical_optimizer();
                let optimized_expr = optimizer.optimize(view.expr)?;
                let desc = RelationDesc::new(optimized_expr.typ(), view.column_names);
                CatalogItem::View(View {
                    create_sql: view.create_sql,
                    optimized_expr,
                    desc,
                    conn_id: None,
                    depends_on,
                })
            }
            Plan::CreateRecordedView(CreateRecordedViewPlan {
                recorded_view: _, ..
            }) => {
                // TODO(teskje): implement
                bail!("not yet implemented")
            }
            Plan::CreateIndex(CreateIndexPlan { index, .. }) => CatalogItem::Index(Index {
                create_sql: index.create_sql,
                on: index.on,
                keys: index.keys,
                conn_id: None,
                depends_on,
                compute_instance: index.compute_instance,
            }),
            Plan::CreateSink(CreateSinkPlan {
                sink,
                with_snapshot,
                ..
            }) => CatalogItem::Sink(Sink {
                create_sql: sink.create_sql,
                from: sink.from,
                connection: SinkConnectionState::Pending(sink.connection_builder),
                envelope: sink.envelope,
                with_snapshot,
                depends_on,
                compute_instance: sink.compute_instance,
            }),
            Plan::CreateType(CreateTypePlan { typ, .. }) => CatalogItem::Type(Type {
                create_sql: typ.create_sql,
                details: CatalogTypeDetails {
                    array_id: None,
                    typ: typ.inner,
                },
                depends_on,
            }),
            Plan::CreateSecret(CreateSecretPlan { secret, .. }) => CatalogItem::Secret(Secret {
                create_sql: secret.create_sql,
            }),
            Plan::CreateConnection(CreateConnectionPlan { connection, .. }) => {
                CatalogItem::Connection(Connection {
                    create_sql: connection.create_sql,
                    connection: connection.connection,
                })
            }
            _ => bail!("catalog entry generated inappropriate plan"),
        })
    }

    pub fn uses_tables(&self, id: GlobalId) -> bool {
        self.state.uses_tables(id)
    }

    /// Return the names of all log sources the given object depends on.
    pub fn log_dependencies(&self, id: GlobalId) -> Vec<GlobalId> {
        self.state.log_dependencies(id)
    }

    /// Serializes the catalog's in-memory state.
    ///
    /// There are no guarantees about the format of the serialized state, except
    /// that the serialized state for two identical catalogs will compare
    /// identically.
    pub fn dump(&self) -> String {
        self.state.dump()
    }

    pub fn config(&self) -> &mz_sql::catalog::CatalogConfig {
        self.state.config()
    }

    pub fn entries(&self) -> impl Iterator<Item = &CatalogEntry> {
        self.state.entry_by_id.values()
    }

    pub fn compute_instances(&self) -> impl Iterator<Item = &ComputeInstance> {
        self.state.compute_instances_by_id.values()
    }

    pub async fn allocate_introspection_source_indexes(
        &mut self,
    ) -> Vec<(&'static BuiltinLog, GlobalId)> {
        let log_amount = BUILTINS::logs().count();
        let system_ids = self
            .storage()
            .await
            .allocate_system_ids(
                log_amount
                    .try_into()
                    .expect("builtin logs should fit into u64"),
            )
            .await
            .expect("cannot fail to allocate system ids");
        BUILTINS::logs().zip(system_ids.into_iter()).collect()
    }

    pub fn pack_item_update(&self, id: GlobalId, diff: Diff) -> Vec<BuiltinTableUpdate> {
        self.state.pack_item_update(id, diff)
    }
}

fn is_reserved_name(name: &str) -> bool {
    name.starts_with("mz_") || name.starts_with("pg_")
}

#[derive(Debug, Clone)]
pub enum Op {
    CreateDatabase {
        name: String,
        oid: u32,
        public_schema_oid: u32,
    },
    CreateSchema {
        database_id: ResolvedDatabaseSpecifier,
        schema_name: String,
        oid: u32,
    },
    CreateRole {
        name: String,
        oid: u32,
    },
    CreateComputeInstance {
        name: String,
        config: Option<ComputeInstanceIntrospectionConfig>,
        introspection_sources: Vec<(&'static BuiltinLog, GlobalId)>,
    },
    CreateComputeInstanceReplica {
        name: String,
        config: ConcreteComputeInstanceReplicaConfig,
        on_cluster_name: String,
        logical_size: Option<String>,
    },
    CreateItem {
        id: GlobalId,
        oid: u32,
        name: QualifiedObjectName,
        item: CatalogItem,
    },
    DropDatabase {
        id: DatabaseId,
    },
    DropSchema {
        database_id: DatabaseId,
        schema_id: SchemaId,
    },
    DropRole {
        name: String,
    },
    DropComputeInstance {
        name: String,
    },
    DropComputeInstanceReplica {
        name: String,
        compute_id: ComputeInstanceId,
    },
    /// Unconditionally removes the identified items. It is required that the
    /// IDs come from the output of `plan_remove`; otherwise consistency rules
    /// may be violated.
    DropItem(GlobalId),
    RenameItem {
        id: GlobalId,
        current_full_name: FullObjectName,
        to_name: String,
    },
    UpdateComputeInstanceStatus {
        event: ComputeInstanceEvent,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum SerializedCatalogItem {
    V1 {
        create_sql: String,
        // The name "eval_env" is historical.
        eval_env: Option<SerializedPlanContext>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SerializedPlanContext {
    pub logical_time: Option<u64>,
    pub wall_time: Option<DateTime<Utc>>,
}

impl From<SerializedPlanContext> for PlanContext {
    fn from(cx: SerializedPlanContext) -> PlanContext {
        PlanContext {
            wall_time: cx.wall_time.unwrap_or_else(|| Utc.timestamp(0, 0)),
            qgm_optimizations: false,
        }
    }
}

impl From<PlanContext> for SerializedPlanContext {
    fn from(cx: PlanContext) -> SerializedPlanContext {
        SerializedPlanContext {
            logical_time: None,
            wall_time: Some(cx.wall_time),
        }
    }
}

impl ConnCatalog<'_> {
    fn resolve_item_name(
        &self,
        name: &PartialObjectName,
    ) -> Result<&QualifiedObjectName, SqlCatalogError> {
        self.resolve_item(name).map(|entry| entry.name())
    }

    /// returns a `PartialObjectName` with the minimum amount of qualifiers to unambiguously resolve
    /// the object.
    fn minimal_qualification(&self, qualified_name: &QualifiedObjectName) -> PartialObjectName {
        let database_id = match &qualified_name.qualifiers.database_spec {
            ResolvedDatabaseSpecifier::Ambient => None,
            ResolvedDatabaseSpecifier::Id(id)
                if self.database.is_some() && self.database == Some(*id) =>
            {
                None
            }
            ResolvedDatabaseSpecifier::Id(id) => Some(id.clone()),
        };

        let schema_spec = if database_id.is_none()
            && self.resolve_item_name(&PartialObjectName {
                database: None,
                schema: None,
                item: qualified_name.item.clone(),
            }) == Ok(qualified_name)
        {
            None
        } else {
            // If `search_path` does not contain `full_name.schema`, the
            // `PartialName` must contain it.
            Some(qualified_name.qualifiers.schema_spec.clone())
        };

        let res = PartialObjectName {
            database: database_id.map(|id| self.get_database(&id).name().to_string()),
            schema: schema_spec.map(|spec| {
                self.get_schema(&qualified_name.qualifiers.database_spec, &spec)
                    .name()
                    .schema
                    .clone()
            }),
            item: qualified_name.item.clone(),
        };
        assert_eq!(self.resolve_item_name(&res), Ok(qualified_name));
        res
    }
}

impl ExprHumanizer for ConnCatalog<'_> {
    fn humanize_id(&self, id: GlobalId) -> Option<String> {
        self.state
            .entry_by_id
            .get(&id)
            .map(|entry| entry.name())
            .map(|name| self.resolve_full_name(name).to_string())
    }

    fn humanize_scalar_type(&self, typ: &ScalarType) -> String {
        use ScalarType::*;

        match typ {
            Array(t) => format!("{}[]", self.humanize_scalar_type(t)),
            List {
                custom_id: Some(global_id),
                ..
            }
            | Map {
                custom_id: Some(global_id),
                ..
            } => {
                let item = self.get_item(global_id);
                self.minimal_qualification(item.name()).to_string()
            }
            List { element_type, .. } => {
                format!("{} list", self.humanize_scalar_type(element_type))
            }
            Map { value_type, .. } => format!(
                "map[{}=>{}]",
                self.humanize_scalar_type(&ScalarType::String),
                self.humanize_scalar_type(value_type)
            ),
            Record {
                custom_id: Some(id),
                ..
            } => {
                let item = self.get_item(id);
                self.minimal_qualification(item.name()).to_string()
            }
            Record { fields, .. } => format!(
                "record({})",
                fields
                    .iter()
                    .map(|f| format!("{}: {}", f.0, self.humanize_column_type(&f.1)))
                    .join(",")
            ),
            PgLegacyChar => "\"char\"".into(),
            ty => {
                let pgrepr_type = mz_pgrepr::Type::from(ty);
                let pg_catalog_schema =
                    SchemaSpecifier::Id(self.state.get_pg_catalog_schema_id().clone());

                let res = if self
                    .effective_search_path(true)
                    .iter()
                    .any(|(_, schema)| schema == &pg_catalog_schema)
                {
                    pgrepr_type.name().to_string()
                } else {
                    // If PG_CATALOG_SCHEMA is not in search path, you need
                    // qualified object name to refer to type.
                    let name = QualifiedObjectName {
                        qualifiers: ObjectQualifiers {
                            database_spec: ResolvedDatabaseSpecifier::Ambient,
                            schema_spec: pg_catalog_schema,
                        },
                        item: pgrepr_type.name().to_string(),
                    };
                    self.resolve_full_name(&name).to_string()
                };
                res
            }
        }
    }
}

impl SessionCatalog for ConnCatalog<'_> {
    fn active_user(&self) -> &str {
        &self.user
    }

    fn get_prepared_statement_desc(&self, name: &str) -> Option<&StatementDesc> {
        self.prepared_statements
            .as_ref()
            .map(|ps| ps.get(name).map(|ps| ps.desc()))
            .flatten()
    }

    fn active_database(&self) -> Option<&DatabaseId> {
        self.database.as_ref()
    }

    fn active_compute_instance(&self) -> &str {
        &self.compute_instance
    }

    fn resolve_database(
        &self,
        database_name: &str,
    ) -> Result<&dyn mz_sql::catalog::CatalogDatabase, SqlCatalogError> {
        Ok(self.state.resolve_database(database_name)?)
    }

    fn get_database(&self, id: &DatabaseId) -> &dyn mz_sql::catalog::CatalogDatabase {
        self.state
            .database_by_id
            .get(id)
            .expect("database doesn't exist")
    }

    fn resolve_schema(
        &self,
        database_name: Option<&str>,
        schema_name: &str,
    ) -> Result<&dyn mz_sql::catalog::CatalogSchema, SqlCatalogError> {
        Ok(self.state.resolve_schema(
            self.database.as_ref(),
            database_name,
            schema_name,
            self.conn_id,
        )?)
    }

    fn resolve_schema_in_database(
        &self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_name: &str,
    ) -> Result<&dyn mz_sql::catalog::CatalogSchema, SqlCatalogError> {
        Ok(self
            .state
            .resolve_schema_in_database(database_spec, schema_name, self.conn_id)?)
    }

    fn get_schema(
        &self,
        database_spec: &ResolvedDatabaseSpecifier,
        schema_spec: &SchemaSpecifier,
    ) -> &dyn CatalogSchema {
        self.state
            .get_schema(database_spec, schema_spec, self.conn_id)
    }

    fn is_system_schema(&self, schema: &str) -> bool {
        self.state.is_system_schema(schema)
    }

    fn resolve_role(
        &self,
        role_name: &str,
    ) -> Result<&dyn mz_sql::catalog::CatalogRole, SqlCatalogError> {
        match self.state.roles.get(role_name) {
            Some(role) => Ok(role),
            None => Err(SqlCatalogError::UnknownRole(role_name.into())),
        }
    }

    fn resolve_compute_instance(
        &self,
        compute_instance_name: Option<&str>,
    ) -> Result<&dyn mz_sql::catalog::CatalogComputeInstance, SqlCatalogError> {
        self.state
            .resolve_compute_instance(
                compute_instance_name.unwrap_or_else(|| self.active_compute_instance()),
            )
            .map(|compute_instance| {
                compute_instance as &dyn mz_sql::catalog::CatalogComputeInstance
            })
    }

    fn resolve_item(
        &self,
        name: &PartialObjectName,
    ) -> Result<&dyn mz_sql::catalog::CatalogItem, SqlCatalogError> {
        Ok(self.state.resolve_entry(
            self.database.as_ref(),
            &self.effective_search_path(true),
            name,
            self.conn_id,
        )?)
    }

    fn resolve_function(
        &self,
        name: &PartialObjectName,
    ) -> Result<&dyn mz_sql::catalog::CatalogItem, SqlCatalogError> {
        Ok(self.state.resolve_function(
            self.database.as_ref(),
            &self.effective_search_path(false),
            name,
            self.conn_id,
        )?)
    }

    fn try_get_item(&self, id: &GlobalId) -> Option<&dyn mz_sql::catalog::CatalogItem> {
        self.state
            .try_get_entry(id)
            .map(|item| item as &dyn mz_sql::catalog::CatalogItem)
    }

    fn get_item(&self, id: &GlobalId) -> &dyn mz_sql::catalog::CatalogItem {
        self.state.get_entry(id)
    }

    fn item_exists(&self, name: &QualifiedObjectName) -> bool {
        self.state.item_exists(name, self.conn_id)
    }

    fn find_available_name(&self, name: QualifiedObjectName) -> QualifiedObjectName {
        self.state.find_available_name(name, self.conn_id)
    }

    fn resolve_full_name(&self, name: &QualifiedObjectName) -> FullObjectName {
        self.state.resolve_full_name(name, Some(self.conn_id))
    }

    fn config(&self) -> &mz_sql::catalog::CatalogConfig {
        &self.state.config()
    }

    fn now(&self) -> EpochMillis {
        (self.state.config().now)()
    }
}

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()
    }
}

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()
    }
}

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

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

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

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

    fn indexes(&self) -> &HashSet<GlobalId> {
        &self.indexes
    }

    fn replica_names(&self) -> HashSet<&String> {
        self.replica_id_by_name.keys().collect::<HashSet<_>>()
    }
}

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

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

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

    fn desc(&self, name: &FullObjectName) -> Result<Cow<RelationDesc>, SqlCatalogError> {
        Ok(self.desc(name)?)
    }

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

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

    fn connection(&self) -> Result<&mz_storage::client::connections::Connection, SqlCatalogError> {
        Ok(&self.connection()?.connection)
    }

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

    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 table_details(&self) -> Option<&[Expr<Aug>]> {
        if let CatalogItem::Table(Table { defaults, .. }) = self.item() {
            Some(defaults)
        } else {
            None
        }
    }

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

    fn uses(&self) -> &[GlobalId] {
        self.uses()
    }

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

#[cfg(test)]
mod tests {
    use mz_ore::now::NOW_ZERO;
    use mz_sql::names::{
        ObjectQualifiers, PartialObjectName, QualifiedObjectName, ResolvedDatabaseSpecifier,
        SchemaSpecifier,
    };

    use crate::catalog::{Catalog, Op};
    use crate::session::Session;

    /// System sessions have an empty `search_path` so it's necessary to
    /// schema-qualify all referenced items.
    ///
    /// Dummy (and ostensibly client) sessions contain system schemas in their
    /// search paths, so do not require schema qualification on system objects such
    /// as types.
    #[tokio::test]
    async fn test_minimal_qualification() -> Result<(), anyhow::Error> {
        struct TestCase {
            input: QualifiedObjectName,
            system_output: PartialObjectName,
            normal_output: PartialObjectName,
        }

        let catalog = Catalog::open_debug_sqlite(NOW_ZERO.clone()).await?;

        let test_cases = vec![
            TestCase {
                input: QualifiedObjectName {
                    qualifiers: ObjectQualifiers {
                        database_spec: ResolvedDatabaseSpecifier::Ambient,
                        schema_spec: SchemaSpecifier::Id(
                            catalog.get_pg_catalog_schema_id().clone(),
                        ),
                    },
                    item: "numeric".to_string(),
                },
                system_output: PartialObjectName {
                    database: None,
                    schema: None,
                    item: "numeric".to_string(),
                },
                normal_output: PartialObjectName {
                    database: None,
                    schema: None,
                    item: "numeric".to_string(),
                },
            },
            TestCase {
                input: QualifiedObjectName {
                    qualifiers: ObjectQualifiers {
                        database_spec: ResolvedDatabaseSpecifier::Ambient,
                        schema_spec: SchemaSpecifier::Id(
                            catalog.get_mz_catalog_schema_id().clone(),
                        ),
                    },
                    item: "mz_array_types".to_string(),
                },
                system_output: PartialObjectName {
                    database: None,
                    schema: None,
                    item: "mz_array_types".to_string(),
                },
                normal_output: PartialObjectName {
                    database: None,
                    schema: None,
                    item: "mz_array_types".to_string(),
                },
            },
        ];

        for tc in test_cases {
            assert_eq!(
                catalog
                    .for_system_session()
                    .minimal_qualification(&tc.input),
                tc.system_output
            );
            assert_eq!(
                catalog
                    .for_session(&Session::dummy())
                    .minimal_qualification(&tc.input),
                tc.normal_output
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_catalog_revision() -> Result<(), anyhow::Error> {
        let mut catalog = Catalog::open_debug_sqlite(NOW_ZERO.clone()).await?;
        assert_eq!(catalog.transient_revision(), 1);
        catalog
            .transact(
                None,
                vec![Op::CreateDatabase {
                    name: "test".to_string(),
                    oid: 1,
                    public_schema_oid: 2,
                }],
                |_catalog| Ok(()),
            )
            .await
            .unwrap();
        assert_eq!(catalog.transient_revision(), 2);
        drop(catalog);

        let catalog = Catalog::open_debug_sqlite(NOW_ZERO.clone()).await?;
        assert_eq!(catalog.transient_revision(), 1);

        Ok(())
    }

    #[tokio::test]
    async fn test_effective_search_path() -> Result<(), anyhow::Error> {
        let catalog = Catalog::open_debug_sqlite(NOW_ZERO.clone()).await?;
        let mz_catalog_schema = (
            ResolvedDatabaseSpecifier::Ambient,
            SchemaSpecifier::Id(catalog.state().get_mz_catalog_schema_id().clone()),
        );
        let pg_catalog_schema = (
            ResolvedDatabaseSpecifier::Ambient,
            SchemaSpecifier::Id(catalog.state().get_pg_catalog_schema_id().clone()),
        );
        let mz_temp_schema = (
            ResolvedDatabaseSpecifier::Ambient,
            SchemaSpecifier::Temporary,
        );

        // Behavior with the default search_schema (public)
        let session = Session::dummy();
        let conn_catalog = catalog.for_session(&session);
        assert_ne!(
            conn_catalog.effective_search_path(false),
            conn_catalog.search_path
        );
        assert_ne!(
            conn_catalog.effective_search_path(true),
            conn_catalog.search_path
        );
        assert_eq!(
            conn_catalog.effective_search_path(false),
            vec![
                mz_catalog_schema.clone(),
                pg_catalog_schema.clone(),
                conn_catalog.search_path[0].clone()
            ]
        );
        assert_eq!(
            conn_catalog.effective_search_path(true),
            vec![
                mz_temp_schema.clone(),
                mz_catalog_schema.clone(),
                pg_catalog_schema.clone(),
                conn_catalog.search_path[0].clone()
            ]
        );

        // missing schemas are added when missing
        let mut session = Session::dummy();
        session.vars_mut().set("search_path", "pg_catalog", false)?;
        let conn_catalog = catalog.for_session(&session);
        assert_ne!(
            conn_catalog.effective_search_path(false),
            conn_catalog.search_path
        );
        assert_ne!(
            conn_catalog.effective_search_path(true),
            conn_catalog.search_path
        );
        assert_eq!(
            conn_catalog.effective_search_path(false),
            vec![mz_catalog_schema.clone(), pg_catalog_schema.clone()]
        );
        assert_eq!(
            conn_catalog.effective_search_path(true),
            vec![
                mz_temp_schema.clone(),
                mz_catalog_schema.clone(),
                pg_catalog_schema.clone()
            ]
        );

        let mut session = Session::dummy();
        session.vars_mut().set("search_path", "mz_catalog", false)?;
        let conn_catalog = catalog.for_session(&session);
        assert_ne!(
            conn_catalog.effective_search_path(false),
            conn_catalog.search_path
        );
        assert_ne!(
            conn_catalog.effective_search_path(true),
            conn_catalog.search_path
        );
        assert_eq!(
            conn_catalog.effective_search_path(false),
            vec![pg_catalog_schema.clone(), mz_catalog_schema.clone()]
        );
        assert_eq!(
            conn_catalog.effective_search_path(true),
            vec![
                mz_temp_schema.clone(),
                pg_catalog_schema.clone(),
                mz_catalog_schema.clone()
            ]
        );

        let mut session = Session::dummy();
        session.vars_mut().set("search_path", "mz_temp", false)?;
        let conn_catalog = catalog.for_session(&session);
        assert_ne!(
            conn_catalog.effective_search_path(false),
            conn_catalog.search_path
        );
        assert_ne!(
            conn_catalog.effective_search_path(true),
            conn_catalog.search_path
        );
        assert_eq!(
            conn_catalog.effective_search_path(false),
            vec![
                mz_catalog_schema.clone(),
                pg_catalog_schema.clone(),
                mz_temp_schema.clone()
            ]
        );
        assert_eq!(
            conn_catalog.effective_search_path(true),
            vec![mz_catalog_schema, pg_catalog_schema, mz_temp_schema]
        );

        Ok(())
    }
}