Skip to main content

mz_adapter/catalog/
migrate.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::time::Duration;
12
13use base64::prelude::*;
14use maplit::btreeset;
15use mz_catalog::builtin::{BUILTINS, BuiltinTable};
16use mz_catalog::durable::objects::{SystemObjectDescription, SystemObjectMapping};
17use mz_catalog::durable::{MOCK_AUTHENTICATION_NONCE_KEY, Transaction};
18use mz_catalog::memory::objects::{StateUpdate, StateUpdateKind};
19use mz_ore::collections::CollectionExt;
20use mz_ore::now::NowFn;
21use mz_persist_types::ShardId;
22use mz_proto::RustType;
23use mz_repr::{CatalogItemId, Diff, Timestamp};
24use mz_sql::ast::display::AstDisplay;
25use mz_sql::ast::{
26    CreateSinkOptionName, CreateViewStatement, CteBlock, DeferredItemName, IfExistsBehavior, Query,
27    SetExpr, SqlServerConfigOptionName, ViewDefinition,
28};
29use mz_sql::catalog::{CatalogItemType, SessionCatalog};
30use mz_sql::names::{FullItemName, QualifiedItemName};
31use mz_sql::normalize;
32use mz_sql::session::vars::{FORCE_SOURCE_TABLE_SYNTAX, Var, VarInput};
33use mz_sql_parser::ast::{Raw, Statement};
34use mz_storage_client::controller::StorageTxn;
35use mz_storage_types::sources::SourceExportStatementDetails;
36use mz_storage_types::sources::load_generator::LoadGeneratorOutput;
37use prost::Message;
38use semver::Version;
39use tracing::info;
40use uuid::Uuid;
41
42// DO NOT add any more imports from `crate` outside of `crate::catalog`.
43use crate::catalog::open::into_consolidatable_updates_startup;
44use crate::catalog::state::LocalExpressionCache;
45use crate::catalog::{BuiltinTableUpdate, CatalogState, ConnCatalog};
46use crate::coord::catalog_implications::parsed_state_updates::ParsedStateUpdate;
47
48/// Catalog key of the `migration_version` setting.
49///
50/// The `migration_version` tracks the version of the binary that last successfully performed and
51/// committed all the catalog migrations (including builtin schema migrations). It can be used by
52/// migration logic to identify the source version from which to migrate.
53///
54/// Note that the durable catalog also knows a `catalog_content_version`. That doesn't work for
55/// this purpose as it is already bumped to the current binary version when the catalog is opened
56/// in writable mode, before any migrations have run.
57const MIGRATION_VERSION_KEY: &str = "migration_version";
58
59pub(crate) fn get_migration_version(txn: &Transaction<'_>) -> Option<Version> {
60    txn.get_setting(MIGRATION_VERSION_KEY.into())
61        .map(|s| s.parse().expect("valid migration version"))
62}
63
64pub(crate) fn set_migration_version(
65    txn: &mut Transaction<'_>,
66    version: Version,
67) -> Result<(), mz_catalog::durable::CatalogError> {
68    txn.set_setting(MIGRATION_VERSION_KEY.into(), Some(version.to_string()))
69}
70
71fn rewrite_ast_items<F>(tx: &mut Transaction<'_>, mut f: F) -> Result<(), anyhow::Error>
72where
73    F: for<'a> FnMut(
74        &'a mut Transaction<'_>,
75        CatalogItemId,
76        &'a mut Statement<Raw>,
77    ) -> Result<(), anyhow::Error>,
78{
79    let mut updated_items = BTreeMap::new();
80
81    for mut item in tx.get_items() {
82        let mut stmt = mz_sql::parse::parse(&item.create_sql)?.into_element().ast;
83        f(tx, item.id, &mut stmt)?;
84
85        item.create_sql = stmt.to_ast_string_stable();
86
87        updated_items.insert(item.id, item);
88    }
89    tx.update_items(updated_items)?;
90    Ok(())
91}
92
93pub(crate) struct MigrateResult {
94    pub(crate) builtin_table_updates: Vec<BuiltinTableUpdate<&'static BuiltinTable>>,
95    pub(crate) catalog_updates: Vec<ParsedStateUpdate>,
96    pub(crate) post_item_updates: Vec<(StateUpdateKind, Timestamp, Diff)>,
97}
98
99/// Migrates all user items and loads them into `state`.
100///
101/// Returns the builtin updates corresponding to all user items.
102pub(crate) async fn migrate(
103    state: &mut CatalogState,
104    tx: &mut Transaction<'_>,
105    local_expr_cache: &mut LocalExpressionCache,
106    item_updates: Vec<StateUpdate>,
107    _now: NowFn,
108    _boot_ts: Timestamp,
109) -> Result<MigrateResult, anyhow::Error> {
110    let catalog_version = get_migration_version(tx).unwrap_or(Version::new(0, 0, 0));
111
112    info!(
113        "migrating statements from catalog version {:?}",
114        catalog_version
115    );
116
117    rewrite_ast_items(tx, |tx, _id, stmt| {
118        // Add per-item AST migrations below.
119        //
120        // Each migration should be a function that takes `stmt` (the AST
121        // representing the creation SQL for the item) as input. Any
122        // mutations to `stmt` will be staged for commit to the catalog.
123        //
124        // Migration functions may also take `tx` as input to stage
125        // arbitrary changes to the catalog.
126        ast_rewrite_create_sink_partition_strategy(stmt)?;
127        ast_rewrite_sql_server_constraints(stmt)?;
128        ast_rewrite_add_missing_index_ids(tx, stmt)?;
129        ast_rewrite_add_missing_doc_on_ids(tx, stmt)?;
130        ast_rewrite_kafka_metadata_refresh_intervals(stmt)?;
131        ast_rewrite_small_commit_intervals(stmt)?;
132        ast_rewrite_strip_builtin_version_pins(stmt)?;
133        ast_rewrite_strip_unsupported_column_collations(stmt)?;
134        Ok(())
135    })?;
136
137    // Load items into catalog. We make sure to consolidate the old updates with the new updates to
138    // avoid trying to apply unmigrated items.
139    let commit_ts = tx.upper();
140    let mut item_updates = into_consolidatable_updates_startup(item_updates, commit_ts);
141    let op_item_updates = tx.get_and_commit_op_updates();
142    let op_item_updates = into_consolidatable_updates_startup(op_item_updates, commit_ts);
143    item_updates.extend(op_item_updates);
144    differential_dataflow::consolidation::consolidate_updates(&mut item_updates);
145
146    // Since some migrations might introduce non-item 'post-item' updates, we sequester those
147    // so they can be applied with other post-item updates after migrations to avoid
148    // accumulating negative diffs.
149    let (post_item_updates, item_updates): (Vec<_>, Vec<_>) = item_updates
150        .into_iter()
151        // The only post-item update kind we currently generate is to
152        // update storage collection metadata.
153        .partition(|(kind, _, _)| matches!(kind, StateUpdateKind::StorageCollectionMetadata(_)));
154
155    let item_updates = item_updates
156        .into_iter()
157        .map(|(kind, ts, diff)| StateUpdate {
158            kind,
159            ts,
160            diff: diff.try_into().expect("valid diff"),
161        })
162        .collect();
163
164    let force_source_table_syntax = state.system_config().force_source_table_syntax();
165    // When this flag is set the legacy syntax is denied. But here we are about to perform a
166    // migration which requires that we parse the current catalog state. To proceed we temporarily disable
167    // the flag and then reset it after migrations are done.
168    if force_source_table_syntax {
169        state
170            .system_config_mut()
171            .set(FORCE_SOURCE_TABLE_SYNTAX.name(), VarInput::Flat("off"))
172            .expect("known parameter");
173    }
174
175    let (mut ast_builtin_table_updates, mut ast_catalog_updates) =
176        state.apply_updates(item_updates, local_expr_cache).await;
177
178    info!("migrating from catalog version {:?}", catalog_version);
179
180    // Special block for `ast_rewrite_sources_to_tables` migration
181    // since it requires a feature flag needs to update multiple AST items at once.
182    if force_source_table_syntax {
183        rewrite_sources_to_tables(tx, &state.for_system_session())?;
184    }
185
186    if force_source_table_syntax {
187        state
188            .system_config_mut()
189            .set(FORCE_SOURCE_TABLE_SYNTAX.name(), VarInput::Flat("on"))
190            .expect("known parameter");
191    }
192
193    // Add whole-catalog migrations below.
194    //
195    // Each migration should be a function that takes `tx` and `conn_cat` as
196    // input and stages arbitrary transformations to the catalog on `tx`.
197
198    let op_item_updates = tx.get_and_commit_op_updates();
199    let (item_builtin_table_updates, item_catalog_updates) =
200        state.apply_updates(op_item_updates, local_expr_cache).await;
201
202    ast_builtin_table_updates.extend(item_builtin_table_updates);
203    ast_catalog_updates.extend(item_catalog_updates);
204
205    info!(
206        "migration from catalog version {:?} complete",
207        catalog_version
208    );
209
210    Ok(MigrateResult {
211        builtin_table_updates: ast_builtin_table_updates,
212        catalog_updates: ast_catalog_updates,
213        post_item_updates,
214    })
215}
216
217// Add new migrations below their appropriate heading, and precede them with a
218// short summary of the migration's purpose and optional additional commentary
219// about safety or approach.
220//
221// The convention is to name the migration function using snake case:
222// > <category>_<description>_<version>
223//
224// Please include the adapter team on any code reviews that add or edit
225// migrations.
226
227/// Migrates all sources to use the new sources as tables model
228///
229/// Suppose we have an old-style source named `source_name` with global id `source_id`. The source
230/// will also have an associated progress source named `progress_name` (which is almost always
231/// `source_name` + "_progress") with global id `progress_id`.
232///
233/// We have two constraints to satisfy. The migration:
234///   1. should not change the schema of a global id *if that global id maps to a
235///      durable collection*. The reason for this constraint is that when a durable collection (i.e
236///      backed by a persist shard) is opened persist will verify that the schema is the expected
237///      one. If we change the Create SQL of a global id to a non-durable definition (e.g a view)
238///      then we are free to also change the schema.
239///   2. should make it such that the SQL object that is constructed with a new-style `CREATE
240///      SOURCE` statement contains the progress data and all other objects related to the
241///      old-style source depend on that object.
242///
243/// With these constraints we consider two cases.
244///
245/// ## Case 1: A multi-output source
246///
247/// Multi-output sources have a dummy output as the contents of `source_name` that is useless. So
248/// we re-purpose that name to be the `CREATE SOURCE` statement and make `progress_name` be a view
249/// of `source_name`. Since the main source is a durable object we must move `source_name` and the
250/// corresponding new-style `CREATE SOURCE` statement under `progress_id`. Then `progress_name` can
251/// move to `source_id` and since it becomes a view we are free to change its schema.
252///
253/// Visually, we are changing this mapping:
254///
255/// |  Global ID  |  SQL Name     | Create SQL                 | Schema   | Durable |
256/// +-------------+---------------+----------------------------+----------+---------|
257/// | source_id   | source_name   | CREATE SOURCE (old-style)  | empty    | yes     |
258/// | progress_id | progress_name | CREATE SUBSOURCE .."       | progress | yes     |
259///
260/// to this mapping:
261///
262/// |  Global ID  |  SQL Name     | Create SQL                | Schema        | Durable |
263/// +-------------+---------------+---------------------------+---------------+---------+
264/// | source_id   | progress_name | CREATE VIEW               | progress data | no      |
265/// | progress_id | source_name   | CREATE SOURCE (new-style) | progress data | yes     |
266///
267/// ## Case 2: A single-output source
268///
269/// Single-output sources have data as the contents of `source_name` and so we can't repurpose that
270/// name to be the `CREATE SOURCE` statement. Here we leave everything intact except for the
271/// Create SQL of each object. Namely, the old-style `CREATE SOURCE` statement becomes a `CREATE
272/// TABLE FROM SOURCE` and the old-style `CREATE SUBSOURCE .. PROGRESS` becomes a new-style `CREATE
273/// SOURCE` statement.
274///
275/// Visually, we are changing this mapping:
276///
277/// |  Global ID  |  SQL Name     | Create SQL                 | Schema      | Durable |
278/// +-------------+---------------+----------------------------+-------------+---------|
279/// | source_id   | source_name   | CREATE SOURCE (old-style)  | source data | yes     |
280/// | progress_id | progress_name | CREATE SUBSOURCE .."       | progress    | yes     |
281///
282/// to this mapping:
283///
284/// |  Global ID  |  SQL Name     | Create SQL                 | Schema      | Durable |
285/// +-------------+---------------+----------------------------+-------------+---------|
286/// | source_id   | source_name   | CREATE TABLE FROM SOURCE   | source data | yes     |
287/// | progress_id | progress_name | CREATE SOURCE (new-style)  | progress    | yes     |
288///
289/// ## Subsource migration
290///
291/// After the migration goes over all the `CREATE SOURCE` statements it then transforms each
292/// non-progress `CREATE SUBSOURCE` statement to be a `CREATE TABLE FROM SOURCE` statement that
293/// points to the original `source_name` but with the altered global id (which is now
294/// `progress_id`).
295fn rewrite_sources_to_tables(
296    tx: &mut Transaction<'_>,
297    catalog: &ConnCatalog<'_>,
298) -> Result<(), anyhow::Error> {
299    use mz_sql::ast::{
300        CreateSourceConnection, CreateSourceStatement, CreateSubsourceOptionName,
301        CreateSubsourceStatement, CreateTableFromSourceStatement, Ident,
302        KafkaSourceConfigOptionName, LoadGenerator, MySqlConfigOptionName, PgConfigOptionName,
303        RawItemName, TableFromSourceColumns, TableFromSourceOption, TableFromSourceOptionName,
304        UnresolvedItemName, Value, WithOptionValue,
305    };
306
307    let mut updated_items = BTreeMap::new();
308
309    let mut sources = vec![];
310    let mut subsources = vec![];
311
312    for item in tx.get_items() {
313        let stmt = mz_sql::parse::parse(&item.create_sql)?.into_element().ast;
314        match stmt {
315            Statement::CreateSubsource(stmt) => subsources.push((item, stmt)),
316            Statement::CreateSource(stmt) => sources.push((item, stmt)),
317            _ => {}
318        }
319    }
320
321    let mut pending_progress_items = BTreeMap::new();
322    let mut migrated_source_ids = BTreeMap::new();
323    // We first go over the sources, which depending on the kind determine what happens with the
324    // progress statements.
325    for (mut source_item, source_stmt) in sources {
326        let CreateSourceStatement {
327            name,
328            in_cluster,
329            col_names,
330            mut connection,
331            include_metadata,
332            format,
333            envelope,
334            if_not_exists,
335            key_constraint,
336            with_options,
337            external_references,
338            progress_subsource,
339        } = source_stmt;
340
341        let (progress_name, progress_item) = match progress_subsource {
342            Some(DeferredItemName::Named(RawItemName::Name(name))) => {
343                let partial_name = normalize::unresolved_item_name(name.clone())?;
344                (name, catalog.resolve_item(&partial_name)?)
345            }
346            Some(DeferredItemName::Named(RawItemName::Id(id, name, _))) => {
347                let gid = id.parse()?;
348                (name, catalog.get_item(&gid))
349            }
350            Some(DeferredItemName::Deferred(_)) => {
351                unreachable!("invalid progress subsource")
352            }
353            None => {
354                info!("migrate: skipping already migrated source: {name}");
355                continue;
356            }
357        };
358        let raw_progress_name =
359            RawItemName::Id(progress_item.id().to_string(), progress_name.clone(), None);
360
361        // We need to jump through some hoops to get to the raw item name of the source
362        let catalog_item = catalog.get_item(&source_item.id);
363        let source_name: &QualifiedItemName = catalog_item.name();
364        let full_source_name: FullItemName = catalog.resolve_full_name(source_name);
365        let source_name: UnresolvedItemName = normalize::unresolve(full_source_name.clone());
366
367        // First, strip the connection options that we no longer need
368        match &mut connection {
369            CreateSourceConnection::Postgres { options, .. } => {
370                options.retain(|o| match o.name {
371                    PgConfigOptionName::Details
372                    | PgConfigOptionName::Publication
373                    | PgConfigOptionName::Failover => true,
374                    PgConfigOptionName::TextColumns | PgConfigOptionName::ExcludeColumns => false,
375                });
376            }
377            CreateSourceConnection::SqlServer { options, .. } => {
378                options.retain(|o| match o.name {
379                    SqlServerConfigOptionName::Details => true,
380                    SqlServerConfigOptionName::TextColumns
381                    | SqlServerConfigOptionName::ExcludeColumns => false,
382                });
383            }
384            CreateSourceConnection::MySql { options, .. } => {
385                options.retain(|o| match o.name {
386                    MySqlConfigOptionName::Details => true,
387                    MySqlConfigOptionName::TextColumns | MySqlConfigOptionName::ExcludeColumns => {
388                        false
389                    }
390                });
391            }
392            CreateSourceConnection::Kafka { .. } | CreateSourceConnection::LoadGenerator { .. } => {
393            }
394        }
395
396        // Then, figure out the new statements for the progress and source.
397        let (new_progress_name, new_progress_stmt, new_source_name, new_source_stmt) =
398            match connection {
399                connection @ (CreateSourceConnection::Postgres { .. }
400                | CreateSourceConnection::MySql { .. }
401                | CreateSourceConnection::SqlServer { .. }
402                | CreateSourceConnection::LoadGenerator {
403                    generator:
404                        LoadGenerator::Tpch | LoadGenerator::Auction | LoadGenerator::Marketing,
405                    ..
406                }) => {
407                    // Assert the expected state of the source
408                    assert_eq!(col_names, &[]);
409                    assert_eq!(key_constraint, None);
410                    assert_eq!(format, None);
411                    assert_eq!(envelope, None);
412                    assert_eq!(include_metadata, &[]);
413                    assert_eq!(external_references, None);
414
415                    // This is a dummy replacement statement for the source object of multi-output
416                    // sources. It is describing the query `TABLE source_name`. This ensures that
417                    // whoever was used to run select queries against the `source_name` + "_progress"
418                    // object still gets the same data after the migration. This switch does
419                    // changes the schema of the object with `source_item.id` but because we're turning
420                    // it into a view, which is not durable, it's ok. We'll never open a persist shard
421                    // for this global id anymore.
422                    let dummy_source_stmt = Statement::CreateView(CreateViewStatement {
423                        if_exists: IfExistsBehavior::Error,
424                        temporary: false,
425                        definition: ViewDefinition {
426                            name: progress_name,
427                            columns: vec![],
428                            query: Query {
429                                ctes: CteBlock::Simple(vec![]),
430                                body: SetExpr::Table(RawItemName::Id(
431                                    progress_item.id().to_string(),
432                                    source_name.clone(),
433                                    None,
434                                )),
435                                order_by: vec![],
436                                limit: None,
437                                offset: None,
438                            },
439                        },
440                    });
441
442                    let new_progress_stmt = CreateSourceStatement {
443                        name: source_name.clone(),
444                        in_cluster,
445                        col_names: vec![],
446                        connection,
447                        include_metadata: vec![],
448                        format: None,
449                        envelope: None,
450                        if_not_exists,
451                        key_constraint: None,
452                        with_options,
453                        external_references: None,
454                        progress_subsource: None,
455                    };
456
457                    migrated_source_ids.insert(source_item.id, progress_item.id());
458
459                    (
460                        full_source_name.item,
461                        new_progress_stmt,
462                        progress_item.name().item.clone(),
463                        dummy_source_stmt,
464                    )
465                }
466                CreateSourceConnection::Kafka {
467                    options,
468                    connection,
469                } => {
470                    let constraints = if let Some(_key_constraint) = key_constraint {
471                        // Primary key not enforced is not enabled for anyone
472                        // TODO: remove the feature altogether
473                        vec![]
474                    } else {
475                        vec![]
476                    };
477
478                    let columns = if col_names.is_empty() {
479                        TableFromSourceColumns::NotSpecified
480                    } else {
481                        TableFromSourceColumns::Named(col_names)
482                    };
483
484                    // All source tables must have a `details` option, which is a serialized proto
485                    // describing any source-specific details for this table statement.
486                    let details = SourceExportStatementDetails::Kafka {};
487                    let table_with_options = vec![TableFromSourceOption {
488                        name: TableFromSourceOptionName::Details,
489                        value: Some(WithOptionValue::Value(Value::String(hex::encode(
490                            details.into_proto().encode_to_vec(),
491                        )))),
492                    }];
493                    // The external reference for a kafka source is the just the topic name
494                    let topic_option = options
495                        .iter()
496                        .find(|o| matches!(o.name, KafkaSourceConfigOptionName::Topic))
497                        .expect("kafka sources must have a topic");
498                    let topic = match &topic_option.value {
499                        Some(WithOptionValue::Value(Value::String(topic))) => topic,
500                        _ => unreachable!("topic must be a string"),
501                    };
502                    let external_reference = UnresolvedItemName::qualified(&[Ident::new(topic)?]);
503
504                    let new_source_stmt =
505                        Statement::CreateTableFromSource(CreateTableFromSourceStatement {
506                            name: source_name,
507                            constraints,
508                            columns,
509                            if_not_exists,
510                            source: raw_progress_name,
511                            include_metadata,
512                            format,
513                            envelope,
514                            external_reference: Some(external_reference),
515                            with_options: table_with_options,
516                        });
517
518                    let new_progress_stmt = CreateSourceStatement {
519                        name: progress_name,
520                        in_cluster,
521                        col_names: vec![],
522                        connection: CreateSourceConnection::Kafka {
523                            options,
524                            connection,
525                        },
526                        include_metadata: vec![],
527                        format: None,
528                        envelope: None,
529                        if_not_exists,
530                        key_constraint: None,
531                        with_options,
532                        external_references: None,
533                        progress_subsource: None,
534                    };
535                    (
536                        progress_item.name().item.clone(),
537                        new_progress_stmt,
538                        full_source_name.item,
539                        new_source_stmt,
540                    )
541                }
542                CreateSourceConnection::LoadGenerator {
543                    generator:
544                        generator @ (LoadGenerator::Clock
545                        | LoadGenerator::Counter
546                        | LoadGenerator::Datums
547                        | LoadGenerator::KeyValue),
548                    options,
549                } => {
550                    let constraints = if let Some(_key_constraint) = key_constraint {
551                        // Should we ignore not enforced primary key constraints here?
552                        vec![]
553                    } else {
554                        vec![]
555                    };
556
557                    let columns = if col_names.is_empty() {
558                        TableFromSourceColumns::NotSpecified
559                    } else {
560                        TableFromSourceColumns::Named(col_names)
561                    };
562
563                    // All source tables must have a `details` option, which is a serialized proto
564                    // describing any source-specific details for this table statement.
565                    let details = SourceExportStatementDetails::LoadGenerator {
566                        output: LoadGeneratorOutput::Default,
567                    };
568                    let table_with_options = vec![TableFromSourceOption {
569                        name: TableFromSourceOptionName::Details,
570                        value: Some(WithOptionValue::Value(Value::String(hex::encode(
571                            details.into_proto().encode_to_vec(),
572                        )))),
573                    }];
574                    // Since these load generators are single-output the external reference
575                    // uses the schema-name for both namespace and name.
576                    let external_reference = FullItemName {
577                        database: mz_sql::names::RawDatabaseSpecifier::Name(
578                            mz_storage_types::sources::load_generator::LOAD_GENERATOR_DATABASE_NAME
579                                .to_owned(),
580                        ),
581                        schema: generator.schema_name().to_string(),
582                        item: generator.schema_name().to_string(),
583                    };
584
585                    let new_source_stmt =
586                        Statement::CreateTableFromSource(CreateTableFromSourceStatement {
587                            name: source_name,
588                            constraints,
589                            columns,
590                            if_not_exists,
591                            source: raw_progress_name,
592                            include_metadata,
593                            format,
594                            envelope,
595                            external_reference: Some(external_reference.into()),
596                            with_options: table_with_options,
597                        });
598
599                    let new_progress_stmt = CreateSourceStatement {
600                        name: progress_name,
601                        in_cluster,
602                        col_names: vec![],
603                        connection: CreateSourceConnection::LoadGenerator { generator, options },
604                        include_metadata: vec![],
605                        format: None,
606                        envelope: None,
607                        if_not_exists,
608                        key_constraint: None,
609                        with_options,
610                        external_references: None,
611                        progress_subsource: None,
612                    };
613                    (
614                        progress_item.name().item.clone(),
615                        new_progress_stmt,
616                        full_source_name.item,
617                        new_source_stmt,
618                    )
619                }
620            };
621
622        // The source can be updated right away but the replacement progress statement will
623        // be installed in the next loop where we go over subsources.
624
625        info!(
626            "migrate: converted source {} to {}",
627            source_item.create_sql, new_source_stmt
628        );
629        source_item.name = new_source_name.clone();
630        source_item.create_sql = new_source_stmt.to_ast_string_stable();
631        updated_items.insert(source_item.id, source_item);
632        pending_progress_items.insert(progress_item.id(), (new_progress_name, new_progress_stmt));
633    }
634
635    for (mut item, stmt) in subsources {
636        match stmt {
637            // Migrate progress statements to the corresponding statement produced from the
638            // previous step.
639            CreateSubsourceStatement {
640                of_source: None, ..
641            } => {
642                let Some((new_name, new_stmt)) = pending_progress_items.remove(&item.id) else {
643                    panic!("encountered orphan progress subsource id: {}", item.id)
644                };
645                item.name = new_name;
646                item.create_sql = new_stmt.to_ast_string_stable();
647                updated_items.insert(item.id, item);
648            }
649            // Migrate each `CREATE SUBSOURCE` statement to an equivalent
650            // `CREATE TABLE ... FROM SOURCE` statement.
651            CreateSubsourceStatement {
652                name,
653                columns,
654                constraints,
655                of_source: Some(raw_source_name),
656                if_not_exists,
657                mut with_options,
658            } => {
659                let new_raw_source_name = match raw_source_name {
660                    RawItemName::Id(old_id, name, None) => {
661                        let old_id: CatalogItemId = old_id.parse().expect("well formed");
662                        let new_id = migrated_source_ids[&old_id].clone();
663                        RawItemName::Id(new_id.to_string(), name, None)
664                    }
665                    _ => unreachable!("unexpected source name: {raw_source_name}"),
666                };
667                // The external reference is a `with_option` on subsource statements but is a
668                // separate field on table statements.
669                let external_reference = match with_options
670                    .iter()
671                    .position(|opt| opt.name == CreateSubsourceOptionName::ExternalReference)
672                {
673                    Some(i) => match with_options.remove(i).value {
674                        Some(WithOptionValue::UnresolvedItemName(name)) => name,
675                        _ => unreachable!("external reference must be an unresolved item name"),
676                    },
677                    None => panic!("subsource must have an external reference"),
678                };
679
680                let with_options = with_options
681                    .into_iter()
682                    .map(|option| {
683                        match option.name {
684                            CreateSubsourceOptionName::Details => TableFromSourceOption {
685                                name: TableFromSourceOptionName::Details,
686                                // The `details` option on both subsources and tables is identical, using the same
687                                // ProtoSourceExportStatementDetails serialized value.
688                                value: option.value,
689                            },
690                            CreateSubsourceOptionName::TextColumns => TableFromSourceOption {
691                                name: TableFromSourceOptionName::TextColumns,
692                                value: option.value,
693                            },
694                            CreateSubsourceOptionName::ExcludeColumns => TableFromSourceOption {
695                                name: TableFromSourceOptionName::ExcludeColumns,
696                                value: option.value,
697                            },
698                            CreateSubsourceOptionName::RetainHistory => TableFromSourceOption {
699                                name: TableFromSourceOptionName::RetainHistory,
700                                value: option.value,
701                            },
702                            CreateSubsourceOptionName::Progress => {
703                                panic!("progress option should not exist on this subsource")
704                            }
705                            CreateSubsourceOptionName::ExternalReference => {
706                                unreachable!("This option is handled separately above.")
707                            }
708                        }
709                    })
710                    .collect::<Vec<_>>();
711
712                let table = CreateTableFromSourceStatement {
713                    name,
714                    constraints,
715                    columns: TableFromSourceColumns::Defined(columns),
716                    if_not_exists,
717                    source: new_raw_source_name,
718                    external_reference: Some(external_reference),
719                    with_options,
720                    // Subsources don't have `envelope`, `include_metadata`, or `format` options.
721                    envelope: None,
722                    include_metadata: vec![],
723                    format: None,
724                };
725
726                info!(
727                    "migrate: converted subsource {} to table {}",
728                    item.create_sql, table
729                );
730                item.create_sql = Statement::CreateTableFromSource(table).to_ast_string_stable();
731                updated_items.insert(item.id, item);
732            }
733        }
734    }
735    assert!(
736        pending_progress_items.is_empty(),
737        "unexpected residual progress items: {pending_progress_items:?}"
738    );
739
740    tx.update_items(updated_items)?;
741
742    Ok(())
743}
744
745// Durable migrations
746
747/// Migrations that run only on the durable catalog before any data is loaded into memory.
748pub(crate) fn durable_migrate(
749    tx: &mut Transaction,
750    _organization_id: Uuid,
751    _boot_ts: Timestamp,
752) -> Result<(), anyhow::Error> {
753    // Migrate the expression cache to a new shard. We're updating the keys to use the explicit
754    // binary version instead of the deploy generation.
755    const EXPR_CACHE_MIGRATION_KEY: &str = "expr_cache_migration";
756    const EXPR_CACHE_MIGRATION_DONE: u64 = 1;
757    if tx.get_config(EXPR_CACHE_MIGRATION_KEY.to_string()) != Some(EXPR_CACHE_MIGRATION_DONE) {
758        if let Some(shard_id) = tx.get_expression_cache_shard() {
759            tx.insert_unfinalized_shards(btreeset! {shard_id})?;
760            tx.set_expression_cache_shard(ShardId::new())?;
761        }
762        tx.set_config(
763            EXPR_CACHE_MIGRATION_KEY.to_string(),
764            Some(EXPR_CACHE_MIGRATION_DONE),
765        )?;
766    }
767
768    // Migrate the builtin migration shard to a new shard. We're updating the keys to use the explicit
769    // binary version instead of the deploy generation.
770    const BUILTIN_MIGRATION_SHARD_MIGRATION_KEY: &str = "migration_shard_migration";
771    const BUILTIN_MIGRATION_SHARD_MIGRATION_DONE: u64 = 1;
772    if tx.get_config(BUILTIN_MIGRATION_SHARD_MIGRATION_KEY.to_string())
773        != Some(BUILTIN_MIGRATION_SHARD_MIGRATION_DONE)
774    {
775        if let Some(shard_id) = tx.get_builtin_migration_shard() {
776            tx.insert_unfinalized_shards(btreeset! {shard_id})?;
777            tx.set_builtin_migration_shard(ShardId::new())?;
778        }
779        tx.set_config(
780            BUILTIN_MIGRATION_SHARD_MIGRATION_KEY.to_string(),
781            Some(BUILTIN_MIGRATION_SHARD_MIGRATION_DONE),
782        )?;
783    }
784
785    if tx
786        .get_setting(MOCK_AUTHENTICATION_NONCE_KEY.to_string())
787        .is_none()
788    {
789        let nonce: [u8; 24] = rand::random();
790        let nonce = BASE64_STANDARD.encode(nonce);
791        tx.set_setting(MOCK_AUTHENTICATION_NONCE_KEY.to_string(), Some(nonce))?;
792    }
793
794    migrate_builtin_tables_to_mvs(tx)?;
795
796    Ok(())
797}
798
799/// Update system object mappings for builtins whose type changed from table to materialized view.
800///
801/// Required for the work of making builtin tables views over `mz_catalog_raw`.
802fn migrate_builtin_tables_to_mvs(tx: &mut Transaction) -> Result<(), anyhow::Error> {
803    // Collect `(schema, name)` of all builtin MVs.
804    let expected_mvs: BTreeSet<_> = BUILTINS::materialized_views()
805        .map(|mv| (mv.schema, mv.name))
806        .collect();
807
808    // Find persisted mappings for builtin tables that must be migrated.
809    let mut to_remove = BTreeSet::new();
810    let mut to_add = Vec::new();
811    for mapping in tx.get_system_object_mappings() {
812        let desc = &mapping.description;
813        if desc.object_type != CatalogItemType::Table {
814            continue;
815        }
816
817        let key = (&*desc.schema_name, &*desc.object_name);
818        if expected_mvs.contains(&key) {
819            info!(
820                "migrate: builtin {}.{} changed type from table to MV",
821                desc.schema_name, desc.object_name,
822            );
823            to_remove.insert(desc.clone());
824            to_add.push(SystemObjectMapping {
825                description: SystemObjectDescription {
826                    schema_name: desc.schema_name.clone(),
827                    object_type: CatalogItemType::MaterializedView,
828                    object_name: desc.object_name.clone(),
829                },
830                unique_identifier: mapping.unique_identifier,
831            });
832        }
833    }
834
835    if !to_remove.is_empty() {
836        tx.remove_system_object_mappings(to_remove)?;
837        tx.set_system_object_mappings(to_add)?;
838    }
839
840    Ok(())
841}
842
843// Add new migrations below their appropriate heading, and precede them with a
844// short summary of the migration's purpose and optional additional commentary
845// about safety or approach.
846//
847// The convention is to name the migration function using snake case:
848// > <category>_<description>_<version>
849//
850// Please include the adapter team on any code reviews that add or edit
851// migrations.
852
853// Remove PARTITION STRATEGY from CREATE SINK statements.
854fn ast_rewrite_create_sink_partition_strategy(
855    stmt: &mut Statement<Raw>,
856) -> Result<(), anyhow::Error> {
857    let Statement::CreateSink(stmt) = stmt else {
858        return Ok(());
859    };
860    stmt.with_options
861        .retain(|op| op.name != CreateSinkOptionName::PartitionStrategy);
862    Ok(())
863}
864
865// Migrate SQL Server constraint information from the columns to dedicated constraints field.
866fn ast_rewrite_sql_server_constraints(stmt: &mut Statement<Raw>) -> Result<(), anyhow::Error> {
867    use mz_sql::ast::{
868        CreateSubsourceOptionName, TableFromSourceOptionName, Value, WithOptionValue,
869    };
870    use mz_sql_server_util::desc::{SqlServerTableConstraint, SqlServerTableConstraintType};
871    use mz_storage_types::sources::ProtoSourceExportStatementDetails;
872    use mz_storage_types::sources::proto_source_export_statement_details::Kind;
873
874    let deets: Option<&mut String> = match stmt {
875        Statement::CreateSubsource(stmt) => stmt.with_options.iter_mut().find_map(|option| {
876            if matches!(option.name, CreateSubsourceOptionName::Details)
877                && let Some(WithOptionValue::Value(Value::String(ref mut details))) = option.value
878            {
879                Some(details)
880            } else {
881                None
882            }
883        }),
884        Statement::CreateTableFromSource(stmt) => stmt.with_options.iter_mut().find_map(|option| {
885            if matches!(option.name, TableFromSourceOptionName::Details)
886                && let Some(WithOptionValue::Value(Value::String(ref mut details))) = option.value
887            {
888                Some(details)
889            } else {
890                None
891            }
892        }),
893        _ => None,
894    };
895    let Some(deets) = deets else {
896        return Ok(());
897    };
898
899    let current_value = hex::decode(&mut *deets)?;
900    let current_value = ProtoSourceExportStatementDetails::decode(&*current_value)?;
901
902    // avoid further work if this isn't SQL Server
903    if !matches!(current_value.kind, Some(Kind::SqlServer(_))) {
904        return Ok(());
905    };
906
907    let SourceExportStatementDetails::SqlServer {
908        mut table,
909        capture_instance,
910        initial_lsn,
911    } = SourceExportStatementDetails::from_proto(current_value)?
912    else {
913        unreachable!("statement details must exist for SQL Server");
914    };
915
916    // Migration has already occured or did not need to happen.
917    if !table.constraints.is_empty() {
918        return Ok(());
919    }
920
921    // Relocates the primary key constraint information from the individual columns to the
922    // constraints field. This ensures that the columns no longer hold constraint information.
923    let mut migrated_constraints: BTreeMap<_, Vec<_>> = BTreeMap::new();
924    for col in table.columns.iter_mut() {
925        if let Some(constraint_name) = col.primary_key_constraint.take() {
926            migrated_constraints
927                .entry(constraint_name)
928                .or_default()
929                .push(col.name.to_string());
930        }
931    }
932
933    table.constraints = migrated_constraints
934        .into_iter()
935        .map(|(constraint_name, column_names)| SqlServerTableConstraint {
936            constraint_name: constraint_name.to_string(),
937            constraint_type: SqlServerTableConstraintType::PrimaryKey,
938            column_names,
939        })
940        .collect();
941
942    let new_value = SourceExportStatementDetails::SqlServer {
943        table,
944        capture_instance,
945        initial_lsn,
946    };
947    *deets = hex::encode(new_value.into_proto().encode_to_vec());
948
949    Ok(())
950}
951
952/// Add missing item IDs to the ON clauses of CREATE INDEX statements.
953fn ast_rewrite_add_missing_index_ids(
954    tx: &Transaction<'_>,
955    stmt: &mut Statement<Raw>,
956) -> Result<(), anyhow::Error> {
957    let Statement::CreateIndex(stmt) = stmt else {
958        return Ok(());
959    };
960
961    let unresolved_name = match stmt.on_name.clone() {
962        mz_sql::ast::RawItemName::Name(name) => name,
963        // ID already present; nothing to do.
964        mz_sql::ast::RawItemName::Id(..) => return Ok(()),
965    };
966
967    let parts = &unresolved_name.0;
968    let (db_name, schema_name, item_name) = match parts.len() {
969        3 => (Some(&parts[0]), &parts[1], &parts[2]),
970        2 => (None, &parts[0], &parts[1]),
971        _ => panic!("invalid unresolved name: {unresolved_name:?}"),
972    };
973
974    let db_id = db_name.map(|x| {
975        let db = tx.get_databases().find(|db| db.name == x.as_str());
976        let db = db.unwrap_or_else(|| panic!("missing database: {x}"));
977        db.id
978    });
979    let schema_id = {
980        let schema = tx
981            .get_schemas()
982            .find(|s| s.name == schema_name.as_str() && s.database_id == db_id);
983        let schema = schema.unwrap_or_else(|| panic!("missing schema: {schema_name}, {db_id:?}"));
984        schema.id
985    };
986    let item_id = {
987        let item = tx
988            .get_items()
989            .find(|i| i.name == item_name.as_str() && i.schema_id == schema_id);
990        let item = item.unwrap_or_else(|| panic!("missing item: {item_name}, {schema_id:?}"));
991        item.id
992    };
993
994    stmt.on_name = mz_sql::ast::RawItemName::Id(item_id.to_string(), unresolved_name, None);
995
996    Ok(())
997}
998
999/// Add missing item IDs to `DOC ON` references in CREATE SINK statements.
1000///
1001/// `DOC ON TYPE x` and `DOC ON COLUMN x.c` used to persist a type reference
1002/// as a bare qualified name, unlike a relation in the same position, because
1003/// name resolution suppressed ids for types. Resolution now prints the id
1004/// (see `NameResolver::resolve_doc_on_name`); this rewrites stored statements
1005/// to match, so `create_sql` reference extraction (`mz_object_dependencies`)
1006/// recovers the sink's edge to the type.
1007///
1008/// References that already carry an id are skipped, so this is idempotent and
1009/// safe to run every boot.
1010fn ast_rewrite_add_missing_doc_on_ids(
1011    tx: &Transaction<'_>,
1012    stmt: &mut Statement<Raw>,
1013) -> Result<(), anyhow::Error> {
1014    if !matches!(stmt, Statement::CreateSink(_)) {
1015        return Ok(());
1016    }
1017    rewrite_doc_on_ids(stmt, |name| {
1018        let parts = &name.0;
1019        let (db_name, schema_name, item_name) = match parts.len() {
1020            3 => (Some(&parts[0]), &parts[1], &parts[2]),
1021            // Names in ambient schemas denote builtin types, which are resolved
1022            // through the system object mappings.
1023            2 => (None, &parts[0], &parts[1]),
1024            _ => panic!("invalid doc on reference: {name:?}"),
1025        };
1026        let db_id = db_name.map(|db_name| {
1027            let db = tx.get_databases().find(|db| db.name == db_name.as_str());
1028            let db = db.unwrap_or_else(|| panic!("missing database in doc on reference: {name:?}"));
1029            db.id
1030        });
1031        let schema = tx
1032            .get_schemas()
1033            .find(|s| s.name == schema_name.as_str() && s.database_id == db_id);
1034        let schema =
1035            schema.unwrap_or_else(|| panic!("missing schema in doc on reference: {name:?}"));
1036
1037        let user_type = tx.get_items().find(|i| {
1038            i.name == item_name.as_str()
1039                && i.schema_id == schema.id
1040                // A type may share its (schema, name) with a secret, connection, sink,
1041                // or function, so explicitly filter on Type.
1042                && i.item_type() == CatalogItemType::Type
1043        });
1044        if let Some(item) = user_type {
1045            return Some(item.id.to_string());
1046        }
1047        // A bare name in an ambient schema denotes a builtin type (an explicit
1048        // `DOC ON TYPE int4`, or a DOC ON injected by purification after mz_system
1049        // commented on one). Builtin types are not durable items, so the lookup
1050        // above cannot find them; their ids live in the system object mappings.
1051        let builtin_type = tx.get_system_object_mappings().find(|m| {
1052            m.description.schema_name == schema.name
1053                && m.description.object_type == CatalogItemType::Type
1054                && m.description.object_name == item_name.as_str()
1055        });
1056        let builtin_type =
1057            builtin_type.unwrap_or_else(|| panic!("missing type in doc on reference: {name:?}"));
1058        Some(builtin_type.unique_identifier.catalog_id.to_string())
1059    });
1060    Ok(())
1061}
1062
1063/// Replaces every bare `DOC ON` reference in `stmt` for which `lookup`
1064/// returns an id with the `[id AS name]` form. `None` leaves the reference as
1065/// a name.
1066fn rewrite_doc_on_ids(
1067    stmt: &mut Statement<Raw>,
1068    lookup: impl FnMut(&mz_sql::ast::UnresolvedItemName) -> Option<String>,
1069) {
1070    use mz_sql::ast::visit_mut::{VisitMut, VisitMutNode};
1071    use mz_sql::ast::{ColumnName, DocOnIdentifier, RawItemName, UnresolvedItemName};
1072
1073    struct Rewriter<F> {
1074        lookup: F,
1075    }
1076
1077    impl<'ast, F> VisitMut<'ast, Raw> for Rewriter<F>
1078    where
1079        F: FnMut(&UnresolvedItemName) -> Option<String>,
1080    {
1081        fn visit_doc_on_identifier_mut(&mut self, node: &mut DocOnIdentifier<Raw>) {
1082            let name = match node {
1083                DocOnIdentifier::Type(name) => name,
1084                DocOnIdentifier::Column(ColumnName {
1085                    relation,
1086                    column: _,
1087                }) => relation,
1088            };
1089            if let RawItemName::Name(unresolved) = name {
1090                if let Some(id) = (self.lookup)(unresolved) {
1091                    let unresolved = unresolved.clone();
1092                    *name = RawItemName::Id(id, unresolved, None);
1093                }
1094            }
1095        }
1096    }
1097
1098    stmt.visit_mut(&mut Rewriter { lookup });
1099}
1100
1101/// Strips the `VERSION` qualifier from by-id references to non-user (builtin)
1102/// items.
1103///
1104/// A version pin on a builtin is meaningless, since builtins are not
1105/// user-versioned. Older binaries could still persist such a pin, and once the
1106/// builtin is converted to an item type without versions (e.g. a materialized
1107/// view) reparsing the pin fails with `InvalidVersion` and panics during
1108/// catalog open, wedging the upgrade. Stripping it makes the reference resolve
1109/// to the latest version.
1110///
1111/// The read-side resolver tolerates these pins too, so this is durable cleanup
1112/// rather than a correctness requirement. Safe to run every boot: stripping an
1113/// absent version is a no-op.
1114fn ast_rewrite_strip_builtin_version_pins(stmt: &mut Statement<Raw>) -> Result<(), anyhow::Error> {
1115    use mz_sql::ast::RawItemName;
1116    use mz_sql::ast::visit_mut::{VisitMut, VisitMutNode};
1117
1118    struct StripBuiltinVersionPins;
1119
1120    impl<'ast> VisitMut<'ast, Raw> for StripBuiltinVersionPins {
1121        fn visit_item_name_mut(&mut self, item_name: &mut RawItemName) {
1122            if let RawItemName::Id(id, _, version) = item_name {
1123                if version.is_some() {
1124                    if let Ok(parsed) = id.parse::<CatalogItemId>() {
1125                        if !parsed.is_user() {
1126                            *version = None;
1127                        }
1128                    }
1129                }
1130            }
1131        }
1132    }
1133
1134    let mut visitor = StripBuiltinVersionPins;
1135    stmt.visit_mut(&mut visitor);
1136    Ok(())
1137}
1138
1139fn ast_rewrite_kafka_metadata_refresh_intervals(
1140    stmt: &mut Statement<Raw>,
1141) -> Result<(), anyhow::Error> {
1142    use mz_sql::ast::{
1143        CreateSinkConnection, CreateSourceConnection, KafkaSinkConfigOptionName,
1144        KafkaSourceConfigOptionName, WithOptionValue,
1145    };
1146    // A user can persist the interval either as a string literal
1147    // (`WithOptionValue::Value`) or, if they wrote it as a double-quoted
1148    // value, as a lexed identifier (`WithOptionValue::UnresolvedItemName`).
1149    // Both shapes must be handled here.
1150    let interval: Option<&mut WithOptionValue<Raw>> = match stmt {
1151        Statement::CreateSource(stmt) => {
1152            if let CreateSourceConnection::Kafka { options, .. } = &mut stmt.connection {
1153                options.iter_mut().find_map(|option| {
1154                    if matches!(
1155                        option.name,
1156                        KafkaSourceConfigOptionName::TopicMetadataRefreshInterval
1157                    ) {
1158                        option.value.as_mut()
1159                    } else {
1160                        None
1161                    }
1162                })
1163            } else {
1164                None
1165            }
1166        }
1167        Statement::CreateSink(stmt) => {
1168            if let CreateSinkConnection::Kafka { options, .. } = &mut stmt.connection {
1169                options.iter_mut().find_map(|option| {
1170                    if matches!(
1171                        option.name,
1172                        KafkaSinkConfigOptionName::TopicMetadataRefreshInterval
1173                    ) {
1174                        option.value.as_mut()
1175                    } else {
1176                        None
1177                    }
1178                })
1179            } else {
1180                None
1181            }
1182        }
1183        _ => None,
1184    };
1185
1186    let Some(interval) = interval else {
1187        return Ok(());
1188    };
1189
1190    rewrite_interval_option_floor_1s(interval, "kafka metadata refresh interval")
1191}
1192
1193/// Planning enforces a 1 second minimum `COMMIT INTERVAL`, but smaller
1194/// intervals used to be accepted (and a sub-millisecond one left the sink
1195/// unable to ever commit). Rewrite any persisted smaller interval to 1s so
1196/// the sink still plans after an upgrade.
1197///
1198/// `COMMIT INTERVAL` is a generic `CREATE SINK` option in the grammar, but only
1199/// Iceberg sinks accept it and only Iceberg planning enforces the 1s floor.
1200fn ast_rewrite_small_commit_intervals(stmt: &mut Statement<Raw>) -> Result<(), anyhow::Error> {
1201    use mz_sql::ast::{CreateSinkConnection, CreateSinkOptionName};
1202
1203    let Statement::CreateSink(stmt) = stmt else {
1204        return Ok(());
1205    };
1206    if !matches!(stmt.connection, CreateSinkConnection::Iceberg { .. }) {
1207        return Ok(());
1208    }
1209    let interval = stmt.with_options.iter_mut().find_map(|o| {
1210        if matches!(o.name, CreateSinkOptionName::CommitInterval) {
1211            o.value.as_mut()
1212        } else {
1213            None
1214        }
1215    });
1216    let Some(interval) = interval else {
1217        return Ok(());
1218    };
1219
1220    rewrite_interval_option_floor_1s(interval, "commit interval")
1221}
1222
1223/// Planning rejects unsupported column collations, but `CREATE TABLE` used to
1224/// accept and ignore them. Strip them so the table still plans after an
1225/// upgrade. The planner never applied them, so the table's columns are
1226/// unchanged.
1227fn ast_rewrite_strip_unsupported_column_collations(
1228    stmt: &mut Statement<Raw>,
1229) -> Result<(), anyhow::Error> {
1230    let Statement::CreateTable(stmt) = stmt else {
1231        return Ok(());
1232    };
1233    for column in &mut stmt.columns {
1234        column
1235            .collation
1236            .take_if(|collation| !mz_sql::plan::is_supported_collation(collation));
1237    }
1238    Ok(())
1239}
1240
1241/// Rewrites an interval option value to `'1s'` if it is below 1 second.
1242fn rewrite_interval_option_floor_1s(
1243    value: &mut mz_sql::ast::WithOptionValue<Raw>,
1244    label: &str,
1245) -> Result<(), anyhow::Error> {
1246    use mz_sql::ast::{Value, WithOptionValue};
1247    use mz_sql::plan::TryFromValue;
1248
1249    let dur = Duration::try_from_value(value.clone())
1250        .map_err(|e| anyhow::anyhow!("invalid value for {label}: {value:?}: {e}"))?;
1251
1252    if dur < Duration::from_secs(1) {
1253        *value = WithOptionValue::Value(Value::String("1s".to_string()));
1254    }
1255
1256    Ok(())
1257}
1258
1259#[cfg(test)]
1260mod tests {
1261    use super::*;
1262
1263    fn strip(sql: &str) -> String {
1264        let mut stmt = mz_sql::parse::parse(sql)
1265            .expect("test sql parses")
1266            .into_element()
1267            .ast;
1268        ast_rewrite_strip_builtin_version_pins(&mut stmt).expect("rewrite succeeds");
1269        stmt.to_ast_string_stable()
1270    }
1271
1272    #[mz_ore::test]
1273    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` (SQL parser stack growth)
1274    fn strips_version_from_builtin_reference() {
1275        // A system (builtin) id must lose its version pin: builtins are never
1276        // user-versioned, so a persisted `VERSION 0` is a stale artifact that
1277        // wedges catalog open once the builtin is converted to a non-table.
1278        let out = strip(
1279            r#"CREATE VIEW "materialize"."public"."v" AS SELECT 1 FROM [s518 AS "mz_catalog"."mz_audit_events" VERSION 0]"#,
1280        );
1281        assert!(!out.contains("VERSION"), "version not stripped: {out}");
1282        // The reference itself is preserved, only the version is dropped.
1283        assert!(out.contains("s518"), "reference dropped: {out}");
1284    }
1285
1286    #[mz_ore::test]
1287    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` (SQL parser stack growth)
1288    fn preserves_version_on_user_reference() {
1289        // A user table legitimately carries versions (`ALTER TABLE ... ADD
1290        // COLUMN`), so the pin must survive.
1291        let out = strip(
1292            r#"CREATE VIEW "materialize"."public"."v" AS SELECT 1 FROM [u5 AS "materialize"."public"."t" VERSION 1]"#,
1293        );
1294        assert!(out.contains("VERSION"), "user version stripped: {out}");
1295        assert!(out.contains("u5"), "reference dropped: {out}");
1296    }
1297
1298    #[mz_ore::test]
1299    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` (SQL parser stack growth)
1300    fn leaves_unpinned_builtin_reference_untouched() {
1301        let out = strip(
1302            r#"CREATE VIEW "materialize"."public"."v" AS SELECT 1 FROM [s518 AS "mz_catalog"."mz_audit_events"]"#,
1303        );
1304        assert!(!out.contains("VERSION"), "unexpected version: {out}");
1305        assert!(out.contains("s518"), "reference dropped: {out}");
1306    }
1307
1308    #[mz_ore::test]
1309    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` (SQL parser stack growth)
1310    fn strips_unsupported_column_collations() {
1311        let mut stmt = mz_sql::parse::parse(
1312            r#"CREATE TABLE "materialize"."public"."t" ("a" [s20 AS "pg_catalog"."text"] COLLATE "unicode", "b" [s21 AS "pg_catalog"."int4"] COLLATE "nonexistent", "c" [s20 AS "pg_catalog"."text"] COLLATE "pg_catalog"."default" NOT NULL)"#,
1313        )
1314        .expect("test sql parses")
1315        .into_element()
1316        .ast;
1317        ast_rewrite_strip_unsupported_column_collations(&mut stmt).expect("rewrite succeeds");
1318        assert_eq!(
1319            stmt.to_ast_string_stable(),
1320            r#"CREATE TABLE "materialize"."public"."t" ("a" [s20 AS "pg_catalog"."text"], "b" [s21 AS "pg_catalog"."int4"], "c" [s20 AS "pg_catalog"."text"] COLLATE "pg_catalog"."default" NOT NULL)"#,
1321        );
1322    }
1323
1324    fn add_doc_on_ids(
1325        sql: &str,
1326        lookup: impl FnMut(&mz_sql::ast::UnresolvedItemName) -> Option<String>,
1327    ) -> String {
1328        let mut stmt = mz_sql::parse::parse(sql)
1329            .expect("test sql parses")
1330            .into_element()
1331            .ast;
1332        rewrite_doc_on_ids(&mut stmt, lookup);
1333        stmt.to_ast_string_stable()
1334    }
1335
1336    #[mz_ore::test]
1337    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` (SQL parser stack growth)
1338    fn adds_ids_to_bare_doc_on_references() {
1339        // The persisted shape of a sink from before types printed ids in DOC
1340        // ON positions: relations carry ids, the type and its column carry
1341        // bare names.
1342        let out = add_doc_on_ids(
1343            r#"CREATE SINK "materialize"."public"."s" FROM [u1 AS "materialize"."public"."t"] INTO KAFKA CONNECTION [u2 AS "materialize"."public"."kc"] (TOPIC = 'top') FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION [u3 AS "materialize"."public"."csr"] (DOC ON TYPE "materialize"."public"."point" = 'p', DOC ON COLUMN "materialize"."public"."point"."x" = 'x', DOC ON TYPE "pg_catalog"."int4" = 'i') ENVELOPE UPSERT"#,
1344            |name| match name.0.len() {
1345                3 => {
1346                    assert_eq!(name.0[2].as_str(), "point", "unexpected lookup: {name:?}");
1347                    Some("u9".into())
1348                }
1349                2 => {
1350                    assert_eq!(name.0[1].as_str(), "int4", "unexpected lookup: {name:?}");
1351                    Some("s23".into())
1352                }
1353                _ => panic!("unexpected lookup: {name:?}"),
1354            },
1355        );
1356        assert!(
1357            out.contains(r#"DOC ON TYPE [u9 AS "materialize"."public"."point"]"#),
1358            "type reference not rewritten: {out}"
1359        );
1360        assert!(
1361            out.contains(r#"DOC ON COLUMN [u9 AS "materialize"."public"."point"]."x""#),
1362            "column reference not rewritten: {out}"
1363        );
1364        assert!(
1365            out.contains(r#"DOC ON TYPE [s23 AS "pg_catalog"."int4"]"#),
1366            "builtin type reference not rewritten: {out}"
1367        );
1368    }
1369
1370    #[mz_ore::test]
1371    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` (SQL parser stack growth)
1372    fn leaves_id_doc_on_references_untouched() {
1373        let out = add_doc_on_ids(
1374            r#"CREATE SINK "materialize"."public"."s" FROM [u1 AS "materialize"."public"."t"] INTO KAFKA CONNECTION [u2 AS "materialize"."public"."kc"] (TOPIC = 'top') FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION [u3 AS "materialize"."public"."csr"] (DOC ON TYPE [u4 AS "materialize"."public"."point"] = 'p', DOC ON COLUMN [u1 AS "materialize"."public"."t"]."c1" = 'c') ENVELOPE UPSERT"#,
1375            |name| panic!("id reference must not be resolved: {name:?}"),
1376        );
1377        assert!(
1378            out.contains(r#"DOC ON TYPE [u4 AS "materialize"."public"."point"]"#),
1379            "id reference altered: {out}"
1380        );
1381    }
1382}