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
// 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.

//! SQL purification.
//!
//! See the [crate-level documentation](crate) for details.

use std::collections::{BTreeMap, BTreeSet};
use std::iter;
use std::path::Path;
use std::sync::Arc;

use anyhow::anyhow;
use itertools::Itertools;
use mz_ccsr::{Client, GetByIdError, GetBySubjectError, Schema as CcsrSchema};
use mz_kafka_util::client::MzClientContext;
use mz_ore::error::ErrorExt;
use mz_ore::iter::IteratorExt;
use mz_ore::str::StrExt;
use mz_postgres_util::replication::WalLevel;
use mz_proto::RustType;
use mz_repr::{strconv, GlobalId, Timestamp};
use mz_sql_parser::ast::display::AstDisplay;
use mz_sql_parser::ast::visit::{visit_function, Visit};
use mz_sql_parser::ast::visit_mut::{visit_expr_mut, VisitMut};
use mz_sql_parser::ast::{
    AlterSourceAction, AlterSourceAddSubsourceOptionName, AlterSourceStatement, AvroDocOn,
    CreateMaterializedViewStatement, CreateSinkConnection, CreateSinkStatement,
    CreateSubsourceOption, CreateSubsourceOptionName, CsrConfigOption, CsrConfigOptionName,
    CsrConnection, CsrSeedAvro, CsrSeedProtobuf, CsrSeedProtobufSchema, DeferredItemName,
    DocOnIdentifier, DocOnSchema, Expr, Function, FunctionArgs, Ident, KafkaSourceConfigOption,
    KafkaSourceConfigOptionName, MaterializedViewOption, MaterializedViewOptionName,
    MySqlConfigOption, MySqlConfigOptionName, PgConfigOption, PgConfigOptionName, RawItemName,
    ReaderSchemaSelectionStrategy, RefreshAtOptionValue, RefreshEveryOptionValue,
    RefreshOptionValue, SourceEnvelope, Statement, UnresolvedItemName,
};
use mz_storage_types::configuration::StorageConfiguration;
use mz_storage_types::connections::inline::IntoInlineConnection;
use mz_storage_types::connections::Connection;
use mz_storage_types::errors::ContextCreationError;
use mz_storage_types::sources::mysql::MySqlSourceDetails;
use mz_storage_types::sources::postgres::PostgresSourcePublicationDetails;
use mz_storage_types::sources::{GenericSourceConnection, SourceConnection};
use prost::Message;
use protobuf_native::compiler::{SourceTreeDescriptorDatabase, VirtualSourceTree};
use protobuf_native::MessageLite;
use rdkafka::admin::AdminClient;
use uuid::Uuid;

use crate::ast::{
    AvroSchema, CreateSourceConnection, CreateSourceFormat, CreateSourceStatement,
    CreateSourceSubsource, CreateSubsourceStatement, CsrConnectionAvro, CsrConnectionProtobuf,
    Format, ProtobufSchema, ReferencedSubsources, Value, WithOptionValue,
};
use crate::catalog::{CatalogItemType, SessionCatalog, SubsourceCatalog};
use crate::kafka_util::{KafkaSinkConfigOptionExtracted, KafkaSourceConfigOptionExtracted};
use crate::names::{
    Aug, FullItemName, PartialItemName, ResolvedColumnName, ResolvedDataType, ResolvedIds,
    ResolvedItemName,
};
use crate::plan::error::PlanError;
use crate::plan::statement::ddl::load_generator_ast_to_generator;
use crate::plan::StatementContext;
use crate::{kafka_util, normalize};

use self::error::{
    CsrPurificationError, KafkaSinkPurificationError, KafkaSourcePurificationError,
    LoadGeneratorSourcePurificationError, MySqlSourcePurificationError, PgSourcePurificationError,
};

pub(crate) mod error;
mod mysql;
mod postgres;

pub(crate) struct RequestedSubsource<'a, T> {
    upstream_name: UnresolvedItemName,
    subsource_name: UnresolvedItemName,
    table: &'a T,
}

fn subsource_gen<'a, T>(
    selected_subsources: &mut Vec<CreateSourceSubsource<Aug>>,
    catalog: &SubsourceCatalog<&'a T>,
    source_name: &UnresolvedItemName,
) -> Result<Vec<RequestedSubsource<'a, T>>, PlanError> {
    let mut validated_requested_subsources = vec![];

    for subsource in selected_subsources {
        let subsource_name = match &subsource.subsource {
            Some(name) => match name {
                DeferredItemName::Deferred(name) => {
                    let partial = normalize::unresolved_item_name(name.clone())?;
                    match partial.schema {
                        Some(_) => name.clone(),
                        // In cases when a prefix is not provided for the deferred name
                        // fallback to using the schema of the source with the given name
                        None => subsource_name_gen(source_name, &partial.item)?,
                    }
                }
                DeferredItemName::Named(..) => {
                    unreachable!("already errored on this condition")
                }
            },
            None => {
                // Use the entered name as the upstream reference, and then use
                // the item as the subsource name to ensure it's created in the
                // current schema or the source's schema if provided, not mirroring
                // the schema of the reference.
                subsource_name_gen(
                    source_name,
                    &normalize::unresolved_item_name(subsource.reference.clone())?.item,
                )?
            }
        };

        let (qualified_upstream_name, desc) = catalog.resolve(subsource.reference.clone())?;

        validated_requested_subsources.push(RequestedSubsource {
            upstream_name: qualified_upstream_name,
            subsource_name,
            table: *desc,
        });
    }

    Ok(validated_requested_subsources)
}

// Convenience function to ensure subsources are not named.
fn named_subsource_err(name: &Option<DeferredItemName<Aug>>) -> Result<(), PlanError> {
    match name {
        Some(DeferredItemName::Named(_)) => {
            sql_bail!("Cannot manually ID qualify subsources")
        }
        _ => Ok(()),
    }
}

/// Generates a subsource name by prepending source schema name if present
///
/// For eg. if source is `a.b`, then `a` will be prepended to the subsource name
/// so that it's generated in the same schema as source
fn subsource_name_gen(
    source_name: &UnresolvedItemName,
    subsource_name: &String,
) -> Result<UnresolvedItemName, PlanError> {
    let mut partial = normalize::unresolved_item_name(source_name.clone())?;
    partial.item = subsource_name.to_string();
    Ok(UnresolvedItemName::from(partial))
}

/// Validates the requested subsources do not have name conflicts with each other
/// and that the same upstream table is not referenced multiple times.
fn validate_subsource_names<T>(
    requested_subsources: &[RequestedSubsource<T>],
) -> Result<(), PlanError> {
    // This condition would get caught during the catalog transaction, but produces a
    // vague, non-contextual error. Instead, error here so we can suggest to the user
    // how to fix the problem.
    if let Some(name) = requested_subsources
        .iter()
        .map(|subsource| &subsource.subsource_name)
        .duplicates()
        .next()
        .cloned()
    {
        let mut upstream_references: Vec<_> = requested_subsources
            .into_iter()
            .filter_map(|subsource| {
                if &subsource.subsource_name == &name {
                    Some(subsource.upstream_name.clone())
                } else {
                    None
                }
            })
            .collect();

        upstream_references.sort();

        Err(PlanError::SubsourceNameConflict {
            name,
            upstream_references,
        })?;
    }

    // We technically could allow multiple subsources to ingest the same upstream table, but
    // it is almost certainly an error on the user's end.
    if let Some(name) = requested_subsources
        .iter()
        .map(|subsource| &subsource.upstream_name)
        .duplicates()
        .next()
        .cloned()
    {
        let mut target_names: Vec<_> = requested_subsources
            .into_iter()
            .filter_map(|subsource| {
                if &subsource.upstream_name == &name {
                    Some(subsource.subsource_name.clone())
                } else {
                    None
                }
            })
            .collect();

        target_names.sort();

        Err(PlanError::SubsourceDuplicateReference { name, target_names })?;
    }

    Ok(())
}

/// Purifies a statement, removing any dependencies on external state.
///
/// See the section on [purification](crate#purification) in the crate
/// documentation for details.
///
/// Note that this doesn't handle CREATE MATERIALIZED VIEW, which is
/// handled by [purify_create_materialized_view_options] instead.
/// This could be made more consistent by a refactoring discussed here:
/// <https://github.com/MaterializeInc/materialize/pull/23870#discussion_r1435922709>
pub async fn purify_statement(
    catalog: impl SessionCatalog,
    now: u64,
    stmt: Statement<Aug>,
    storage_configuration: &StorageConfiguration,
) -> Result<
    (
        Vec<(GlobalId, CreateSubsourceStatement<Aug>)>,
        Statement<Aug>,
    ),
    PlanError,
