1use 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
42use 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
48const 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
99pub(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 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 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 let (post_item_updates, item_updates): (Vec<_>, Vec<_>) = item_updates
150 .into_iter()
151 .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 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 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 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
217fn 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 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 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 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 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_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 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 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 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 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 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 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 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 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 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 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 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 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 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
745pub(crate) fn durable_migrate(
749 tx: &mut Transaction,
750 _organization_id: Uuid,
751 _boot_ts: Timestamp,
752) -> Result<(), anyhow::Error> {
753 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 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
799fn migrate_builtin_tables_to_mvs(tx: &mut Transaction) -> Result<(), anyhow::Error> {
803 let expected_mvs: BTreeSet<_> = BUILTINS::materialized_views()
805 .map(|mv| (mv.schema, mv.name))
806 .collect();
807
808 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
843fn 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
865fn 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 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 if !table.constraints.is_empty() {
918 return Ok(());
919 }
920
921 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
952fn 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 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
999fn 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 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 && i.item_type() == CatalogItemType::Type
1043 });
1044 if let Some(item) = user_type {
1045 return Some(item.id.to_string());
1046 }
1047 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
1063fn 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
1101fn 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 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
1193fn 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
1223fn 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
1241fn 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)] fn strips_version_from_builtin_reference() {
1275 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 assert!(out.contains("s518"), "reference dropped: {out}");
1284 }
1285
1286 #[mz_ore::test]
1287 #[cfg_attr(miri, ignore)] fn preserves_version_on_user_reference() {
1289 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)] 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)] 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)] fn adds_ids_to_bare_doc_on_references() {
1339 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)] 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}