> {
    match stmt {
        Statement::CreateSource(stmt) => {
            purify_create_source(catalog, now, stmt, storage_configuration).await
        }
        Statement::AlterSource(stmt) => {
            purify_alter_source(catalog, stmt, storage_configuration).await
        }
        Statement::CreateSink(stmt) => {
            let r = purify_create_sink(catalog, stmt, storage_configuration).await?;
            Ok((vec![], r))
        }
        o => unreachable!("{:?} does not need to be purified", o),
    }
}

/// Updates the CREATE SINK statement with materialize comments
/// if `enable_sink_doc_on_option` feature flag is enabled
pub(crate) fn add_materialize_comments(
    catalog: &dyn SessionCatalog,
    stmt: &mut CreateSinkStatement<Aug>,
) -> Result<(), PlanError> {
    // updating avro format with comments so that they are frozen in the `create_sql`
    // only if the feature is enabled
    if catalog.system_vars().enable_sink_doc_on_option() {
        let from_id = stmt.from.item_id();
        let from = catalog.get_item(from_id);
        let object_ids = from.references().0.clone().into_iter().chain_one(from.id());

        // add comments to the avro doc comments
        if let Some(Format::Avro(AvroSchema::Csr {
            csr_connection:
                CsrConnectionAvro {
                    connection:
                        CsrConnection {
                            connection: _,
                            options,
                        },
                    ..
                },
        })) = &mut stmt.format
        {
            let user_provided_comments = &options
                .iter()
                .filter_map(|CsrConfigOption { name, .. }| match name {
                    CsrConfigOptionName::AvroDocOn(doc_on) => Some(doc_on.clone()),
                    _ => None,
                })
                .collect::<BTreeSet<_>>();

            // Adding existing comments if not already provided by user
            for object_id in object_ids {
                let item = catalog.get_item(&object_id);
                let full_name = catalog.resolve_full_name(item.name());
                let full_resolved_name = ResolvedItemName::Item {
                    id: object_id,
                    qualifiers: item.name().qualifiers.clone(),
                    full_name: full_name.clone(),
                    print_id: !matches!(
                        item.item_type(),
                        CatalogItemType::Func | CatalogItemType::Type
                    ),
                };

                if let Some(comments_map) = catalog.get_item_comments(&object_id) {
                    // Getting comment on the item
                    let doc_on_item_key = AvroDocOn {
                        identifier: DocOnIdentifier::Type(full_resolved_name.clone()),
                        for_schema: DocOnSchema::All,
                    };
                    if !user_provided_comments.contains(&doc_on_item_key) {
                        if let Some(root_comment) = comments_map.get(&None) {
                            options.push(CsrConfigOption {
                                name: CsrConfigOptionName::AvroDocOn(doc_on_item_key),
                                value: Some(mz_sql_parser::ast::WithOptionValue::Value(
                                    Value::String(root_comment.clone()),
                                )),
                            });
                        }
                    }

                    // Getting comments on columns in the item
                    if let Ok(desc) = item.desc(&full_name) {
                        for (pos, column_name) in desc.iter_names().enumerate() {
                            let comment = comments_map.get(&Some(pos + 1));
                            if let Some(comment_str) = comment {
                                let doc_on_column_key = AvroDocOn {
                                    identifier: DocOnIdentifier::Column(
                                        ResolvedColumnName::Column {
                                            relation: full_resolved_name.clone(),
                                            name: column_name.to_owned(),
                                            index: pos,
                                        },
                                    ),
                                    for_schema: DocOnSchema::All,
                                };
                                if !user_provided_comments.contains(&doc_on_column_key) {
                                    options.push(CsrConfigOption {
                                        name: CsrConfigOptionName::AvroDocOn(doc_on_column_key),
                                        value: Some(mz_sql_parser::ast::WithOptionValue::Value(
                                            Value::String(comment_str.clone()),
                                        )),
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Checks that the sink described in the statement can connect to its external
/// resources.
///
/// We must not leave any state behind in the Kafka broker, so just ensure that
/// we can connect. This means we don't ensure that we can create the topic and
/// introduces TOCTOU errors, but creating an inoperable sink is infinitely
/// preferable to leaking state in users' environments.
async fn purify_create_sink(
    catalog: impl SessionCatalog,
    mut stmt: CreateSinkStatement<Aug>,
    storage_configuration: &StorageConfiguration,
) -> Result<Statement<Aug>, PlanError> {
    add_materialize_comments(&catalog, &mut stmt)?;
    // General purification
    let CreateSinkStatement {
        connection, format, ..
    } = &stmt;

    match &connection {
        CreateSinkConnection::Kafka {
            connection,
            options,
            key: _,
        } => {
            let scx = StatementContext::new(None, &catalog);
            let connection = {
                let item = scx.get_item_by_resolved_name(connection)?;
                // Get Kafka connection
                match item.connection()? {
                    Connection::Kafka(connection) => {
                        connection.clone().into_inline_connection(scx.catalog)
                    }
                    _ => sql_bail!(
                        "{} is not a kafka connection",
                        scx.catalog.resolve_full_name(item.name())
                    ),
                }
            };

            let extracted_options: KafkaSinkConfigOptionExtracted = options.clone().try_into()?;

            if extracted_options.legacy_ids == Some(true) {
                sql_bail!("LEGACY IDs option is not supported");
            }

            let client: AdminClient<_> = connection
                .create_with_context(
                    storage_configuration,
                    MzClientContext::default(),
                    &BTreeMap::new(),
                )
                .await
                .map_err(|e| {
                    // anyhow doesn't support Clone, so not trivial to move into PlanError
                    KafkaSinkPurificationError::AdminClientError(Arc::new(e))
                })?;

            let metadata = client
                .inner()
                .fetch_metadata(
                    None,
                    storage_configuration
                        .parameters
                        .kafka_timeout_config
                        .fetch_metadata_timeout,
                )
                .map_err(|e| {
                    KafkaSinkPurificationError::AdminClientError(Arc::new(
                        ContextCreationError::KafkaError(e),
                    ))
                })?;

            if metadata.brokers().len() == 0 {
                Err(KafkaSinkPurificationError::ZeroBrokers)?;
            }
        }
    }

    if let Some(format) = format {
        match format {
            Format::Avro(AvroSchema::Csr {
                csr_connection: CsrConnectionAvro { connection, .. },
            })
            | Format::Protobuf(ProtobufSchema::Csr {
                csr_connection: CsrConnectionProtobuf { connection, .. },
            }) => {
                let connection = {
                    let scx = StatementContext::new(None, &catalog);
                    let item = scx.get_item_by_resolved_name(&connection.connection)?;
                    // Get Kafka connection
                    match item.connection()? {
                        Connection::Csr(connection) => {
                            connection.clone().into_inline_connection(&catalog)
                        }
                        _ => Err(CsrPurificationError::NotCsrConnection(
                            scx.catalog.resolve_full_name(item.name()),
                        ))?,
                    }
                };

                let client = connection
                    .connect(storage_configuration)
                    .await
                    .map_err(|e| CsrPurificationError::ClientError(Arc::new(e)))?;

                client
                    .list_subjects()
                    .await
                    .map_err(|e| CsrPurificationError::ListSubjectsError(Arc::new(e)))?;
            }
            Format::Avro(AvroSchema::InlineSchema { .. })
            | Format::Bytes
            | Format::Csv { .. }
            | Format::Json { .. }
            | Format::Protobuf(ProtobufSchema::InlineSchema { .. })
            | Format::Regex(..)
            | Format::Text => {}
        }
    }

    Ok(Statement::CreateSink(stmt))
}

async fn purify_create_source(
    catalog: impl SessionCatalog,
    now: u64,
    mut stmt: CreateSourceStatement<Aug>,
    storage_configuration: &StorageConfiguration,
) -> Result<
    (
        Vec<(GlobalId, CreateSubsourceStatement<Aug>)>,
        Statement<Aug>,
    ),
    PlanError,
> {
    let CreateSourceStatement {
        name: source_name,
        connection,
        format,
        envelope,
        include_metadata,
        referenced_subsources,
        progress_subsource,
        ..
    } = &mut stmt;

    // Disallow manually targetting subsources, this syntax is reserved for purification only
    named_subsource_err(progress_subsource)?;

    if let Some(ReferencedSubsources::SubsetTables(subsources)) = referenced_subsources {
        for CreateSourceSubsource {
            subsource,
            reference: _,
        } in subsources
        {
            named_subsource_err(subsource)?;
        }
    }

    let mut subsource_id_counter = 0;
    let mut get_transient_subsource_id = move || {
        subsource_id_counter += 1;
        subsource_id_counter
    };

    let mut subsources = vec![];

    let progress_desc = match &connection {
        CreateSourceConnection::Kafka { .. } => {
            &mz_storage_types::sources::kafka::KAFKA_PROGRESS_DESC
        }
        CreateSourceConnection::Postgres { .. } => {
            &mz_storage_types::sources::postgres::PG_PROGRESS_DESC
        }
        CreateSourceConnection::MySql { .. } => {
            &mz_storage_types::sources::mysql::MYSQL_PROGRESS_DESC
        }
        CreateSourceConnection::LoadGenerator { .. } => {
            &mz_storage_types::sources::load_generator::LOAD_GEN_PROGRESS_DESC
        }
    };

    match connection {
        CreateSourceConnection::Kafka {
            connection,
            options: base_with_options,
            ..
        } => {
            if let Some(referenced_subsources) = referenced_subsources {
                Err(KafkaSourcePurificationError::ReferencedSubsources(
                    referenced_subsources.clone(),
                ))?;
            }

            let scx = StatementContext::new(None, &catalog);
            let connection = {
                let item = scx.get_item_by_resolved_name(connection)?;
                // Get Kafka connection
                match item.connection()? {
                    Connection::Kafka(connection) => {
                        connection.clone().into_inline_connection(&catalog)
                    }
                    _ => Err(KafkaSourcePurificationError::NotKafkaConnection(
                        scx.catalog.resolve_full_name(item.name()),
                    ))?,
                }
            };

            let extracted_options: KafkaSourceConfigOptionExtracted =
                base_with_options.clone().try_into()?;

            let topic = extracted_options
                .topic
                .ok_or(KafkaSourcePurificationError::ConnectionMissingTopic)?;

            let consumer = connection
                .create_with_context(
                    storage_configuration,
                    MzClientContext::default(),
                    &BTreeMap::new(),
                )
                .await
                .map_err(|e| {
                    // anyhow doesn't support Clone, so not trivial to move into PlanError
                    KafkaSourcePurificationError::KafkaConsumerError(
                        e.display_with_causes().to_string(),
                    )
                })?;
            let consumer = Arc::new(consumer);

            match (
                extracted_options.start_offset,
                extracted_options.start_timestamp,
            ) {
                (None, None) => {
                    // Validate that the topic at least exists.
                    kafka_util::ensure_topic_exists(
                        Arc::clone(&consumer),
                        &topic,
                        storage_configuration
                            .parameters
                            .kafka_timeout_config
                            .fetch_metadata_timeout,
                    )
                    .await?;
                }
                (Some(_), Some(_)) => {
                    sql_bail!("cannot specify START TIMESTAMP and START OFFSET at same time")
                }
                (Some(start_offsets), None) => {
                    // Validate the start offsets.
                    kafka_util::validate_start_offsets(
                        Arc::clone(&consumer),
                        &topic,
                        start_offsets,
                        storage_configuration
                            .parameters
                            .kafka_timeout_config
                            .fetch_metadata_timeout,
                    )
                    .await?;
                }
                (None, Some(time_offset)) => {
                    // Translate `START TIMESTAMP` to a start offset.
                    let start_offsets = kafka_util::lookup_start_offsets(
                        Arc::clone(&consumer),
                        &topic,
                        time_offset,
                        now,
                        storage_configuration
                            .parameters
                            .kafka_timeout_config
                            .fetch_metadata_timeout,
                    )
                    .await?;

                    base_with_options.retain(|val| {
                        !matches!(val.name, KafkaSourceConfigOptionName::StartTimestamp)
                    });
                    base_with_options.push(KafkaSourceConfigOption {
                        name: KafkaSourceConfigOptionName::StartOffset,
                        value: Some(WithOptionValue::Sequence(
                            start_offsets
                                .iter()
                                .map(|offset| {
                                    WithOptionValue::Value(Value::Number(offset.to_string()))
                                })
                                .collect(),
                        )),
                    });
                }
            }
        }
        CreateSourceConnection::Postgres {
            connection,
            options,
        } => {
            let scx = StatementContext::new(None, &catalog);
            let connection = {
                let item = scx.get_item_by_resolved_name(connection)?;
                match item.connection().map_err(PlanError::from)? {
                    Connection::Postgres(connection) => {
                        connection.clone().into_inline_connection(&catalog)
                    }
                    _ => Err(PgSourcePurificationError::NotPgConnection(
                        scx.catalog.resolve_full_name(item.name()),
                    ))?,
                }
            };
            let crate::plan::statement::PgConfigOptionExtracted {
                publication,
                mut text_columns,
                details,
                ..
            } = options.clone().try_into()?;
            let publication =
                publication.ok_or(PgSourcePurificationError::ConnectionMissingPublication)?;

            if details.is_some() {
                Err(PgSourcePurificationError::UserSpecifiedDetails)?;
            }

            // verify that we can connect upstream and snapshot publication metadata
            let config = connection
                .config(
                    &*storage_configuration.connection_context.secrets_reader,
                    storage_configuration,
                )
                .await?;

            let wal_level = mz_postgres_util::get_wal_level(
                &storage_configuration.connection_context.ssh_tunnel_manager,
                &config,
            )
            .await?;

            if wal_level < WalLevel::Logical {
                Err(PgSourcePurificationError::InsufficientWalLevel { wal_level })?;
            }

            let max_wal_senders = mz_postgres_util::get_max_wal_senders(
                &storage_configuration.connection_context.ssh_tunnel_manager,
                &config,
            )
            .await?;

            if max_wal_senders < 1 {
                Err(PgSourcePurificationError::ReplicationDisabled)?;
            }

            let available_replication_slots = mz_postgres_util::available_replication_slots(
                &storage_configuration.connection_context.ssh_tunnel_manager,
                &config,
            )
            .await?;

            // We need 1 replication slot for the snapshots and 1 for the continuing replication
            if available_replication_slots < 2 {
                Err(PgSourcePurificationError::InsufficientReplicationSlotsAvailable { count: 2 })?;
            }

            let publication_tables = mz_postgres_util::publication_info(
                &storage_configuration.connection_context.ssh_tunnel_manager,
                &config,
                &publication,
            )
            .await?;

            if publication_tables.is_empty() {
                Err(PgSourcePurificationError::EmptyPublication(
                    publication.to_string(),
                ))?;
            }

            let publication_catalog = postgres::derive_catalog_from_publication_tables(
                &connection.database,
                &publication_tables,
            )?;

            let mut validated_requested_subsources = vec![];
            match referenced_subsources
                .as_mut()
                .ok_or(PgSourcePurificationError::RequiresReferencedSubsources)?
            {
                ReferencedSubsources::All => {
                    for table in &publication_tables {
                        let upstream_name = UnresolvedItemName::qualified(&[
                            Ident::new(&connection.database)?,
                            Ident::new(&table.namespace)?,
                            Ident::new(&table.name)?,
                        ]);
                        let subsource_name = subsource_name_gen(source_name, &table.name)?;
                        validated_requested_subsources.push(RequestedSubsource {
                            upstream_name,
                            subsource_name,
                            table,
                        });
                    }
                }
                ReferencedSubsources::SubsetSchemas(schemas) => {
                    let available_schemas: BTreeSet<_> = mz_postgres_util::get_schemas(
                        &storage_configuration.connection_context.ssh_tunnel_manager,
                        &config,
                    )
                    .await?
                    .into_iter()
                    .map(|s| s.name)
                    .collect();

                    let requested_schemas: BTreeSet<_> =
                        schemas.iter().map(|s| s.as_str().to_string()).collect();

                    let missing_schemas: Vec<_> = requested_schemas
                        .difference(&available_schemas)
                        .map(|s| s.to_string())
                        .collect();

                    if !missing_schemas.is_empty() {
                        Err(PgSourcePurificationError::DatabaseMissingFilteredSchemas {
                            database: connection.database.clone(),
                            schemas: missing_schemas,
                        })?;
                    }

                    for table in &publication_tables {
                        if !requested_schemas.contains(table.namespace.as_str()) {
                            continue;
                        }

                        let upstream_name = UnresolvedItemName::qualified(&[
                            Ident::new(&connection.database)?,
                            Ident::new(&table.namespace)?,
                            Ident::new(&table.name)?,
                        ]);
                        let subsource_name = subsource_name_gen(source_name, &table.name)?;
                        validated_requested_subsources.push(RequestedSubsource {
                            upstream_name,
                            subsource_name,
                            table,
                        });
                    }
                }
                ReferencedSubsources::SubsetTables(subsources) => {
                    // The user manually selected a subset of upstream tables so we need to
                    // validate that the names actually exist and are not ambiguous
                    validated_requested_subsources.extend(subsource_gen(
                        subsources,
                        &publication_catalog,
                        source_name,
                    )?);
                }
            };

            if validated_requested_subsources.is_empty() {
                sql_bail!(
                    "[internal error]: Postgres source must ingest at least one table, but {} matched none",
                    referenced_subsources.as_ref().unwrap().to_ast_string()
                );
            }

            validate_subsource_names(&validated_requested_subsources)?;

            postgres::validate_requested_subsources_privileges(
                &config,
                &validated_requested_subsources,
                &storage_configuration.connection_context.ssh_tunnel_manager,
            )
            .await?;

            let text_cols_dict = postgres::generate_text_columns(
                &publication_catalog,
                &mut text_columns,
                &PgConfigOptionName::TextColumns.to_ast_string(),
            )?;

            // Normalize options to contain full qualified values.
            if let Some(text_cols_option) = options
                .iter_mut()
                .find(|option| option.name == PgConfigOptionName::TextColumns)
            {
                let mut seq: Vec<_> = text_columns
                    .into_iter()
                    .map(WithOptionValue::UnresolvedItemName)
                    .collect();

                seq.sort();
                seq.dedup();

                text_cols_option.value = Some(WithOptionValue::Sequence(seq));
            }

            let (targeted_subsources, new_subsources) = postgres::generate_targeted_subsources(
                &scx,
                validated_requested_subsources,
                text_cols_dict,
                get_transient_subsource_id,
                &publication_tables,
            )?;

            *referenced_subsources = Some(ReferencedSubsources::SubsetTables(targeted_subsources));
            subsources.extend(new_subsources);

            // Record the active replication timeline_id to allow detection of a future upstream
            // point-in-time-recovery that will put the source into an error state.
            let replication_client = config
                .connect_replication(&storage_configuration.connection_context.ssh_tunnel_manager)
                .await?;
            let timeline_id = mz_postgres_util::get_timeline_id(&replication_client).await?;

            // Remove any old detail references
            options.retain(|PgConfigOption { name, .. }| name != &PgConfigOptionName::Details);
            let details = PostgresSourcePublicationDetails {
                tables: publication_tables,
                slot: format!(
                    "materialize_{}",
                    Uuid::new_v4().to_string().replace('-', "")
                ),
                timeline_id: Some(timeline_id),
            };
            options.push(PgConfigOption {
                name: PgConfigOptionName::Details,
                value: Some(WithOptionValue::Value(Value::String(hex::encode(
                    details.into_proto().encode_to_vec(),
                )))),
            })
        }
        CreateSourceConnection::MySql {
            connection,
            options,
        } => {
            let scx = StatementContext::new(None, &catalog);
            let connection_item = scx.get_item_by_resolved_name(connection)?;
            let connection = match connection_item.connection()? {
                Connection::MySql(connection) => {
                    connection.clone().into_inline_connection(&catalog)
                }
                _ => Err(MySqlSourcePurificationError::NotMySqlConnection(
                    scx.catalog.resolve_full_name(connection_item.name()),
                ))?,
            };
            let crate::plan::statement::ddl::MySqlConfigOptionExtracted {
                details,
                text_columns,
                ignore_columns,
                seen: _,
            } = options.clone().try_into()?;

            if details.is_some() {
                Err(MySqlSourcePurificationError::UserSpecifiedDetails)?;
            }

            let config = connection
                .config(
                    &*storage_configuration.connection_context.secrets_reader,
                    storage_configuration,
                )
                .await?;

            let mut conn = config
                .connect(
                    "mysql purification",
                    &storage_configuration.connection_context.ssh_tunnel_manager,
                )
                .await?;

            // Check if the MySQL database is configured to allow row-based consistent GTID replication
            let mut replication_errors = vec![];
            for error in [
                mz_mysql_util::ensure_gtid_consistency(&mut conn)
                    .await
                    .err(),
                mz_mysql_util::ensure_full_row_binlog_format(&mut conn)
                    .await
                    .err(),
                mz_mysql_util::ensure_replication_commit_order(&mut conn)
                    .await
                    .err(),
            ] {
                match error {
                    Some(mz_mysql_util::MySqlError::InvalidSystemSetting {
                        setting,
                        expected,
                        actual,
                    }) => {
                        replication_errors.push((setting, expected, actual));
                    }
                    Some(err) => Err(err)?,
                    None => (),
                }
            }
            if !replication_errors.is_empty() {
                Err(MySqlSourcePurificationError::ReplicationSettingsError(
                    replication_errors,
                ))?;
            }

            // Determine which table schemas to request from mysql. Note that in mysql
            // a 'schema' is the same as a 'database', and a fully qualified table
            // name is 'schema_name.table_name' (there is no db_name)
            let table_schema_request = match referenced_subsources
                .as_mut()
                .ok_or(MySqlSourcePurificationError::RequiresReferencedSubsources)?
            {
                ReferencedSubsources::All => mz_mysql_util::SchemaRequest::All,
                ReferencedSubsources::SubsetSchemas(schemas) => {
                    mz_mysql_util::SchemaRequest::Schemas(
                        schemas.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                    )
                }
                ReferencedSubsources::SubsetTables(tables) => mz_mysql_util::SchemaRequest::Tables(
                    tables
                        .iter()
                        .map(|t| {
                            let idents = &t.reference.0;
                            // We only support fully qualified table names for now
                            if idents.len() != 2 {
                                Err(MySqlSourcePurificationError::InvalidTableReference(
                                    t.reference.to_ast_string(),
                                ))?;
                            }
                            Ok((idents[0].as_str(), idents[1].as_str()))
                        })
                        .collect::<Result<Vec<_>, MySqlSourcePurificationError>>()?,
                ),
            };

            let text_cols_map =
                mysql::map_column_refs(&text_columns, MySqlConfigOptionName::TextColumns)?;
            let ignore_cols_map =
                mysql::map_column_refs(&ignore_columns, MySqlConfigOptionName::IgnoreColumns)?;

            // Retrieve schemas for all requested tables
            // NOTE: mysql will only expose the schemas of tables we have at least one privilege on
            // and we can't tell if a table exists without a privilege, so in some cases we may
            // return an EmptyDatabase error in the case of privilege issues.
            let tables = mz_mysql_util::schema_info(
                &mut *conn,
                &table_schema_request,
                &text_cols_map,
                &ignore_cols_map,
            )
            .await
            .map_err(|err| match err {
                mz_mysql_util::MySqlError::UnsupportedDataTypes { columns } => {
                    PlanError::from(MySqlSourcePurificationError::UnrecognizedTypes {
                        cols: columns
                            .into_iter()
                            .map(|c| (c.qualified_table_name, c.column_name, c.column_type))
                            .collect(),
                    })
                }
                mz_mysql_util::MySqlError::DuplicatedColumnNames {
                    qualified_table_name,
                    columns,
                } => PlanError::from(MySqlSourcePurificationError::DuplicatedColumnNames(
                    qualified_table_name,
                    columns,
                )),
                _ => err.into(),
            })?;

            if tables.is_empty() {
                Err(MySqlSourcePurificationError::EmptyDatabase)?;
            }

            let mysql_catalog = mysql::derive_catalog_from_tables(&tables)?;

            // Normalize column options and remove unused column references.
            if let Some(text_cols_option) = options
                .iter_mut()
                .find(|option| option.name == MySqlConfigOptionName::TextColumns)
            {
                text_cols_option.value = Some(WithOptionValue::Sequence(
                    mysql::normalize_column_refs(text_columns, &mysql_catalog)?,
                ));
            }
            if let Some(ignore_cols_option) = options
                .iter_mut()
                .find(|option| option.name == MySqlConfigOptionName::IgnoreColumns)
            {
                ignore_cols_option.value = Some(WithOptionValue::Sequence(
                    mysql::normalize_column_refs(ignore_columns, &mysql_catalog)?,
                ));
            }

            let mut validated_requested_subsources = vec![];
            match referenced_subsources
                .as_mut()
                .ok_or(MySqlSourcePurificationError::RequiresReferencedSubsources)?
            {
                ReferencedSubsources::All => {
                    for table in &tables {
                        let upstream_name = mysql::mysql_upstream_name(table)?;
                        let subsource_name = subsource_name_gen(source_name, &table.name)?;
                        validated_requested_subsources.push(RequestedSubsource {
                            upstream_name,
                            subsource_name,
                            table,
                        });
                    }
                }
                ReferencedSubsources::SubsetSchemas(schemas) => {
                    let available_schemas: BTreeSet<_> =
                        tables.iter().map(|t| t.schema_name.as_str()).collect();
                    let requested_schemas: BTreeSet<_> =
                        schemas.iter().map(|s| s.as_str()).collect();
                    let missing_schemas: Vec<_> = requested_schemas
                        .difference(&available_schemas)
                        .map(|s| s.to_string())
                        .collect();
                    if !missing_schemas.is_empty() {
                        Err(MySqlSourcePurificationError::NoTablesFoundForSchemas(
                            missing_schemas,
                        ))?;
                    }

                    for table in &tables {
                        if !requested_schemas.contains(table.schema_name.as_str()) {
                            continue;
                        }

                        let upstream_name = mysql::mysql_upstream_name(table)?;
                        let subsource_name = subsource_name_gen(source_name, &table.name)?;
                        validated_requested_subsources.push(RequestedSubsource {
                            upstream_name,
                            subsource_name,
                            table,
                        });
                    }
                }
                ReferencedSubsources::SubsetTables(subsources) => {
                    // The user manually selected a subset of upstream tables so we need to
                    // validate that the names actually exist and are not ambiguous
                    validated_requested_subsources.extend(subsource_gen(
                        subsources,
                        &mysql_catalog,
                        source_name,
                    )?);
                }
            }

            if validated_requested_subsources.is_empty() {
                sql_bail!(
                    "[internal error]: MySQL source must ingest at least one table, but {} matched none",
                    referenced_subsources.as_ref().unwrap().to_ast_string()
                );
            }

            validate_subsource_names(&validated_requested_subsources)?;

            mysql::validate_requested_subsources_privileges(
                &validated_requested_subsources,
                &mut conn,
            )
            .await?;

            let (targeted_subsources, new_subsources) = mysql::generate_targeted_subsources(
                &scx,
                validated_requested_subsources,
                get_transient_subsource_id,
            )?;

            *referenced_subsources = Some(ReferencedSubsources::SubsetTables(targeted_subsources));
            subsources.extend(new_subsources);

            // Retrieve the current @gtid_executed value of the server to mark as the effective
            // initial snapshot point such that we can ensure consistency if the initial source
            // snapshot is broken up over multiple points in time.
            let initial_gtid_set =
                mz_mysql_util::query_sys_var(&mut conn, "global.gtid_executed").await?;

            // Remove any old detail references
            options
                .retain(|MySqlConfigOption { name, .. }| name != &MySqlConfigOptionName::Details);
            let details = MySqlSourceDetails {
                tables,
                initial_gtid_set,
            };
            options.push(MySqlConfigOption {
                name: MySqlConfigOptionName::Details,
                value: Some(WithOptionValue::Value(Value::String(hex::encode(
                    details.into_proto().encode_to_vec(),
                )))),
            })
        }
        CreateSourceConnection::LoadGenerator { generator, options } => {
            let scx = StatementContext::new(None, &catalog);

            let (_load_generator, available_subsources) =
                load_generator_ast_to_generator(&scx, generator, options, include_metadata)?;

            let mut targeted_subsources = vec![];

            let mut validated_requested_subsources = vec![];
            match referenced_subsources {
                Some(ReferencedSubsources::All) => {
                    let available_subsources = match &available_subsources {
                        Some(available_subsources) => available_subsources,
                        None => Err(LoadGeneratorSourcePurificationError::ForAllTables)?,
                    };
                    for (name, (_, desc)) in available_subsources {
                        let upstream_name = UnresolvedItemName::from(name.clone());
                        let subsource_name = subsource_name_gen(source_name, &name.item)?;
                        validated_requested_subsources.push((upstream_name, subsource_name, desc));
                    }
                }
                Some(ReferencedSubsources::SubsetSchemas(..)) => {
                    Err(LoadGeneratorSourcePurificationError::ForSchemas)?
                }
                Some(ReferencedSubsources::SubsetTables(_)) => {
                    Err(LoadGeneratorSourcePurificationError::ForTables)?
                }
                None => {
                    if available_subsources.is_some() {
                        Err(LoadGeneratorSourcePurificationError::MultiOutputRequiresForAllTables)?
                    }
                }
            };

            // Now that we have an explicit list of validated requested subsources we can create them
            for (upstream_name, subsource_name, desc) in validated_requested_subsources.into_iter()
            {
                let (columns, table_constraints) = scx.relation_desc_into_table_defs(desc)?;

                // Create the targeted AST node for the original CREATE SOURCE statement
                let transient_id = GlobalId::Transient(get_transient_subsource_id());

                let subsource =
                    scx.allocate_resolved_item_name(transient_id, subsource_name.clone())?;

                targeted_subsources.push(CreateSourceSubsource {
                    reference: upstream_name,
                    subsource: Some(DeferredItemName::Named(subsource)),
                });

                // Create the subsource statement
                let subsource = CreateSubsourceStatement {
                    name: subsource_name,
                    columns,
                    // unlike sources that come from an external upstream, we
                    // have more leniency to introduce different constraints
                    // every time the load generator is run; i.e. we are not as
                    // worried about introducing junk data.
                    constraints: table_constraints,
                    if_not_exists: false,
                    with_options: vec![CreateSubsourceOption {
                        name: CreateSubsourceOptionName::References,
                        value: Some(WithOptionValue::Value(Value::Boolean(true))),
                    }],
                };
                subsources.push((transient_id, subsource));
            }
            if available_subsources.is_some() {
                *referenced_subsources =
                    Some(ReferencedSubsources::SubsetTables(targeted_subsources));
            }
        }
    }

    // Generate progress subsource

    // Create the targeted AST node for the original CREATE SOURCE statement
    let transient_id = GlobalId::Transient(subsource_id_counter);

    let scx = StatementContext::new(None, &catalog);

    // Take name from input or generate name
    let (name, subsource) = match progress_subsource {
        Some(name) => match name {
            DeferredItemName::Deferred(name) => (
                name.clone(),
                scx.allocate_resolved_item_name(transient_id, name.clone())?,
            ),
            DeferredItemName::Named(_) => unreachable!("already checked for this value"),
        },
        None => {
            let (item, prefix) = source_name.0.split_last().unwrap();
            let item_name = Ident::try_generate_name(item.to_string(), "_progress", |candidate| {
                let mut suggested_name = prefix.to_vec();
                suggested_name.push(candidate.clone());

                let partial = normalize::unresolved_item_name(UnresolvedItemName(suggested_name))?;
                let qualified = scx.allocate_qualified_name(partial)?;
                let item_exists = scx.catalog.get_item_by_name(&qualified).is_some();
                let type_exists = scx.catalog.get_type_by_name(&qualified).is_some();
                Ok::<_, PlanError>(!item_exists && !type_exists)
            })?;

            let mut full_name = prefix.to_vec();
            full_name.push(item_name);
            let full_name = normalize::unresolved_item_name(UnresolvedItemName(full_name))?;
            let qualified_name = scx.allocate_qualified_name(full_name)?;
            let full_name = scx.catalog.resolve_full_name(&qualified_name);

            (
                UnresolvedItemName::from(full_name.clone()),
                crate::names::ResolvedItemName::Item {
                    id: transient_id,
                    qualifiers: qualified_name.qualifiers,
                    full_name,
                    print_id: true,
                },
            )
        }
    };

    let (columns, constraints) = scx.relation_desc_into_table_defs(progress_desc)?;

    *progress_subsource = Some(DeferredItemName::Named(subsource));

    // Create the subsource statement
    let subsource = CreateSubsourceStatement {
        name,
        columns,
        constraints,
        if_not_exists: false,
        with_options: vec![CreateSubsourceOption {
            name: CreateSubsourceOptionName::Progress,
            value: Some(WithOptionValue::Value(Value::Boolean(true))),
        }],
    };
    subsources.push((transient_id, subsource));

    purify_source_format(
        &catalog,
        format,
        connection,
        envelope,
        storage_configuration,
    )
    .await?;

    Ok((subsources, Statement::CreateSource(stmt)))
}

/// Equivalent to `purify_create_source` but for `AlterSourceStatement`.
///
/// On success, returns the `GlobalId` and `CreateSubsourceStatement`s for any
/// subsources created by this statement, in addition to the
/// `AlterSourceStatement` with any modifications that are only accessible while
/// we are permitted to use async code.
async fn purify_alter_source(
    catalog: impl SessionCatalog,
    mut stmt: AlterSourceStatement<Aug>,
    storage_configuration: &StorageConfiguration,
) -> Result<
    (
        Vec<(GlobalId, CreateSubsourceStatement<Aug>)>,
        Statement<Aug>,
    ),
    PlanError,
> {
    let scx = StatementContext::new(None, &catalog);
    let AlterSourceStatement {
        source_name,
        action,
        if_exists,
    } = &mut stmt;

    // Get connection
    let pg_source_connection = {
        // Get name.
        let item = match scx.resolve_item(RawItemName::Name(source_name.clone())) {
            Ok(item) => item,
            Err(_) if *if_exists => {
                return Ok((vec![], Statement::AlterSource(stmt)));
            }
            Err(e) => return Err(e),
        };

        // Ensure it's an ingestion-based and alterable source.
        let desc = match item.source_desc()? {
            Some(desc) => desc.clone().into_inline_connection(scx.catalog),
            None => {
                sql_bail!("cannot ALTER this type of source")
            }
        };

        // Ensure it's a source that supports ALTER SOURCE...
        match desc.connection {
            GenericSourceConnection::Postgres(pg_connection) => pg_connection,
            _ => sql_bail!(
                "{} is a {} source, which does not support ALTER SOURCE.",
                scx.catalog.minimal_qualification(item.name()),
                desc.connection.name()
            ),
        }
    };

    // If we don't need to handle added subsources, early return.
    let (targeted_subsources, details, options) = match action {
        AlterSourceAction::AddSubsources {
            subsources,
            details,
            options,
        } => (subsources, details, options),
        _ => return Ok((vec![], Statement::AlterSource(stmt))),
    };

    assert!(
        details.is_none(),
        "details cannot be set before purification"
    );

    let crate::plan::statement::ddl::AlterSourceAddSubsourceOptionExtracted {
        mut text_columns,
        ..
    } = options.clone().try_into()?;

    for CreateSourceSubsource {
        subsource,
        reference: _,
    } in targeted_subsources.iter()
    {
        named_subsource_err(subsource)?;
    }

    // Get PostgresConnection for generating subsources.
    let pg_connection = &pg_source_connection.connection;

    let config = pg_connection
        .config(
            &*storage_configuration.connection_context.secrets_reader,
            storage_configuration,
        )
        .await?;

    let available_replication_slots = mz_postgres_util::available_replication_slots(
        &storage_configuration.connection_context.ssh_tunnel_manager,
        &config,
    )
    .await?;

    // We need 1 additional replication slot for the snapshots
    if available_replication_slots < 1 {
        Err(PgSourcePurificationError::InsufficientReplicationSlotsAvailable { count: 1 })?;
    }

    let mut publication_tables = mz_postgres_util::publication_info(
        &storage_configuration.connection_context.ssh_tunnel_manager,
        &config,
        &pg_source_connection.publication,
    )
    .await?;

    if publication_tables.is_empty() {
        Err(PgSourcePurificationError::EmptyPublication(
            pg_source_connection.publication.to_string(),
        ))?;
    }

    let publication_catalog = postgres::derive_catalog_from_publication_tables(
        &pg_connection.database,
        &publication_tables,
    )?;

    let validated_requested_subsources =
        subsource_gen(targeted_subsources, &publication_catalog, source_name)?;

    // Determine duplicate references to tables by cross-referencing the table
    // positions in the current publication info to thei
    let mut current_subsources = BTreeMap::new();
    for idx in pg_source_connection.table_casts.keys() {
        // Table casts all have their values increased by to accommodate for the
        // primary source--this means that to look them up in the publication
        // tables you must subtract one.
        let native_idx = *idx - 1;
        let table_desc = &pg_source_connection.publication_details.tables[native_idx];
        current_subsources.insert(
            UnresolvedItemName(vec![
                Ident::new(pg_connection.database.clone())?,
                Ident::new(table_desc.namespace.clone())?,
                Ident::new(table_desc.name.clone())?,
            ]),
            native_idx,
        );
    }

    for RequestedSubsource { upstream_name, .. } in validated_requested_subsources.iter() {
        if current_subsources.contains_key(upstream_name) {
            Err(PlanError::SubsourceAlreadyReferredTo {
                name: upstream_name.clone(),
            })?;
        }
    }

    validate_subsource_names(&validated_requested_subsources)?;

    postgres::validate_requested_subsources_privileges(
        &config,
        &validated_requested_subsources,
        &storage_configuration.connection_context.ssh_tunnel_manager,
    )
    .await?;
    let mut subsource_id_counter = 0;
    let get_transient_subsource_id = move || {
        subsource_id_counter += 1;
        subsource_id_counter
    };

    let text_cols_dict = postgres::generate_text_columns(
        &publication_catalog,
        &mut text_columns,
        &AlterSourceAddSubsourceOptionName::TextColumns.to_ast_string(),
    )?;

    // Normalize options to contain full qualified values.
    if let Some(text_cols_option) = options
        .iter_mut()
        .find(|option| option.name == AlterSourceAddSubsourceOptionName::TextColumns)
    {
        let mut seq: Vec<_> = text_columns
            .into_iter()
            .map(WithOptionValue::UnresolvedItemName)
            .collect();

        seq.sort();
        seq.dedup();

        text_cols_option.value = Some(WithOptionValue::Sequence(seq));
    }

    let (named_subsources, new_subsources) = postgres::generate_targeted_subsources(
        &scx,
        validated_requested_subsources,
        text_cols_dict,
        get_transient_subsource_id,
        &publication_tables,
    )?;

    *targeted_subsources = named_subsources;

    // An index from table name -> output index.
    let mut new_name_to_output_map = BTreeMap::new();
    for (i, table) in publication_tables.iter().enumerate() {
        new_name_to_output_map.insert(
            UnresolvedItemName(vec![
                Ident::new(pg_connection.database.clone())?,
                Ident::new(table.namespace.clone())?,
                Ident::new(table.name.clone())?,
            ]),
            i,
        );
    }

    // Fixup the publication info
    for (name, idx) in current_subsources {
        let table = pg_source_connection.publication_details.tables[idx].clone();

        // Determine if this current subsource is in the new publication tables.
        match new_name_to_output_map.get(&name) {
            // These are tables that were previously defined; we want to
            // duplicate their definition to the new `publication_tables`
            // because this command is meant only to add new tables, not update
            // the schema of existing tables.
            Some(cur_idx) => publication_tables[*cur_idx] = table,
            // These are tables that no longer exist in the publication but the
            // user has kept around. When the ingestion restarts after adding
            // the new table, they will error out, but that is not the problem
            // or scope of this function.
            None => publication_tables.push(table),
        }
    }

    let timeline_id = match pg_source_connection.publication_details.timeline_id {
        None => {
            // If we had not yet been able to fill in the source's timeline ID, fill it in now.
            let replication_client = config
                .connect_replication(&storage_configuration.connection_context.ssh_tunnel_manager)
                .await?;
            let timeline_id = mz_postgres_util::get_timeline_id(&replication_client).await?;
            Some(timeline_id)
        }
        timeline_id => timeline_id,
    };

    let new_details = PostgresSourcePublicationDetails {
        tables: publication_tables,
        slot: pg_source_connection.publication_details.slot.clone(),
        timeline_id,
    };

    *details = Some(WithOptionValue::Value(Value::String(hex::encode(
        new_details.into_proto().encode_to_vec(),
    ))));

    Ok((new_subsources, Statement::AlterSource(stmt)))
}

async fn purify_source_format(
    catalog: &dyn SessionCatalog,
    format: &mut Option<CreateSourceFormat<Aug>>,
    connection: &mut CreateSourceConnection<Aug>,
    envelope: &Option<SourceEnvelope>,
    storage_configuration: &StorageConfiguration,
) -> Result<(), PlanError> {
    if matches!(format, Some(CreateSourceFormat::KeyValue { .. }))
        && !matches!(connection, CreateSourceConnection::Kafka { .. })
    {
        sql_bail!("Kafka sources are the only source type that can provide KEY/VALUE formats")
    }

    match format.as_mut() {
        None => {}
        Some(CreateSourceFormat::Bare(format)) => {
            purify_source_format_single(
                catalog,
                format,
                connection,
                envelope,
                storage_configuration,
            )
            .await?;
        }

        Some(CreateSourceFormat::KeyValue { key, value: val }) => {
            purify_source_format_single(catalog, key, connection, envelope, storage_configuration)
                .await?;
            purify_source_format_single(catalog, val, connection, envelope, storage_configuration)
                .await?;
        }
    }
    Ok(())
}

async fn purify_source_format_single(
    catalog: &dyn SessionCatalog,
    format: &mut Format<Aug>,
    connection: &mut CreateSourceConnection<Aug>,
    envelope: &Option<SourceEnvelope>,
    storage_configuration: &StorageConfiguration,
) -> Result<(), PlanError> {
    match format {
        Format::Avro(schema) => match schema {
            AvroSchema::Csr { csr_connection } => {
                purify_csr_connection_avro(
                    catalog,
                    connection,
                    csr_connection,
                    envelope,
                    storage_configuration,
                )
                .await?
            }
            AvroSchema::InlineSchema { .. } => {}
        },
        Format::Protobuf(schema) => match schema {
            ProtobufSchema::Csr { csr_connection } => {
                purify_csr_connection_proto(
                    catalog,
                    connection,
                    csr_connection,
                    envelope,
                    storage_configuration,
                )
                .await?;
            }
            ProtobufSchema::InlineSchema { .. } => {}
        },
        Format::Bytes
        | Format::Regex(_)
        | Format::Json { .. }
        | Format::Text
        | Format::Csv { .. } => (),
    }
    Ok(())
}

async fn purify_csr_connection_proto(
    catalog: &dyn SessionCatalog,
    connection: &mut CreateSourceConnection<Aug>,
    csr_connection: &mut CsrConnectionProtobuf<Aug>,
    envelope: &Option<SourceEnvelope>,
    storage_configuration: &StorageConfiguration,
) -> Result<(), PlanError> {
    let topic = if let CreateSourceConnection::Kafka { options, .. } = connection {
        let KafkaSourceConfigOptionExtracted { topic, .. } = options
            .clone()
            .try_into()
            .expect("already verified options valid provided");
        topic.expect("already validated topic provided")
    } else {
        sql_bail!("Confluent Schema Registry is only supported with Kafka sources")
    };

    let CsrConnectionProtobuf {
        seed,
        connection: CsrConnection {
            connection,
            options: _,
        },
    } = csr_connection;
    match seed {
        None => {
            let scx = StatementContext::new(None, &*catalog);

            let ccsr_connection = match scx.get_item_by_resolved_name(connection)?.connection()? {
                Connection::Csr(connection) => connection.clone().into_inline_connection(catalog),
                _ => sql_bail!("{} is not a schema registry connection", connection),
            };

            let ccsr_client = ccsr_connection
                .connect(storage_configuration)
                .await
                .map_err(|e| CsrPurificationError::ClientError(Arc::new(e)))?;

            let value = compile_proto(&format!("{}-value", topic), &ccsr_client).await?;
            let key = compile_proto(&format!("{}-key", topic), &ccsr_client)
                .await
                .ok();

            if matches!(envelope, Some(SourceEnvelope::Debezium)) && key.is_none() {
                sql_bail!("Key schema is required for ENVELOPE DEBEZIUM");
            }

            *seed = Some(CsrSeedProtobuf { value, key });
        }
        Some(_) => (),
    }

    Ok(())
}

async fn purify_csr_connection_avro(
    catalog: &dyn SessionCatalog,
    connection: &mut CreateSourceConnection<Aug>,
    csr_connection: &mut CsrConnectionAvro<Aug>,
    envelope: &Option<SourceEnvelope>,
    storage_configuration: &StorageConfiguration,
) -> Result<(), PlanError> {
    let topic = if let CreateSourceConnection::Kafka { options, .. } = connection {
        let KafkaSourceConfigOptionExtracted { topic, .. } = options
            .clone()
            .try_into()
            .expect("already verified options valid provided");
        topic.expect("already validated topic provided")
    } else {
        sql_bail!("Confluent Schema Registry is only supported with Kafka sources")
    };

    let CsrConnectionAvro {
        connection: CsrConnection { connection, .. },
        seed,
        key_strategy,
        value_strategy,
    } = csr_connection;
    if seed.is_none() {
        let scx = StatementContext::new(None, &*catalog);
        let csr_connection = match scx.get_item_by_resolved_name(connection)?.connection()? {
            Connection::Csr(connection) => connection.clone().into_inline_connection(catalog),
            _ => sql_bail!("{} is not a schema registry connection", connection),
        };
        let ccsr_client = csr_connection
            .connect(storage_configuration)
            .await
            .map_err(|e| CsrPurificationError::ClientError(Arc::new(e)))?;

        let Schema {
            key_schema,
            value_schema,
        } = get_remote_csr_schema(
            &ccsr_client,
            key_strategy.clone().unwrap_or_default(),
            value_strategy.clone().unwrap_or_default(),
            topic,
        )
        .await?;
        if matches!(envelope, Some(SourceEnvelope::Debezium)) && key_schema.is_none() {
            sql_bail!("Key schema is required for ENVELOPE DEBEZIUM");
        }

        *seed = Some(CsrSeedAvro {
            key_schema,
            value_schema,
        })
    }

    Ok(())
}

#[derive(Debug)]
pub struct Schema {
    pub key_schema: Option<String>,
    pub value_schema: String,
}

async fn get_schema_with_strategy(
    client: &Client,
    strategy: ReaderSchemaSelectionStrategy,
    subject: &str,
) -> Result<Option<String>, PlanError> {
    match strategy {
        ReaderSchemaSelectionStrategy::Latest => {
            match client.get_schema_by_subject(subject).await {
                Ok(CcsrSchema { raw, .. }) => Ok(Some(raw)),
                Err(GetBySubjectError::SubjectNotFound)
                | Err(GetBySubjectError::VersionNotFound(_)) => Ok(None),
                Err(e) => Err(PlanError::FetchingCsrSchemaFailed {
                    schema_lookup: format!("subject {}", subject.quoted()),
                    cause: Arc::new(e),
                }),
            }
        }
        ReaderSchemaSelectionStrategy::Inline(raw) => Ok(Some(raw)),
        ReaderSchemaSelectionStrategy::ById(id) => match client.get_schema_by_id(id).await {
            Ok(CcsrSchema { raw, .. }) => Ok(Some(raw)),
            Err(GetByIdError::SchemaNotFound) => Ok(None),
            Err(e) => Err(PlanError::FetchingCsrSchemaFailed {
                schema_lookup: format!("ID {}", id),
                cause: Arc::new(e),
            }),
        },
    }
}

async fn get_remote_csr_schema(
    ccsr_client: &mz_ccsr::Client,
    key_strategy: ReaderSchemaSelectionStrategy,
    value_strategy: ReaderSchemaSelectionStrategy,
    topic: String,
) -> Result<Schema, PlanError> {
    let value_schema_name = format!("{}-value", topic);
    let value_schema =
        get_schema_with_strategy(ccsr_client, value_strategy, &value_schema_name).await?;
    let value_schema = value_schema.ok_or_else(|| anyhow!("No value schema found"))?;
    let subject = format!("{}-key", topic);
    let key_schema = get_schema_with_strategy(ccsr_client, key_strategy, &subject).await?;
    Ok(Schema {
        key_schema,
        value_schema,
    })
}

/// Collect protobuf message descriptor from CSR and compile the descriptor.
async fn compile_proto(
    subject_name: &String,
    ccsr_client: &Client,
) -> Result<CsrSeedProtobufSchema, PlanError> {
    let (primary_subject, dependency_subjects) = ccsr_client
        .get_subject_and_references(subject_name)
        .await
        .map_err(|e| PlanError::FetchingCsrSchemaFailed {
            schema_lookup: format!("subject {}", subject_name.quoted()),
            cause: Arc::new(e),
        })?;

    // Compile .proto files into a file descriptor set.
    let mut source_tree = VirtualSourceTree::new();
    for subject in iter::once(&primary_subject).chain(dependency_subjects.iter()) {
        source_tree.as_mut().add_file(
            Path::new(&subject.name),
            subject.schema.raw.as_bytes().to_vec(),
        );
    }
    let mut db = SourceTreeDescriptorDatabase::new(source_tree.as_mut());
    let fds = db
        .as_mut()
        .build_file_descriptor_set(&[Path::new(&primary_subject.name)])
        .map_err(|cause| PlanError::InvalidProtobufSchema { cause })?;

    // Ensure there is exactly one message in the file.
    let primary_fd = fds.file(0);
    let message_name = match primary_fd.message_type_size() {
        1 => String::from_utf8_lossy(primary_fd.message_type(0).name()).into_owned(),
        0 => bail_unsupported!(9598, "Protobuf schemas with no messages"),
        _ => bail_unsupported!(9598, "Protobuf schemas with multiple messages"),
    };

    // Encode the file descriptor set into a SQL byte string.
    let bytes = &fds
        .serialize()
        .map_err(|cause| PlanError::InvalidProtobufSchema { cause })?;
    let mut schema = String::new();
    strconv::format_bytes(&mut schema, bytes);

    Ok(CsrSeedProtobufSchema {
        schema,
        message_name,
    })
}

const MZ_NOW_NAME: &str = "mz_now";
const MZ_NOW_SCHEMA: &str = "mz_catalog";

/// Purifies a CREATE MATERIALIZED VIEW statement. Additionally, it adjusts `resolved_ids` if
/// references to ids appear or disappear during the purification.
///
/// Note that in contrast with [`purify_statement`], this doesn't need to be async, because
/// this function is not making any network calls.
pub fn purify_create_materialized_view_options(
    catalog: impl SessionCatalog,
    mz_now: Option<Timestamp>,
    cmvs: &mut CreateMaterializedViewStatement<Aug>,
    resolved_ids: &mut ResolvedIds,
) {
    // 0. Preparations:
    // Prepare an expression that calls `mz_now()`, which we can insert in various later steps.
    let (mz_now_id, mz_now_expr) = {
        let item = catalog
            .resolve_function(&PartialItemName {
                database: None,
                schema: Some(MZ_NOW_SCHEMA.to_string()),
                item: MZ_NOW_NAME.to_string(),
            })
            .expect("we should be able to resolve mz_now");
        (
            item.id(),
            Expr::Function(Function {
                name: ResolvedItemName::Item {
                    id: item.id(),
                    qualifiers: item.name().qualifiers.clone(),
                    full_name: catalog.resolve_full_name(item.name()),
                    print_id: false,
                },
                args: FunctionArgs::Args {
                    args: Vec::new(),
                    order_by: Vec::new(),
                },
                filter: None,
                over: None,
                distinct: false,
            }),
        )
    };
    // Prepare the `mz_timestamp` type.
    let (mz_timestamp_id, mz_timestamp_type) = {
        let item = catalog.get_system_type("mz_timestamp");
        let full_name = catalog.resolve_full_name(item.name());
        (
            item.id(),
            ResolvedDataType::Named {
                id: item.id(),
                qualifiers: item.name().qualifiers.clone(),
                full_name,
                modifiers: vec![],
                print_id: true,
            },
        )
    };

    let mut introduced_mz_timestamp = false;

    for option in cmvs.with_options.iter_mut() {
        // 1. Purify `REFRESH AT CREATION` to `REFRESH AT mz_now()`.
        if matches!(
            option.value,
            Some(WithOptionValue::Refresh(RefreshOptionValue::AtCreation))
        ) {
            option.value = Some(WithOptionValue::Refresh(RefreshOptionValue::At(
                RefreshAtOptionValue {
                    time: mz_now_expr.clone(),
                },
            )));
        }

        // 2. If `REFRESH EVERY` doesn't have an `ALIGNED TO`, then add `ALIGNED TO mz_now()`.
        if let Some(WithOptionValue::Refresh(RefreshOptionValue::Every(
            RefreshEveryOptionValue { aligned_to, .. },
        ))) = &mut option.value
        {
            if aligned_to.is_none() {
                *aligned_to = Some(mz_now_expr.clone());
            }
        }

        // 3. Substitute `mz_now()` with the timestamp chosen for the CREATE MATERIALIZED VIEW
        // statement. (This has to happen after the above steps, which might introduce `mz_now()`.)
        match &mut option.value {
            Some(WithOptionValue::Refresh(RefreshOptionValue::At(RefreshAtOptionValue {
                time,
            }))) => {
                let mut visitor = MzNowPurifierVisitor::new(mz_now, mz_timestamp_type.clone());
                visitor.visit_expr_mut(time);
                introduced_mz_timestamp |= visitor.introduced_mz_timestamp;
            }
            Some(WithOptionValue::Refresh(RefreshOptionValue::Every(
                RefreshEveryOptionValue {
                    interval: _,
                    aligned_to: Some(aligned_to),
                },
            ))) => {
                let mut visitor = MzNowPurifierVisitor::new(mz_now, mz_timestamp_type.clone());
                visitor.visit_expr_mut(aligned_to);
                introduced_mz_timestamp |= visitor.introduced_mz_timestamp;
            }
            _ => {}
        }
    }

    // 4. If the user didn't give any REFRESH option, then default to ON COMMIT.
    if !cmvs.with_options.iter().any(|o| {
        matches!(
            o,
            MaterializedViewOption {
                value: Some(WithOptionValue::Refresh(..)),
                ..
            }
        )
    }) {
        cmvs.with_options.push(MaterializedViewOption {
            name: MaterializedViewOptionName::Refresh,
            value: Some(WithOptionValue::Refresh(RefreshOptionValue::OnCommit)),
        })
    }

    // 5. Attend to `resolved_ids`: The purification might have
    // - added references to `mz_timestamp`;
    // - removed references to `mz_now`.
    if introduced_mz_timestamp {
        resolved_ids.0.insert(mz_timestamp_id);
    }
    // Even though we always remove `mz_now()` from the `with_options`, there might be `mz_now()`
    // remaining in the main query expression of the MV, so let's visit the entire statement to look
    // for `mz_now()` everywhere.
    let mut visitor = ExprContainsTemporalVisitor::new();
    visitor.visit_create_materialized_view_statement(cmvs);
    if !visitor.contains_temporal {
        resolved_ids.0.remove(&mz_now_id);
    }
}

/// Returns true if the [MaterializedViewOption] either already involves `mz_now()` or will involve
/// after purification.
pub fn materialized_view_option_contains_temporal(mvo: &MaterializedViewOption<Aug>) -> bool {
    match &mvo.value {
        Some(WithOptionValue::Refresh(RefreshOptionValue::At(RefreshAtOptionValue { time }))) => {
            let mut visitor = ExprContainsTemporalVisitor::new();
            visitor.visit_expr(time);
            visitor.contains_temporal
        }
        Some(WithOptionValue::Refresh(RefreshOptionValue::Every(RefreshEveryOptionValue {
            interval: _,
            aligned_to: Some(aligned_to),
        }))) => {
            let mut visitor = ExprContainsTemporalVisitor::new();
            visitor.visit_expr(aligned_to);
            visitor.contains_temporal
        }
        Some(WithOptionValue::Refresh(RefreshOptionValue::Every(RefreshEveryOptionValue {
            interval: _,
            aligned_to: None,
        }))) => {
            // For a `REFRESH EVERY` without an `ALIGNED TO`, purification will default the
            // `ALIGNED TO` to `mz_now()`.
            true
        }
        Some(WithOptionValue::Refresh(RefreshOptionValue::AtCreation)) => {
            // `REFRESH AT CREATION` will be purified to `REFRESH AT mz_now()`.
            true
        }
        _ => false,
    }
}

/// Determines whether the AST involves `mz_now()`.
struct ExprContainsTemporalVisitor {
    pub contains_temporal: bool,
}

impl ExprContainsTemporalVisitor {
    pub fn new() -> ExprContainsTemporalVisitor {
        ExprContainsTemporalVisitor {
            contains_temporal: false,
        }
    }
}

impl Visit<'_, Aug> for ExprContainsTemporalVisitor {
    fn visit_function(&mut self, func: &Function<Aug>) {
        self.contains_temporal |= func.name.full_item_name().item == MZ_NOW_NAME;
        visit_function(self, func);
    }
}

struct MzNowPurifierVisitor {
    pub mz_now: Option<Timestamp>,
    pub mz_timestamp_type: ResolvedDataType,
    pub introduced_mz_timestamp: bool,
}

impl MzNowPurifierVisitor {
    pub fn new(
        mz_now: Option<Timestamp>,
        mz_timestamp_type: ResolvedDataType,
    ) -> MzNowPurifierVisitor {
        MzNowPurifierVisitor {
            mz_now,
            mz_timestamp_type,
            introduced_mz_timestamp: false,
        }
    }
}

impl VisitMut<'_, Aug> for MzNowPurifierVisitor {
    fn visit_expr_mut(&mut self, expr: &'_ mut Expr<Aug>) {
        match expr {
            Expr::Function(Function {
                name:
                    ResolvedItemName::Item {
                        full_name: FullItemName { item, .. },
                        ..
                    },
                ..
            }) if item == &MZ_NOW_NAME.to_string() => {
                let mz_now = self.mz_now.expect(
                    "we should have chosen a timestamp if the expression contains mz_now()",
                );
                // We substitute `mz_now()` with number + a cast to `mz_timestamp`. The cast is to
                // not alter the type of the expression.
                *expr = Expr::Cast {
                    expr: Box::new(Expr::Value(Value::Number(mz_now.to_string()))),
                    data_type: self.mz_timestamp_type.clone(),
                };
                self.introduced_mz_timestamp = true;
            }
            _ => visit_expr_mut(self, expr),
        }
    }
}