1use std::collections::{BTreeMap, BTreeSet};
16use std::fmt::Write;
17use std::iter;
18use std::num::NonZeroU32;
19use std::time::Duration;
20
21use crate::plan::{
22 AlterQueryPolicyPlan, CreateQueryPolicyPlan, QueryPlanFeature, QueryPolicyMode, QueryPolicyRule,
23};
24use chrono::DateTime;
25use itertools::Itertools;
26use mz_adapter_types::compaction::{CompactionWindow, DEFAULT_LOGICAL_COMPACTION_WINDOW_DURATION};
27use mz_arrow_util::builder::ArrowBuilder;
28use mz_auth::password::Password;
29use mz_controller_types::{ClusterId, DEFAULT_REPLICA_LOGGING_INTERVAL, ReplicaId};
30use mz_expr::{CollectionPlan, UnmaterializableFunc};
31use mz_interchange::avro::{AvroSchemaGenerator, DocTarget};
32use mz_ore::cast::{CastFrom, TryCastFrom};
33use mz_ore::collections::{CollectionExt, HashSet};
34use mz_ore::num::NonNeg;
35use mz_ore::str::StrExt;
36use mz_ore::{soft_assert_or_log, soft_panic_or_log};
37use mz_proto::RustType;
38use mz_repr::adt::interval::Interval;
39use mz_repr::adt::mz_acl_item::{MzAclItem, PrivilegeMap};
40use mz_repr::adt::timestamp::CheckedTimestamp;
41use mz_repr::network_policy_id::NetworkPolicyId;
42use mz_repr::optimize::OptimizerFeatureOverrides;
43use mz_repr::refresh_schedule::{RefreshEvery, RefreshSchedule};
44use mz_repr::role_id::RoleId;
45use mz_repr::{
46 CatalogItemId, ColumnName, RelationDesc, RelationVersion, RelationVersionSelector,
47 SqlColumnType, SqlRelationType, SqlScalarType, Timestamp, VersionedRelationDesc,
48 preserves_order, strconv,
49};
50use mz_sql_parser::ast::{
51 self, AlterClusterAction, AlterClusterStatement, AlterConnectionAction, AlterConnectionOption,
52 AlterConnectionOptionName, AlterConnectionStatement, AlterIndexAction, AlterIndexStatement,
53 AlterMaterializedViewApplyReplacementStatement, AlterNetworkPolicyStatement,
54 AlterObjectRenameStatement, AlterObjectSwapStatement, AlterRetainHistoryStatement,
55 AlterRoleOption, AlterRoleStatement, AlterSecretStatement, AlterSetClusterStatement,
56 AlterSinkAction, AlterSinkStatement, AlterSourceAction, AlterSourceAddSubsourceOption,
57 AlterSourceAddSubsourceOptionName, AlterSourceStatement, AlterSystemResetAllStatement,
58 AlterSystemResetStatement, AlterSystemSetStatement, AlterTableAddColumnStatement, AvroSchema,
59 AvroSchemaOption, AvroSchemaOptionName, ClusterAlterOption, ClusterAlterOptionName,
60 ClusterAlterOptionValue, ClusterAlterUntilReadyOption, ClusterAlterUntilReadyOptionName,
61 ClusterAutoScalingStrategyOptionValue, ClusterFeature, ClusterFeatureName, ClusterOption,
62 ClusterOptionName, ClusterScheduleOptionValue, ColumnDef, ColumnOption, CommentObjectType,
63 CommentStatement, ConnectionOption, ConnectionOptionName, CreateClusterReplicaStatement,
64 CreateClusterStatement, CreateConnectionOption, CreateConnectionOptionName,
65 CreateConnectionStatement, CreateConnectionType, CreateDatabaseStatement, CreateIndexStatement,
66 CreateMaterializedViewStatement, CreateMetricSinkOption, CreateMetricSinkOptionName,
67 CreateMetricSinkStatement, CreateNetworkPolicyStatement, CreateRoleStatement,
68 CreateSchemaStatement, CreateSecretStatement, CreateSinkConnection, CreateSinkOption,
69 CreateSinkOptionName, CreateSinkStatement, CreateSourceConnection, CreateSourceOption,
70 CreateSourceOptionName, CreateSourceStatement, CreateSubsourceOption,
71 CreateSubsourceOptionName, CreateSubsourceStatement, CreateTableFromSourceStatement,
72 CreateTableStatement, CreateTypeAs, CreateTypeListOption, CreateTypeListOptionName,
73 CreateTypeMapOption, CreateTypeMapOptionName, CreateTypeStatement, CreateViewStatement,
74 CreateWebhookSourceStatement, CsrConfigOption, CsrConfigOptionName, CsrConnection,
75 CsrConnectionAvro, CsrConnectionProtobuf, CsrSeedProtobuf, CsvColumns, DeferredItemName,
76 DocOnIdentifier, DocOnSchema, DropObjectsStatement, DropOwnedStatement, Expr, Format,
77 FormatSpecifier, GlueAvroOption, GlueAvroOptionName, IcebergSinkConfigOption, Ident,
78 IfExistsBehavior, IndexOption, IndexOptionName, KafkaSinkConfigOption, KeyConstraint,
79 LoadGeneratorOption, LoadGeneratorOptionName, MaterializedViewOption,
80 MaterializedViewOptionName, MySqlConfigOption, MySqlConfigOptionName, NetworkPolicyOption,
81 NetworkPolicyOptionName, NetworkPolicyRuleDefinition, NetworkPolicyRuleOption,
82 NetworkPolicyRuleOptionName, OnHydrationOptionValue, PgConfigOption, PgConfigOptionName,
83 ProtobufSchema, QualifiedReplica, RefreshAtOptionValue, RefreshEveryOptionValue,
84 RefreshOptionValue, ReplicaDefinition, ReplicaOption, ReplicaOptionName, RoleAttribute,
85 SetRoleVar, SourceErrorPolicy, SourceIncludeMetadata, SqlServerConfigOption,
86 SqlServerConfigOptionName, Statement, TableConstraint, TableFromSourceColumns,
87 TableFromSourceOption, TableFromSourceOptionName, TableOption, TableOptionName,
88 UnresolvedDatabaseName, UnresolvedItemName, UnresolvedObjectName, UnresolvedSchemaName, Value,
89 ViewDefinition, WithOptionValue,
90};
91use mz_sql_parser::ast::{
92 AlterQueryPolicyStatement, CreateQueryPolicyStatement, QueryPolicyOption,
93 QueryPolicyRuleDefinition, QueryPolicyRuleOption, QueryPolicyRuleOptionName,
94};
95use mz_sql_parser::ident;
96use mz_sql_parser::parser::StatementParseResult;
97use mz_storage_types::connections::inline::ReferencedConnection;
98use mz_storage_types::connections::{Connection, KafkaTopicOptions};
99use mz_storage_types::sinks::{
100 IcebergSinkConnection, KafkaIdStyle, KafkaSinkConnection, KafkaSinkFormat, KafkaSinkFormatType,
101 SinkEnvelope, StorageSinkConnection, iceberg_type_overrides,
102};
103use mz_storage_types::sources::encoding::{
104 AvroEncoding, ColumnSpec, CsvEncoding, DataEncoding, ProtobufEncoding, RegexEncoding,
105 SourceDataEncoding, included_column_desc,
106};
107use mz_storage_types::sources::envelope::{
108 KeyEnvelope, NoneEnvelope, SourceEnvelope, UnplannedSourceEnvelope, UpsertStyle,
109};
110use mz_storage_types::sources::kafka::{
111 KafkaMetadataKind, KafkaSourceConnection, KafkaSourceExportDetails, kafka_metadata_columns_desc,
112};
113use mz_storage_types::sources::load_generator::{
114 KeyValueLoadGenerator, LOAD_GENERATOR_KEY_VALUE_OFFSET_DEFAULT, LoadGenerator,
115 LoadGeneratorOutput, LoadGeneratorSourceConnection, LoadGeneratorSourceExportDetails,
116};
117use mz_storage_types::sources::mysql::{
118 MySqlSourceConnection, MySqlSourceDetails, ProtoMySqlSourceDetails,
119};
120use mz_storage_types::sources::postgres::{
121 PostgresSourceConnection, PostgresSourcePublicationDetails,
122 ProtoPostgresSourcePublicationDetails,
123};
124use mz_storage_types::sources::sql_server::{
125 ProtoSqlServerSourceExtras, SqlServerSourceExportDetails,
126};
127use mz_storage_types::sources::{
128 GenericSourceConnection, MySqlSourceExportDetails, PostgresSourceExportDetails,
129 ProtoSourceExportStatementDetails, SourceConnection, SourceDesc, SourceExportDataConfig,
130 SourceExportDetails, SourceExportStatementDetails, SqlServerSourceConnection,
131 SqlServerSourceExtras, Timeline,
132};
133use mz_storage_types::wire_format::WireFormat;
134use prost::Message;
135
136use crate::ast::display::AstDisplay;
137use crate::catalog::{
138 CatalogCluster, CatalogDatabase, CatalogError, CatalogItem, CatalogItemType,
139 CatalogRecordField, CatalogType, CatalogTypeDetails, ObjectType, SystemObjectType,
140};
141use crate::iceberg::IcebergSinkConfigOptionExtracted;
142use crate::kafka_util::{KafkaSinkConfigOptionExtracted, KafkaSourceConfigOptionExtracted};
143use crate::names::{
144 Aug, CommentObjectId, DatabaseId, DependencyIds, ObjectId, PartialItemName, QualifiedItemName,
145 ResolvedClusterName, ResolvedColumnReference, ResolvedDataType, ResolvedDatabaseSpecifier,
146 ResolvedItemName, ResolvedNetworkPolicyName, SchemaSpecifier, SystemObjectId,
147};
148use crate::normalize::{self, ident};
149use crate::plan::error::PlanError;
150use crate::plan::query::{
151 ExprContext, QueryLifetime, TypeResolutionBudget, plan_expr, scalar_type_from_sql,
152};
153use crate::plan::scope::Scope;
154use crate::plan::statement::ddl::connection::{INALTERABLE_OPTIONS, MUTUALLY_EXCLUSIVE_SETS};
155use crate::plan::statement::{StatementContext, StatementDesc, scl};
156use crate::plan::typeconv::CastContext;
157use crate::plan::with_options::{OptionalDuration, OptionalString, TryFromValue};
158use crate::plan::{
159 AlterClusterPlan, AlterClusterPlanStrategy, AlterClusterRenamePlan,
160 AlterClusterReplicaRenamePlan, AlterClusterSwapPlan, AlterConnectionPlan, AlterItemRenamePlan,
161 AlterMaterializedViewApplyReplacementPlan, AlterNetworkPolicyPlan, AlterNoopPlan,
162 AlterOptionParameter, AlterRetainHistoryPlan, AlterRolePlan, AlterSchemaRenamePlan,
163 AlterSchemaSwapPlan, AlterSecretPlan, AlterSetClusterPlan, AlterSinkPlan,
164 AlterSourceTimestampIntervalPlan, AlterSystemResetAllPlan, AlterSystemResetPlan,
165 AlterSystemSetPlan, AlterTablePlan, AutoScalingStrategy, ClusterSchedule, CommentPlan,
166 ComputeReplicaConfig, ComputeReplicaIntrospectionConfig, ConnectionDetails,
167 CreateClusterManagedPlan, CreateClusterPlan, CreateClusterReplicaPlan,
168 CreateClusterUnmanagedPlan, CreateClusterVariant, CreateConnectionPlan, CreateDatabasePlan,
169 CreateIndexPlan, CreateMaterializedViewPlan, CreateMetricSinkPlan, CreateNetworkPolicyPlan,
170 CreateRolePlan, CreateSchemaPlan, CreateSecretPlan, CreateSinkPlan, CreateSourcePlan,
171 CreateTablePlan, CreateTypePlan, CreateViewPlan, DataSourceDesc, DropObjectsPlan,
172 DropOwnedPlan, HirRelationExpr, Index, MaterializedView, MetricSink, NetworkPolicyRule,
173 NetworkPolicyRuleAction, NetworkPolicyRuleDirection, OnHydration, Plan, PlanClusterOption,
174 PlanNotice, PolicyAddress, QueryContext, ReplicaConfig, Secret, Sink, Source, Table,
175 TableDataSource, Type, VariableValue, View, WebhookBodyFormat, WebhookHeaderFilters,
176 WebhookHeaders, WebhookValidation, literal, plan_utils, query, transform_ast,
177};
178use crate::session::vars::{
179 self, ENABLE_AUTO_SCALING_STRATEGY, ENABLE_CLUSTER_SCHEDULE_REFRESH,
180 ENABLE_COLLECTION_PARTITION_BY, ENABLE_CREATE_TABLE_FROM_SOURCE, ENABLE_KAFKA_SINK_HEADERS,
181 ENABLE_METRIC_SINK, ENABLE_REFRESH_EVERY_MVS, ENABLE_REPLICA_TARGETED_MATERIALIZED_VIEWS,
182 VarInput,
183};
184use crate::{names, parse};
185
186mod connection;
187
188const MAX_NUM_COLUMNS: usize = 256;
193
194const MAX_KAFKA_TOPIC_METADATA_REFRESH_INTERVAL: Duration = Duration::from_secs(60 * 60);
195const MIN_KAFKA_TOPIC_METADATA_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
196
197static MANAGED_REPLICA_PATTERN: std::sync::LazyLock<regex::Regex> =
198 std::sync::LazyLock::new(|| regex::Regex::new(r"^r(\d)+$").unwrap());
199
200fn check_partition_by(desc: &RelationDesc, mut partition_by: Vec<Ident>) -> Result<(), PlanError> {
204 if partition_by.len() > desc.len() {
205 tracing::error!(
206 "PARTITION BY contains more columns than the relation. (expected at most {}, got {})",
207 desc.len(),
208 partition_by.len()
209 );
210 partition_by.truncate(desc.len());
211 }
212
213 let desc_prefix = desc.iter().take(partition_by.len());
214 for (idx, ((desc_name, desc_type), partition_name)) in
215 desc_prefix.zip_eq(partition_by).enumerate()
216 {
217 let partition_name = normalize::column_name(partition_name);
218 if *desc_name != partition_name {
219 sql_bail!(
220 "PARTITION BY columns should be a prefix of the relation's columns (expected {desc_name} at index {idx}, got {partition_name})"
221 );
222 }
223 if !preserves_order(&desc_type.scalar_type) {
224 sql_bail!("PARTITION BY column {partition_name} has unsupported type");
225 }
226 }
227 Ok(())
228}
229
230pub fn describe_create_database(
231 _: &StatementContext,
232 _: CreateDatabaseStatement,
233) -> Result<StatementDesc, PlanError> {
234 Ok(StatementDesc::new(None))
235}
236
237pub fn plan_create_database(
238 _: &StatementContext,
239 CreateDatabaseStatement {
240 name,
241 if_not_exists,
242 }: CreateDatabaseStatement,
243) -> Result<Plan, PlanError> {
244 Ok(Plan::CreateDatabase(CreateDatabasePlan {
245 name: normalize::ident(name.0),
246 if_not_exists,
247 }))
248}
249
250pub fn describe_create_schema(
251 _: &StatementContext,
252 _: CreateSchemaStatement,
253) -> Result<StatementDesc, PlanError> {
254 Ok(StatementDesc::new(None))
255}
256
257pub fn plan_create_schema(
258 scx: &StatementContext,
259 CreateSchemaStatement {
260 mut name,
261 if_not_exists,
262 }: CreateSchemaStatement,
263) -> Result<Plan, PlanError> {
264 if name.0.len() > 2 {
265 sql_bail!("schema name {} has more than two components", name);
266 }
267 let schema_name = normalize::ident(
268 name.0
269 .pop()
270 .expect("names always have at least one component"),
271 );
272 let database_spec = match name.0.pop() {
273 None => match scx.catalog.active_database() {
274 Some(id) => ResolvedDatabaseSpecifier::Id(id.clone()),
275 None => sql_bail!("no database specified and no active database"),
276 },
277 Some(n) => match scx.resolve_database(&UnresolvedDatabaseName(n.clone())) {
278 Ok(database) => ResolvedDatabaseSpecifier::Id(database.id()),
279 Err(_) => sql_bail!("invalid database {}", n.as_str()),
280 },
281 };
282 Ok(Plan::CreateSchema(CreateSchemaPlan {
283 database_spec,
284 schema_name,
285 if_not_exists,
286 }))
287}
288
289pub fn describe_create_table(
290 _: &StatementContext,
291 _: CreateTableStatement<Aug>,
292) -> Result<StatementDesc, PlanError> {
293 Ok(StatementDesc::new(None))
294}
295
296pub fn plan_create_table(
297 scx: &StatementContext,
298 stmt: CreateTableStatement<Aug>,
299) -> Result<Plan, PlanError> {
300 let CreateTableStatement {
301 name,
302 columns,
303 constraints,
304 if_not_exists,
305 temporary,
306 with_options,
307 } = &stmt;
308
309 let names: Vec<_> = columns
310 .iter()
311 .filter(|c| {
312 let is_versioned = c
316 .options
317 .iter()
318 .any(|o| matches!(o.option, ColumnOption::Versioned { .. }));
319 !is_versioned
320 })
321 .map(|c| normalize::column_name(c.name.clone()))
322 .collect();
323
324 if let Some(dup) = names.iter().duplicates().next() {
325 sql_bail!("column {} specified more than once", dup.quoted());
326 }
327
328 let mut column_types = Vec::with_capacity(columns.len());
331 let mut defaults = Vec::with_capacity(columns.len());
332 let mut changes = BTreeMap::new();
333 let mut keys = Vec::new();
334
335 for (i, c) in columns.into_iter().enumerate() {
336 if c.collation
337 .as_ref()
338 .is_some_and(|collation| !query::is_supported_collation(collation))
339 {
340 bail_unsupported!("COLLATE");
341 }
342 let aug_data_type = &c.data_type;
343 let ty = query::scalar_type_from_sql(scx, aug_data_type)?;
344 let mut nullable = true;
345 let mut default = Expr::null();
346 let mut versioned = false;
347 for option in &c.options {
348 match &option.option {
349 ColumnOption::NotNull => nullable = false,
350 ColumnOption::Default(expr) => {
351 let mut expr = expr.clone();
354 transform_ast::transform(scx, &mut expr)?;
355 let _ = query::plan_default_expr(scx, &expr, &ty)?;
356 default = expr.clone();
357 }
358 ColumnOption::Unique { is_primary } => {
359 keys.push(vec![i]);
360 if *is_primary {
361 nullable = false;
362 }
363 }
364 ColumnOption::Versioned { action, version } => {
365 let version = normalize::relation_version(*version);
366 versioned = true;
367
368 let name = normalize::column_name(c.name.clone());
369 let typ = ty.clone().nullable(nullable);
370
371 changes.insert(version, (action.clone(), name, typ));
372 }
373 other => {
374 bail_unsupported!(format!("CREATE TABLE with column constraint: {}", other))
375 }
376 }
377 }
378 if !versioned {
381 column_types.push(ty.nullable(nullable));
382 }
383 defaults.push(default);
384 }
385
386 let mut seen_primary = false;
387 'c: for constraint in constraints {
388 match constraint {
389 TableConstraint::Unique {
390 name: _,
391 columns,
392 is_primary,
393 nulls_not_distinct,
394 } => {
395 if seen_primary && *is_primary {
396 sql_bail!(
397 "multiple primary keys for table {} are not allowed",
398 name.to_ast_string_stable()
399 );
400 }
401 seen_primary = *is_primary || seen_primary;
402
403 let mut key = vec![];
404 for column in columns {
405 let column = normalize::column_name(column.clone());
406 match names.iter().position(|name| *name == column) {
407 None => sql_bail!("unknown column in constraint: {}", column),
408 Some(i) => {
409 let nullable = &mut column_types[i].nullable;
410 if *is_primary {
411 if *nulls_not_distinct {
412 sql_bail!(
413 "[internal error] PRIMARY KEY does not support NULLS NOT DISTINCT"
414 );
415 }
416
417 *nullable = false;
418 } else if !(*nulls_not_distinct || !*nullable) {
419 break 'c;
422 }
423
424 key.push(i);
425 }
426 }
427 }
428
429 if *is_primary {
430 keys.insert(0, key);
431 } else {
432 keys.push(key);
433 }
434 }
435 TableConstraint::ForeignKey { .. } => {
436 scx.require_feature_flag(&vars::UNSAFE_ENABLE_TABLE_FOREIGN_KEY)?
439 }
440 TableConstraint::Check { .. } => {
441 scx.require_feature_flag(&vars::UNSAFE_ENABLE_TABLE_CHECK_CONSTRAINT)?
444 }
445 }
446 }
447
448 if !keys.is_empty() {
449 scx.require_feature_flag(&vars::UNSAFE_ENABLE_TABLE_KEYS)?
452 }
453
454 let typ = SqlRelationType::new(column_types).with_keys(keys);
455
456 let temporary = *temporary;
457 let name = if temporary {
458 scx.allocate_temporary_qualified_name(normalize::unresolved_item_name(name.to_owned())?)?
459 } else {
460 scx.allocate_qualified_name(normalize::unresolved_item_name(name.to_owned())?)?
461 };
462
463 let full_name = scx.catalog.resolve_full_name(&name);
465 let partial_name = PartialItemName::from(full_name.clone());
466 if let (false, Ok(item)) = (
469 if_not_exists,
470 scx.catalog.resolve_item_or_type(&partial_name),
471 ) {
472 return Err(PlanError::ItemAlreadyExists {
473 name: full_name.to_string(),
474 item_type: item.item_type(),
475 });
476 }
477
478 let desc = RelationDesc::new(typ, names);
479 let mut desc = VersionedRelationDesc::new(desc);
480 for (version, (_action, name, typ)) in changes.into_iter() {
481 let new_version = desc.add_column(name, typ);
482 if version != new_version {
483 return Err(PlanError::InvalidTable {
484 name: full_name.item,
485 });
486 }
487 }
488
489 let create_sql = normalize::create_statement(scx, Statement::CreateTable(stmt.clone()))?;
490
491 let original_desc = desc.at_version(RelationVersionSelector::Specific(RelationVersion::root()));
497 let options = plan_table_options(scx, &original_desc, with_options.clone())?;
498
499 let compaction_window = options.iter().find_map(|o| {
500 #[allow(irrefutable_let_patterns)]
501 if let crate::plan::TableOption::RetainHistory(lcw) = o {
502 Some(lcw.clone())
503 } else {
504 None
505 }
506 });
507
508 let table = Table {
509 create_sql,
510 desc,
511 temporary,
512 compaction_window,
513 data_source: TableDataSource::TableWrites { defaults },
514 };
515 Ok(Plan::CreateTable(CreateTablePlan {
516 name,
517 table,
518 if_not_exists: *if_not_exists,
519 }))
520}
521
522pub fn describe_create_table_from_source(
523 _: &StatementContext,
524 _: CreateTableFromSourceStatement<Aug>,
525) -> Result<StatementDesc, PlanError> {
526 Ok(StatementDesc::new(None))
527}
528
529pub fn describe_create_webhook_source(
530 _: &StatementContext,
531 _: CreateWebhookSourceStatement<Aug>,
532) -> Result<StatementDesc, PlanError> {
533 Ok(StatementDesc::new(None))
534}
535
536pub fn describe_create_source(
537 _: &StatementContext,
538 _: CreateSourceStatement<Aug>,
539) -> Result<StatementDesc, PlanError> {
540 Ok(StatementDesc::new(None))
541}
542
543pub fn describe_create_subsource(
544 _: &StatementContext,
545 _: CreateSubsourceStatement<Aug>,
546) -> Result<StatementDesc, PlanError> {
547 Ok(StatementDesc::new(None))
548}
549
550generate_extracted_config!(
551 CreateSourceOption,
552 (TimestampInterval, Duration),
553 (RetainHistory, OptionalDuration)
554);
555
556generate_extracted_config!(
557 PgConfigOption,
558 (Details, String),
559 (Publication, String),
560 (Failover, bool, Default(false)),
561 (TextColumns, Vec::<UnresolvedItemName>, Default(vec![])),
562 (ExcludeColumns, Vec::<UnresolvedItemName>, Default(vec![]))
563);
564
565generate_extracted_config!(
566 MySqlConfigOption,
567 (Details, String),
568 (TextColumns, Vec::<UnresolvedItemName>, Default(vec![])),
569 (ExcludeColumns, Vec::<UnresolvedItemName>, Default(vec![]))
570);
571
572generate_extracted_config!(
573 SqlServerConfigOption,
574 (Details, String),
575 (TextColumns, Vec::<UnresolvedItemName>, Default(vec![])),
576 (ExcludeColumns, Vec::<UnresolvedItemName>, Default(vec![]))
577);
578
579pub fn plan_create_webhook_source(
580 scx: &StatementContext,
581 mut stmt: CreateWebhookSourceStatement<Aug>,
582) -> Result<Plan, PlanError> {
583 if stmt.is_table {
584 scx.require_feature_flag(&ENABLE_CREATE_TABLE_FROM_SOURCE)?;
585 }
586
587 let in_cluster = source_sink_cluster_config(scx, &mut stmt.in_cluster)?;
590 let create_sql =
591 normalize::create_statement(scx, Statement::CreateWebhookSource(stmt.clone()))?;
592
593 let CreateWebhookSourceStatement {
594 name,
595 if_not_exists,
596 body_format,
597 include_headers,
598 validate_using,
599 is_table,
600 in_cluster: _,
602 } = stmt;
603
604 let validate_using = validate_using
605 .map(|stmt| query::plan_webhook_validate_using(scx, stmt))
606 .transpose()?;
607 if let Some(WebhookValidation { expression, .. }) = &validate_using {
608 if !expression.contains_column() {
611 return Err(PlanError::WebhookValidationDoesNotUseColumns);
612 }
613 if expression.contains_unmaterializable_except(&[UnmaterializableFunc::CurrentTimestamp]) {
617 return Err(PlanError::WebhookValidationNonDeterministic);
618 }
619 if let Some(func) = expression.unbounded_func() {
621 bail_unsupported!(format!(
622 "{} in a webhook CHECK expression",
623 mz_expr::func_for_error(func)
624 ));
625 }
626 }
627
628 let body_format = match body_format {
629 Format::Bytes => WebhookBodyFormat::Bytes,
630 Format::Json { array } => WebhookBodyFormat::Json { array },
631 Format::Text => WebhookBodyFormat::Text,
632 ty => {
634 return Err(PlanError::Unsupported {
635 feature: format!("{ty} is not a valid BODY FORMAT for a WEBHOOK source"),
636 discussion_no: None,
637 });
638 }
639 };
640
641 let mut column_ty = vec![
642 SqlColumnType {
644 scalar_type: SqlScalarType::from(body_format),
645 nullable: false,
646 },
647 ];
648 let mut column_names = vec!["body".to_string()];
649
650 let mut headers = WebhookHeaders::default();
651
652 if let Some(filters) = include_headers.column {
654 column_ty.push(SqlColumnType {
655 scalar_type: SqlScalarType::Map {
656 value_type: Box::new(SqlScalarType::String),
657 custom_id: None,
658 },
659 nullable: false,
660 });
661 column_names.push("headers".to_string());
662
663 let (allow, block): (BTreeSet<_>, BTreeSet<_>) =
664 filters.into_iter().partition_map(|filter| {
665 if filter.block {
666 itertools::Either::Right(filter.header_name)
667 } else {
668 itertools::Either::Left(filter.header_name)
669 }
670 });
671 headers.header_column = Some(WebhookHeaderFilters { allow, block });
672 }
673
674 for header in include_headers.mappings {
676 let scalar_type = header
677 .use_bytes
678 .then_some(SqlScalarType::Bytes)
679 .unwrap_or(SqlScalarType::String);
680 column_ty.push(SqlColumnType {
681 scalar_type,
682 nullable: true,
683 });
684 column_names.push(header.column_name.into_string());
685
686 let column_idx = column_ty.len() - 1;
687 assert_eq!(
689 column_idx,
690 column_names.len() - 1,
691 "header column names and types don't match"
692 );
693 headers
694 .mapped_headers
695 .insert(column_idx, (header.header_name, header.use_bytes));
696 }
697
698 let mut unique_check = HashSet::with_capacity(column_names.len());
700 for name in &column_names {
701 if !unique_check.insert(name) {
702 return Err(PlanError::AmbiguousColumn(name.clone().into()));
703 }
704 }
705 if column_names.len() > MAX_NUM_COLUMNS {
706 return Err(PlanError::TooManyColumns {
707 max_num_columns: MAX_NUM_COLUMNS,
708 req_num_columns: column_names.len(),
709 });
710 }
711
712 let typ = SqlRelationType::new(column_ty);
713 let desc = RelationDesc::new(typ, column_names);
714
715 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name)?)?;
717 let full_name = scx.catalog.resolve_full_name(&name);
718 let partial_name = PartialItemName::from(full_name.clone());
719 if let (false, Ok(item)) = (if_not_exists, scx.catalog.resolve_item(&partial_name)) {
720 return Err(PlanError::ItemAlreadyExists {
721 name: full_name.to_string(),
722 item_type: item.item_type(),
723 });
724 }
725
726 let timeline = Timeline::EpochMilliseconds;
729
730 let plan = if is_table {
731 let data_source = DataSourceDesc::Webhook {
732 validate_using,
733 body_format,
734 headers,
735 cluster_id: Some(in_cluster.id()),
736 };
737 let data_source = TableDataSource::DataSource {
738 desc: data_source,
739 timeline,
740 };
741 Plan::CreateTable(CreateTablePlan {
742 name,
743 if_not_exists,
744 table: Table {
745 create_sql,
746 desc: VersionedRelationDesc::new(desc),
747 temporary: false,
748 compaction_window: None,
749 data_source,
750 },
751 })
752 } else {
753 let data_source = DataSourceDesc::Webhook {
754 validate_using,
755 body_format,
756 headers,
757 cluster_id: None,
759 };
760 Plan::CreateSource(CreateSourcePlan {
761 name,
762 source: Source {
763 create_sql,
764 data_source,
765 desc,
766 compaction_window: None,
767 },
768 if_not_exists,
769 timeline,
770 in_cluster: Some(in_cluster.id()),
771 })
772 };
773
774 Ok(plan)
775}
776
777pub fn plan_create_source(
778 scx: &StatementContext,
779 mut stmt: CreateSourceStatement<Aug>,
780) -> Result<Plan, PlanError> {
781 let CreateSourceStatement {
782 name,
783 in_cluster: _,
784 col_names,
785 connection: source_connection,
786 envelope,
787 if_not_exists,
788 format,
789 key_constraint,
790 include_metadata,
791 with_options,
792 external_references: referenced_subsources,
793 progress_subsource,
794 } = &stmt;
795
796 mz_ore::soft_assert_or_log!(
797 referenced_subsources.is_none(),
798 "referenced subsources must be cleared in purification"
799 );
800
801 let force_source_table_syntax = scx.catalog.system_vars().enable_create_table_from_source()
802 && scx.catalog.system_vars().force_source_table_syntax();
803
804 if force_source_table_syntax {
807 if envelope.is_some() || format.is_some() || !include_metadata.is_empty() {
808 Err(PlanError::UseTablesForSources(
809 "CREATE SOURCE (ENVELOPE|FORMAT|INCLUDE)".to_string(),
810 ))?;
811 }
812 }
813
814 let envelope = envelope.clone().unwrap_or(ast::SourceEnvelope::None);
815
816 if !matches!(source_connection, CreateSourceConnection::Kafka { .. })
817 && include_metadata
818 .iter()
819 .any(|sic| matches!(sic, SourceIncludeMetadata::Headers { .. }))
820 {
821 sql_bail!("INCLUDE HEADERS with non-Kafka sources not supported");
823 }
824 if !matches!(
825 source_connection,
826 CreateSourceConnection::Kafka { .. } | CreateSourceConnection::LoadGenerator { .. }
827 ) && !include_metadata.is_empty()
828 {
829 bail_unsupported!("INCLUDE metadata with non-Kafka sources");
830 }
831
832 if !include_metadata.is_empty()
833 && !matches!(
834 envelope,
835 ast::SourceEnvelope::Upsert { .. }
836 | ast::SourceEnvelope::None
837 | ast::SourceEnvelope::Debezium
838 )
839 {
840 sql_bail!("INCLUDE <metadata> requires ENVELOPE (NONE|UPSERT|DEBEZIUM)");
841 }
842
843 let external_connection =
844 plan_generic_source_connection(scx, source_connection, include_metadata)?;
845
846 let CreateSourceOptionExtracted {
847 timestamp_interval,
848 retain_history,
849 seen: _,
850 } = CreateSourceOptionExtracted::try_from(with_options.clone())?;
851
852 let metadata_columns_desc = match external_connection {
853 GenericSourceConnection::Kafka(KafkaSourceConnection {
854 ref metadata_columns,
855 ..
856 }) => kafka_metadata_columns_desc(metadata_columns),
857 _ => vec![],
858 };
859
860 let (mut desc, envelope, encoding) = apply_source_envelope_encoding(
862 scx,
863 &envelope,
864 format,
865 Some(external_connection.default_key_desc()),
866 external_connection.default_value_desc(),
867 include_metadata,
868 metadata_columns_desc,
869 &external_connection,
870 )?;
871 plan_utils::maybe_rename_columns(format!("source {}", name), &mut desc, col_names)?;
872
873 let names: Vec<_> = desc.iter_names().cloned().collect();
874 if let Some(dup) = names.iter().duplicates().next() {
875 sql_bail!("column {} specified more than once", dup.quoted());
876 }
877
878 if let Some(KeyConstraint::PrimaryKeyNotEnforced { columns }) = key_constraint.clone() {
880 scx.require_feature_flag(&vars::ENABLE_PRIMARY_KEY_NOT_ENFORCED)?;
883
884 let key_columns = columns
885 .into_iter()
886 .map(normalize::column_name)
887 .collect::<Vec<_>>();
888
889 let mut uniq = BTreeSet::new();
890 for col in key_columns.iter() {
891 if !uniq.insert(col) {
892 sql_bail!("Repeated column name in source key constraint: {}", col);
893 }
894 }
895
896 let key_indices = key_columns
897 .iter()
898 .map(|col| {
899 let name_idx = desc
900 .get_by_name(col)
901 .map(|(idx, _type)| idx)
902 .ok_or_else(|| sql_err!("No such column in source key constraint: {}", col))?;
903 if desc.get_unambiguous_name(name_idx).is_none() {
904 sql_bail!("Ambiguous column in source key constraint: {}", col);
905 }
906 Ok(name_idx)
907 })
908 .collect::<Result<Vec<_>, _>>()?;
909
910 if !desc.typ().keys.is_empty() {
911 return Err(key_constraint_err(&desc, &key_columns));
912 } else {
913 desc = desc.with_key(key_indices);
914 }
915 }
916
917 let timestamp_interval = match timestamp_interval {
918 Some(duration) => {
919 if scx.pcx.is_some() {
923 let min = scx.catalog.system_vars().min_timestamp_interval();
924 let max = scx.catalog.system_vars().max_timestamp_interval();
925 if duration < min || duration > max {
926 return Err(PlanError::InvalidTimestampInterval {
927 min,
928 max,
929 requested: duration,
930 });
931 }
932 }
933 duration
934 }
935 None => scx.catalog.system_vars().default_timestamp_interval(),
936 };
937
938 let (desc, data_source) = match progress_subsource {
939 Some(name) => {
940 let DeferredItemName::Named(name) = name else {
941 sql_bail!("[internal error] progress subsource must be named during purification");
942 };
943 let ResolvedItemName::Item { id, .. } = name else {
944 sql_bail!("[internal error] invalid target id");
945 };
946
947 let details = match external_connection {
948 GenericSourceConnection::Kafka(ref c) => {
949 SourceExportDetails::Kafka(KafkaSourceExportDetails {
950 metadata_columns: c.metadata_columns.clone(),
951 })
952 }
953 GenericSourceConnection::LoadGenerator(ref c) => match c.load_generator {
954 LoadGenerator::Auction
955 | LoadGenerator::Marketing
956 | LoadGenerator::Tpch { .. } => SourceExportDetails::None,
957 LoadGenerator::Counter { .. }
958 | LoadGenerator::Clock
959 | LoadGenerator::Datums
960 | LoadGenerator::KeyValue(_) => {
961 SourceExportDetails::LoadGenerator(LoadGeneratorSourceExportDetails {
962 output: LoadGeneratorOutput::Default,
963 })
964 }
965 },
966 GenericSourceConnection::Postgres(_)
967 | GenericSourceConnection::MySql(_)
968 | GenericSourceConnection::SqlServer(_) => SourceExportDetails::None,
969 };
970
971 let data_source = DataSourceDesc::OldSyntaxIngestion {
972 desc: SourceDesc {
973 connection: external_connection,
974 timestamp_interval,
975 },
976 progress_subsource: *id,
977 data_config: SourceExportDataConfig {
978 encoding,
979 envelope: envelope.clone(),
980 },
981 details,
982 };
983 (desc, data_source)
984 }
985 None => {
986 let desc = external_connection.timestamp_desc();
987 let data_source = DataSourceDesc::Ingestion(SourceDesc {
988 connection: external_connection,
989 timestamp_interval,
990 });
991 (desc, data_source)
992 }
993 };
994
995 let if_not_exists = *if_not_exists;
996 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name.clone())?)?;
997
998 let full_name = scx.catalog.resolve_full_name(&name);
1000 let partial_name = PartialItemName::from(full_name.clone());
1001 if let (false, Ok(item)) = (
1004 if_not_exists,
1005 scx.catalog.resolve_item_or_type(&partial_name),
1006 ) {
1007 return Err(PlanError::ItemAlreadyExists {
1008 name: full_name.to_string(),
1009 item_type: item.item_type(),
1010 });
1011 }
1012
1013 let in_cluster = source_sink_cluster_config(scx, &mut stmt.in_cluster)?;
1017
1018 let create_sql = normalize::create_statement(scx, Statement::CreateSource(stmt))?;
1019
1020 let timeline = match envelope {
1022 SourceEnvelope::CdcV2 => {
1023 Timeline::External(scx.catalog.resolve_full_name(&name).to_string())
1024 }
1025 _ => Timeline::EpochMilliseconds,
1026 };
1027
1028 let compaction_window = plan_retain_history_option(scx, retain_history)?;
1029
1030 let source = Source {
1031 create_sql,
1032 data_source,
1033 desc,
1034 compaction_window,
1035 };
1036
1037 Ok(Plan::CreateSource(CreateSourcePlan {
1038 name,
1039 source,
1040 if_not_exists,
1041 timeline,
1042 in_cluster: Some(in_cluster.id()),
1043 }))
1044}
1045
1046pub fn plan_generic_source_connection(
1047 scx: &StatementContext<'_>,
1048 source_connection: &CreateSourceConnection<Aug>,
1049 include_metadata: &Vec<SourceIncludeMetadata>,
1050) -> Result<GenericSourceConnection<ReferencedConnection>, PlanError> {
1051 Ok(match source_connection {
1052 CreateSourceConnection::Kafka {
1053 connection,
1054 options,
1055 } => GenericSourceConnection::Kafka(plan_kafka_source_connection(
1056 scx,
1057 connection,
1058 options,
1059 include_metadata,
1060 )?),
1061 CreateSourceConnection::Postgres {
1062 connection,
1063 options,
1064 } => GenericSourceConnection::Postgres(plan_postgres_source_connection(
1065 scx, connection, options,
1066 )?),
1067 CreateSourceConnection::SqlServer {
1068 connection,
1069 options,
1070 } => GenericSourceConnection::SqlServer(plan_sqlserver_source_connection(
1071 scx, connection, options,
1072 )?),
1073 CreateSourceConnection::MySql {
1074 connection,
1075 options,
1076 } => {
1077 GenericSourceConnection::MySql(plan_mysql_source_connection(scx, connection, options)?)
1078 }
1079 CreateSourceConnection::LoadGenerator { generator, options } => {
1080 GenericSourceConnection::LoadGenerator(plan_load_generator_source_connection(
1081 scx,
1082 generator,
1083 options,
1084 include_metadata,
1085 )?)
1086 }
1087 })
1088}
1089
1090fn plan_load_generator_source_connection(
1091 scx: &StatementContext<'_>,
1092 generator: &ast::LoadGenerator,
1093 options: &Vec<LoadGeneratorOption<Aug>>,
1094 include_metadata: &Vec<SourceIncludeMetadata>,
1095) -> Result<LoadGeneratorSourceConnection, PlanError> {
1096 let load_generator =
1097 load_generator_ast_to_generator(scx, generator, options, include_metadata)?;
1098 let LoadGeneratorOptionExtracted {
1099 tick_interval,
1100 as_of,
1101 up_to,
1102 ..
1103 } = options.clone().try_into()?;
1104 let tick_micros = match tick_interval {
1105 Some(interval) => Some(interval.as_micros().try_into()?),
1106 None => None,
1107 };
1108 if up_to < as_of {
1109 sql_bail!("UP TO cannot be less than AS OF");
1110 }
1111 Ok(LoadGeneratorSourceConnection {
1112 load_generator,
1113 tick_micros,
1114 as_of,
1115 up_to,
1116 })
1117}
1118
1119fn plan_mysql_source_connection(
1120 scx: &StatementContext<'_>,
1121 connection: &ResolvedItemName,
1122 options: &Vec<MySqlConfigOption<Aug>>,
1123) -> Result<MySqlSourceConnection<ReferencedConnection>, PlanError> {
1124 let connection_item = scx.get_item_by_resolved_name(connection)?;
1125 match connection_item.connection()? {
1126 Connection::MySql(connection) => connection,
1127 _ => sql_bail!(
1128 "{} is not a MySQL connection",
1129 scx.catalog.resolve_full_name(connection_item.name())
1130 ),
1131 };
1132 let MySqlConfigOptionExtracted {
1133 details,
1134 text_columns: _,
1138 exclude_columns: _,
1139 seen: _,
1140 } = options.clone().try_into()?;
1141 let details = details
1142 .as_ref()
1143 .ok_or_else(|| internal_err!("MySQL source missing details"))?;
1144 let details = hex::decode(details).map_err(|e| sql_err!("{}", e))?;
1145 let details = ProtoMySqlSourceDetails::decode(&*details).map_err(|e| sql_err!("{}", e))?;
1146 let details = MySqlSourceDetails::from_proto(details).map_err(|e| sql_err!("{}", e))?;
1147 Ok(MySqlSourceConnection {
1148 connection: connection_item.id(),
1149 connection_id: connection_item.id(),
1150 details,
1151 })
1152}
1153
1154fn plan_sqlserver_source_connection(
1155 scx: &StatementContext<'_>,
1156 connection: &ResolvedItemName,
1157 options: &Vec<SqlServerConfigOption<Aug>>,
1158) -> Result<SqlServerSourceConnection<ReferencedConnection>, PlanError> {
1159 let connection_item = scx.get_item_by_resolved_name(connection)?;
1160 match connection_item.connection()? {
1161 Connection::SqlServer(connection) => connection,
1162 _ => sql_bail!(
1163 "{} is not a SQL Server connection",
1164 scx.catalog.resolve_full_name(connection_item.name())
1165 ),
1166 };
1167 let SqlServerConfigOptionExtracted { details, .. } = options.clone().try_into()?;
1168 let details = details
1169 .as_ref()
1170 .ok_or_else(|| internal_err!("SQL Server source missing details"))?;
1171 let extras = hex::decode(details)
1172 .map_err(|e| sql_err!("{e}"))
1173 .and_then(|raw| ProtoSqlServerSourceExtras::decode(&*raw).map_err(|e| sql_err!("{e}")))
1174 .and_then(|proto| SqlServerSourceExtras::from_proto(proto).map_err(|e| sql_err!("{e}")))?;
1175 Ok(SqlServerSourceConnection {
1176 connection_id: connection_item.id(),
1177 connection: connection_item.id(),
1178 extras,
1179 })
1180}
1181
1182fn plan_postgres_source_connection(
1183 scx: &StatementContext<'_>,
1184 connection: &ResolvedItemName,
1185 options: &Vec<PgConfigOption<Aug>>,
1186) -> Result<PostgresSourceConnection<ReferencedConnection>, PlanError> {
1187 let connection_item = scx.get_item_by_resolved_name(connection)?;
1188 let PgConfigOptionExtracted {
1189 details,
1190 publication,
1191 failover,
1192 text_columns: _,
1196 exclude_columns: _,
1200 seen,
1201 } = options.clone().try_into()?;
1202 if seen.contains(&PgConfigOptionName::Failover) {
1203 scx.require_feature_flag(&vars::ENABLE_POSTGRES_SOURCE_FAILOVER)?;
1204 }
1205 let details = details
1206 .as_ref()
1207 .ok_or_else(|| internal_err!("Postgres source missing details"))?;
1208 let details = hex::decode(details).map_err(|e| sql_err!("{}", e))?;
1209 let details =
1210 ProtoPostgresSourcePublicationDetails::decode(&*details).map_err(|e| sql_err!("{}", e))?;
1211 let publication_details =
1212 PostgresSourcePublicationDetails::from_proto(details).map_err(|e| sql_err!("{}", e))?;
1213 Ok(PostgresSourceConnection {
1214 connection: connection_item.id(),
1215 connection_id: connection_item.id(),
1216 publication: publication.ok_or_else(|| internal_err!("PUBLICATION option is required"))?,
1218 publication_details,
1219 failover,
1220 })
1221}
1222
1223fn plan_kafka_source_connection(
1224 scx: &StatementContext<'_>,
1225 connection_name: &ResolvedItemName,
1226 options: &Vec<ast::KafkaSourceConfigOption<Aug>>,
1227 include_metadata: &Vec<SourceIncludeMetadata>,
1228) -> Result<KafkaSourceConnection<ReferencedConnection>, PlanError> {
1229 let connection_item = scx.get_item_by_resolved_name(connection_name)?;
1230 if !matches!(connection_item.connection()?, Connection::Kafka(_)) {
1231 sql_bail!(
1232 "{} is not a kafka connection",
1233 scx.catalog.resolve_full_name(connection_item.name())
1234 )
1235 }
1236 let KafkaSourceConfigOptionExtracted {
1237 group_id_prefix,
1238 topic,
1239 topic_metadata_refresh_interval,
1240 start_timestamp: _, start_offset,
1242 seen: _,
1243 }: KafkaSourceConfigOptionExtracted = options.clone().try_into()?;
1244 let topic = topic.ok_or_else(|| internal_err!("TOPIC option is required"))?;
1246 let mut start_offsets = BTreeMap::new();
1247 if let Some(offsets) = start_offset {
1248 for (part, offset) in offsets.iter().enumerate() {
1249 if *offset < 0 {
1250 sql_bail!("START OFFSET must be a nonnegative integer");
1251 }
1252 start_offsets.insert(i32::try_from(part)?, *offset);
1253 }
1254 }
1255 if topic_metadata_refresh_interval > Duration::from_secs(60 * 60) {
1256 sql_bail!("TOPIC METADATA REFRESH INTERVAL cannot be greater than 1 hour");
1259 }
1260 if topic_metadata_refresh_interval < Duration::from_secs(1) {
1261 sql_bail!("TOPIC METADATA REFRESH INTERVAL must be at least 1 second");
1264 }
1265 let metadata_columns = include_metadata
1266 .into_iter()
1267 .flat_map(|item| match item {
1268 SourceIncludeMetadata::Timestamp { alias } => {
1269 let name = match alias {
1270 Some(name) => name.to_string(),
1271 None => "timestamp".to_owned(),
1272 };
1273 Some((name, KafkaMetadataKind::Timestamp))
1274 }
1275 SourceIncludeMetadata::Partition { alias } => {
1276 let name = match alias {
1277 Some(name) => name.to_string(),
1278 None => "partition".to_owned(),
1279 };
1280 Some((name, KafkaMetadataKind::Partition))
1281 }
1282 SourceIncludeMetadata::Offset { alias } => {
1283 let name = match alias {
1284 Some(name) => name.to_string(),
1285 None => "offset".to_owned(),
1286 };
1287 Some((name, KafkaMetadataKind::Offset))
1288 }
1289 SourceIncludeMetadata::Headers { alias } => {
1290 let name = match alias {
1291 Some(name) => name.to_string(),
1292 None => "headers".to_owned(),
1293 };
1294 Some((name, KafkaMetadataKind::Headers))
1295 }
1296 SourceIncludeMetadata::Header {
1297 alias,
1298 key,
1299 use_bytes,
1300 } => Some((
1301 alias.to_string(),
1302 KafkaMetadataKind::Header {
1303 key: key.clone(),
1304 use_bytes: *use_bytes,
1305 },
1306 )),
1307 SourceIncludeMetadata::Key { .. } => {
1308 None
1310 }
1311 })
1312 .collect();
1313 Ok(KafkaSourceConnection {
1314 connection: connection_item.id(),
1315 connection_id: connection_item.id(),
1316 topic,
1317 start_offsets,
1318 group_id_prefix,
1319 topic_metadata_refresh_interval,
1320 metadata_columns,
1321 })
1322}
1323
1324fn apply_source_envelope_encoding(
1325 scx: &StatementContext,
1326 envelope: &ast::SourceEnvelope,
1327 format: &Option<FormatSpecifier<Aug>>,
1328 key_desc: Option<RelationDesc>,
1329 value_desc: RelationDesc,
1330 include_metadata: &[SourceIncludeMetadata],
1331 metadata_columns_desc: Vec<(&str, SqlColumnType)>,
1332 source_connection: &GenericSourceConnection<ReferencedConnection>,
1333) -> Result<
1334 (
1335 RelationDesc,
1336 SourceEnvelope,
1337 Option<SourceDataEncoding<ReferencedConnection>>,
1338 ),
1339 PlanError,
1340> {
1341 let encoding = match format {
1342 Some(format) => Some(get_encoding(scx, format, envelope)?),
1343 None => None,
1344 };
1345
1346 let (key_desc, value_desc) = match &encoding {
1347 Some(encoding) => {
1348 match value_desc.typ().columns() {
1351 [typ] => match typ.scalar_type {
1352 SqlScalarType::Bytes => {}
1353 _ => sql_bail!(
1354 "The schema produced by the source is incompatible with format decoding"
1355 ),
1356 },
1357 _ => sql_bail!(
1358 "The schema produced by the source is incompatible with format decoding"
1359 ),
1360 }
1361
1362 let (key_desc, value_desc) = encoding.desc()?;
1363
1364 let key_desc = key_desc.map(|desc| {
1371 let is_kafka = matches!(source_connection, GenericSourceConnection::Kafka(_));
1372 let is_envelope_none = matches!(envelope, ast::SourceEnvelope::None);
1373 if is_kafka && is_envelope_none {
1374 RelationDesc::from_names_and_types(
1375 desc.into_iter()
1376 .map(|(name, typ)| (name, typ.nullable(true))),
1377 )
1378 } else {
1379 desc
1380 }
1381 });
1382 (key_desc, value_desc)
1383 }
1384 None => (key_desc, value_desc),
1385 };
1386
1387 let key_envelope_no_encoding = matches!(
1400 source_connection,
1401 GenericSourceConnection::LoadGenerator(LoadGeneratorSourceConnection {
1402 load_generator: LoadGenerator::KeyValue(_),
1403 ..
1404 })
1405 );
1406 let mut key_envelope = get_key_envelope(
1407 include_metadata,
1408 encoding.as_ref(),
1409 key_envelope_no_encoding,
1410 )?;
1411
1412 match (&envelope, &key_envelope) {
1413 (ast::SourceEnvelope::Debezium, KeyEnvelope::None) => {}
1414 (ast::SourceEnvelope::Debezium, _) => sql_bail!(
1415 "Cannot use INCLUDE KEY with ENVELOPE DEBEZIUM: Debezium values include all keys."
1416 ),
1417 _ => {}
1418 };
1419
1420 let envelope = match &envelope {
1429 ast::SourceEnvelope::None => UnplannedSourceEnvelope::None(key_envelope),
1431 ast::SourceEnvelope::Debezium => {
1432 let after_idx = match typecheck_debezium(&value_desc) {
1434 Ok((_before_idx, after_idx)) => Ok(after_idx),
1435 Err(type_err) => match encoding.as_ref().map(|e| &e.value) {
1436 Some(DataEncoding::Avro(_)) => Err(type_err),
1437 _ => Err(sql_err!(
1438 "ENVELOPE DEBEZIUM requires that VALUE FORMAT is set to AVRO"
1439 )),
1440 },
1441 }?;
1442
1443 UnplannedSourceEnvelope::Upsert {
1444 style: UpsertStyle::Debezium { after_idx },
1445 }
1446 }
1447 ast::SourceEnvelope::Upsert {
1448 value_decode_err_policy,
1449 } => {
1450 let key_encoding = match encoding.as_ref().and_then(|e| e.key.as_ref()) {
1451 None => {
1452 if !key_envelope_no_encoding {
1453 bail_unsupported!(format!(
1454 "UPSERT requires a key/value format: {:?}",
1455 format
1456 ))
1457 }
1458 None
1459 }
1460 Some(key_encoding) => Some(key_encoding),
1461 };
1462 if key_envelope == KeyEnvelope::None {
1465 key_envelope = get_unnamed_key_envelope(key_encoding)?;
1466 }
1467 let style = match value_decode_err_policy.as_slice() {
1469 [] => UpsertStyle::Default(key_envelope),
1470 [SourceErrorPolicy::Inline { alias }] => {
1471 scx.require_feature_flag(&vars::ENABLE_ENVELOPE_UPSERT_INLINE_ERRORS)?;
1472 UpsertStyle::ValueErrInline {
1473 key_envelope,
1474 error_column: alias
1475 .as_ref()
1476 .map_or_else(|| "error".to_string(), |a| a.to_string()),
1477 }
1478 }
1479 _ => {
1480 bail_unsupported!("ENVELOPE UPSERT with unsupported value decode error policy")
1481 }
1482 };
1483
1484 UnplannedSourceEnvelope::Upsert { style }
1485 }
1486 ast::SourceEnvelope::CdcV2 => {
1487 scx.require_feature_flag(&vars::ENABLE_ENVELOPE_MATERIALIZE)?;
1488 match format {
1490 Some(FormatSpecifier::Bare(Format::Avro(_))) => {}
1491 _ => bail_unsupported!("non-Avro-encoded ENVELOPE MATERIALIZE"),
1492 }
1493 UnplannedSourceEnvelope::CdcV2
1494 }
1495 };
1496
1497 let metadata_desc = included_column_desc(metadata_columns_desc);
1498 let (envelope, desc) = envelope.desc(key_desc, value_desc, metadata_desc)?;
1499
1500 Ok((desc, envelope, encoding))
1501}
1502
1503fn plan_source_export_desc(
1506 scx: &StatementContext,
1507 name: &UnresolvedItemName,
1508 columns: &Vec<ColumnDef<Aug>>,
1509 constraints: &Vec<TableConstraint<Aug>>,
1510) -> Result<RelationDesc, PlanError> {
1511 let names: Vec<_> = columns
1512 .iter()
1513 .map(|c| normalize::column_name(c.name.clone()))
1514 .collect();
1515
1516 if let Some(dup) = names.iter().duplicates().next() {
1517 sql_bail!("column {} specified more than once", dup.quoted());
1518 }
1519
1520 let mut column_types = Vec::with_capacity(columns.len());
1523 let mut keys = Vec::new();
1524
1525 for (i, c) in columns.into_iter().enumerate() {
1526 let aug_data_type = &c.data_type;
1527 let ty = query::scalar_type_from_sql(scx, aug_data_type)?;
1528 let mut nullable = true;
1529 for option in &c.options {
1530 match &option.option {
1531 ColumnOption::NotNull => nullable = false,
1532 ColumnOption::Default(_) => {
1533 bail_unsupported!("Source export with default value")
1534 }
1535 ColumnOption::Unique { is_primary } => {
1536 keys.push(vec![i]);
1537 if *is_primary {
1538 nullable = false;
1539 }
1540 }
1541 other => {
1542 bail_unsupported!(format!("Source export with column constraint: {}", other))
1543 }
1544 }
1545 }
1546 column_types.push(ty.nullable(nullable));
1547 }
1548
1549 let mut seen_primary = false;
1550 'c: for constraint in constraints {
1551 match constraint {
1552 TableConstraint::Unique {
1553 name: _,
1554 columns,
1555 is_primary,
1556 nulls_not_distinct,
1557 } => {
1558 if seen_primary && *is_primary {
1559 sql_bail!(
1560 "multiple primary keys for source export {} are not allowed",
1561 name.to_ast_string_stable()
1562 );
1563 }
1564 seen_primary = *is_primary || seen_primary;
1565
1566 let mut key = vec![];
1567 for column in columns {
1568 let column = normalize::column_name(column.clone());
1569 match names.iter().position(|name| *name == column) {
1570 None => sql_bail!("unknown column in constraint: {}", column),
1571 Some(i) => {
1572 let nullable = &mut column_types[i].nullable;
1573 if *is_primary {
1574 if *nulls_not_distinct {
1575 sql_bail!(
1576 "[internal error] PRIMARY KEY does not support NULLS NOT DISTINCT"
1577 );
1578 }
1579 *nullable = false;
1580 } else if !(*nulls_not_distinct || !*nullable) {
1581 break 'c;
1584 }
1585
1586 key.push(i);
1587 }
1588 }
1589 }
1590
1591 if *is_primary {
1592 keys.insert(0, key);
1593 } else {
1594 keys.push(key);
1595 }
1596 }
1597 TableConstraint::ForeignKey { .. } => {
1598 bail_unsupported!("Source export with a foreign key")
1599 }
1600 TableConstraint::Check { .. } => {
1601 bail_unsupported!("Source export with a check constraint")
1602 }
1603 }
1604 }
1605
1606 let typ = SqlRelationType::new(column_types).with_keys(keys);
1607 let desc = RelationDesc::new(typ, names);
1608 Ok(desc)
1609}
1610
1611generate_extracted_config!(
1612 CreateSubsourceOption,
1613 (Progress, bool, Default(false)),
1614 (ExternalReference, UnresolvedItemName),
1615 (RetainHistory, OptionalDuration),
1616 (TextColumns, Vec::<Ident>, Default(vec![])),
1617 (ExcludeColumns, Vec::<Ident>, Default(vec![])),
1618 (Details, String)
1619);
1620
1621pub fn plan_create_subsource(
1622 scx: &StatementContext,
1623 stmt: CreateSubsourceStatement<Aug>,
1624) -> Result<Plan, PlanError> {
1625 let CreateSubsourceStatement {
1626 name,
1627 columns,
1628 of_source,
1629 constraints,
1630 if_not_exists,
1631 with_options,
1632 } = &stmt;
1633
1634 let CreateSubsourceOptionExtracted {
1635 progress,
1636 retain_history,
1637 external_reference,
1638 text_columns,
1639 exclude_columns,
1640 details,
1641 seen: _,
1642 } = with_options.clone().try_into()?;
1643
1644 if !(progress ^ (external_reference.is_some() && of_source.is_some())) {
1649 bail_internal!(
1650 "CREATE SUBSOURCE statement must specify either PROGRESS or REFERENCES option"
1651 );
1652 }
1653
1654 let desc = plan_source_export_desc(scx, name, columns, constraints)?;
1655
1656 let data_source = if let Some(source_reference) = of_source {
1657 if scx.catalog.system_vars().enable_create_table_from_source()
1660 && scx.catalog.system_vars().force_source_table_syntax()
1661 {
1662 Err(PlanError::UseTablesForSources(
1663 "CREATE SUBSOURCE".to_string(),
1664 ))?;
1665 }
1666
1667 let ingestion_id = *source_reference.item_id();
1670 let external_reference = external_reference.ok_or_else(|| {
1671 sql_err!("CREATE SUBSOURCE with REFERENCES requires EXTERNAL REFERENCE option")
1672 })?;
1673
1674 let details = details
1677 .as_ref()
1678 .ok_or_else(|| internal_err!("source-export subsource missing details"))?;
1679 let details = hex::decode(details).map_err(|e| sql_err!("{}", e))?;
1680 let details =
1681 ProtoSourceExportStatementDetails::decode(&*details).map_err(|e| sql_err!("{}", e))?;
1682 let details =
1683 SourceExportStatementDetails::from_proto(details).map_err(|e| sql_err!("{}", e))?;
1684 let details = match details {
1685 SourceExportStatementDetails::Postgres {
1686 table,
1687 cast_oid_full_range,
1688 initial_lsn,
1689 } => SourceExportDetails::Postgres(PostgresSourceExportDetails {
1690 column_casts: crate::pure::postgres::generate_column_casts(
1691 scx,
1692 &table,
1693 &text_columns,
1694 cast_oid_full_range,
1695 )?,
1696 table,
1697 initial_lsn,
1698 }),
1699 SourceExportStatementDetails::MySql {
1700 table,
1701 initial_gtid_set,
1702 binlog_full_metadata,
1703 } => SourceExportDetails::MySql(MySqlSourceExportDetails {
1704 table,
1705 initial_gtid_set,
1706 text_columns: text_columns.into_iter().map(|c| c.into_string()).collect(),
1707 exclude_columns: exclude_columns
1708 .into_iter()
1709 .map(|c| c.into_string())
1710 .collect(),
1711 binlog_full_metadata,
1712 }),
1713 SourceExportStatementDetails::SqlServer {
1714 table,
1715 capture_instance,
1716 initial_lsn,
1717 } => SourceExportDetails::SqlServer(SqlServerSourceExportDetails {
1718 capture_instance,
1719 table,
1720 initial_lsn,
1721 text_columns: text_columns.into_iter().map(|c| c.into_string()).collect(),
1722 exclude_columns: exclude_columns
1723 .into_iter()
1724 .map(|c| c.into_string())
1725 .collect(),
1726 }),
1727 SourceExportStatementDetails::LoadGenerator { output } => {
1728 SourceExportDetails::LoadGenerator(LoadGeneratorSourceExportDetails { output })
1729 }
1730 SourceExportStatementDetails::Kafka {} => {
1731 bail_unsupported!("subsources cannot reference Kafka sources")
1732 }
1733 };
1734 DataSourceDesc::IngestionExport {
1735 ingestion_id,
1736 external_reference,
1737 details,
1738 data_config: SourceExportDataConfig {
1740 envelope: SourceEnvelope::None(NoneEnvelope {
1741 key_envelope: KeyEnvelope::None,
1742 key_arity: 0,
1743 }),
1744 encoding: None,
1745 },
1746 }
1747 } else if progress {
1748 DataSourceDesc::Progress
1749 } else {
1750 sql_bail!("CREATE SUBSOURCE must specify one of PROGRESS or REFERENCES option")
1751 };
1752
1753 let if_not_exists = *if_not_exists;
1754 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name.clone())?)?;
1755
1756 let create_sql = normalize::create_statement(scx, Statement::CreateSubsource(stmt))?;
1757
1758 let compaction_window = plan_retain_history_option(scx, retain_history)?;
1759 let source = Source {
1760 create_sql,
1761 data_source,
1762 desc,
1763 compaction_window,
1764 };
1765
1766 Ok(Plan::CreateSource(CreateSourcePlan {
1767 name,
1768 source,
1769 if_not_exists,
1770 timeline: Timeline::EpochMilliseconds,
1771 in_cluster: None,
1772 }))
1773}
1774
1775generate_extracted_config!(
1776 TableFromSourceOption,
1777 (TextColumns, Vec::<Ident>, Default(vec![])),
1778 (ExcludeColumns, Vec::<Ident>, Default(vec![])),
1779 (ExcludeConstraints, Vec::<String>, Default(vec![])),
1780 (ExcludeAllConstraints, bool, Default(false)),
1781 (ExcludeAllNotNullConstraints, bool, Default(false)),
1782 (PartitionBy, Vec<Ident>),
1783 (RetainHistory, OptionalDuration),
1784 (Details, String)
1785);
1786
1787pub fn plan_create_table_from_source(
1788 scx: &StatementContext,
1789 stmt: CreateTableFromSourceStatement<Aug>,
1790) -> Result<Plan, PlanError> {
1791 if !scx.catalog.system_vars().enable_create_table_from_source() {
1792 sql_bail!("CREATE TABLE ... FROM SOURCE is not supported");
1793 }
1794
1795 let CreateTableFromSourceStatement {
1796 name,
1797 columns,
1798 constraints,
1799 if_not_exists,
1800 source,
1801 external_reference,
1802 envelope,
1803 format,
1804 include_metadata,
1805 with_options,
1806 } = &stmt;
1807
1808 let envelope = envelope.clone().unwrap_or(ast::SourceEnvelope::None);
1809
1810 let TableFromSourceOptionExtracted {
1811 text_columns,
1812 exclude_columns,
1813 exclude_constraints: _,
1814 exclude_all_constraints: _,
1815 exclude_all_not_null_constraints: _,
1816 retain_history,
1817 partition_by,
1818 details,
1819 seen: _,
1820 } = with_options.clone().try_into()?;
1821
1822 let source_item = scx.get_item_by_resolved_name(source)?;
1823 let ingestion_id = source_item.id();
1824
1825 let details = details
1828 .as_ref()
1829 .ok_or_else(|| internal_err!("source-export missing details"))?;
1830 let details = hex::decode(details).map_err(|e| sql_err!("{}", e))?;
1831 let details =
1832 ProtoSourceExportStatementDetails::decode(&*details).map_err(|e| sql_err!("{}", e))?;
1833 let details =
1834 SourceExportStatementDetails::from_proto(details).map_err(|e| sql_err!("{}", e))?;
1835
1836 if !matches!(details, SourceExportStatementDetails::Kafka { .. })
1837 && include_metadata
1838 .iter()
1839 .any(|sic| matches!(sic, SourceIncludeMetadata::Headers { .. }))
1840 {
1841 sql_bail!("INCLUDE HEADERS with non-Kafka source table not supported");
1843 }
1844 if !matches!(
1845 details,
1846 SourceExportStatementDetails::Kafka { .. }
1847 | SourceExportStatementDetails::LoadGenerator { .. }
1848 ) && !include_metadata.is_empty()
1849 {
1850 bail_unsupported!("INCLUDE metadata with non-Kafka source table");
1851 }
1852
1853 let details = match details {
1854 SourceExportStatementDetails::Postgres {
1855 table,
1856 cast_oid_full_range,
1857 initial_lsn,
1858 } => SourceExportDetails::Postgres(PostgresSourceExportDetails {
1859 column_casts: crate::pure::postgres::generate_column_casts(
1860 scx,
1861 &table,
1862 &text_columns,
1863 cast_oid_full_range,
1864 )?,
1865 table,
1866 initial_lsn,
1867 }),
1868 SourceExportStatementDetails::MySql {
1869 table,
1870 initial_gtid_set,
1871 binlog_full_metadata,
1872 } => SourceExportDetails::MySql(MySqlSourceExportDetails {
1873 table,
1874 initial_gtid_set,
1875 text_columns: text_columns.into_iter().map(|c| c.into_string()).collect(),
1876 exclude_columns: exclude_columns
1877 .into_iter()
1878 .map(|c| c.into_string())
1879 .collect(),
1880 binlog_full_metadata,
1881 }),
1882 SourceExportStatementDetails::SqlServer {
1883 table,
1884 capture_instance,
1885 initial_lsn,
1886 } => SourceExportDetails::SqlServer(SqlServerSourceExportDetails {
1887 table,
1888 capture_instance,
1889 initial_lsn,
1890 text_columns: text_columns.into_iter().map(|c| c.into_string()).collect(),
1891 exclude_columns: exclude_columns
1892 .into_iter()
1893 .map(|c| c.into_string())
1894 .collect(),
1895 }),
1896 SourceExportStatementDetails::LoadGenerator { output } => {
1897 SourceExportDetails::LoadGenerator(LoadGeneratorSourceExportDetails { output })
1898 }
1899 SourceExportStatementDetails::Kafka {} => {
1900 if !include_metadata.is_empty()
1901 && !matches!(
1902 envelope,
1903 ast::SourceEnvelope::Upsert { .. }
1904 | ast::SourceEnvelope::None
1905 | ast::SourceEnvelope::Debezium
1906 )
1907 {
1908 sql_bail!("INCLUDE <metadata> requires ENVELOPE (NONE|UPSERT|DEBEZIUM)");
1910 }
1911
1912 let metadata_columns = include_metadata
1913 .into_iter()
1914 .flat_map(|item| match item {
1915 SourceIncludeMetadata::Timestamp { alias } => {
1916 let name = match alias {
1917 Some(name) => name.to_string(),
1918 None => "timestamp".to_owned(),
1919 };
1920 Some((name, KafkaMetadataKind::Timestamp))
1921 }
1922 SourceIncludeMetadata::Partition { alias } => {
1923 let name = match alias {
1924 Some(name) => name.to_string(),
1925 None => "partition".to_owned(),
1926 };
1927 Some((name, KafkaMetadataKind::Partition))
1928 }
1929 SourceIncludeMetadata::Offset { alias } => {
1930 let name = match alias {
1931 Some(name) => name.to_string(),
1932 None => "offset".to_owned(),
1933 };
1934 Some((name, KafkaMetadataKind::Offset))
1935 }
1936 SourceIncludeMetadata::Headers { alias } => {
1937 let name = match alias {
1938 Some(name) => name.to_string(),
1939 None => "headers".to_owned(),
1940 };
1941 Some((name, KafkaMetadataKind::Headers))
1942 }
1943 SourceIncludeMetadata::Header {
1944 alias,
1945 key,
1946 use_bytes,
1947 } => Some((
1948 alias.to_string(),
1949 KafkaMetadataKind::Header {
1950 key: key.clone(),
1951 use_bytes: *use_bytes,
1952 },
1953 )),
1954 SourceIncludeMetadata::Key { .. } => {
1955 None
1957 }
1958 })
1959 .collect();
1960
1961 SourceExportDetails::Kafka(KafkaSourceExportDetails { metadata_columns })
1962 }
1963 };
1964
1965 let source_connection = &source_item
1966 .source_desc()?
1967 .ok_or_else(|| sql_err!("item is not a source"))?
1968 .connection;
1969
1970 let (key_desc, value_desc) =
1975 if matches!(columns, TableFromSourceColumns::Defined(_)) || !constraints.is_empty() {
1976 let columns = match columns {
1977 TableFromSourceColumns::Defined(columns) => columns,
1978 _ => bail_internal!("expected column definitions to be present"),
1979 };
1980 let desc = plan_source_export_desc(scx, name, columns, constraints)?;
1981 (None, desc)
1982 } else {
1983 let key_desc = source_connection.default_key_desc();
1984 let value_desc = source_connection.default_value_desc();
1985 (Some(key_desc), value_desc)
1986 };
1987
1988 let metadata_columns_desc = match &details {
1989 SourceExportDetails::Kafka(KafkaSourceExportDetails {
1990 metadata_columns, ..
1991 }) => kafka_metadata_columns_desc(metadata_columns),
1992 _ => vec![],
1993 };
1994
1995 let (mut desc, envelope, encoding) = apply_source_envelope_encoding(
1996 scx,
1997 &envelope,
1998 format,
1999 key_desc,
2000 value_desc,
2001 include_metadata,
2002 metadata_columns_desc,
2003 source_connection,
2004 )?;
2005 if let TableFromSourceColumns::Named(col_names) = columns {
2006 plan_utils::maybe_rename_columns(format!("source table {}", name), &mut desc, col_names)?;
2007 }
2008
2009 let names: Vec<_> = desc.iter_names().cloned().collect();
2010 if let Some(dup) = names.iter().duplicates().next() {
2011 sql_bail!("column {} specified more than once", dup.quoted());
2012 }
2013
2014 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name.clone())?)?;
2015
2016 let timeline = match envelope {
2019 SourceEnvelope::CdcV2 => {
2020 Timeline::External(scx.catalog.resolve_full_name(&name).to_string())
2021 }
2022 _ => Timeline::EpochMilliseconds,
2023 };
2024
2025 if let Some(partition_by) = partition_by {
2026 scx.require_feature_flag(&ENABLE_COLLECTION_PARTITION_BY)?;
2027 check_partition_by(&desc, partition_by)?;
2028 }
2029
2030 let data_source = DataSourceDesc::IngestionExport {
2031 ingestion_id,
2032 external_reference: external_reference
2034 .as_ref()
2035 .ok_or_else(|| sql_err!("EXTERNAL REFERENCE is required"))?
2036 .clone(),
2037 details,
2038 data_config: SourceExportDataConfig { envelope, encoding },
2039 };
2040
2041 let if_not_exists = *if_not_exists;
2042
2043 let create_sql = normalize::create_statement(scx, Statement::CreateTableFromSource(stmt))?;
2044
2045 let compaction_window = plan_retain_history_option(scx, retain_history)?;
2046 let table = Table {
2047 create_sql,
2048 desc: VersionedRelationDesc::new(desc),
2049 temporary: false,
2050 compaction_window,
2051 data_source: TableDataSource::DataSource {
2052 desc: data_source,
2053 timeline,
2054 },
2055 };
2056
2057 Ok(Plan::CreateTable(CreateTablePlan {
2058 name,
2059 table,
2060 if_not_exists,
2061 }))
2062}
2063
2064generate_extracted_config!(
2065 LoadGeneratorOption,
2066 (TickInterval, Duration),
2067 (AsOf, u64, Default(0_u64)),
2068 (UpTo, u64, Default(u64::MAX)),
2069 (ScaleFactor, f64),
2070 (MaxCardinality, u64),
2071 (Keys, u64),
2072 (SnapshotRounds, u64),
2073 (TransactionalSnapshot, bool),
2074 (ValueSize, u64),
2075 (Seed, u64),
2076 (Partitions, u64),
2077 (BatchSize, u64)
2078);
2079
2080impl LoadGeneratorOptionExtracted {
2081 pub(super) fn ensure_only_valid_options(
2082 &self,
2083 loadgen: &ast::LoadGenerator,
2084 ) -> Result<(), PlanError> {
2085 use mz_sql_parser::ast::LoadGeneratorOptionName::*;
2086
2087 let mut options = self.seen.clone();
2088
2089 let permitted_options: &[_] = match loadgen {
2090 ast::LoadGenerator::Auction => &[TickInterval, AsOf, UpTo],
2091 ast::LoadGenerator::Clock => &[TickInterval, AsOf, UpTo],
2092 ast::LoadGenerator::Counter => &[TickInterval, AsOf, UpTo, MaxCardinality],
2093 ast::LoadGenerator::Marketing => &[TickInterval, AsOf, UpTo],
2094 ast::LoadGenerator::Datums => &[TickInterval, AsOf, UpTo],
2095 ast::LoadGenerator::Tpch => &[TickInterval, AsOf, UpTo, ScaleFactor],
2096 ast::LoadGenerator::KeyValue => &[
2097 TickInterval,
2098 Keys,
2099 SnapshotRounds,
2100 TransactionalSnapshot,
2101 ValueSize,
2102 Seed,
2103 Partitions,
2104 BatchSize,
2105 ],
2106 };
2107
2108 for o in permitted_options {
2109 options.remove(o);
2110 }
2111
2112 if !options.is_empty() {
2113 sql_bail!(
2114 "{} load generators do not support {} values",
2115 loadgen,
2116 options.iter().join(", ")
2117 )
2118 }
2119
2120 Ok(())
2121 }
2122}
2123
2124pub(crate) fn load_generator_ast_to_generator(
2125 scx: &StatementContext,
2126 loadgen: &ast::LoadGenerator,
2127 options: &[LoadGeneratorOption<Aug>],
2128 include_metadata: &[SourceIncludeMetadata],
2129) -> Result<LoadGenerator, PlanError> {
2130 let extracted: LoadGeneratorOptionExtracted = options.to_vec().try_into()?;
2131 extracted.ensure_only_valid_options(loadgen)?;
2132
2133 if loadgen != &ast::LoadGenerator::KeyValue && !include_metadata.is_empty() {
2134 sql_bail!("INCLUDE metadata only supported with `KEY VALUE` load generators");
2135 }
2136
2137 let load_generator = match loadgen {
2138 ast::LoadGenerator::Auction => LoadGenerator::Auction,
2139 ast::LoadGenerator::Clock => {
2140 scx.require_feature_flag(&vars::ENABLE_LOAD_GENERATOR_CLOCK)?;
2141 LoadGenerator::Clock
2142 }
2143 ast::LoadGenerator::Counter => {
2144 scx.require_feature_flag(&vars::ENABLE_LOAD_GENERATOR_COUNTER)?;
2145 let LoadGeneratorOptionExtracted {
2146 max_cardinality, ..
2147 } = extracted;
2148 LoadGenerator::Counter { max_cardinality }
2149 }
2150 ast::LoadGenerator::Marketing => LoadGenerator::Marketing,
2151 ast::LoadGenerator::Datums => {
2152 scx.require_feature_flag(&vars::ENABLE_LOAD_GENERATOR_DATUMS)?;
2153 LoadGenerator::Datums
2154 }
2155 ast::LoadGenerator::Tpch => {
2156 let LoadGeneratorOptionExtracted { scale_factor, .. } = extracted;
2157
2158 let sf: f64 = scale_factor.unwrap_or(0.01);
2160 if !sf.is_finite() || sf < 0.0 {
2161 sql_bail!("unsupported scale factor {sf}");
2162 }
2163
2164 let f_to_i = |multiplier: f64| -> Result<i64, PlanError> {
2165 let total = (sf * multiplier).floor();
2166 let mut i = i64::try_cast_from(total)
2167 .ok_or_else(|| sql_err!("unsupported scale factor {sf}"))?;
2168 if i < 1 {
2169 i = 1;
2170 }
2171 Ok(i)
2172 };
2173
2174 let count_supplier = f_to_i(10_000f64)?;
2177 let count_part = f_to_i(200_000f64)?;
2178 let count_customer = f_to_i(150_000f64)?;
2179 let count_orders = f_to_i(150_000f64 * 10f64)?;
2180 let count_clerk = f_to_i(1_000f64)?;
2181
2182 LoadGenerator::Tpch {
2183 count_supplier,
2184 count_part,
2185 count_customer,
2186 count_orders,
2187 count_clerk,
2188 }
2189 }
2190 mz_sql_parser::ast::LoadGenerator::KeyValue => {
2191 scx.require_feature_flag(&vars::ENABLE_LOAD_GENERATOR_KEY_VALUE)?;
2192 let LoadGeneratorOptionExtracted {
2193 keys,
2194 snapshot_rounds,
2195 transactional_snapshot,
2196 value_size,
2197 tick_interval,
2198 seed,
2199 partitions,
2200 batch_size,
2201 ..
2202 } = extracted;
2203
2204 let mut include_offset = None;
2205 for im in include_metadata {
2206 match im {
2207 SourceIncludeMetadata::Offset { alias } => {
2208 include_offset = match alias {
2209 Some(alias) => Some(alias.to_string()),
2210 None => Some(LOAD_GENERATOR_KEY_VALUE_OFFSET_DEFAULT.to_string()),
2211 }
2212 }
2213 SourceIncludeMetadata::Key { .. } => continue,
2214
2215 _ => {
2216 sql_bail!("only `INCLUDE OFFSET` and `INCLUDE KEY` is supported");
2217 }
2218 };
2219 }
2220
2221 let lgkv = KeyValueLoadGenerator {
2222 keys: keys.ok_or_else(|| sql_err!("LOAD GENERATOR KEY VALUE requires KEYS"))?,
2223 snapshot_rounds: snapshot_rounds
2224 .ok_or_else(|| sql_err!("LOAD GENERATOR KEY VALUE requires SNAPSHOT ROUNDS"))?,
2225 transactional_snapshot: transactional_snapshot.unwrap_or(true),
2227 value_size: value_size
2228 .ok_or_else(|| sql_err!("LOAD GENERATOR KEY VALUE requires VALUE SIZE"))?,
2229 partitions: partitions
2230 .ok_or_else(|| sql_err!("LOAD GENERATOR KEY VALUE requires PARTITIONS"))?,
2231 tick_interval,
2232 batch_size: batch_size
2233 .ok_or_else(|| sql_err!("LOAD GENERATOR KEY VALUE requires BATCH SIZE"))?,
2234 seed: seed.ok_or_else(|| sql_err!("LOAD GENERATOR KEY VALUE requires SEED"))?,
2235 include_offset,
2236 };
2237
2238 if lgkv.keys == 0
2239 || lgkv.partitions == 0
2240 || lgkv.value_size == 0
2241 || lgkv.batch_size == 0
2242 {
2243 sql_bail!("LOAD GENERATOR KEY VALUE options must be non-zero")
2244 }
2245
2246 if lgkv.keys % lgkv.partitions != 0 {
2247 sql_bail!("KEYS must be a multiple of PARTITIONS")
2248 }
2249
2250 if lgkv.batch_size > lgkv.keys {
2251 sql_bail!("KEYS must be larger than BATCH SIZE")
2252 }
2253
2254 if (lgkv.keys / lgkv.partitions) % lgkv.batch_size != 0 {
2257 sql_bail!("PARTITIONS * BATCH SIZE must be a divisor of KEYS")
2258 }
2259
2260 if lgkv.snapshot_rounds == 0 {
2261 sql_bail!("SNAPSHOT ROUNDS must be larger than 0")
2262 }
2263
2264 LoadGenerator::KeyValue(lgkv)
2265 }
2266 };
2267
2268 Ok(load_generator)
2269}
2270
2271fn typecheck_debezium(value_desc: &RelationDesc) -> Result<(Option<usize>, usize), PlanError> {
2272 let before = value_desc.get_by_name(&"before".into());
2273 let (after_idx, after_ty) = value_desc
2274 .get_by_name(&"after".into())
2275 .ok_or_else(|| sql_err!("'after' column missing from debezium input"))?;
2276 let before_idx = if let Some((before_idx, before_ty)) = before {
2277 if !matches!(before_ty.scalar_type, SqlScalarType::Record { .. }) {
2278 sql_bail!("'before' column must be of type record");
2279 }
2280 if before_ty != after_ty {
2281 sql_bail!("'before' type differs from 'after' column");
2282 }
2283 Some(before_idx)
2284 } else {
2285 None
2286 };
2287 Ok((before_idx, after_idx))
2288}
2289
2290fn get_encoding(
2291 scx: &StatementContext,
2292 format: &FormatSpecifier<Aug>,
2293 envelope: &ast::SourceEnvelope,
2294) -> Result<SourceDataEncoding<ReferencedConnection>, PlanError> {
2295 let encoding = match format {
2296 FormatSpecifier::Bare(format) => get_encoding_inner(scx, format)?,
2297 FormatSpecifier::KeyValue { key, value } => {
2298 let key = {
2299 let encoding = get_encoding_inner(scx, key)?;
2300 Some(encoding.key.unwrap_or(encoding.value))
2301 };
2302 let value = get_encoding_inner(scx, value)?.value;
2303 SourceDataEncoding { key, value }
2304 }
2305 };
2306
2307 let requires_keyvalue = matches!(
2308 envelope,
2309 ast::SourceEnvelope::Debezium | ast::SourceEnvelope::Upsert { .. }
2310 );
2311 let is_keyvalue = encoding.key.is_some();
2312 if requires_keyvalue && !is_keyvalue {
2313 sql_bail!("ENVELOPE [DEBEZIUM] UPSERT requires that KEY FORMAT be specified");
2314 };
2315
2316 Ok(encoding)
2317}
2318
2319fn source_sink_cluster_config<'a, 'ctx>(
2325 scx: &'a StatementContext<'ctx>,
2326 in_cluster: &mut Option<ResolvedClusterName>,
2327) -> Result<&'a dyn CatalogCluster<'ctx>, PlanError> {
2328 let cluster = match in_cluster {
2329 None => {
2330 let cluster = scx.catalog.resolve_cluster(None)?;
2331 *in_cluster = Some(ResolvedClusterName {
2332 id: cluster.id(),
2333 print_name: None,
2334 });
2335 cluster
2336 }
2337 Some(in_cluster) => scx.catalog.get_cluster(in_cluster.id),
2338 };
2339
2340 Ok(cluster)
2341}
2342
2343generate_extracted_config!(AvroSchemaOption, (ConfluentWireFormat, bool, Default(true)));
2344
2345generate_extracted_config!(
2349 GlueAvroOption,
2350 (SchemaName, String),
2351 (KeySchemaName, String),
2352 (ValueSchemaName, String),
2353 (KeyCompatibilityLevel, String),
2354 (ValueCompatibilityLevel, String)
2355);
2356
2357#[derive(Debug)]
2358pub struct Schema {
2359 pub key_schema: Option<String>,
2360 pub value_schema: String,
2361 pub key_reference_schemas: Vec<String>,
2363 pub value_reference_schemas: Vec<String>,
2365 pub wire_format: WireFormat<ReferencedConnection>,
2369}
2370
2371fn get_encoding_inner(
2372 scx: &StatementContext,
2373 format: &Format<Aug>,
2374) -> Result<SourceDataEncoding<ReferencedConnection>, PlanError> {
2375 let value = match format {
2376 Format::Bytes => DataEncoding::Bytes,
2377 Format::Avro(schema) => {
2378 let Schema {
2379 key_schema,
2380 value_schema,
2381 key_reference_schemas,
2382 value_reference_schemas,
2383 wire_format,
2384 } = match schema {
2385 AvroSchema::InlineSchema {
2388 schema: ast::Schema { schema },
2389 with_options,
2390 } => {
2391 let AvroSchemaOptionExtracted {
2392 confluent_wire_format,
2393 ..
2394 } = with_options.clone().try_into()?;
2395 let wire_format = if confluent_wire_format {
2396 WireFormat::Confluent { registry: None }
2397 } else {
2398 WireFormat::None
2399 };
2400 Schema {
2401 key_schema: None,
2402 value_schema: schema.clone(),
2403 key_reference_schemas: vec![],
2404 value_reference_schemas: vec![],
2405 wire_format,
2406 }
2407 }
2408 AvroSchema::Csr {
2409 csr_connection:
2410 CsrConnectionAvro {
2411 connection,
2412 seed,
2413 key_strategy: _,
2414 value_strategy: _,
2415 },
2416 } => {
2417 let item = scx.get_item_by_resolved_name(&connection.connection)?;
2418 let csr_connection = match item.connection()? {
2419 Connection::Csr(_) => item.id(),
2420 _ => {
2421 sql_bail!(
2422 "{} is not a Confluent Schema Registry connection",
2423 scx.catalog
2424 .resolve_full_name(item.name())
2425 .to_string()
2426 .quoted()
2427 )
2428 }
2429 };
2430
2431 if let Some(seed) = seed {
2432 Schema {
2433 key_schema: seed.key_schema.clone(),
2434 value_schema: seed.value_schema.clone(),
2435 key_reference_schemas: seed.key_reference_schemas.clone(),
2436 value_reference_schemas: seed.value_reference_schemas.clone(),
2437 wire_format: WireFormat::Confluent {
2438 registry: Some(csr_connection),
2439 },
2440 }
2441 } else {
2442 sql_bail!("Avro CSR seed resolution has not been performed")
2443 }
2444 }
2445 AvroSchema::Glue {
2446 connection,
2447 with_options: _,
2448 seed,
2449 } => {
2450 let item = scx.get_item_by_resolved_name(connection)?;
2451 let glue_connection = match item.connection()? {
2452 Connection::GlueSchemaRegistry(_) => item.id(),
2453 _ => {
2454 sql_bail!(
2455 "{} is not an AWS Glue Schema Registry connection",
2456 scx.catalog
2457 .resolve_full_name(item.name())
2458 .to_string()
2459 .quoted()
2460 )
2461 }
2462 };
2463
2464 let Some(seed) = seed else {
2468 sql_bail!("Avro Glue seed resolution has not been performed");
2469 };
2470
2471 Schema {
2472 key_schema: None,
2473 value_schema: seed.value_schema.clone(),
2474 key_reference_schemas: vec![],
2475 value_reference_schemas: vec![],
2476 wire_format: WireFormat::Glue {
2477 registry: Some(glue_connection),
2478 },
2479 }
2480 }
2481 };
2482
2483 if let Some(key_schema) = key_schema {
2484 return Ok(SourceDataEncoding {
2485 key: Some(DataEncoding::Avro(AvroEncoding {
2486 schema: key_schema,
2487 reference_schemas: key_reference_schemas,
2488 wire_format: wire_format.clone(),
2489 })),
2490 value: DataEncoding::Avro(AvroEncoding {
2491 schema: value_schema,
2492 reference_schemas: value_reference_schemas,
2493 wire_format,
2494 }),
2495 });
2496 } else {
2497 DataEncoding::Avro(AvroEncoding {
2498 schema: value_schema,
2499 reference_schemas: value_reference_schemas,
2500 wire_format,
2501 })
2502 }
2503 }
2504 Format::Protobuf(schema) => match schema {
2505 ProtobufSchema::Csr {
2506 csr_connection:
2507 CsrConnectionProtobuf {
2508 connection:
2509 CsrConnection {
2510 connection,
2511 options,
2512 },
2513 seed,
2514 },
2515 } => {
2516 if let Some(CsrSeedProtobuf { key, value }) = seed {
2517 let item = scx.get_item_by_resolved_name(connection)?;
2518 let _ = match item.connection()? {
2519 Connection::Csr(connection) => connection,
2520 _ => {
2521 sql_bail!(
2522 "{} is not a schema registry connection",
2523 scx.catalog
2524 .resolve_full_name(item.name())
2525 .to_string()
2526 .quoted()
2527 )
2528 }
2529 };
2530
2531 if !options.is_empty() {
2532 sql_bail!("Protobuf CSR connections do not support any options");
2533 }
2534
2535 let value = DataEncoding::Protobuf(ProtobufEncoding {
2536 descriptors: strconv::parse_bytes(&value.schema)?,
2537 message_name: value.message_name.clone(),
2538 confluent_wire_format: true,
2539 });
2540 if let Some(key) = key {
2541 return Ok(SourceDataEncoding {
2542 key: Some(DataEncoding::Protobuf(ProtobufEncoding {
2543 descriptors: strconv::parse_bytes(&key.schema)?,
2544 message_name: key.message_name.clone(),
2545 confluent_wire_format: true,
2546 })),
2547 value,
2548 });
2549 }
2550 value
2551 } else {
2552 sql_bail!("Protobuf CSR seed resolution has not been performed")
2553 }
2554 }
2555 ProtobufSchema::InlineSchema {
2556 message_name,
2557 schema: ast::Schema { schema },
2558 } => {
2559 let descriptors = strconv::parse_bytes(schema)?;
2560
2561 DataEncoding::Protobuf(ProtobufEncoding {
2562 descriptors,
2563 message_name: message_name.to_owned(),
2564 confluent_wire_format: false,
2565 })
2566 }
2567 },
2568 Format::Regex(regex) => DataEncoding::Regex(RegexEncoding {
2569 regex: mz_repr::adt::regex::Regex::new(regex, false)
2570 .map_err(|e| sql_err!("parsing regex: {e}"))?,
2571 }),
2572 Format::Csv { columns, delimiter } => {
2573 let columns = match columns {
2574 CsvColumns::Header { names } => {
2575 if names.is_empty() {
2576 sql_bail!("[internal error] column spec should get names in purify")
2577 }
2578 ColumnSpec::Header {
2579 names: names.iter().cloned().map(|n| n.into_string()).collect(),
2580 }
2581 }
2582 CsvColumns::Count(n) => ColumnSpec::Count(usize::cast_from(*n)),
2583 };
2584 DataEncoding::Csv(CsvEncoding {
2585 columns,
2586 delimiter: u8::try_from(*delimiter)
2587 .map_err(|_| sql_err!("CSV delimiter must be an ASCII character"))?,
2588 })
2589 }
2590 Format::Json { array: false } => DataEncoding::Json,
2591 Format::Json { array: true } => bail_unsupported!("JSON ARRAY format in sources"),
2592 Format::Text => DataEncoding::Text,
2593 };
2594 Ok(SourceDataEncoding { key: None, value })
2595}
2596
2597fn get_key_envelope(
2599 included_items: &[SourceIncludeMetadata],
2600 encoding: Option<&SourceDataEncoding<ReferencedConnection>>,
2601 key_envelope_no_encoding: bool,
2602) -> Result<KeyEnvelope, PlanError> {
2603 let key_definition = included_items
2604 .iter()
2605 .find(|i| matches!(i, SourceIncludeMetadata::Key { .. }));
2606 if let Some(SourceIncludeMetadata::Key { alias }) = key_definition {
2607 match (alias, encoding.and_then(|e| e.key.as_ref())) {
2608 (Some(name), Some(_)) => Ok(KeyEnvelope::Named(name.as_str().to_string())),
2609 (None, Some(key)) => get_unnamed_key_envelope(Some(key)),
2610 (Some(name), _) if key_envelope_no_encoding => {
2611 Ok(KeyEnvelope::Named(name.as_str().to_string()))
2612 }
2613 (None, _) if key_envelope_no_encoding => get_unnamed_key_envelope(None),
2614 (_, None) => {
2615 sql_bail!(
2619 "INCLUDE KEY requires specifying KEY FORMAT .. VALUE FORMAT, \
2620 got bare FORMAT"
2621 );
2622 }
2623 }
2624 } else {
2625 Ok(KeyEnvelope::None)
2626 }
2627}
2628
2629fn get_unnamed_key_envelope(
2632 key: Option<&DataEncoding<ReferencedConnection>>,
2633) -> Result<KeyEnvelope, PlanError> {
2634 let is_composite = match key {
2638 Some(DataEncoding::Bytes | DataEncoding::Json | DataEncoding::Text) => false,
2639 Some(
2640 DataEncoding::Avro(_)
2641 | DataEncoding::Csv(_)
2642 | DataEncoding::Protobuf(_)
2643 | DataEncoding::Regex { .. },
2644 ) => true,
2645 None => false,
2646 };
2647
2648 if is_composite {
2649 Ok(KeyEnvelope::Flattened)
2650 } else {
2651 Ok(KeyEnvelope::Named("key".to_string()))
2652 }
2653}
2654
2655pub fn describe_create_view(
2656 _: &StatementContext,
2657 _: CreateViewStatement<Aug>,
2658) -> Result<StatementDesc, PlanError> {
2659 Ok(StatementDesc::new(None))
2660}
2661
2662pub fn plan_view(
2663 scx: &StatementContext,
2664 def: &mut ViewDefinition<Aug>,
2665 temporary: bool,
2666) -> Result<(QualifiedItemName, View), PlanError> {
2667 let create_sql = normalize::create_statement(
2668 scx,
2669 Statement::CreateView(CreateViewStatement {
2670 if_exists: IfExistsBehavior::Error,
2671 temporary,
2672 definition: def.clone(),
2673 }),
2674 )?;
2675
2676 let ViewDefinition {
2677 name,
2678 columns,
2679 query,
2680 } = def;
2681
2682 let query::PlannedRootQuery {
2683 expr,
2684 mut desc,
2685 finishing,
2686 scope: _,
2687 } = query::plan_root_query(scx, query.clone(), QueryLifetime::View)?;
2688 assert!(HirRelationExpr::is_trivial_row_set_finishing_hir(
2694 &finishing,
2695 expr.arity()
2696 ));
2697 if expr.contains_parameters()? {
2698 return Err(PlanError::ParameterNotAllowed("views".to_string()));
2699 }
2700
2701 let dependencies = expr
2702 .depends_on()
2703 .into_iter()
2704 .map(|gid| scx.catalog.resolve_item_id(&gid))
2705 .collect();
2706
2707 let name = if temporary {
2708 scx.allocate_temporary_qualified_name(normalize::unresolved_item_name(name.to_owned())?)?
2709 } else {
2710 scx.allocate_qualified_name(normalize::unresolved_item_name(name.to_owned())?)?
2711 };
2712
2713 plan_utils::maybe_rename_columns_exact(
2714 scx.catalog,
2715 format!("view {}", scx.catalog.resolve_full_name(&name)),
2716 &mut desc,
2717 columns,
2718 )?;
2719 let names: Vec<ColumnName> = desc.iter_names().cloned().collect();
2720
2721 if let Some(dup) = names.iter().duplicates().next() {
2722 sql_bail!("column {} specified more than once", dup.quoted());
2723 }
2724
2725 let view = View {
2726 create_sql,
2727 expr,
2728 dependencies,
2729 column_names: names,
2730 temporary,
2731 };
2732
2733 Ok((name, view))
2734}
2735
2736pub fn plan_create_view(
2737 scx: &StatementContext,
2738 mut stmt: CreateViewStatement<Aug>,
2739) -> Result<Plan, PlanError> {
2740 let CreateViewStatement {
2741 temporary,
2742 if_exists,
2743 definition,
2744 } = &mut stmt;
2745 let (name, view) = plan_view(scx, definition, *temporary)?;
2746
2747 let ignore_if_exists_errors = scx.pcx().map_or(false, |pcx| pcx.ignore_if_exists_errors);
2750
2751 let replace = if *if_exists == IfExistsBehavior::Replace && !ignore_if_exists_errors {
2752 let if_exists = true;
2753 let cascade = false;
2754 let maybe_item_to_drop = plan_drop_item(
2755 scx,
2756 ObjectType::View,
2757 if_exists,
2758 definition.name.clone(),
2759 cascade,
2760 )?;
2761
2762 if let Some(id) = maybe_item_to_drop {
2764 let dependencies = view.expr.depends_on();
2765 let invalid_drop = scx
2766 .get_item(&id)
2767 .global_ids()
2768 .any(|gid| dependencies.contains(&gid));
2769 if invalid_drop {
2770 let item = scx.catalog.get_item(&id);
2771 sql_bail!(
2772 "cannot replace view {0}: depended upon by new {0} definition",
2773 scx.catalog.resolve_full_name(item.name())
2774 );
2775 }
2776
2777 Some(id)
2778 } else {
2779 None
2780 }
2781 } else {
2782 None
2783 };
2784 let drop_ids = replace
2785 .map(|id| {
2786 scx.catalog
2787 .item_dependents(id)
2788 .into_iter()
2789 .map(|id| id.unwrap_item_id())
2790 .collect()
2791 })
2792 .unwrap_or_default();
2793
2794 validate_view_dependencies(scx, &view.dependencies.0)?;
2795
2796 let full_name = scx.catalog.resolve_full_name(&name);
2798 let partial_name = PartialItemName::from(full_name.clone());
2799 if let (Ok(item), IfExistsBehavior::Error, false) = (
2802 scx.catalog.resolve_item_or_type(&partial_name),
2803 *if_exists,
2804 ignore_if_exists_errors,
2805 ) {
2806 return Err(PlanError::ItemAlreadyExists {
2807 name: full_name.to_string(),
2808 item_type: item.item_type(),
2809 });
2810 }
2811
2812 Ok(Plan::CreateView(CreateViewPlan {
2813 name,
2814 view,
2815 replace,
2816 drop_ids,
2817 if_not_exists: *if_exists == IfExistsBehavior::Skip,
2818 ambiguous_columns: *scx.ambiguous_columns.borrow(),
2819 }))
2820}
2821
2822fn validate_view_dependencies(
2824 scx: &StatementContext,
2825 dependencies: &BTreeSet<CatalogItemId>,
2826) -> Result<(), PlanError> {
2827 for id in dependencies {
2828 let item = scx.catalog.get_item(id);
2829 if item.replacement_target().is_some() {
2830 let name = scx.catalog.minimal_qualification(item.name());
2831 return Err(PlanError::InvalidDependency {
2832 name: name.to_string(),
2833 item_type: format!("replacement {}", item.item_type()),
2834 });
2835 }
2836 }
2837
2838 Ok(())
2839}
2840
2841pub fn describe_create_materialized_view(
2842 _: &StatementContext,
2843 _: CreateMaterializedViewStatement<Aug>,
2844) -> Result<StatementDesc, PlanError> {
2845 Ok(StatementDesc::new(None))
2846}
2847
2848pub fn describe_create_network_policy(
2849 _: &StatementContext,
2850 _: CreateNetworkPolicyStatement<Aug>,
2851) -> Result<StatementDesc, PlanError> {
2852 Ok(StatementDesc::new(None))
2853}
2854
2855pub fn describe_alter_network_policy(
2856 _: &StatementContext,
2857 _: AlterNetworkPolicyStatement<Aug>,
2858) -> Result<StatementDesc, PlanError> {
2859 Ok(StatementDesc::new(None))
2860}
2861
2862fn check_refresh_time(option: &str, ts: Timestamp) -> Result<(), PlanError> {
2864 let renderable = i64::try_from(ts)
2865 .ok()
2866 .and_then(DateTime::from_timestamp_millis)
2867 .is_some_and(|dt| CheckedTimestamp::try_from(dt).is_ok());
2868 if !renderable {
2869 sql_bail!("{option} time too large: {ts}");
2870 }
2871 Ok(())
2872}
2873
2874pub fn plan_create_materialized_view(
2875 scx: &StatementContext,
2876 mut stmt: CreateMaterializedViewStatement<Aug>,
2877) -> Result<Plan, PlanError> {
2878 let cluster_id =
2879 crate::plan::statement::resolve_cluster_for_materialized_view(scx.catalog, &stmt)?;
2880 stmt.in_cluster = Some(ResolvedClusterName {
2881 id: cluster_id,
2882 print_name: None,
2883 });
2884
2885 let target_replica = match &stmt.in_cluster_replica {
2886 Some(replica_name) => {
2887 scx.require_feature_flag(&ENABLE_REPLICA_TARGETED_MATERIALIZED_VIEWS)?;
2888
2889 let cluster = scx.catalog.get_cluster(cluster_id);
2890 let replica_id = cluster
2891 .replica_ids()
2892 .get(replica_name.as_str())
2893 .copied()
2894 .ok_or_else(|| {
2895 CatalogError::UnknownClusterReplica(replica_name.as_str().to_string())
2896 })?;
2897 Some(replica_id)
2898 }
2899 None => None,
2900 };
2901
2902 let create_sql =
2903 normalize::create_statement(scx, Statement::CreateMaterializedView(stmt.clone()))?;
2904
2905 let partial_name = normalize::unresolved_item_name(stmt.name)?;
2906 let name = scx.allocate_qualified_name(partial_name.clone())?;
2907
2908 let query::PlannedRootQuery {
2909 expr,
2910 mut desc,
2911 finishing,
2912 scope: _,
2913 } = query::plan_root_query(scx, stmt.query, QueryLifetime::MaterializedView)?;
2914 assert!(HirRelationExpr::is_trivial_row_set_finishing_hir(
2916 &finishing,
2917 expr.arity()
2918 ));
2919 if expr.contains_parameters()? {
2920 return Err(PlanError::ParameterNotAllowed(
2921 "materialized views".to_string(),
2922 ));
2923 }
2924
2925 plan_utils::maybe_rename_columns_exact(
2926 scx.catalog,
2927 format!("materialized view {}", scx.catalog.resolve_full_name(&name)),
2928 &mut desc,
2929 &stmt.columns,
2930 )?;
2931 let column_names: Vec<ColumnName> = desc.iter_names().cloned().collect();
2932
2933 let MaterializedViewOptionExtracted {
2934 assert_not_null,
2935 partition_by,
2936 retain_history,
2937 refresh,
2938 seen: _,
2939 }: MaterializedViewOptionExtracted = stmt.with_options.try_into()?;
2940
2941 if let Some(partition_by) = partition_by {
2942 scx.require_feature_flag(&ENABLE_COLLECTION_PARTITION_BY)?;
2943 check_partition_by(&desc, partition_by)?;
2944 }
2945
2946 let refresh_schedule = {
2947 let mut refresh_schedule = RefreshSchedule::default();
2948 let mut on_commits_seen = 0;
2949 for refresh_option_value in refresh {
2950 if !matches!(refresh_option_value, RefreshOptionValue::OnCommit) {
2951 scx.require_feature_flag(&ENABLE_REFRESH_EVERY_MVS)?;
2952 }
2953 match refresh_option_value {
2954 RefreshOptionValue::OnCommit => {
2955 on_commits_seen += 1;
2956 }
2957 RefreshOptionValue::AtCreation => {
2958 soft_panic_or_log!("REFRESH AT CREATION should have been purified away");
2959 bail_internal!("REFRESH AT CREATION should have been purified away")
2960 }
2961 RefreshOptionValue::At(RefreshAtOptionValue { mut time }) => {
2962 transform_ast::transform(scx, &mut time)?; let ecx = &ExprContext {
2964 qcx: &QueryContext::root(scx, QueryLifetime::OneShot),
2965 name: "REFRESH AT",
2966 scope: &Scope::empty(),
2967 relation_type: &SqlRelationType::empty(),
2968 allow_aggregates: false,
2969 allow_subqueries: false,
2970 allow_parameters: false,
2971 allow_windows: false,
2972 };
2973 let hir = plan_expr(ecx, &time)?.cast_to(
2974 ecx,
2975 CastContext::Assignment,
2976 &SqlScalarType::MzTimestamp,
2977 )?;
2978 let timestamp = hir
2980 .into_literal_mz_timestamp()
2981 .ok_or_else(|| PlanError::InvalidRefreshAt)?;
2982 check_refresh_time("REFRESH AT", timestamp)?;
2983 refresh_schedule.ats.push(timestamp);
2984 }
2985 RefreshOptionValue::Every(RefreshEveryOptionValue {
2986 interval,
2987 aligned_to,
2988 }) => {
2989 let interval = Interval::try_from_value(Value::Interval(interval))?;
2990 if interval.as_microseconds() <= 0 {
2991 sql_bail!("REFRESH interval must be positive; got: {}", interval);
2992 }
2993 if interval.months != 0 {
2994 sql_bail!("REFRESH interval must not involve units larger than days");
2999 }
3000 let interval = interval.duration()?;
3001 if u64::try_from(interval.as_millis()).is_err()
3006 || Interval::from_duration(&interval).is_err()
3007 {
3008 sql_bail!("REFRESH interval too large");
3009 }
3010 if interval.as_micros() < 1000 {
3011 sql_bail!("REFRESH interval must be at least 1 ms")
3012 }
3013
3014 let mut aligned_to = match aligned_to {
3015 Some(aligned_to) => aligned_to,
3016 None => {
3017 soft_panic_or_log!(
3018 "ALIGNED TO should have been filled in by purification"
3019 );
3020 sql_bail!(
3021 "INTERNAL ERROR: ALIGNED TO should have been filled in by purification"
3022 )
3023 }
3024 };
3025
3026 transform_ast::transform(scx, &mut aligned_to)?;
3028
3029 let ecx = &ExprContext {
3030 qcx: &QueryContext::root(scx, QueryLifetime::OneShot),
3031 name: "REFRESH EVERY ... ALIGNED TO",
3032 scope: &Scope::empty(),
3033 relation_type: &SqlRelationType::empty(),
3034 allow_aggregates: false,
3035 allow_subqueries: false,
3036 allow_parameters: false,
3037 allow_windows: false,
3038 };
3039 let aligned_to_hir = plan_expr(ecx, &aligned_to)?.cast_to(
3040 ecx,
3041 CastContext::Assignment,
3042 &SqlScalarType::MzTimestamp,
3043 )?;
3044 let aligned_to_const = aligned_to_hir
3046 .into_literal_mz_timestamp()
3047 .ok_or_else(|| PlanError::InvalidRefreshEveryAlignedTo)?;
3048 check_refresh_time("REFRESH EVERY ... ALIGNED TO", aligned_to_const)?;
3049
3050 refresh_schedule.everies.push(RefreshEvery {
3051 interval,
3052 aligned_to: aligned_to_const,
3053 });
3054 }
3055 }
3056 }
3057
3058 if on_commits_seen > 1 {
3059 sql_bail!("REFRESH ON COMMIT cannot be specified multiple times");
3060 }
3061 if on_commits_seen > 0 && refresh_schedule != RefreshSchedule::default() {
3062 sql_bail!("REFRESH ON COMMIT is not compatible with any of the other REFRESH options");
3063 }
3064
3065 if refresh_schedule == RefreshSchedule::default() {
3066 None
3067 } else {
3068 Some(refresh_schedule)
3069 }
3070 };
3071
3072 let as_of = stmt.as_of.map(Timestamp::from);
3073 let compaction_window = plan_retain_history_option(scx, retain_history)?;
3074 let mut non_null_assertions = assert_not_null
3075 .into_iter()
3076 .map(normalize::column_name)
3077 .map(|assertion_name| {
3078 column_names
3079 .iter()
3080 .position(|col| col == &assertion_name)
3081 .ok_or_else(|| {
3082 sql_err!(
3083 "column {} in ASSERT NOT NULL option not found",
3084 assertion_name.quoted()
3085 )
3086 })
3087 })
3088 .collect::<Result<Vec<_>, _>>()?;
3089 non_null_assertions.sort();
3090 if let Some(dup) = non_null_assertions.iter().duplicates().next() {
3091 let dup = &column_names[*dup];
3092 sql_bail!("duplicate column {} in non-null assertions", dup.quoted());
3093 }
3094
3095 if let Some(dup) = column_names.iter().duplicates().next() {
3096 sql_bail!("column {} specified more than once", dup.quoted());
3097 }
3098
3099 let if_exists = match scx.pcx().map(|pcx| pcx.ignore_if_exists_errors) {
3102 Ok(true) => IfExistsBehavior::Skip,
3103 _ => stmt.if_exists,
3104 };
3105
3106 let mut replace = None;
3107 let mut if_not_exists = false;
3108 match if_exists {
3109 IfExistsBehavior::Replace => {
3110 let if_exists = true;
3111 let cascade = false;
3112 let replace_id = plan_drop_item(
3113 scx,
3114 ObjectType::MaterializedView,
3115 if_exists,
3116 partial_name.clone().into(),
3117 cascade,
3118 )?;
3119
3120 if let Some(id) = replace_id {
3122 let dependencies = expr.depends_on();
3123 let invalid_drop = scx
3124 .get_item(&id)
3125 .global_ids()
3126 .any(|gid| dependencies.contains(&gid));
3127 if invalid_drop {
3128 let item = scx.catalog.get_item(&id);
3129 sql_bail!(
3130 "cannot replace materialized view {0}: depended upon by new {0} definition",
3131 scx.catalog.resolve_full_name(item.name())
3132 );
3133 }
3134 replace = Some(id);
3135 }
3136 }
3137 IfExistsBehavior::Skip => if_not_exists = true,
3138 IfExistsBehavior::Error => (),
3139 }
3140 let drop_ids = replace
3141 .map(|id| {
3142 scx.catalog
3143 .item_dependents(id)
3144 .into_iter()
3145 .map(|id| id.unwrap_item_id())
3146 .collect()
3147 })
3148 .unwrap_or_default();
3149 let mut dependencies: BTreeSet<_> = expr
3150 .depends_on()
3151 .into_iter()
3152 .map(|gid| scx.catalog.resolve_item_id(&gid))
3153 .collect();
3154
3155 let mut replacement_target = None;
3157 if let Some(target_name) = &stmt.replacement_for {
3158 scx.require_feature_flag(&vars::ENABLE_REPLACEMENT_MATERIALIZED_VIEWS)?;
3159
3160 let target = scx.get_item_by_resolved_name(target_name)?;
3161 if target.item_type() != CatalogItemType::MaterializedView {
3162 return Err(PlanError::InvalidReplacement {
3163 item_type: target.item_type(),
3164 item_name: scx.catalog.minimal_qualification(target.name()),
3165 replacement_type: CatalogItemType::MaterializedView,
3166 replacement_name: partial_name,
3167 });
3168 }
3169 if target.id().is_system() {
3170 sql_bail!(
3171 "cannot replace {} because it is required by the database system",
3172 scx.catalog.minimal_qualification(target.name()),
3173 );
3174 }
3175
3176 for dependent in scx.catalog.item_dependents(target.id()) {
3178 if let ObjectId::Item(id) = dependent
3179 && dependencies.contains(&id)
3180 {
3181 sql_bail!(
3182 "replacement would cause {} to depend on itself",
3183 scx.catalog.minimal_qualification(target.name()),
3184 );
3185 }
3186 }
3187
3188 dependencies.insert(target.id());
3189
3190 for use_id in target.used_by() {
3191 let use_item = scx.get_item(use_id);
3192 if use_item.replacement_target() == Some(target.id()) {
3193 sql_bail!(
3194 "cannot replace {} because it already has a replacement: {}",
3195 scx.catalog.minimal_qualification(target.name()),
3196 scx.catalog.minimal_qualification(use_item.name()),
3197 );
3198 }
3199 }
3200
3201 replacement_target = Some(target.id());
3202 }
3203
3204 validate_view_dependencies(scx, &dependencies)?;
3205
3206 let full_name = scx.catalog.resolve_full_name(&name);
3208 let partial_name = PartialItemName::from(full_name.clone());
3209 if let (IfExistsBehavior::Error, Ok(item)) =
3212 (if_exists, scx.catalog.resolve_item_or_type(&partial_name))
3213 {
3214 return Err(PlanError::ItemAlreadyExists {
3215 name: full_name.to_string(),
3216 item_type: item.item_type(),
3217 });
3218 }
3219
3220 Ok(Plan::CreateMaterializedView(CreateMaterializedViewPlan {
3221 name,
3222 materialized_view: MaterializedView {
3223 create_sql,
3224 expr,
3225 dependencies: DependencyIds(dependencies),
3226 column_names,
3227 replacement_target,
3228 cluster_id,
3229 target_replica,
3230 non_null_assertions,
3231 compaction_window,
3232 refresh_schedule,
3233 as_of,
3234 },
3235 replace,
3236 drop_ids,
3237 if_not_exists,
3238 ambiguous_columns: *scx.ambiguous_columns.borrow(),
3239 }))
3240}
3241
3242generate_extracted_config!(
3243 MaterializedViewOption,
3244 (AssertNotNull, Ident, AllowMultiple),
3245 (PartitionBy, Vec<Ident>),
3246 (RetainHistory, OptionalDuration),
3247 (Refresh, RefreshOptionValue<Aug>, AllowMultiple)
3248);
3249
3250pub fn describe_create_sink(
3251 _: &StatementContext,
3252 _: CreateSinkStatement<Aug>,
3253) -> Result<StatementDesc, PlanError> {
3254 Ok(StatementDesc::new(None))
3255}
3256
3257generate_extracted_config!(
3258 CreateSinkOption,
3259 (Snapshot, bool),
3260 (PartitionStrategy, String),
3261 (Version, u64),
3262 (CommitInterval, Duration)
3263);
3264
3265pub fn plan_create_sink(
3266 scx: &StatementContext,
3267 stmt: CreateSinkStatement<Aug>,
3268) -> Result<Plan, PlanError> {
3269 let Some(name) = stmt.name.clone() else {
3271 return Err(PlanError::MissingName(CatalogItemType::Sink));
3272 };
3273 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name)?)?;
3274 let full_name = scx.catalog.resolve_full_name(&name);
3275 let partial_name = PartialItemName::from(full_name.clone());
3276 if let (false, Ok(item)) = (stmt.if_not_exists, scx.catalog.resolve_item(&partial_name)) {
3277 return Err(PlanError::ItemAlreadyExists {
3278 name: full_name.to_string(),
3279 item_type: item.item_type(),
3280 });
3281 }
3282
3283 plan_sink(scx, stmt)
3284}
3285
3286fn plan_sink(
3291 scx: &StatementContext,
3292 mut stmt: CreateSinkStatement<Aug>,
3293) -> Result<Plan, PlanError> {
3294 let CreateSinkStatement {
3295 name,
3296 in_cluster: _,
3297 from,
3298 connection,
3299 format,
3300 envelope,
3301 mode,
3302 if_not_exists,
3303 with_options,
3304 } = stmt.clone();
3305
3306 let Some(name) = name else {
3307 return Err(PlanError::MissingName(CatalogItemType::Sink));
3308 };
3309 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name)?)?;
3310
3311 let envelope = match (&connection, envelope, mode) {
3312 (CreateSinkConnection::Kafka { .. }, Some(ast::SinkEnvelope::Upsert), None) => {
3314 SinkEnvelope::Upsert
3315 }
3316 (CreateSinkConnection::Kafka { .. }, Some(ast::SinkEnvelope::Debezium), None) => {
3317 SinkEnvelope::Debezium
3318 }
3319 (CreateSinkConnection::Kafka { .. }, None, None) => {
3320 sql_bail!("ENVELOPE clause is required")
3321 }
3322 (CreateSinkConnection::Kafka { .. }, _, Some(_)) => {
3323 sql_bail!("MODE is not supported for Kafka sinks, use ENVELOPE instead")
3324 }
3325 (CreateSinkConnection::Iceberg { .. }, None, Some(ast::IcebergSinkMode::Upsert)) => {
3327 SinkEnvelope::Upsert
3328 }
3329 (CreateSinkConnection::Iceberg { .. }, None, Some(ast::IcebergSinkMode::Append)) => {
3330 SinkEnvelope::Append
3331 }
3332 (CreateSinkConnection::Iceberg { .. }, None, None) => {
3333 sql_bail!("MODE clause is required")
3334 }
3335 (CreateSinkConnection::Iceberg { .. }, Some(_), _) => {
3336 sql_bail!("ENVELOPE is not supported for Iceberg sinks, use MODE instead")
3337 }
3338 };
3339
3340 let from_name = &from;
3341 let from = scx.get_item_by_resolved_name(&from)?;
3342
3343 {
3344 use CatalogItemType::*;
3345 match from.item_type() {
3346 Table | Source | MaterializedView => {
3347 if from.replacement_target().is_some() {
3348 let name = scx.catalog.minimal_qualification(from.name());
3349 return Err(PlanError::InvalidSinkFrom {
3350 name: name.to_string(),
3351 item_type: format!("replacement {}", from.item_type()),
3352 });
3353 }
3354 }
3355 Sink | MetricSink | View | Index | Type | Func | Secret | Connection => {
3356 let name = scx.catalog.minimal_qualification(from.name());
3357 return Err(PlanError::InvalidSinkFrom {
3358 name: name.to_string(),
3359 item_type: from.item_type().to_string(),
3360 });
3361 }
3362 }
3363 }
3364
3365 if from.id().is_system() {
3366 bail_unsupported!("creating a sink directly on a catalog object");
3367 }
3368
3369 let desc = from
3370 .relation_desc()
3371 .ok_or_else(|| sql_err!("item does not have a relation description"))?;
3372 let key_indices = match &connection {
3373 CreateSinkConnection::Kafka { key: Some(key), .. }
3374 | CreateSinkConnection::Iceberg { key: Some(key), .. } => {
3375 let key_columns = key
3376 .key_columns
3377 .clone()
3378 .into_iter()
3379 .map(normalize::column_name)
3380 .collect::<Vec<_>>();
3381 let mut uniq = BTreeSet::new();
3382 for col in key_columns.iter() {
3383 if !uniq.insert(col) {
3384 sql_bail!("duplicate column referenced in KEY: {}", col);
3385 }
3386 }
3387 let indices = key_columns
3388 .iter()
3389 .map(|col| {
3390 let name_idx =
3391 desc.get_by_name(col)
3392 .map(|(idx, _type)| idx)
3393 .ok_or_else(|| {
3394 sql_err!("column referenced in KEY does not exist: {}", col)
3395 })?;
3396 if desc.get_unambiguous_name(name_idx).is_none() {
3397 sql_bail!("column referenced in KEY is ambiguous: {}", col);
3398 }
3399 Ok(name_idx)
3400 })
3401 .collect::<Result<Vec<_>, _>>()?;
3402
3403 if matches!(&connection, CreateSinkConnection::Iceberg { .. }) {
3406 let cols: Vec<_> = desc.iter().collect();
3407 for &idx in &indices {
3408 let (col_name, col_type) = cols[idx];
3409 let scalar = &col_type.scalar_type;
3410 let is_valid = matches!(
3411 scalar,
3412 SqlScalarType::Bool
3414 | SqlScalarType::Int16
3415 | SqlScalarType::Int32
3416 | SqlScalarType::Int64
3417 | SqlScalarType::UInt16
3418 | SqlScalarType::UInt32
3419 | SqlScalarType::UInt64
3420 | SqlScalarType::Numeric { .. }
3422 | SqlScalarType::Date
3424 | SqlScalarType::Time
3425 | SqlScalarType::Timestamp { .. }
3426 | SqlScalarType::TimestampTz { .. }
3427 | SqlScalarType::Interval
3428 | SqlScalarType::MzTimestamp
3429 | SqlScalarType::String
3431 | SqlScalarType::Char { .. }
3432 | SqlScalarType::VarChar { .. }
3433 | SqlScalarType::PgLegacyChar
3434 | SqlScalarType::PgLegacyName
3435 | SqlScalarType::Bytes
3436 | SqlScalarType::Jsonb
3437 | SqlScalarType::Uuid
3439 | SqlScalarType::Oid
3440 | SqlScalarType::RegProc
3441 | SqlScalarType::RegType
3442 | SqlScalarType::RegClass
3443 | SqlScalarType::MzAclItem
3444 | SqlScalarType::AclItem
3445 | SqlScalarType::Int2Vector
3446 );
3447 if !is_valid {
3448 return Err(PlanError::IcebergSinkUnsupportedKeyType {
3449 column: col_name.to_string(),
3450 column_type: format!("{:?}", scalar),
3451 });
3452 }
3453 }
3454 }
3455
3456 let is_valid_key = desc
3457 .typ()
3458 .keys
3459 .iter()
3460 .any(|key_columns| key_columns.iter().all(|column| indices.contains(column)));
3461
3462 if !is_valid_key && envelope == SinkEnvelope::Upsert {
3463 if key.not_enforced || scx.pcx.is_none() {
3468 scx.catalog
3469 .add_notice(PlanNotice::UpsertSinkKeyNotEnforced {
3470 key: key_columns.clone(),
3471 name: name.item.clone(),
3472 })
3473 } else {
3474 return Err(PlanError::UpsertSinkWithInvalidKey {
3475 name: from_name.full_name_str(),
3476 desired_key: key_columns.iter().map(|c| c.to_string()).collect(),
3477 valid_keys: desc
3478 .typ()
3479 .keys
3480 .iter()
3481 .map(|key| {
3482 key.iter()
3483 .map(|col| desc.get_name(*col).as_str().into())
3484 .collect()
3485 })
3486 .collect(),
3487 });
3488 }
3489 }
3490 Some(indices)
3491 }
3492 CreateSinkConnection::Kafka { key: None, .. }
3493 | CreateSinkConnection::Iceberg { key: None, .. } => None,
3494 };
3495
3496 if key_indices.is_some() && envelope == SinkEnvelope::Append {
3497 sql_bail!("KEY is not supported for MODE APPEND Iceberg sinks");
3498 }
3499
3500 if envelope == SinkEnvelope::Append {
3502 if let CreateSinkConnection::Iceberg { .. } = &connection {
3503 use mz_storage_types::sinks::{
3504 ICEBERG_APPEND_DIFF_COLUMN, ICEBERG_APPEND_TIMESTAMP_COLUMN,
3505 };
3506 for (col_name, _) in desc.iter() {
3507 if col_name.as_str() == ICEBERG_APPEND_DIFF_COLUMN
3508 || col_name.as_str() == ICEBERG_APPEND_TIMESTAMP_COLUMN
3509 {
3510 sql_bail!(
3511 "column {} conflicts with the system column that MODE APPEND \
3512 adds to the Iceberg table",
3513 col_name.quoted()
3514 );
3515 }
3516 }
3517 }
3518 }
3519
3520 let headers_index = match &connection {
3521 CreateSinkConnection::Kafka {
3522 headers: Some(headers),
3523 ..
3524 } => {
3525 scx.require_feature_flag(&ENABLE_KAFKA_SINK_HEADERS)?;
3526
3527 match envelope {
3528 SinkEnvelope::Upsert | SinkEnvelope::Append => (),
3529 SinkEnvelope::Debezium => {
3530 sql_bail!("HEADERS option is not supported with ENVELOPE DEBEZIUM")
3531 }
3532 };
3533
3534 let headers = normalize::column_name(headers.clone());
3535 let (idx, ty) = desc
3536 .get_by_name(&headers)
3537 .ok_or_else(|| sql_err!("HEADERS column ({}) is unknown", headers))?;
3538
3539 if desc.get_unambiguous_name(idx).is_none() {
3540 sql_bail!("HEADERS column ({}) is ambiguous", headers);
3541 }
3542
3543 match &ty.scalar_type {
3544 SqlScalarType::Map { value_type, .. }
3545 if matches!(&**value_type, SqlScalarType::String | SqlScalarType::Bytes) => {}
3546 _ => sql_bail!(
3547 "HEADERS column must have type map[text => text] or map[text => bytea]"
3548 ),
3549 }
3550
3551 Some(idx)
3552 }
3553 _ => None,
3554 };
3555
3556 let relation_key_indices = desc.typ().keys.get(0).cloned();
3558
3559 let key_desc_and_indices = key_indices.map(|key_indices| {
3560 let cols = desc
3561 .iter()
3562 .map(|(name, ty)| (name.clone(), ty.clone()))
3563 .collect::<Vec<_>>();
3564 let (names, types): (Vec<_>, Vec<_>) =
3565 key_indices.iter().map(|&idx| cols[idx].clone()).unzip();
3566 let typ = SqlRelationType::new(types);
3567 (RelationDesc::new(typ, names), key_indices)
3568 });
3569
3570 if key_desc_and_indices.is_none() && envelope == SinkEnvelope::Upsert {
3571 return Err(PlanError::UpsertSinkWithoutKey);
3572 }
3573
3574 let CreateSinkOptionExtracted {
3575 snapshot,
3576 version,
3577 partition_strategy: _,
3578 seen: _,
3579 commit_interval,
3580 } = with_options.try_into()?;
3581
3582 let connection_builder = match connection {
3583 CreateSinkConnection::Kafka {
3584 connection,
3585 options,
3586 ..
3587 } => kafka_sink_builder(
3588 scx,
3589 connection,
3590 options,
3591 format,
3592 relation_key_indices,
3593 key_desc_and_indices,
3594 headers_index,
3595 desc.into_owned(),
3596 envelope,
3597 from.id(),
3598 commit_interval,
3599 )?,
3600 CreateSinkConnection::Iceberg {
3601 catalog_connection,
3602 aws_connection,
3603 options,
3604 ..
3605 } => iceberg_sink_builder(
3606 scx,
3607 catalog_connection,
3608 aws_connection,
3609 options,
3610 relation_key_indices,
3611 key_desc_and_indices,
3612 commit_interval,
3613 &desc,
3614 )?,
3615 };
3616
3617 let with_snapshot = snapshot.unwrap_or(true);
3619 let version = version.unwrap_or(0);
3621
3622 let in_cluster = source_sink_cluster_config(scx, &mut stmt.in_cluster)?;
3626 let create_sql = normalize::create_statement(scx, Statement::CreateSink(stmt))?;
3627
3628 Ok(Plan::CreateSink(CreateSinkPlan {
3629 name,
3630 sink: Sink {
3631 create_sql,
3632 from: from.global_id(),
3633 connection: connection_builder,
3634 envelope,
3635 version,
3636 commit_interval,
3637 },
3638 with_snapshot,
3639 if_not_exists,
3640 in_cluster: in_cluster.id(),
3641 }))
3642}
3643
3644fn key_constraint_err(desc: &RelationDesc, user_keys: &[ColumnName]) -> PlanError {
3645 let user_keys = user_keys.iter().map(|column| column.as_str()).join(", ");
3646
3647 let existing_keys = desc
3648 .typ()
3649 .keys
3650 .iter()
3651 .map(|key_columns| {
3652 key_columns
3653 .iter()
3654 .map(|col| desc.get_name(*col).as_str())
3655 .join(", ")
3656 })
3657 .join(", ");
3658
3659 sql_err!(
3660 "Key constraint ({}) conflicts with existing key ({})",
3661 user_keys,
3662 existing_keys
3663 )
3664}
3665
3666#[derive(Debug, Default, PartialEq, Clone)]
3669pub struct CsrConfigOptionExtracted {
3670 seen: ::std::collections::BTreeSet<CsrConfigOptionName<Aug>>,
3671 pub(crate) avro_key_fullname: Option<String>,
3672 pub(crate) avro_value_fullname: Option<String>,
3673 pub(crate) null_defaults: bool,
3674 pub(crate) value_doc_options: BTreeMap<DocTarget, String>,
3675 pub(crate) key_doc_options: BTreeMap<DocTarget, String>,
3676 pub(crate) key_compatibility_level: Option<mz_ccsr::CompatibilityLevel>,
3677 pub(crate) value_compatibility_level: Option<mz_ccsr::CompatibilityLevel>,
3678}
3679
3680impl std::convert::TryFrom<Vec<CsrConfigOption<Aug>>> for CsrConfigOptionExtracted {
3681 type Error = crate::plan::PlanError;
3682 fn try_from(v: Vec<CsrConfigOption<Aug>>) -> Result<CsrConfigOptionExtracted, Self::Error> {
3683 let mut extracted = CsrConfigOptionExtracted::default();
3684 let mut common_doc_comments = BTreeMap::new();
3685 for option in v {
3686 if !extracted.seen.insert(option.name.clone()) {
3687 return Err(PlanError::Unstructured({
3688 format!("{} specified more than once", option.name)
3689 }));
3690 }
3691 let option_name = option.name.clone();
3692 let option_name_str = option_name.to_ast_string_simple();
3693 let better_error = |e: PlanError| PlanError::InvalidOptionValue {
3694 option_name: option_name.to_ast_string_simple(),
3695 err: e.into(),
3696 };
3697 let to_compatibility_level = |val: Option<WithOptionValue<Aug>>| {
3698 val.map(|s| match s {
3699 WithOptionValue::Value(Value::String(s)) => {
3700 mz_ccsr::CompatibilityLevel::try_from(s.to_uppercase().as_str())
3701 }
3702 _ => Err("must be a string".to_string()),
3703 })
3704 .transpose()
3705 .map_err(PlanError::Unstructured)
3706 .map_err(better_error)
3707 };
3708 match option.name {
3709 CsrConfigOptionName::AvroKeyFullname => {
3710 extracted.avro_key_fullname =
3711 <Option<String>>::try_from_value(option.value).map_err(better_error)?;
3712 }
3713 CsrConfigOptionName::AvroValueFullname => {
3714 extracted.avro_value_fullname =
3715 <Option<String>>::try_from_value(option.value).map_err(better_error)?;
3716 }
3717 CsrConfigOptionName::NullDefaults => {
3718 extracted.null_defaults =
3719 <bool>::try_from_value(option.value).map_err(better_error)?;
3720 }
3721 CsrConfigOptionName::AvroDocOn(doc_on) => {
3722 let value = String::try_from_value(option.value.ok_or_else(|| {
3723 PlanError::InvalidOptionValue {
3724 option_name: option_name_str,
3725 err: Box::new(PlanError::Unstructured("cannot be empty".to_string())),
3726 }
3727 })?)
3728 .map_err(better_error)?;
3729 let key = match doc_on.identifier {
3730 DocOnIdentifier::Column(ast::ColumnName {
3731 relation: ResolvedItemName::Item { id, .. },
3732 column: ResolvedColumnReference::Column { name, index: _ },
3733 }) => DocTarget::Field {
3734 object_id: id,
3735 column_name: name,
3736 },
3737 DocOnIdentifier::Type(ResolvedItemName::Item { id, .. }) => {
3738 DocTarget::Type(id)
3739 }
3740 _ => sql_bail!("invalid DOC ON identifier"),
3741 };
3742
3743 match doc_on.for_schema {
3744 DocOnSchema::KeyOnly => {
3745 extracted.key_doc_options.insert(key, value);
3746 }
3747 DocOnSchema::ValueOnly => {
3748 extracted.value_doc_options.insert(key, value);
3749 }
3750 DocOnSchema::All => {
3751 common_doc_comments.insert(key, value);
3752 }
3753 }
3754 }
3755 CsrConfigOptionName::KeyCompatibilityLevel => {
3756 extracted.key_compatibility_level = to_compatibility_level(option.value)?;
3757 }
3758 CsrConfigOptionName::ValueCompatibilityLevel => {
3759 extracted.value_compatibility_level = to_compatibility_level(option.value)?;
3760 }
3761 }
3762 }
3763
3764 for (key, value) in common_doc_comments {
3765 if !extracted.key_doc_options.contains_key(&key) {
3766 extracted.key_doc_options.insert(key.clone(), value.clone());
3767 }
3768 if !extracted.value_doc_options.contains_key(&key) {
3769 extracted.value_doc_options.insert(key, value);
3770 }
3771 }
3772 Ok(extracted)
3773 }
3774}
3775
3776fn iceberg_sink_builder(
3777 scx: &StatementContext,
3778 catalog_connection: ResolvedItemName,
3779 storage_connection: Option<ResolvedItemName>,
3780 options: Vec<IcebergSinkConfigOption<Aug>>,
3781 relation_key_indices: Option<Vec<usize>>,
3782 key_desc_and_indices: Option<(RelationDesc, Vec<usize>)>,
3783 commit_interval: Option<Duration>,
3784 desc: &RelationDesc,
3785) -> Result<StorageSinkConnection<ReferencedConnection>, PlanError> {
3786 ArrowBuilder::validate_desc_for_parquet(desc, iceberg_type_overrides)
3790 .map_err(|e| sql_err!("{}", e))?;
3791
3792 let catalog_connection_item = scx.get_item_by_resolved_name(&catalog_connection)?;
3793 let catalog_connection_id = catalog_connection_item.id();
3794 if !matches!(
3795 catalog_connection_item.connection()?,
3796 Connection::IcebergCatalog(_)
3797 ) {
3798 sql_bail!(
3799 "{} is not an iceberg catalog connection",
3800 scx.catalog
3801 .resolve_full_name(catalog_connection_item.name())
3802 .to_string()
3803 .quoted()
3804 );
3805 };
3806
3807 let storage_connection_item = storage_connection
3808 .map(|c| scx.get_item_by_resolved_name(&c))
3809 .transpose()?;
3810 let storage_connection_id = storage_connection_item.as_ref().map(|c| c.id());
3811 if let Some(c) = &storage_connection_item
3812 && !matches!(c.connection()?, Connection::Aws(_))
3813 {
3814 sql_bail!(
3815 "{} is not an AWS connection",
3816 scx.catalog.resolve_full_name(c.name()).to_string().quoted()
3817 );
3818 }
3819
3820 let IcebergSinkConfigOptionExtracted {
3821 table,
3822 namespace,
3823 seen: _,
3824 }: IcebergSinkConfigOptionExtracted = options.try_into()?;
3825
3826 let Some(table) = table else {
3827 sql_bail!("Iceberg sink must specify TABLE");
3828 };
3829 let Some(namespace) = namespace else {
3830 sql_bail!("Iceberg sink must specify NAMESPACE");
3831 };
3832 match commit_interval {
3833 None => sql_bail!("Iceberg sink must specify COMMIT INTERVAL"),
3834 Some(interval) if interval < Duration::from_secs(1) => {
3840 sql_bail!("COMMIT INTERVAL must be at least 1 second")
3841 }
3842 Some(_) => {}
3843 }
3844
3845 Ok(StorageSinkConnection::Iceberg(IcebergSinkConnection {
3846 catalog_connection_id,
3847 catalog_connection: catalog_connection_id,
3848 storage_connection_id,
3849 storage_connection: storage_connection_id,
3850 table,
3851 namespace,
3852 relation_key_indices,
3853 key_desc_and_indices,
3854 }))
3855}
3856
3857fn kafka_sink_builder(
3858 scx: &StatementContext,
3859 connection: ResolvedItemName,
3860 options: Vec<KafkaSinkConfigOption<Aug>>,
3861 format: Option<FormatSpecifier<Aug>>,
3862 relation_key_indices: Option<Vec<usize>>,
3863 key_desc_and_indices: Option<(RelationDesc, Vec<usize>)>,
3864 headers_index: Option<usize>,
3865 value_desc: RelationDesc,
3866 envelope: SinkEnvelope,
3867 sink_from: CatalogItemId,
3868 commit_interval: Option<Duration>,
3869) -> Result<StorageSinkConnection<ReferencedConnection>, PlanError> {
3870 let connection_item = scx.get_item_by_resolved_name(&connection)?;
3872 let connection_id = connection_item.id();
3873 match connection_item.connection()? {
3874 Connection::Kafka(_) => (),
3875 _ => sql_bail!(
3876 "{} is not a kafka connection",
3877 scx.catalog.resolve_full_name(connection_item.name())
3878 ),
3879 };
3880
3881 if commit_interval.is_some() {
3882 sql_bail!("COMMIT INTERVAL option is not supported with KAFKA sinks");
3883 }
3884
3885 let KafkaSinkConfigOptionExtracted {
3886 topic,
3887 compression_type,
3888 partition_by,
3889 progress_group_id_prefix,
3890 transactional_id_prefix,
3891 legacy_ids,
3892 topic_config,
3893 topic_metadata_refresh_interval,
3894 topic_partition_count,
3895 topic_replication_factor,
3896 seen: _,
3897 }: KafkaSinkConfigOptionExtracted = options.try_into()?;
3898
3899 let transactional_id = match (transactional_id_prefix, legacy_ids) {
3900 (Some(_), Some(true)) => {
3901 sql_bail!("LEGACY IDS cannot be used at the same time as TRANSACTIONAL ID PREFIX")
3902 }
3903 (None, Some(true)) => KafkaIdStyle::Legacy,
3904 (prefix, _) => KafkaIdStyle::Prefix(prefix),
3905 };
3906
3907 let progress_group_id = match (progress_group_id_prefix, legacy_ids) {
3908 (Some(_), Some(true)) => {
3909 sql_bail!("LEGACY IDS cannot be used at the same time as PROGRESS GROUP ID PREFIX")
3910 }
3911 (None, Some(true)) => KafkaIdStyle::Legacy,
3912 (prefix, _) => KafkaIdStyle::Prefix(prefix),
3913 };
3914
3915 let topic_name = topic.ok_or_else(|| sql_err!("KAFKA CONNECTION must specify TOPIC"))?;
3916
3917 if topic_metadata_refresh_interval > MAX_KAFKA_TOPIC_METADATA_REFRESH_INTERVAL {
3918 sql_bail!("TOPIC METADATA REFRESH INTERVAL cannot be greater than 1 hour");
3921 } else if topic_metadata_refresh_interval < MIN_KAFKA_TOPIC_METADATA_REFRESH_INTERVAL {
3922 sql_bail!("TOPIC METADATA REFRESH INTERVAL must be at least 1 second");
3925 }
3926
3927 let assert_positive = |val: Option<i32>, name: &str| {
3928 if let Some(val) = val {
3929 if val <= 0 {
3930 sql_bail!("{} must be a positive integer", name);
3931 }
3932 }
3933 val.map(NonNeg::try_from)
3934 .transpose()
3935 .map_err(|_| PlanError::Unstructured(format!("{} must be a positive integer", name)))
3936 };
3937 let topic_partition_count = assert_positive(topic_partition_count, "TOPIC PARTITION COUNT")?;
3938 let topic_replication_factor =
3939 assert_positive(topic_replication_factor, "TOPIC REPLICATION FACTOR")?;
3940
3941 let gen_avro_schema_options = |conn| {
3944 let CsrConnectionAvro {
3945 connection:
3946 CsrConnection {
3947 connection,
3948 options,
3949 },
3950 seed,
3951 key_strategy,
3952 value_strategy,
3953 } = conn;
3954 if seed.is_some() {
3955 sql_bail!("SEED option does not make sense with sinks");
3956 }
3957 if key_strategy.is_some() {
3958 sql_bail!("KEY STRATEGY option does not make sense with sinks");
3959 }
3960 if value_strategy.is_some() {
3961 sql_bail!("VALUE STRATEGY option does not make sense with sinks");
3962 }
3963
3964 let item = scx.get_item_by_resolved_name(&connection)?;
3965 let csr_connection = match item.connection()? {
3966 Connection::Csr(_) => item.id(),
3967 _ => {
3968 sql_bail!(
3969 "{} is not a schema registry connection",
3970 scx.catalog
3971 .resolve_full_name(item.name())
3972 .to_string()
3973 .quoted()
3974 )
3975 }
3976 };
3977 let extracted_options: CsrConfigOptionExtracted = options.try_into()?;
3978
3979 if key_desc_and_indices.is_none() && extracted_options.avro_key_fullname.is_some() {
3980 sql_bail!("Cannot specify AVRO KEY FULLNAME without a corresponding KEY field");
3981 }
3982
3983 if key_desc_and_indices.is_some()
3984 && (extracted_options.avro_key_fullname.is_some()
3985 ^ extracted_options.avro_value_fullname.is_some())
3986 {
3987 sql_bail!(
3988 "Must specify both AVRO KEY FULLNAME and AVRO VALUE FULLNAME when specifying generated schema names"
3989 );
3990 }
3991
3992 Ok((csr_connection, extracted_options))
3993 };
3994
3995 let map_format = |format: Format<Aug>, desc: &RelationDesc, is_key: bool| match format {
3996 Format::Json { array: false } => Ok::<_, PlanError>(KafkaSinkFormatType::Json),
3997 Format::Bytes if desc.arity() == 1 => {
3998 let col_type = &desc.typ().column_types[0].scalar_type;
3999 if !mz_pgrepr::Value::can_encode_binary(col_type) {
4000 bail_unsupported!(format!(
4001 "BYTES format with non-encodable type: {:?}",
4002 col_type
4003 ));
4004 }
4005
4006 Ok(KafkaSinkFormatType::Bytes)
4007 }
4008 Format::Text if desc.arity() == 1 => Ok(KafkaSinkFormatType::Text),
4009 Format::Bytes | Format::Text => {
4010 bail_unsupported!("BYTES or TEXT format with multiple columns")
4011 }
4012 Format::Json { array: true } => bail_unsupported!("JSON ARRAY format in sinks"),
4013 Format::Avro(AvroSchema::Csr { csr_connection }) => {
4014 let (csr_connection, options) = gen_avro_schema_options(csr_connection)?;
4015 let schema = if is_key {
4016 AvroSchemaGenerator::new(
4017 desc.clone(),
4018 false,
4019 options.key_doc_options,
4020 options.avro_key_fullname.as_deref().unwrap_or("row"),
4021 options.null_defaults,
4022 Some(sink_from),
4023 false,
4024 )?
4025 .schema()
4026 .to_string()
4027 } else {
4028 AvroSchemaGenerator::new(
4029 desc.clone(),
4030 matches!(envelope, SinkEnvelope::Debezium),
4031 options.value_doc_options,
4032 options.avro_value_fullname.as_deref().unwrap_or("envelope"),
4033 options.null_defaults,
4034 Some(sink_from),
4035 true,
4036 )?
4037 .schema()
4038 .to_string()
4039 };
4040 Ok(KafkaSinkFormatType::Avro {
4041 schema,
4042 compatibility_level: if is_key {
4043 options.key_compatibility_level
4044 } else {
4045 options.value_compatibility_level
4046 },
4047 schema_name: None,
4049 wire_format: WireFormat::Confluent {
4050 registry: Some(csr_connection),
4051 },
4052 })
4053 }
4054 Format::Avro(AvroSchema::Glue {
4055 connection,
4056 with_options,
4057 seed,
4058 }) => {
4059 if seed.is_some() {
4060 sql_bail!("SEED option does not make sense with sinks");
4061 }
4062
4063 let extracted: GlueAvroOptionExtracted = with_options.try_into()?;
4064 let GlueAvroOptionExtracted {
4065 schema_name,
4066 key_schema_name,
4067 value_schema_name,
4068 key_compatibility_level,
4069 value_compatibility_level,
4070 seen: _,
4071 } = extracted;
4072
4073 if schema_name.is_some() {
4078 sql_bail!(
4079 "SCHEMA NAME is not supported for AWS Glue Schema Registry sinks, \
4080 use KEY SCHEMA NAME and VALUE SCHEMA NAME instead"
4081 );
4082 }
4083
4084 if key_desc_and_indices.is_none()
4090 && (key_schema_name.is_some() || key_compatibility_level.is_some())
4091 {
4092 sql_bail!(
4093 "KEY SCHEMA NAME and KEY COMPATIBILITY LEVEL require a corresponding KEY field"
4094 );
4095 }
4096
4097 let item = scx.get_item_by_resolved_name(&connection)?;
4098 let glue_connection = match item.connection()? {
4099 Connection::GlueSchemaRegistry(_) => item.id(),
4100 _ => {
4101 sql_bail!(
4102 "{} is not an AWS Glue Schema Registry connection",
4103 scx.catalog
4104 .resolve_full_name(item.name())
4105 .to_string()
4106 .quoted()
4107 )
4108 }
4109 };
4110
4111 let compatibility_level = {
4115 let raw = if is_key {
4116 key_compatibility_level
4117 } else {
4118 value_compatibility_level
4119 };
4120 raw.map(|s| {
4121 mz_ccsr::CompatibilityLevel::try_from(s.to_uppercase().as_str())
4122 .map_err(PlanError::Unstructured)
4123 })
4124 .transpose()?
4125 };
4126
4127 let schema_name = if is_key {
4131 key_schema_name
4132 } else {
4133 value_schema_name
4134 };
4135
4136 let schema = if is_key {
4139 AvroSchemaGenerator::new(
4140 desc.clone(),
4141 false,
4142 Default::default(),
4143 "row",
4144 false,
4145 Some(sink_from),
4146 false,
4147 )?
4148 .schema()
4149 .to_string()
4150 } else {
4151 AvroSchemaGenerator::new(
4152 desc.clone(),
4153 matches!(envelope, SinkEnvelope::Debezium),
4154 Default::default(),
4155 "envelope",
4156 false,
4157 Some(sink_from),
4158 true,
4159 )?
4160 .schema()
4161 .to_string()
4162 };
4163 Ok(KafkaSinkFormatType::Avro {
4164 schema,
4165 compatibility_level,
4166 schema_name,
4167 wire_format: WireFormat::Glue {
4168 registry: Some(glue_connection),
4169 },
4170 })
4171 }
4172 format => bail_unsupported!(format!("sink format {:?}", format)),
4173 };
4174
4175 let partition_by = match &partition_by {
4176 Some(partition_by) => {
4177 let mut scope = Scope::from_source(None, value_desc.iter_names());
4178
4179 match envelope {
4180 SinkEnvelope::Upsert | SinkEnvelope::Append => (),
4181 SinkEnvelope::Debezium => {
4182 let key_indices: HashSet<_> = key_desc_and_indices
4183 .as_ref()
4184 .map(|(_desc, indices)| indices.as_slice())
4185 .unwrap_or_default()
4186 .into_iter()
4187 .collect();
4188 for (i, item) in scope.items.iter_mut().enumerate() {
4189 if !key_indices.contains(&i) {
4190 item.error_if_referenced = Some(|_table, column| {
4191 PlanError::InvalidPartitionByEnvelopeDebezium {
4192 column_name: column.to_string(),
4193 }
4194 });
4195 }
4196 }
4197 }
4198 };
4199
4200 let ecx = &ExprContext {
4201 qcx: &QueryContext::root(scx, QueryLifetime::OneShot),
4202 name: "PARTITION BY",
4203 scope: &scope,
4204 relation_type: value_desc.typ(),
4205 allow_aggregates: false,
4206 allow_subqueries: false,
4207 allow_parameters: false,
4208 allow_windows: false,
4209 };
4210 let expr = plan_expr(ecx, partition_by)?.cast_to(
4211 ecx,
4212 CastContext::Assignment,
4213 &SqlScalarType::UInt64,
4214 )?;
4215 let expr = expr.lower_uncorrelated(scx.catalog.system_vars())?;
4216
4217 Some(expr)
4218 }
4219 _ => None,
4220 };
4221
4222 let format = match format {
4224 Some(FormatSpecifier::KeyValue { key, value }) => {
4225 let key_format = match key_desc_and_indices.as_ref() {
4226 Some((desc, _indices)) => Some(map_format(key, desc, true)?),
4227 None => None,
4228 };
4229 KafkaSinkFormat {
4230 value_format: map_format(value, &value_desc, false)?,
4231 key_format,
4232 }
4233 }
4234 Some(FormatSpecifier::Bare(format)) => {
4235 let key_format = match key_desc_and_indices.as_ref() {
4236 Some((desc, _indices)) => Some(map_format(format.clone(), desc, true)?),
4237 None => None,
4238 };
4239 KafkaSinkFormat {
4240 value_format: map_format(format, &value_desc, false)?,
4241 key_format,
4242 }
4243 }
4244 None => bail_unsupported!("sink without format"),
4245 };
4246
4247 Ok(StorageSinkConnection::Kafka(KafkaSinkConnection {
4248 connection_id,
4249 connection: connection_id,
4250 format,
4251 topic: topic_name,
4252 relation_key_indices,
4253 key_desc_and_indices,
4254 headers_index,
4255 value_desc,
4256 partition_by,
4257 compression_type,
4258 progress_group_id,
4259 transactional_id,
4260 topic_options: KafkaTopicOptions {
4261 partition_count: topic_partition_count,
4262 replication_factor: topic_replication_factor,
4263 topic_config: topic_config.unwrap_or_default(),
4264 },
4265 topic_metadata_refresh_interval,
4266 }))
4267}
4268
4269pub fn describe_create_metric_sink(
4270 _: &StatementContext,
4271 _: CreateMetricSinkStatement<Aug>,
4272) -> Result<StatementDesc, PlanError> {
4273 Ok(StatementDesc::new(None))
4274}
4275
4276const METRIC_SINK_SOURCE_COLUMNS: &[(&str, fn(&SqlScalarType) -> bool)] = &[
4280 ("metric_name", |t| matches!(t, SqlScalarType::String)),
4281 ("metric_type", |t| matches!(t, SqlScalarType::String)),
4282 (
4283 "labels",
4284 |t| matches!(t, SqlScalarType::Map { value_type, .. } if matches!(**value_type, SqlScalarType::String)),
4285 ),
4286 ("value", |t| matches!(t, SqlScalarType::Float64)),
4287 ("help", |t| matches!(t, SqlScalarType::String)),
4288];
4289
4290generate_extracted_config!(CreateMetricSinkOption, (Prefix, String));
4291
4292const METRIC_SINK_PREFIX_MARKER: &str = "mz_metric_sink_";
4299
4300pub const METRIC_SINK_CURATED_PREFIX_MARKER: &str = "mz_metric_sink_curated_";
4303
4304pub fn validate_metric_sink_prefix(prefix: &str) -> Result<(), PlanError> {
4309 if prefix.is_empty() {
4310 return Err(sql_err!("metric sink prefix must not be empty"));
4311 }
4312 let mut chars = prefix.chars();
4313 let valid = match chars.next() {
4314 Some(c) if c.is_ascii_alphabetic() || c == '_' || c == ':' => {
4315 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':')
4316 }
4317 _ => false,
4318 };
4319 if !valid {
4320 return Err(sql_err!(
4321 "metric sink prefix {:?} is not a valid start of a Prometheus metric name",
4322 prefix
4323 ));
4324 }
4325 if !prefix.starts_with(METRIC_SINK_PREFIX_MARKER) {
4326 return Err(sql_err!(
4327 "metric sink prefix {:?} must start with {:?}",
4328 prefix,
4329 METRIC_SINK_PREFIX_MARKER
4330 ));
4331 }
4332 Ok(())
4333}
4334
4335pub fn validate_user_metric_sink_prefix(prefix: &str) -> Result<(), PlanError> {
4344 validate_metric_sink_prefix(prefix)?;
4345 if prefix.starts_with(METRIC_SINK_CURATED_PREFIX_MARKER)
4346 || METRIC_SINK_CURATED_PREFIX_MARKER.starts_with(prefix)
4347 {
4348 return Err(sql_err!(
4349 "metric sink prefix {:?} overlaps {:?}, which is reserved for the built-in metric sinks",
4350 prefix,
4351 METRIC_SINK_CURATED_PREFIX_MARKER
4352 ));
4353 }
4354 Ok(())
4355}
4356
4357pub fn validate_metric_sink_desc(desc: &RelationDesc) -> Result<(), PlanError> {
4363 for (name, type_ok) in METRIC_SINK_SOURCE_COLUMNS {
4364 let col = ColumnName::from(*name);
4365 let (_, column_type) = desc
4366 .get_by_name(&col)
4367 .ok_or_else(|| sql_err!("metric sink source must expose column {:?}", name))?;
4368 if !type_ok(&column_type.scalar_type) {
4369 return Err(sql_err!(
4370 "metric sink source column {:?} is not of the required type",
4371 name
4372 ));
4373 }
4374 }
4375 Ok(())
4376}
4377
4378pub fn plan_create_metric_sink(
4386 scx: &StatementContext,
4387 mut stmt: CreateMetricSinkStatement<Aug>,
4388) -> Result<Plan, PlanError> {
4389 scx.require_feature_flag(&ENABLE_METRIC_SINK)?;
4390
4391 let CreateMetricSinkStatement {
4392 name,
4393 in_cluster,
4394 if_not_exists,
4395 from,
4396 with_options,
4397 } = &mut stmt;
4398
4399 let if_not_exists = *if_not_exists;
4400 let CreateMetricSinkOptionExtracted { prefix, seen: _ } = with_options.clone().try_into()?;
4401 let Some(prefix) = prefix else {
4404 sql_bail!("CREATE METRIC SINK requires a PREFIX option");
4405 };
4406 validate_user_metric_sink_prefix(&prefix)?;
4407 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name.clone())?)?;
4408 let full_name = scx.catalog.resolve_full_name(&name);
4409 let partial_name = PartialItemName::from(full_name.clone());
4410 if let (false, Ok(item)) = (if_not_exists, scx.catalog.resolve_item(&partial_name)) {
4411 return Err(PlanError::ItemAlreadyExists {
4412 name: full_name.to_string(),
4413 item_type: item.item_type(),
4414 });
4415 }
4416
4417 let from_item = scx.get_item_by_resolved_name(from)?;
4418 let desc = from_item.relation_desc().ok_or_else(|| {
4422 sql_err!(
4423 "cannot create metric sink from {} because it is a {}",
4424 scx.catalog.minimal_qualification(from_item.name()),
4425 from_item.item_type(),
4426 )
4427 })?;
4428 validate_metric_sink_desc(&desc)?;
4429
4430 let cluster_id = match in_cluster {
4431 None => scx.resolve_cluster(None)?.id(),
4432 Some(in_cluster) => in_cluster.id,
4433 };
4434 *in_cluster = Some(ResolvedClusterName {
4435 id: cluster_id,
4436 print_name: None,
4437 });
4438 let from_global_id = from_item.global_id();
4439
4440 let create_sql = normalize::create_statement(scx, Statement::CreateMetricSink(stmt))?;
4441
4442 Ok(Plan::CreateMetricSink(CreateMetricSinkPlan {
4443 name,
4444 metric_sink: MetricSink {
4445 create_sql,
4446 from: from_global_id,
4447 cluster_id,
4448 prefix,
4449 },
4450 if_not_exists,
4451 }))
4452}
4453
4454pub fn describe_create_index(
4455 _: &StatementContext,
4456 _: CreateIndexStatement<Aug>,
4457) -> Result<StatementDesc, PlanError> {
4458 Ok(StatementDesc::new(None))
4459}
4460
4461pub fn plan_create_index(
4462 scx: &StatementContext,
4463 mut stmt: CreateIndexStatement<Aug>,
4464) -> Result<Plan, PlanError> {
4465 let CreateIndexStatement {
4466 name,
4467 on_name,
4468 in_cluster,
4469 key_parts,
4470 with_options,
4471 if_not_exists,
4472 } = &mut stmt;
4473 let on = scx.get_item_by_resolved_name(on_name)?;
4474
4475 {
4476 use CatalogItemType::*;
4477 match on.item_type() {
4478 Table | Source | View | MaterializedView => {
4479 if on.replacement_target().is_some() {
4480 sql_bail!(
4481 "index cannot be created on {} because it is a replacement {}",
4482 on_name.full_name_str(),
4483 on.item_type(),
4484 );
4485 }
4486 }
4487 Sink | MetricSink | Index | Type | Func | Secret | Connection => {
4488 sql_bail!(
4489 "index cannot be created on {} because it is a {}",
4490 on_name.full_name_str(),
4491 on.item_type(),
4492 );
4493 }
4494 }
4495 }
4496
4497 let on_desc = on
4498 .relation_desc()
4499 .ok_or_else(|| sql_err!("item does not have a relation description"))?;
4500
4501 let filled_key_parts = match key_parts {
4502 Some(kp) => kp.to_vec(),
4503 None => {
4504 let mut name_counts = BTreeMap::new();
4509 for name in on_desc.iter_names() {
4510 *name_counts.entry(name).or_insert(0usize) += 1;
4511 }
4512 let key = on_desc.typ().default_key();
4513 key.iter()
4514 .map(|i| {
4515 let name = on_desc.get_name(*i);
4516 if name_counts.get(name).copied() == Some(1) {
4517 Expr::Identifier(vec![normalize::column_name_ident(name)])
4518 } else {
4519 Expr::Value(Value::Number((i + 1).to_string()))
4520 }
4521 })
4522 .collect()
4523 }
4524 };
4525 let keys = query::plan_index_exprs(scx, &on_desc, filled_key_parts.clone())?;
4526
4527 let index_name = if let Some(name) = name {
4528 QualifiedItemName {
4529 qualifiers: on.name().qualifiers.clone(),
4530 item: normalize::ident(name.clone()),
4531 }
4532 } else {
4533 let mut idx_name = QualifiedItemName {
4534 qualifiers: on.name().qualifiers.clone(),
4535 item: on.name().item.clone(),
4536 };
4537 if key_parts.is_none() {
4538 idx_name.item += "_primary_idx";
4540 } else {
4541 let index_name_col_suffix = keys
4544 .iter()
4545 .map(|k| match k {
4546 mz_expr::MirScalarExpr::Column(i, name) => {
4547 match (on_desc.get_unambiguous_name(*i), &name.0) {
4548 (Some(col_name), _) => col_name.to_string(),
4549 (None, Some(name)) => name.to_string(),
4550 (None, None) => format!("{}", i + 1),
4551 }
4552 }
4553 _ => "expr".to_string(),
4554 })
4555 .join("_");
4556 write!(idx_name.item, "_{index_name_col_suffix}_idx")
4557 .expect("write on strings cannot fail");
4558 idx_name.item = normalize::ident(Ident::new(&idx_name.item)?)
4559 }
4560
4561 if !*if_not_exists {
4562 scx.catalog.find_available_name(idx_name)
4563 } else {
4564 idx_name
4565 }
4566 };
4567
4568 let full_name = scx.catalog.resolve_full_name(&index_name);
4570 let partial_name = PartialItemName::from(full_name.clone());
4571 if let (Ok(item), false, false) = (
4579 scx.catalog.resolve_item_or_type(&partial_name),
4580 *if_not_exists,
4581 scx.pcx().map_or(false, |pcx| pcx.ignore_if_exists_errors),
4582 ) {
4583 return Err(PlanError::ItemAlreadyExists {
4584 name: full_name.to_string(),
4585 item_type: item.item_type(),
4586 });
4587 }
4588
4589 let options = plan_index_options(scx, with_options.clone())?;
4590 let cluster_id = match in_cluster {
4591 None => scx.resolve_cluster(None)?.id(),
4592 Some(in_cluster) => in_cluster.id,
4593 };
4594
4595 *in_cluster = Some(ResolvedClusterName {
4596 id: cluster_id,
4597 print_name: None,
4598 });
4599
4600 *name = Some(Ident::new(index_name.item.clone())?);
4602 *key_parts = Some(filled_key_parts);
4603 let if_not_exists = *if_not_exists;
4604
4605 let create_sql = normalize::create_statement(scx, Statement::CreateIndex(stmt))?;
4606 let compaction_window = options.iter().find_map(|o| {
4607 #[allow(irrefutable_let_patterns)]
4608 if let crate::plan::IndexOption::RetainHistory(lcw) = o {
4609 Some(lcw.clone())
4610 } else {
4611 None
4612 }
4613 });
4614
4615 Ok(Plan::CreateIndex(CreateIndexPlan {
4616 name: index_name,
4617 index: Index {
4618 create_sql,
4619 on: on.global_id(),
4620 keys,
4621 cluster_id,
4622 compaction_window,
4623 },
4624 if_not_exists,
4625 }))
4626}
4627
4628pub fn describe_create_type(
4629 _: &StatementContext,
4630 _: CreateTypeStatement<Aug>,
4631) -> Result<StatementDesc, PlanError> {
4632 Ok(StatementDesc::new(None))
4633}
4634
4635pub fn plan_create_type(
4636 scx: &StatementContext,
4637 stmt: CreateTypeStatement<Aug>,
4638) -> Result<Plan, PlanError> {
4639 let create_sql = normalize::create_statement(scx, Statement::CreateType(stmt.clone()))?;
4640 let CreateTypeStatement { name, as_type, .. } = stmt;
4641
4642 fn validate_data_type(
4650 scx: &StatementContext,
4651 data_type: ResolvedDataType,
4652 as_type: &str,
4653 key: &str,
4654 budget: &mut TypeResolutionBudget,
4655 ) -> Result<(CatalogItemId, Vec<i64>), PlanError> {
4656 let (id, modifiers) = match data_type {
4657 ResolvedDataType::Named { id, modifiers, .. } => (id, modifiers),
4658 _ => sql_bail!(
4659 "CREATE TYPE ... AS {}option {} can only use named data types, but \
4660 found unnamed data type {}. Use CREATE TYPE to create a named type first",
4661 as_type,
4662 key,
4663 data_type.human_readable_name(),
4664 ),
4665 };
4666
4667 let item = scx.catalog.get_item(&id);
4668 match item.type_details() {
4669 None => sql_bail!(
4670 "{} must be of class type, but received {} which is of class {}",
4671 key,
4672 scx.catalog.resolve_full_name(item.name()),
4673 item.item_type()
4674 ),
4675 Some(CatalogTypeDetails {
4676 typ: CatalogType::Char,
4677 ..
4678 }) => {
4679 bail_unsupported!("embedding char type in a list or map")
4680 }
4681 _ => {
4682 budget.resolve_child(scx.catalog, id, &modifiers)?;
4685
4686 Ok((id, modifiers))
4687 }
4688 }
4689 }
4690
4691 let mut budget = TypeResolutionBudget::for_root(scx.catalog);
4692 let inner = match as_type {
4693 CreateTypeAs::List { options } => {
4694 let CreateTypeListOptionExtracted {
4695 element_type,
4696 seen: _,
4697 } = CreateTypeListOptionExtracted::try_from(options)?;
4698 let element_type =
4699 element_type.ok_or_else(|| sql_err!("ELEMENT TYPE option is required"))?;
4700 let (id, modifiers) =
4701 validate_data_type(scx, element_type, "LIST ", "ELEMENT TYPE", &mut budget)?;
4702 CatalogType::List {
4703 element_reference: id,
4704 element_modifiers: modifiers,
4705 }
4706 }
4707 CreateTypeAs::Map { options } => {
4708 let CreateTypeMapOptionExtracted {
4709 key_type,
4710 value_type,
4711 seen: _,
4712 } = CreateTypeMapOptionExtracted::try_from(options)?;
4713 let key_type = key_type.ok_or_else(|| sql_err!("KEY TYPE option is required"))?;
4714 let value_type = value_type.ok_or_else(|| sql_err!("VALUE TYPE option is required"))?;
4715 let (key_id, key_modifiers) = validate_data_type(
4719 scx,
4720 key_type,
4721 "MAP ",
4722 "KEY TYPE",
4723 &mut TypeResolutionBudget::for_root(scx.catalog),
4724 )?;
4725 let (value_id, value_modifiers) =
4726 validate_data_type(scx, value_type, "MAP ", "VALUE TYPE", &mut budget)?;
4727 CatalogType::Map {
4728 key_reference: key_id,
4729 key_modifiers,
4730 value_reference: value_id,
4731 value_modifiers,
4732 }
4733 }
4734 CreateTypeAs::Record { column_defs } => {
4735 let mut fields = vec![];
4736 for column_def in column_defs {
4737 let data_type = column_def.data_type;
4738 let key = ident(column_def.name.clone());
4739 let (id, modifiers) = validate_data_type(scx, data_type, "", &key, &mut budget)?;
4740 fields.push(CatalogRecordField {
4741 name: ColumnName::from(key.clone()),
4742 type_reference: id,
4743 type_modifiers: modifiers,
4744 });
4745 }
4746 CatalogType::Record { fields }
4747 }
4748 };
4749
4750 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name)?)?;
4751
4752 let full_name = scx.catalog.resolve_full_name(&name);
4754 let partial_name = PartialItemName::from(full_name.clone());
4755 if let Ok(item) = scx.catalog.resolve_item_or_type(&partial_name) {
4758 if item.item_type().conflicts_with_type() {
4759 return Err(PlanError::ItemAlreadyExists {
4760 name: full_name.to_string(),
4761 item_type: item.item_type(),
4762 });
4763 }
4764 }
4765
4766 Ok(Plan::CreateType(CreateTypePlan {
4767 name,
4768 typ: Type { create_sql, inner },
4769 }))
4770}
4771
4772generate_extracted_config!(CreateTypeListOption, (ElementType, ResolvedDataType));
4773
4774generate_extracted_config!(
4775 CreateTypeMapOption,
4776 (KeyType, ResolvedDataType),
4777 (ValueType, ResolvedDataType)
4778);
4779
4780#[derive(Debug)]
4781pub enum PlannedAlterRoleOption {
4782 Attributes(PlannedRoleAttributes),
4783 Variable(PlannedRoleVariable),
4784}
4785
4786#[derive(Debug, Clone)]
4787pub struct PlannedRoleAttributes {
4788 pub inherit: Option<bool>,
4789 pub password: Option<Password>,
4790 pub scram_iterations: Option<NonZeroU32>,
4791 pub nopassword: Option<bool>,
4795 pub superuser: Option<bool>,
4796 pub login: Option<bool>,
4797}
4798
4799fn plan_role_attributes(
4800 options: Vec<RoleAttribute>,
4801 scx: &StatementContext,
4802) -> Result<PlannedRoleAttributes, PlanError> {
4803 let mut planned_attributes = PlannedRoleAttributes {
4804 inherit: None,
4805 password: None,
4806 scram_iterations: None,
4807 superuser: None,
4808 login: None,
4809 nopassword: None,
4810 };
4811
4812 for option in options {
4813 match option {
4814 RoleAttribute::Inherit | RoleAttribute::NoInherit
4815 if planned_attributes.inherit.is_some() =>
4816 {
4817 sql_bail!("conflicting or redundant options");
4818 }
4819 RoleAttribute::CreateCluster | RoleAttribute::NoCreateCluster => {
4820 bail_never_supported!(
4821 "CREATECLUSTER attribute",
4822 "sql/create-role/#details",
4823 "Use system privileges instead."
4824 );
4825 }
4826 RoleAttribute::CreateDB | RoleAttribute::NoCreateDB => {
4827 bail_never_supported!(
4828 "CREATEDB attribute",
4829 "sql/create-role/#details",
4830 "Use system privileges instead."
4831 );
4832 }
4833 RoleAttribute::CreateRole | RoleAttribute::NoCreateRole => {
4834 bail_never_supported!(
4835 "CREATEROLE attribute",
4836 "sql/create-role/#details",
4837 "Use system privileges instead."
4838 );
4839 }
4840 RoleAttribute::Password(_) if planned_attributes.password.is_some() => {
4841 sql_bail!("conflicting or redundant options");
4842 }
4843
4844 RoleAttribute::Inherit => planned_attributes.inherit = Some(true),
4845 RoleAttribute::NoInherit => planned_attributes.inherit = Some(false),
4846 RoleAttribute::Password(password) => {
4847 if let Some(password) = password {
4848 planned_attributes.password = Some(password.into());
4849 planned_attributes.scram_iterations =
4850 Some(scx.catalog.system_vars().scram_iterations())
4851 } else {
4852 planned_attributes.nopassword = Some(true);
4853 }
4854 }
4855 RoleAttribute::SuperUser => {
4856 if planned_attributes.superuser == Some(false) {
4857 sql_bail!("conflicting or redundant options");
4858 }
4859 planned_attributes.superuser = Some(true);
4860 }
4861 RoleAttribute::NoSuperUser => {
4862 if planned_attributes.superuser == Some(true) {
4863 sql_bail!("conflicting or redundant options");
4864 }
4865 planned_attributes.superuser = Some(false);
4866 }
4867 RoleAttribute::Login => {
4868 if planned_attributes.login == Some(false) {
4869 sql_bail!("conflicting or redundant options");
4870 }
4871 planned_attributes.login = Some(true);
4872 }
4873 RoleAttribute::NoLogin => {
4874 if planned_attributes.login == Some(true) {
4875 sql_bail!("conflicting or redundant options");
4876 }
4877 planned_attributes.login = Some(false);
4878 }
4879 }
4880 }
4881 if planned_attributes.inherit == Some(false) {
4882 bail_unsupported!("non inherit roles");
4883 }
4884
4885 Ok(planned_attributes)
4886}
4887
4888#[derive(Debug)]
4889pub enum PlannedRoleVariable {
4890 Set { name: String, value: VariableValue },
4891 Reset { name: String },
4892}
4893
4894impl PlannedRoleVariable {
4895 pub fn name(&self) -> &str {
4896 match self {
4897 PlannedRoleVariable::Set { name, .. } => name,
4898 PlannedRoleVariable::Reset { name } => name,
4899 }
4900 }
4901}
4902
4903fn plan_role_variable(
4904 scx: &StatementContext,
4905 variable: SetRoleVar,
4906) -> Result<PlannedRoleVariable, PlanError> {
4907 let plan = match variable {
4908 SetRoleVar::Set { name, value } => {
4909 let name = name.to_string();
4910 let value = scl::plan_set_variable_to(value)?;
4911 if let VariableValue::Values(values) = &value {
4914 vars::check_transaction_isolation_feature_flag(
4915 &name,
4916 VarInput::SqlSet(values),
4917 scx.catalog.system_vars(),
4918 )?;
4919 }
4920 PlannedRoleVariable::Set { name, value }
4921 }
4922 SetRoleVar::Reset { name } => PlannedRoleVariable::Reset {
4923 name: name.to_string(),
4924 },
4925 };
4926 Ok(plan)
4927}
4928
4929pub fn describe_create_role(
4930 _: &StatementContext,
4931 _: CreateRoleStatement,
4932) -> Result<StatementDesc, PlanError> {
4933 Ok(StatementDesc::new(None))
4934}
4935
4936pub fn plan_create_role(
4937 scx: &StatementContext,
4938 CreateRoleStatement { name, options }: CreateRoleStatement,
4939) -> Result<Plan, PlanError> {
4940 let attributes = plan_role_attributes(options, scx)?;
4941 Ok(Plan::CreateRole(CreateRolePlan {
4942 name: normalize::ident(name),
4943 attributes: attributes.into(),
4944 }))
4945}
4946
4947generate_extracted_config!(
4948 QueryPolicyRuleOption,
4949 (Action, String),
4950 (Metric, String),
4951 (Value, String)
4952);
4953
4954fn plan_query_policy_options(
4955 options: Vec<QueryPolicyOption<Aug>>,
4956) -> Result<(Option<QueryPolicyMode>, Option<Vec<QueryPolicyRule>>), PlanError> {
4957 let mut mode = None;
4958 let mut rules = None;
4959 for option in options {
4960 match option {
4961 QueryPolicyOption::Mode(value) => {
4962 if mode.is_some() {
4963 sql_bail!("MODE specified more than once");
4964 }
4965 mode = Some(match value {
4966 Value::String(value) if value.eq_ignore_ascii_case("warn") => {
4967 QueryPolicyMode::Warn
4968 }
4969 Value::String(value) if value.eq_ignore_ascii_case("enforce") => {
4970 QueryPolicyMode::Enforce
4971 }
4972 _ => sql_bail!("query policy MODE must be 'warn' or 'enforce'"),
4973 });
4974 }
4975 QueryPolicyOption::Rules(definitions) => {
4976 if rules.is_some() {
4977 sql_bail!("RULES specified more than once");
4978 }
4979 let mut names = BTreeSet::new();
4980 let mut planned = Vec::new();
4981 for QueryPolicyRuleDefinition { name, options } in definitions {
4982 let name = normalize::ident(name);
4983 if !names.insert(name.clone()) {
4984 sql_bail!("duplicate query policy rule name {name}");
4985 }
4986 let QueryPolicyRuleOptionExtracted {
4987 action,
4988 metric,
4989 value,
4990 ..
4991 } = options.try_into()?;
4992 let (Some(action), Some(metric), Some(value)) = (action, metric, value) else {
4993 sql_bail!(
4994 "ACTION, METRIC, and VALUE must be specified for each query policy rule"
4995 );
4996 };
4997 if !action.eq_ignore_ascii_case("reject") {
4998 sql_bail!(
4999 "unsupported query policy action: {action}. Only 'reject' is supported"
5000 );
5001 }
5002 if !metric.eq_ignore_ascii_case("query_plan_includes") {
5003 sql_bail!(
5004 "unsupported query policy metric: {metric}. Only 'query_plan_includes' is supported"
5005 );
5006 }
5007 let value = match value.to_ascii_lowercase().as_str() {
5008 "temporary_dataflow" => QueryPlanFeature::TemporaryDataflow,
5009 "storage_read" => QueryPlanFeature::StorageRead,
5010 _ => sql_bail!("unsupported query policy value: {value}"),
5011 };
5012 planned.push(QueryPolicyRule { name, value });
5013 }
5014 rules = Some(planned);
5015 }
5016 }
5017 }
5018 Ok((mode, rules))
5019}
5020
5021pub fn plan_create_query_policy(
5022 scx: &StatementContext,
5023 CreateQueryPolicyStatement { name, options }: CreateQueryPolicyStatement<Aug>,
5024) -> Result<Plan, PlanError> {
5025 scx.require_feature_flag(&vars::ENABLE_QUERY_POLICIES)?;
5026 let (mode, rules) = plan_query_policy_options(options)?;
5027 let Some(rules) = rules else {
5028 sql_bail!("RULES must be specified when creating query policies");
5029 };
5030 Ok(Plan::CreateQueryPolicy(CreateQueryPolicyPlan {
5031 name: normalize::ident(name),
5032 mode: mode.unwrap_or_default(),
5033 rules,
5034 }))
5035}
5036
5037pub fn plan_alter_query_policy(
5038 scx: &StatementContext,
5039 AlterQueryPolicyStatement { name, options }: AlterQueryPolicyStatement<Aug>,
5040) -> Result<Plan, PlanError> {
5041 scx.require_feature_flag(&vars::ENABLE_QUERY_POLICIES)?;
5042 let name = normalize::ident(name);
5043 let policy = scx.catalog.resolve_query_policy(&name)?;
5044 let (mode, rules) = plan_query_policy_options(options)?;
5045 Ok(Plan::AlterQueryPolicy(AlterQueryPolicyPlan {
5046 id: policy.id(),
5047 name,
5048 mode: mode.unwrap_or_else(|| policy.mode()),
5049 rules: rules.unwrap_or_else(|| policy.rules().to_vec()),
5050 }))
5051}
5052
5053pub fn plan_create_network_policy(
5054 ctx: &StatementContext,
5055 CreateNetworkPolicyStatement { name, options }: CreateNetworkPolicyStatement<Aug>,
5056) -> Result<Plan, PlanError> {
5057 ctx.require_feature_flag(&vars::ENABLE_NETWORK_POLICIES)?;
5058 let policy_options: NetworkPolicyOptionExtracted = options.try_into()?;
5059
5060 let Some(rule_defs) = policy_options.rules else {
5061 sql_bail!("RULES must be specified when creating network policies.");
5062 };
5063
5064 let mut rules = vec![];
5065 for NetworkPolicyRuleDefinition { name, options } in rule_defs {
5066 let NetworkPolicyRuleOptionExtracted {
5067 seen: _,
5068 direction,
5069 action,
5070 address,
5071 } = options.try_into()?;
5072 let (direction, action, address) = match (direction, action, address) {
5073 (Some(direction), Some(action), Some(address)) => (
5074 NetworkPolicyRuleDirection::try_from(direction.as_str())?,
5075 NetworkPolicyRuleAction::try_from(action.as_str())?,
5076 PolicyAddress::try_from(address.as_str())?,
5077 ),
5078 (_, _, _) => {
5079 sql_bail!("Direction, Address, and Action must specified when creating a rule")
5080 }
5081 };
5082 rules.push(NetworkPolicyRule {
5083 name: normalize::ident(name),
5084 direction,
5085 action,
5086 address,
5087 });
5088 }
5089
5090 if rules.len()
5091 > ctx
5092 .catalog
5093 .system_vars()
5094 .max_rules_per_network_policy()
5095 .try_into()?
5096 {
5097 sql_bail!("RULES count exceeds max_rules_per_network_policy.")
5098 }
5099
5100 Ok(Plan::CreateNetworkPolicy(CreateNetworkPolicyPlan {
5101 name: normalize::ident(name),
5102 rules,
5103 }))
5104}
5105
5106pub fn plan_alter_network_policy(
5107 ctx: &StatementContext,
5108 AlterNetworkPolicyStatement { name, options }: AlterNetworkPolicyStatement<Aug>,
5109) -> Result<Plan, PlanError> {
5110 ctx.require_feature_flag(&vars::ENABLE_NETWORK_POLICIES)?;
5111
5112 let policy_options: NetworkPolicyOptionExtracted = options.try_into()?;
5113 let policy = ctx
5114 .catalog
5115 .resolve_network_policy(normalize::ident_ref(&name))?;
5116
5117 let Some(rule_defs) = policy_options.rules else {
5118 sql_bail!("RULES must be specified when creating network policies.");
5119 };
5120
5121 let mut rules = vec![];
5122 for NetworkPolicyRuleDefinition { name, options } in rule_defs {
5123 let NetworkPolicyRuleOptionExtracted {
5124 seen: _,
5125 direction,
5126 action,
5127 address,
5128 } = options.try_into()?;
5129
5130 let (direction, action, address) = match (direction, action, address) {
5131 (Some(direction), Some(action), Some(address)) => (
5132 NetworkPolicyRuleDirection::try_from(direction.as_str())?,
5133 NetworkPolicyRuleAction::try_from(action.as_str())?,
5134 PolicyAddress::try_from(address.as_str())?,
5135 ),
5136 (_, _, _) => {
5137 sql_bail!("Direction, Address, and Action must specified when creating a rule")
5138 }
5139 };
5140 rules.push(NetworkPolicyRule {
5141 name: normalize::ident(name),
5142 direction,
5143 action,
5144 address,
5145 });
5146 }
5147 if rules.len()
5148 > ctx
5149 .catalog
5150 .system_vars()
5151 .max_rules_per_network_policy()
5152 .try_into()?
5153 {
5154 sql_bail!("RULES count exceeds max_rules_per_network_policy.")
5155 }
5156
5157 Ok(Plan::AlterNetworkPolicy(AlterNetworkPolicyPlan {
5158 id: policy.id(),
5159 name: normalize::ident(name),
5160 rules,
5161 }))
5162}
5163
5164pub fn describe_create_cluster(
5165 _: &StatementContext,
5166 _: CreateClusterStatement<Aug>,
5167) -> Result<StatementDesc, PlanError> {
5168 Ok(StatementDesc::new(None))
5169}
5170
5171generate_extracted_config!(
5177 ClusterOption,
5178 (AutoScalingStrategy, ClusterAutoScalingStrategyOptionValue),
5179 (AvailabilityZones, Vec<String>),
5180 (Disk, bool),
5181 (ExperimentalArrangementCompression, bool),
5182 (IntrospectionDebugging, bool),
5183 (IntrospectionInterval, OptionalDuration),
5184 (Managed, bool),
5185 (Replicas, Vec<ReplicaDefinition<Aug>>),
5186 (ReplicationFactor, u32),
5187 (Size, String),
5188 (Schedule, ClusterScheduleOptionValue),
5189 (WorkloadClass, OptionalString),
5190 (QueryPolicy, OptionalString)
5191);
5192
5193generate_extracted_config!(
5194 NetworkPolicyOption,
5195 (Rules, Vec<NetworkPolicyRuleDefinition<Aug>>)
5196);
5197
5198generate_extracted_config!(
5199 NetworkPolicyRuleOption,
5200 (Direction, String),
5201 (Action, String),
5202 (Address, String)
5203);
5204
5205generate_extracted_config!(ClusterAlterOption, (Wait, ClusterAlterOptionValue<Aug>));
5206
5207generate_extracted_config!(
5208 ClusterAlterUntilReadyOption,
5209 (Timeout, Duration),
5210 (OnTimeout, String)
5211);
5212
5213generate_extracted_config!(
5214 ClusterFeature,
5215 (ReoptimizeImportedViews, Option<bool>, Default(None)),
5216 (EnableEagerDeltaJoins, Option<bool>, Default(None)),
5217 (EnableNewOuterJoinLowering, Option<bool>, Default(None)),
5218 (EnableVariadicLeftJoinLowering, Option<bool>, Default(None)),
5219 (EnableLetrecFixpointAnalysis, Option<bool>, Default(None)),
5220 (EnableJoinPrioritizeArranged, Option<bool>, Default(None)),
5221 (
5222 EnableProjectionPushdownAfterRelationCse,
5223 Option<bool>,
5224 Default(None)
5225 ),
5226 (
5227 EnableUnionCancellationAfterRelationCse,
5228 Option<bool>,
5229 Default(None)
5230 )
5231);
5232
5233pub fn plan_create_cluster(
5237 scx: &StatementContext,
5238 stmt: CreateClusterStatement<Aug>,
5239) -> Result<Plan, PlanError> {
5240 let plan = plan_create_cluster_inner(scx, stmt)?;
5241
5242 if let CreateClusterVariant::Managed(_) = &plan.variant {
5244 let stmt = unplan_create_cluster(scx, plan.clone())
5245 .map_err(|e| PlanError::Replan(e.to_string()))?;
5246 let create_sql = stmt.to_ast_string_stable();
5247 let stmt = parse::parse(&create_sql)
5248 .map_err(|e| PlanError::Replan(e.to_string()))?
5249 .into_element()
5250 .ast;
5251 let (stmt, _resolved_ids) =
5252 names::resolve(scx.catalog, stmt).map_err(|e| PlanError::Replan(e.to_string()))?;
5253 let stmt = match stmt {
5254 Statement::CreateCluster(stmt) => stmt,
5255 stmt => {
5256 return Err(PlanError::Replan(format!(
5257 "replan does not match: plan={plan:?}, create_sql={create_sql:?}, stmt={stmt:?}"
5258 )));
5259 }
5260 };
5261 let replan =
5262 plan_create_cluster_inner(scx, stmt).map_err(|e| PlanError::Replan(e.to_string()))?;
5263 if plan != replan {
5264 return Err(PlanError::Replan(format!(
5265 "replan does not match: plan={plan:?}, replan={replan:?}"
5266 )));
5267 }
5268 }
5269
5270 Ok(Plan::CreateCluster(plan))
5271}
5272
5273pub fn plan_create_cluster_inner(
5274 scx: &StatementContext,
5275 CreateClusterStatement {
5276 name,
5277 options,
5278 features,
5279 if_not_exists,
5280 }: CreateClusterStatement<Aug>,
5281) -> Result<CreateClusterPlan, PlanError> {
5282 let ClusterOptionExtracted {
5283 auto_scaling_strategy,
5284 availability_zones,
5285 experimental_arrangement_compression,
5286 introspection_debugging,
5287 introspection_interval,
5288 managed,
5289 replicas,
5290 replication_factor,
5291 seen: _,
5292 size,
5293 disk,
5294 schedule,
5295 workload_class,
5296 query_policy,
5297 }: ClusterOptionExtracted = options.try_into()?;
5298
5299 let managed = managed.unwrap_or_else(|| replicas.is_none());
5300
5301 if !scx.catalog.active_role_id().is_system() {
5302 if !features.is_empty() {
5303 sql_bail!("FEATURES not supported for non-system users");
5304 }
5305 if workload_class.is_some() {
5306 sql_bail!("WORKLOAD CLASS not supported for non-system users");
5307 }
5308 }
5309
5310 let schedule = schedule.unwrap_or(ClusterScheduleOptionValue::Manual);
5311 let workload_class = workload_class.and_then(|v| v.0);
5312 let query_policy = match query_policy {
5313 Some(name) => {
5314 scx.require_feature_flag(&vars::ENABLE_QUERY_POLICIES)?;
5315 name.0
5316 .map(|name| scx.catalog.resolve_query_policy(&name).map(|p| p.id()))
5317 .transpose()?
5318 }
5319 None => None,
5320 };
5321
5322 if managed {
5323 if replicas.is_some() {
5324 sql_bail!("REPLICAS not supported for managed clusters");
5325 }
5326 let Some(size) = size else {
5327 sql_bail!("SIZE must be specified for managed clusters");
5328 };
5329
5330 if disk.is_some() {
5331 if scx.catalog.is_cluster_size_cc(&size) {
5335 sql_bail!(
5336 "DISK option not supported for modern cluster sizes because disk is always enabled"
5337 );
5338 }
5339
5340 scx.catalog
5341 .add_notice(PlanNotice::ReplicaDiskOptionDeprecated);
5342 }
5343
5344 let compute = plan_compute_replica_config(
5345 introspection_interval,
5346 introspection_debugging.unwrap_or(false),
5347 experimental_arrangement_compression.unwrap_or(false),
5348 )?;
5349
5350 let replication_factor = if matches!(schedule, ClusterScheduleOptionValue::Manual) {
5351 replication_factor.unwrap_or_else(|| {
5352 scx.catalog
5353 .system_vars()
5354 .default_cluster_replication_factor()
5355 })
5356 } else {
5357 scx.require_feature_flag(&ENABLE_CLUSTER_SCHEDULE_REFRESH)?;
5358 if replication_factor.is_some() {
5359 sql_bail!(
5360 "REPLICATION FACTOR cannot be given together with any SCHEDULE other than MANUAL"
5361 );
5362 }
5363 0
5367 };
5368 let availability_zones = availability_zones.unwrap_or_default();
5369
5370 if !availability_zones.is_empty() {
5371 scx.require_feature_flag(&vars::ENABLE_MANAGED_CLUSTER_AVAILABILITY_ZONES)?;
5372 }
5373
5374 let ClusterFeatureExtracted {
5376 reoptimize_imported_views,
5377 enable_eager_delta_joins,
5378 enable_new_outer_join_lowering,
5379 enable_variadic_left_join_lowering,
5380 enable_letrec_fixpoint_analysis,
5381 enable_join_prioritize_arranged,
5382 enable_projection_pushdown_after_relation_cse,
5383 enable_union_cancellation_after_relation_cse,
5384 seen: _,
5385 } = ClusterFeatureExtracted::try_from(features)?;
5386 let optimizer_feature_overrides = OptimizerFeatureOverrides {
5387 reoptimize_imported_views,
5388 enable_eager_delta_joins,
5389 enable_new_outer_join_lowering,
5390 enable_variadic_left_join_lowering,
5391 enable_letrec_fixpoint_analysis,
5392 enable_join_prioritize_arranged,
5393 enable_projection_pushdown_after_relation_cse,
5394 enable_union_cancellation_after_relation_cse,
5395 ..Default::default()
5396 };
5397
5398 let auto_scaling_strategy = match auto_scaling_strategy {
5401 Some(value) => {
5402 scx.require_feature_flag(&ENABLE_AUTO_SCALING_STRATEGY)?;
5403 let strategy = plan_auto_scaling_strategy(value)?;
5404 if let Some(strategy) = &strategy {
5405 let schedule_non_manual =
5406 !matches!(schedule, ClusterScheduleOptionValue::Manual);
5407 validate_auto_scaling_strategy(strategy, Some(&size), schedule_non_manual)?;
5408 }
5409 strategy
5410 }
5411 None => None,
5412 };
5413
5414 let schedule = plan_cluster_schedule(schedule)?;
5415
5416 Ok(CreateClusterPlan {
5417 name: normalize::ident(name),
5418 variant: CreateClusterVariant::Managed(CreateClusterManagedPlan {
5419 replication_factor,
5420 size,
5421 availability_zones,
5422 compute,
5423 optimizer_feature_overrides,
5424 schedule,
5425 auto_scaling_strategy,
5426 }),
5427 workload_class,
5428 if_not_exists,
5429 query_policy,
5430 })
5431 } else {
5432 let Some(replica_defs) = replicas else {
5433 sql_bail!("REPLICAS must be specified for unmanaged clusters");
5434 };
5435 if auto_scaling_strategy.is_some() {
5436 sql_bail!("AUTO SCALING STRATEGY not supported for unmanaged clusters");
5437 }
5438 if availability_zones.is_some() {
5439 sql_bail!("AVAILABILITY ZONES not supported for unmanaged clusters");
5440 }
5441 if replication_factor.is_some() {
5442 sql_bail!("REPLICATION FACTOR not supported for unmanaged clusters");
5443 }
5444 if introspection_debugging.is_some() {
5445 sql_bail!("INTROSPECTION DEBUGGING not supported for unmanaged clusters");
5446 }
5447 if introspection_interval.is_some() {
5448 sql_bail!("INTROSPECTION INTERVAL not supported for unmanaged clusters");
5449 }
5450 if experimental_arrangement_compression.is_some() {
5451 sql_bail!("EXPERIMENTAL ARRANGEMENT COMPRESSION not supported for unmanaged clusters");
5452 }
5453 if size.is_some() {
5454 sql_bail!("SIZE not supported for unmanaged clusters");
5455 }
5456 if disk.is_some() {
5457 sql_bail!("DISK not supported for unmanaged clusters");
5458 }
5459 if !features.is_empty() {
5460 sql_bail!("FEATURES not supported for unmanaged clusters");
5461 }
5462 if !matches!(schedule, ClusterScheduleOptionValue::Manual) {
5463 sql_bail!(
5464 "cluster schedules other than MANUAL are not supported for unmanaged clusters"
5465 );
5466 }
5467
5468 let mut replicas = vec![];
5469 for ReplicaDefinition { name, options } in replica_defs {
5470 replicas.push((normalize::ident(name), plan_replica_config(scx, options)?));
5471 }
5472
5473 Ok(CreateClusterPlan {
5474 name: normalize::ident(name),
5475 variant: CreateClusterVariant::Unmanaged(CreateClusterUnmanagedPlan { replicas }),
5476 workload_class,
5477 if_not_exists,
5478 query_policy,
5479 })
5480 }
5481}
5482
5483pub fn unplan_create_cluster(
5490 scx: &StatementContext,
5491 CreateClusterPlan {
5492 name,
5493 variant,
5494 workload_class,
5495 if_not_exists,
5496 query_policy,
5497 }: CreateClusterPlan,
5498) -> Result<CreateClusterStatement<Aug>, PlanError> {
5499 match variant {
5500 CreateClusterVariant::Managed(CreateClusterManagedPlan {
5501 replication_factor,
5502 size,
5503 availability_zones,
5504 compute,
5505 optimizer_feature_overrides,
5506 schedule,
5507 auto_scaling_strategy,
5508 }) => {
5509 let schedule = unplan_cluster_schedule(schedule);
5510 let auto_scaling_strategy = auto_scaling_strategy
5511 .as_ref()
5512 .map(unplan_auto_scaling_strategy);
5513 let OptimizerFeatureOverrides {
5514 enable_reduce_mfp_fusion: _,
5515 enable_cardinality_estimates: _,
5516 persist_fast_path_limit: _,
5517 reoptimize_imported_views,
5518 enable_eager_delta_joins,
5519 enable_new_outer_join_lowering,
5520 enable_variadic_left_join_lowering,
5521 enable_letrec_fixpoint_analysis,
5522 enable_join_prioritize_arranged,
5523 enable_projection_pushdown_after_relation_cse,
5524 enable_union_cancellation_after_relation_cse,
5525 enable_less_reduce_in_eqprop: _,
5526 enable_dequadratic_eqprop_map: _,
5527 enable_eq_classes_withholding_errors: _,
5528 enable_fast_path_plan_insights: _,
5529 enable_cast_elimination: _,
5530 enable_case_literal_transform: _,
5531 enable_simplify_quantified_comparisons: _,
5532 enable_simplify_from_less_existence: _,
5533 enable_coalesce_case_transform: _,
5534 enable_will_distinct_propagation: _,
5535 enable_fixed_correlated_cte_lowering: _,
5536 } = optimizer_feature_overrides;
5537 let features_extracted = ClusterFeatureExtracted {
5539 seen: Default::default(),
5541 reoptimize_imported_views,
5542 enable_eager_delta_joins,
5543 enable_new_outer_join_lowering,
5544 enable_variadic_left_join_lowering,
5545 enable_letrec_fixpoint_analysis,
5546 enable_join_prioritize_arranged,
5547 enable_projection_pushdown_after_relation_cse,
5548 enable_union_cancellation_after_relation_cse,
5549 };
5550 let features = features_extracted.into_values(scx.catalog);
5551 let availability_zones = if availability_zones.is_empty() {
5552 None
5553 } else {
5554 Some(availability_zones)
5555 };
5556 let (introspection_interval, introspection_debugging, arrangement_compression) =
5557 unplan_compute_replica_config(compute);
5558 let replication_factor = match &schedule {
5561 ClusterScheduleOptionValue::Manual => Some(replication_factor),
5562 ClusterScheduleOptionValue::Refresh { .. } => {
5563 soft_assert_or_log!(
5570 replication_factor <= 1,
5571 "replication factor, {replication_factor:?}, must be <= 1 with a refresh schedule"
5572 );
5573 None
5574 }
5575 };
5576 let workload_class = workload_class.map(|s| OptionalString(Some(s)));
5577 let options_extracted = ClusterOptionExtracted {
5578 seen: Default::default(),
5580 auto_scaling_strategy,
5581 availability_zones,
5582 disk: None,
5583 experimental_arrangement_compression: Some(arrangement_compression),
5584 introspection_debugging: Some(introspection_debugging),
5585 introspection_interval,
5586 managed: Some(true),
5587 replicas: None,
5588 replication_factor,
5589 size: Some(size),
5590 schedule: Some(schedule),
5591 workload_class,
5592 query_policy: query_policy.map(|id| {
5593 OptionalString(Some(scx.catalog.get_query_policy(&id).name().to_string()))
5594 }),
5595 };
5596 let options = options_extracted.into_values(scx.catalog);
5597 let name = Ident::new_unchecked(name);
5598 Ok(CreateClusterStatement {
5599 name,
5600 options,
5601 features,
5602 if_not_exists,
5603 })
5604 }
5605 CreateClusterVariant::Unmanaged(_) => {
5606 bail_unsupported!("SHOW CREATE for unmanaged clusters")
5607 }
5608 }
5609}
5610
5611generate_extracted_config!(
5612 ReplicaOption,
5613 (AvailabilityZone, String),
5614 (BilledAs, String),
5615 (ComputeAddresses, Vec<String>),
5616 (ComputectlAddresses, Vec<String>),
5617 (Disk, bool),
5618 (ExperimentalArrangementCompression, bool, Default(false)),
5619 (Internal, bool, Default(false)),
5620 (IntrospectionDebugging, bool, Default(false)),
5621 (IntrospectionInterval, OptionalDuration),
5622 (Size, String),
5623 (StorageAddresses, Vec<String>),
5624 (StoragectlAddresses, Vec<String>),
5625 (Workers, u16)
5626);
5627
5628fn plan_replica_config(
5629 scx: &StatementContext,
5630 options: Vec<ReplicaOption<Aug>>,
5631) -> Result<ReplicaConfig, PlanError> {
5632 let ReplicaOptionExtracted {
5633 availability_zone,
5634 billed_as,
5635 computectl_addresses,
5636 disk,
5637 experimental_arrangement_compression,
5638 internal,
5639 introspection_debugging,
5640 introspection_interval,
5641 size,
5642 storagectl_addresses,
5643 ..
5644 }: ReplicaOptionExtracted = options.try_into()?;
5645
5646 let compute = plan_compute_replica_config(
5647 introspection_interval,
5648 introspection_debugging,
5649 experimental_arrangement_compression,
5650 )?;
5651
5652 match (
5653 size,
5654 availability_zone,
5655 billed_as,
5656 storagectl_addresses,
5657 computectl_addresses,
5658 ) {
5659 (None, _, None, None, None) => {
5661 sql_bail!("SIZE option must be specified");
5664 }
5665 (Some(size), availability_zone, billed_as, None, None) => {
5666 if disk.is_some() {
5667 if scx.catalog.is_cluster_size_cc(&size) {
5671 sql_bail!(
5672 "DISK option not supported for modern cluster sizes because disk is always enabled"
5673 );
5674 }
5675
5676 scx.catalog
5677 .add_notice(PlanNotice::ReplicaDiskOptionDeprecated);
5678 }
5679
5680 Ok(ReplicaConfig::Orchestrated {
5681 size,
5682 availability_zone,
5683 compute,
5684 billed_as,
5685 internal,
5686 })
5687 }
5688
5689 (None, None, None, storagectl_addresses, computectl_addresses) => {
5690 scx.require_feature_flag(&vars::UNSAFE_ENABLE_UNORCHESTRATED_CLUSTER_REPLICAS)?;
5691
5692 let Some(storagectl_addrs) = storagectl_addresses else {
5696 sql_bail!("missing STORAGECTL ADDRESSES option");
5697 };
5698 let Some(computectl_addrs) = computectl_addresses else {
5699 sql_bail!("missing COMPUTECTL ADDRESSES option");
5700 };
5701
5702 if storagectl_addrs.len() != computectl_addrs.len() {
5703 sql_bail!(
5704 "COMPUTECTL ADDRESSES and STORAGECTL ADDRESSES must have the same length"
5705 );
5706 }
5707
5708 if disk.is_some() {
5709 sql_bail!("DISK can't be specified for unorchestrated clusters");
5710 }
5711
5712 Ok(ReplicaConfig::Unorchestrated {
5713 storagectl_addrs,
5714 computectl_addrs,
5715 compute,
5716 })
5717 }
5718 _ => {
5719 sql_bail!("invalid mixture of orchestrated and unorchestrated replica options");
5722 }
5723 }
5724}
5725
5726fn plan_compute_replica_config(
5730 introspection_interval: Option<OptionalDuration>,
5731 introspection_debugging: bool,
5732 arrangement_compression: bool,
5733) -> Result<ComputeReplicaConfig, PlanError> {
5734 let introspection_interval = introspection_interval
5735 .map(|OptionalDuration(i)| i)
5736 .unwrap_or(Some(DEFAULT_REPLICA_LOGGING_INTERVAL));
5737 let introspection = match introspection_interval {
5738 Some(interval) => Some(ComputeReplicaIntrospectionConfig {
5739 interval,
5740 debugging: introspection_debugging,
5741 }),
5742 None if introspection_debugging => {
5743 sql_bail!("INTROSPECTION DEBUGGING cannot be specified without INTROSPECTION INTERVAL")
5744 }
5745 None => None,
5746 };
5747 let compute = ComputeReplicaConfig {
5748 introspection,
5749 arrangement_compression,
5750 };
5751 Ok(compute)
5752}
5753
5754fn unplan_compute_replica_config(
5759 compute_replica_config: ComputeReplicaConfig,
5760) -> (Option<OptionalDuration>, bool, bool) {
5761 let ComputeReplicaConfig {
5762 introspection,
5763 arrangement_compression,
5764 } = compute_replica_config;
5765 match introspection {
5766 Some(ComputeReplicaIntrospectionConfig {
5767 debugging,
5768 interval,
5769 }) => (
5770 Some(OptionalDuration(Some(interval))),
5771 debugging,
5772 arrangement_compression,
5773 ),
5774 None => (Some(OptionalDuration(None)), false, arrangement_compression),
5775 }
5776}
5777
5778fn plan_cluster_schedule(
5782 schedule: ClusterScheduleOptionValue,
5783) -> Result<ClusterSchedule, PlanError> {
5784 Ok(match schedule {
5785 ClusterScheduleOptionValue::Manual => ClusterSchedule::Manual,
5786 ClusterScheduleOptionValue::Refresh {
5788 hydration_time_estimate: None,
5789 } => ClusterSchedule::Refresh {
5790 hydration_time_estimate: Duration::from_millis(0),
5791 },
5792 ClusterScheduleOptionValue::Refresh {
5794 hydration_time_estimate: Some(interval_value),
5795 } => {
5796 let interval = Interval::try_from_value(Value::Interval(interval_value))?;
5797 if interval.as_microseconds() < 0 {
5798 sql_bail!(
5799 "HYDRATION TIME ESTIMATE must be non-negative; got: {}",
5800 interval
5801 );
5802 }
5803 if interval.months != 0 {
5804 sql_bail!("HYDRATION TIME ESTIMATE must not involve units larger than days");
5808 }
5809 let duration = interval.duration()?;
5810 if u64::try_from(duration.as_millis()).is_err()
5811 || Interval::from_duration(&duration).is_err()
5812 {
5813 sql_bail!("HYDRATION TIME ESTIMATE too large");
5814 }
5815 ClusterSchedule::Refresh {
5816 hydration_time_estimate: duration,
5817 }
5818 }
5819 })
5820}
5821
5822fn unplan_cluster_schedule(schedule: ClusterSchedule) -> ClusterScheduleOptionValue {
5826 match schedule {
5827 ClusterSchedule::Manual => ClusterScheduleOptionValue::Manual,
5828 ClusterSchedule::Refresh {
5829 hydration_time_estimate,
5830 } => {
5831 let interval = Interval::from_duration(&hydration_time_estimate)
5832 .expect("planning ensured that this is convertible back to Interval");
5833 let interval_value = literal::unplan_interval(&interval);
5834 ClusterScheduleOptionValue::Refresh {
5835 hydration_time_estimate: Some(interval_value),
5836 }
5837 }
5838 }
5839}
5840
5841fn plan_auto_scaling_strategy(
5849 value: ClusterAutoScalingStrategyOptionValue,
5850) -> Result<Option<AutoScalingStrategy>, PlanError> {
5851 let ClusterAutoScalingStrategyOptionValue { on_hydration } = value;
5852 let Some(on_hydration) = on_hydration else {
5853 return Ok(None);
5855 };
5856
5857 let hydration_size = String::try_from_value(on_hydration.hydration_size)?;
5858
5859 let linger_duration = on_hydration
5860 .linger_duration
5861 .map(Duration::try_from_value)
5862 .transpose()?;
5863
5864 Ok(Some(AutoScalingStrategy {
5865 on_hydration: Some(OnHydration {
5866 hydration_size,
5867 linger_duration,
5868 }),
5869 }))
5870}
5871
5872fn validate_auto_scaling_strategy(
5881 strategy: &AutoScalingStrategy,
5882 cluster_size: Option<&str>,
5883 schedule_non_manual: bool,
5884) -> Result<(), PlanError> {
5885 if let (Some(on_hydration), Some(cluster_size)) = (&strategy.on_hydration, cluster_size) {
5886 if on_hydration.hydration_size == cluster_size {
5887 return Err(PlanError::HydrationSizeEqualsClusterSize {
5888 size: cluster_size.to_string(),
5889 });
5890 }
5891 }
5892 if schedule_non_manual {
5893 sql_bail!("AUTO SCALING STRATEGY cannot be combined with a SCHEDULE other than MANUAL");
5894 }
5895 Ok(())
5896}
5897
5898fn unplan_auto_scaling_strategy(
5903 strategy: &AutoScalingStrategy,
5904) -> ClusterAutoScalingStrategyOptionValue {
5905 ClusterAutoScalingStrategyOptionValue {
5906 on_hydration: strategy
5907 .on_hydration
5908 .as_ref()
5909 .map(|on_hydration| OnHydrationOptionValue {
5910 hydration_size: Value::String(on_hydration.hydration_size.clone()),
5911 linger_duration: on_hydration.linger_duration.map(|d| {
5912 let interval = Interval::from_duration(&d)
5913 .expect("planning ensured this is convertible back to Interval");
5914 Value::Interval(literal::unplan_interval(&interval))
5915 }),
5916 }),
5917 }
5918}
5919
5920pub fn describe_create_cluster_replica(
5921 _: &StatementContext,
5922 _: CreateClusterReplicaStatement<Aug>,
5923) -> Result<StatementDesc, PlanError> {
5924 Ok(StatementDesc::new(None))
5925}
5926
5927pub fn plan_create_cluster_replica(
5928 scx: &StatementContext,
5929 CreateClusterReplicaStatement {
5930 definition: ReplicaDefinition { name, options },
5931 of_cluster,
5932 if_not_exists,
5933 }: CreateClusterReplicaStatement<Aug>,
5934) -> Result<Plan, PlanError> {
5935 let cluster = scx
5936 .catalog
5937 .resolve_cluster(Some(&normalize::ident(of_cluster)))?;
5938
5939 let config = plan_replica_config(scx, options)?;
5940
5941 if let ReplicaConfig::Orchestrated { internal: true, .. } = &config {
5942 if MANAGED_REPLICA_PATTERN.is_match(name.as_str()) {
5943 return Err(PlanError::MangedReplicaName(name.into_string()));
5944 }
5945 } else {
5946 ensure_cluster_is_not_managed(scx, cluster.id())?;
5947 }
5948
5949 Ok(Plan::CreateClusterReplica(CreateClusterReplicaPlan {
5950 name: normalize::ident(name),
5951 cluster_id: cluster.id(),
5952 config,
5953 if_not_exists,
5954 }))
5955}
5956
5957pub fn describe_create_secret(
5958 _: &StatementContext,
5959 _: CreateSecretStatement<Aug>,
5960) -> Result<StatementDesc, PlanError> {
5961 Ok(StatementDesc::new(None))
5962}
5963
5964pub fn plan_create_secret(
5965 scx: &StatementContext,
5966 stmt: CreateSecretStatement<Aug>,
5967) -> Result<Plan, PlanError> {
5968 let CreateSecretStatement {
5969 name,
5970 if_not_exists,
5971 value,
5972 } = &stmt;
5973
5974 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name.to_owned())?)?;
5975 let mut create_sql_statement = stmt.clone();
5976 create_sql_statement.value = Expr::Value(Value::String("********".to_string()));
5977 let create_sql =
5978 normalize::create_statement(scx, Statement::CreateSecret(create_sql_statement))?;
5979 let secret_as = query::plan_secret_as(scx, value.clone())?;
5980
5981 let secret = Secret {
5982 create_sql,
5983 secret_as,
5984 };
5985
5986 Ok(Plan::CreateSecret(CreateSecretPlan {
5987 name,
5988 secret,
5989 if_not_exists: *if_not_exists,
5990 }))
5991}
5992
5993pub fn describe_create_connection(
5994 _: &StatementContext,
5995 _: CreateConnectionStatement<Aug>,
5996) -> Result<StatementDesc, PlanError> {
5997 Ok(StatementDesc::new(None))
5998}
5999
6000generate_extracted_config!(CreateConnectionOption, (Validate, bool));
6001
6002pub fn plan_create_connection(
6003 scx: &StatementContext,
6004 mut stmt: CreateConnectionStatement<Aug>,
6005) -> Result<Plan, PlanError> {
6006 let CreateConnectionStatement {
6007 name,
6008 connection_type,
6009 values,
6010 if_not_exists,
6011 with_options,
6012 } = stmt.clone();
6013 let connection_options_extracted = connection::ConnectionOptionExtracted::try_from(values)?;
6014 let details = connection_options_extracted.try_into_connection_details(scx, connection_type)?;
6015 let name = scx.allocate_qualified_name(normalize::unresolved_item_name(name)?)?;
6016
6017 let options = CreateConnectionOptionExtracted::try_from(with_options)?;
6018 if options.validate.is_some() {
6019 scx.require_feature_flag(&vars::ENABLE_CONNECTION_VALIDATION_SYNTAX)?;
6020 }
6021 let validate = match options.validate {
6022 Some(val) => val,
6023 None => {
6024 scx.catalog
6025 .system_vars()
6026 .enable_default_connection_validation()
6027 && details.to_connection().validate_by_default()
6028 }
6029 };
6030
6031 let full_name = scx.catalog.resolve_full_name(&name);
6033 let partial_name = PartialItemName::from(full_name.clone());
6034 if let (false, Ok(item)) = (if_not_exists, scx.catalog.resolve_item(&partial_name)) {
6035 return Err(PlanError::ItemAlreadyExists {
6036 name: full_name.to_string(),
6037 item_type: item.item_type(),
6038 });
6039 }
6040
6041 if let ConnectionDetails::Ssh { key_1, key_2, .. } = &details {
6044 stmt.values.retain(|v| {
6045 v.name != ConnectionOptionName::PublicKey1 && v.name != ConnectionOptionName::PublicKey2
6046 });
6047 stmt.values.push(ConnectionOption {
6048 name: ConnectionOptionName::PublicKey1,
6049 value: Some(WithOptionValue::Value(Value::String(key_1.public_key()))),
6050 });
6051 stmt.values.push(ConnectionOption {
6052 name: ConnectionOptionName::PublicKey2,
6053 value: Some(WithOptionValue::Value(Value::String(key_2.public_key()))),
6054 });
6055 }
6056 let create_sql = normalize::create_statement(scx, Statement::CreateConnection(stmt))?;
6057
6058 let plan = CreateConnectionPlan {
6059 name,
6060 if_not_exists,
6061 connection: crate::plan::Connection {
6062 create_sql,
6063 details,
6064 },
6065 validate,
6066 };
6067 Ok(Plan::CreateConnection(plan))
6068}
6069
6070fn plan_drop_database(
6071 scx: &StatementContext,
6072 if_exists: bool,
6073 name: &UnresolvedDatabaseName,
6074 cascade: bool,
6075) -> Result<Option<DatabaseId>, PlanError> {
6076 Ok(match resolve_database(scx, name, if_exists)? {
6077 Some(database) => {
6078 if !cascade && database.has_schemas() {
6079 sql_bail!(
6080 "database '{}' cannot be dropped with RESTRICT while it contains schemas",
6081 name,
6082 );
6083 }
6084 Some(database.id())
6085 }
6086 None => None,
6087 })
6088}
6089
6090pub fn describe_drop_objects(
6091 _: &StatementContext,
6092 _: DropObjectsStatement,
6093) -> Result<StatementDesc, PlanError> {
6094 Ok(StatementDesc::new(None))
6095}
6096
6097pub fn plan_drop_objects(
6098 scx: &mut StatementContext,
6099 DropObjectsStatement {
6100 object_type,
6101 if_exists,
6102 names,
6103 cascade,
6104 }: DropObjectsStatement,
6105) -> Result<Plan, PlanError> {
6106 if object_type == mz_sql_parser::ast::ObjectType::Func {
6107 bail_unsupported!("DROP FUNCTION");
6108 }
6109 let object_type = object_type.into();
6110
6111 let mut referenced_ids = Vec::new();
6112 for name in names {
6113 let id = match &name {
6114 UnresolvedObjectName::Cluster(name) => {
6115 plan_drop_cluster(scx, if_exists, name, cascade)?.map(ObjectId::Cluster)
6116 }
6117 UnresolvedObjectName::ClusterReplica(name) => {
6118 plan_drop_cluster_replica(scx, if_exists, name)?.map(ObjectId::ClusterReplica)
6119 }
6120 UnresolvedObjectName::Database(name) => {
6121 plan_drop_database(scx, if_exists, name, cascade)?.map(ObjectId::Database)
6122 }
6123 UnresolvedObjectName::Schema(name) => {
6124 plan_drop_schema(scx, if_exists, name, cascade)?.map(ObjectId::Schema)
6125 }
6126 UnresolvedObjectName::Role(name) => {
6127 plan_drop_role(scx, if_exists, name)?.map(ObjectId::Role)
6128 }
6129 UnresolvedObjectName::Item(name) => {
6130 plan_drop_item_name(scx, object_type, if_exists, name.clone())?.map(ObjectId::Item)
6134 }
6135 UnresolvedObjectName::NetworkPolicy(name) => {
6136 plan_drop_network_policy(scx, if_exists, name)?.map(ObjectId::NetworkPolicy)
6137 }
6138 UnresolvedObjectName::QueryPolicy(name) => {
6139 match scx.catalog.resolve_query_policy(name.as_str()) {
6140 Ok(policy) => Some(ObjectId::QueryPolicy(policy.id())),
6141 Err(_) if if_exists => None,
6142 Err(error) => return Err(error.into()),
6143 }
6144 }
6145 };
6146 match id {
6147 Some(id) => referenced_ids.push(id),
6148 None => scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
6149 name: name.to_ast_string_simple(),
6150 object_type,
6151 }),
6152 }
6153 }
6154
6155 if !cascade {
6159 let dropped_items: BTreeSet<CatalogItemId> = referenced_ids
6160 .iter()
6161 .filter_map(|id| match id {
6162 ObjectId::Item(id) => Some(*id),
6163 _ => None,
6164 })
6165 .collect();
6166 for id in &dropped_items {
6167 let catalog_item = scx.catalog.get_item(id);
6168 ensure_no_blocking_dependents(scx, object_type, catalog_item, &dropped_items)?;
6169 }
6170 }
6171
6172 let drop_ids = scx.catalog.object_dependents(&referenced_ids);
6173
6174 Ok(Plan::DropObjects(DropObjectsPlan {
6175 cascade,
6176 referenced_ids,
6177 drop_ids,
6178 object_type,
6179 }))
6180}
6181
6182fn plan_drop_schema(
6183 scx: &StatementContext,
6184 if_exists: bool,
6185 name: &UnresolvedSchemaName,
6186 cascade: bool,
6187) -> Result<Option<(ResolvedDatabaseSpecifier, SchemaSpecifier)>, PlanError> {
6188 let normalized = normalize::unresolved_schema_name(name.clone())?;
6192 if normalized.database.is_none() && normalized.schema == mz_repr::namespaces::MZ_TEMP_SCHEMA {
6193 sql_bail!("cannot drop schema {name} because it is a temporary schema",)
6194 }
6195
6196 Ok(match resolve_schema(scx, name.clone(), if_exists)? {
6197 Some((database_spec, schema_spec)) => {
6198 if let ResolvedDatabaseSpecifier::Ambient = database_spec {
6199 sql_bail!(
6200 "cannot drop schema {name} because it is required by the database system",
6201 );
6202 }
6203 if let SchemaSpecifier::Temporary = schema_spec {
6204 sql_bail!("cannot drop schema {name} because it is a temporary schema",)
6205 }
6206 let schema = scx.get_schema(&database_spec, &schema_spec);
6207 if !cascade && schema.has_items() {
6208 let full_schema_name = scx.catalog.resolve_full_schema_name(schema.name());
6209 sql_bail!(
6210 "schema '{}' cannot be dropped without CASCADE while it contains objects",
6211 full_schema_name
6212 );
6213 }
6214 Some((database_spec, schema_spec))
6215 }
6216 None => None,
6217 })
6218}
6219
6220fn plan_drop_role(
6221 scx: &StatementContext,
6222 if_exists: bool,
6223 name: &Ident,
6224) -> Result<Option<RoleId>, PlanError> {
6225 match scx.catalog.resolve_role(name.as_str()) {
6226 Ok(role) => {
6227 let id = role.id();
6228 if &id == scx.catalog.active_role_id() {
6229 sql_bail!("current role cannot be dropped");
6230 }
6231 for role in scx.catalog.get_roles() {
6232 for (member_id, grantor_id) in role.membership() {
6233 if &id == grantor_id {
6234 let member_role = scx.catalog.get_role(member_id);
6235 sql_bail!(
6236 "cannot drop role {}: still depended up by membership of role {} in role {}",
6237 name.as_str(),
6238 role.name(),
6239 member_role.name()
6240 );
6241 }
6242 }
6243 }
6244 Ok(Some(role.id()))
6245 }
6246 Err(_) if if_exists => Ok(None),
6247 Err(e) => Err(e.into()),
6248 }
6249}
6250
6251fn plan_drop_cluster(
6252 scx: &StatementContext,
6253 if_exists: bool,
6254 name: &Ident,
6255 cascade: bool,
6256) -> Result<Option<ClusterId>, PlanError> {
6257 Ok(match resolve_cluster(scx, name, if_exists)? {
6258 Some(cluster) => {
6259 if !cascade && !cluster.bound_objects().is_empty() {
6260 return Err(PlanError::DependentObjectsStillExist {
6261 object_type: "cluster".to_string(),
6262 object_name: cluster.name().to_string(),
6263 dependents: Vec::new(),
6264 });
6265 }
6266 Some(cluster.id())
6267 }
6268 None => None,
6269 })
6270}
6271
6272fn plan_drop_network_policy(
6273 scx: &StatementContext,
6274 if_exists: bool,
6275 name: &Ident,
6276) -> Result<Option<NetworkPolicyId>, PlanError> {
6277 match scx.catalog.resolve_network_policy(name.as_str()) {
6278 Ok(policy) => {
6279 if scx.catalog.system_vars().default_network_policy_name() == policy.name() {
6282 Err(PlanError::NetworkPolicyInUse)
6283 } else {
6284 Ok(Some(policy.id()))
6285 }
6286 }
6287 Err(_) if if_exists => Ok(None),
6288 Err(e) => Err(e.into()),
6289 }
6290}
6291
6292fn plan_drop_cluster_replica(
6293 scx: &StatementContext,
6294 if_exists: bool,
6295 name: &QualifiedReplica,
6296) -> Result<Option<(ClusterId, ReplicaId)>, PlanError> {
6297 let cluster = resolve_cluster_replica(scx, name, if_exists)?;
6298 Ok(cluster.map(|(cluster, replica_id)| (cluster.id(), replica_id)))
6299}
6300
6301fn plan_drop_item(
6303 scx: &StatementContext,
6304 object_type: ObjectType,
6305 if_exists: bool,
6306 name: UnresolvedItemName,
6307 cascade: bool,
6308) -> Result<Option<CatalogItemId>, PlanError> {
6309 let Some(id) = plan_drop_item_name(scx, object_type, if_exists, name)? else {
6310 return Ok(None);
6311 };
6312 if !cascade {
6313 let catalog_item = scx.catalog.get_item(&id);
6314 ensure_no_blocking_dependents(scx, object_type, catalog_item, &BTreeSet::new())?;
6315 }
6316 Ok(Some(id))
6317}
6318
6319fn plan_drop_item_name(
6323 scx: &StatementContext,
6324 object_type: ObjectType,
6325 if_exists: bool,
6326 name: UnresolvedItemName,
6327) -> Result<Option<CatalogItemId>, PlanError> {
6328 let resolved = match resolve_item_or_type(scx, object_type, name, if_exists) {
6329 Ok(r) => r,
6330 Err(PlanError::MismatchedObjectType {
6332 name,
6333 is_type: ObjectType::MaterializedView,
6334 expected_type: ObjectType::View,
6335 }) => {
6336 return Err(PlanError::DropViewOnMaterializedView(name.to_string()));
6337 }
6338 e => e?,
6339 };
6340
6341 Ok(match resolved {
6342 Some(catalog_item) => {
6343 if catalog_item.id().is_system() {
6344 sql_bail!(
6345 "cannot drop {} {} because it is required by the database system",
6346 catalog_item.item_type(),
6347 scx.catalog.minimal_qualification(catalog_item.name()),
6348 );
6349 }
6350 Some(catalog_item.id())
6351 }
6352 None => None,
6353 })
6354}
6355
6356fn ensure_no_blocking_dependents(
6361 scx: &StatementContext,
6362 object_type: ObjectType,
6363 catalog_item: &dyn CatalogItem,
6364 also_dropped: &BTreeSet<CatalogItemId>,
6365) -> Result<(), PlanError> {
6366 for id in catalog_item.used_by() {
6367 if also_dropped.contains(id) {
6368 continue;
6369 }
6370 let dep = scx.catalog.get_item(id);
6371 if dependency_prevents_drop(object_type, dep) {
6372 return Err(PlanError::DependentObjectsStillExist {
6373 object_type: catalog_item.item_type().to_string(),
6374 object_name: scx
6375 .catalog
6376 .minimal_qualification(catalog_item.name())
6377 .to_string(),
6378 dependents: vec![(
6379 dep.item_type().to_string(),
6380 scx.catalog.minimal_qualification(dep.name()).to_string(),
6381 )],
6382 });
6383 }
6384 }
6385 Ok(())
6388}
6389
6390fn dependency_prevents_drop(object_type: ObjectType, dep: &dyn CatalogItem) -> bool {
6392 match object_type {
6393 ObjectType::Type => true,
6394 ObjectType::Table
6395 | ObjectType::View
6396 | ObjectType::MaterializedView
6397 | ObjectType::Source
6398 | ObjectType::Sink
6399 | ObjectType::MetricSink
6400 | ObjectType::Index
6401 | ObjectType::Role
6402 | ObjectType::Cluster
6403 | ObjectType::ClusterReplica
6404 | ObjectType::Secret
6405 | ObjectType::Connection
6406 | ObjectType::Database
6407 | ObjectType::Schema
6408 | ObjectType::Func
6409 | ObjectType::NetworkPolicy
6410 | ObjectType::QueryPolicy => match dep.item_type() {
6411 CatalogItemType::Func
6412 | CatalogItemType::Table
6413 | CatalogItemType::Source
6414 | CatalogItemType::View
6415 | CatalogItemType::MaterializedView
6416 | CatalogItemType::Sink
6417 | CatalogItemType::MetricSink
6418 | CatalogItemType::Type
6419 | CatalogItemType::Secret
6420 | CatalogItemType::Connection => true,
6421 CatalogItemType::Index => false,
6422 },
6423 }
6424}
6425
6426pub fn describe_alter_index_options(
6427 _: &StatementContext,
6428 _: AlterIndexStatement<Aug>,
6429) -> Result<StatementDesc, PlanError> {
6430 Ok(StatementDesc::new(None))
6431}
6432
6433pub fn describe_drop_owned(
6434 _: &StatementContext,
6435 _: DropOwnedStatement<Aug>,
6436) -> Result<StatementDesc, PlanError> {
6437 Ok(StatementDesc::new(None))
6438}
6439
6440pub fn plan_drop_owned(
6441 scx: &StatementContext,
6442 drop: DropOwnedStatement<Aug>,
6443) -> Result<Plan, PlanError> {
6444 let cascade = drop.cascade();
6445 let role_ids: BTreeSet<_> = drop.role_names.into_iter().map(|role| role.id).collect();
6446 let mut drop_ids = Vec::new();
6447 let mut privilege_revokes = Vec::new();
6448 let mut default_privilege_revokes = Vec::new();
6449
6450 fn update_privilege_revokes(
6451 object_id: SystemObjectId,
6452 privileges: &PrivilegeMap,
6453 role_ids: &BTreeSet<RoleId>,
6454 privilege_revokes: &mut Vec<(SystemObjectId, MzAclItem)>,
6455 ) {
6456 privilege_revokes.extend(iter::zip(
6457 iter::repeat(object_id),
6458 privileges
6459 .all_values()
6460 .filter(|privilege| role_ids.contains(&privilege.grantee))
6461 .cloned(),
6462 ));
6463 }
6464
6465 for replica in scx.catalog.get_cluster_replicas() {
6467 if role_ids.contains(&replica.owner_id()) {
6468 drop_ids.push((replica.cluster_id(), replica.replica_id()).into());
6469 }
6470 }
6471
6472 for cluster in scx.catalog.get_clusters() {
6474 if role_ids.contains(&cluster.owner_id()) {
6475 if !cascade {
6477 let non_owned_bound_objects: Vec<_> = cluster
6478 .bound_objects()
6479 .into_iter()
6480 .map(|item_id| scx.catalog.get_item(item_id))
6481 .filter(|item| !role_ids.contains(&item.owner_id()))
6482 .collect();
6483 if !non_owned_bound_objects.is_empty() {
6484 let names: Vec<_> = non_owned_bound_objects
6485 .into_iter()
6486 .map(|item| {
6487 (
6488 item.item_type().to_string(),
6489 scx.catalog.resolve_full_name(item.name()).to_string(),
6490 )
6491 })
6492 .collect();
6493 return Err(PlanError::DependentObjectsStillExist {
6494 object_type: "cluster".to_string(),
6495 object_name: cluster.name().to_string(),
6496 dependents: names,
6497 });
6498 }
6499 }
6500 drop_ids.push(cluster.id().into());
6501 }
6502 update_privilege_revokes(
6503 SystemObjectId::Object(cluster.id().into()),
6504 cluster.privileges(),
6505 &role_ids,
6506 &mut privilege_revokes,
6507 );
6508 }
6509
6510 for item in scx.catalog.get_items() {
6512 if role_ids.contains(&item.owner_id()) {
6513 if !cascade {
6514 let check_if_dependents_exist = |used_by: &[CatalogItemId]| {
6516 let non_owned_dependencies: Vec<_> = used_by
6517 .into_iter()
6518 .map(|item_id| scx.catalog.get_item(item_id))
6519 .filter(|item| dependency_prevents_drop(item.item_type().into(), *item))
6520 .filter(|item| !role_ids.contains(&item.owner_id()))
6521 .collect();
6522 if !non_owned_dependencies.is_empty() {
6523 let names: Vec<_> = non_owned_dependencies
6524 .into_iter()
6525 .map(|item| {
6526 let item_typ = item.item_type().to_string();
6527 let item_name =
6528 scx.catalog.resolve_full_name(item.name()).to_string();
6529 (item_typ, item_name)
6530 })
6531 .collect();
6532 Err(PlanError::DependentObjectsStillExist {
6533 object_type: item.item_type().to_string(),
6534 object_name: scx
6535 .catalog
6536 .resolve_full_name(item.name())
6537 .to_string()
6538 .to_string(),
6539 dependents: names,
6540 })
6541 } else {
6542 Ok(())
6543 }
6544 };
6545
6546 if let Some(id) = item.progress_id() {
6549 let progress_item = scx.catalog.get_item(&id);
6550 check_if_dependents_exist(progress_item.used_by())?;
6551 }
6552 check_if_dependents_exist(item.used_by())?;
6553 }
6554 drop_ids.push(item.id().into());
6555 }
6556 update_privilege_revokes(
6557 SystemObjectId::Object(item.id().into()),
6558 item.privileges(),
6559 &role_ids,
6560 &mut privilege_revokes,
6561 );
6562 }
6563
6564 for schema in scx.catalog.get_schemas() {
6566 if !schema.id().is_temporary() {
6567 if role_ids.contains(&schema.owner_id()) {
6568 if !cascade {
6569 let non_owned_dependencies: Vec<_> = schema
6570 .item_ids()
6571 .map(|item_id| scx.catalog.get_item(&item_id))
6572 .filter(|item| dependency_prevents_drop(item.item_type().into(), *item))
6573 .filter(|item| !role_ids.contains(&item.owner_id()))
6574 .collect();
6575 if !non_owned_dependencies.is_empty() {
6576 let full_schema_name = scx.catalog.resolve_full_schema_name(schema.name());
6577 sql_bail!(
6578 "schema {} cannot be dropped without CASCADE while it contains non-owned objects",
6579 full_schema_name.to_string().quoted()
6580 );
6581 }
6582 }
6583 drop_ids.push((*schema.database(), *schema.id()).into())
6584 }
6585 update_privilege_revokes(
6586 SystemObjectId::Object((*schema.database(), *schema.id()).into()),
6587 schema.privileges(),
6588 &role_ids,
6589 &mut privilege_revokes,
6590 );
6591 }
6592 }
6593
6594 for database in scx.catalog.get_databases() {
6596 if role_ids.contains(&database.owner_id()) {
6597 if !cascade {
6598 let non_owned_schemas: Vec<_> = database
6599 .schemas()
6600 .into_iter()
6601 .filter(|schema| !role_ids.contains(&schema.owner_id()))
6602 .collect();
6603 if !non_owned_schemas.is_empty() {
6604 sql_bail!(
6605 "database {} cannot be dropped without CASCADE while it contains non-owned schemas",
6606 database.name().quoted(),
6607 );
6608 }
6609 }
6610 drop_ids.push(database.id().into());
6611 }
6612 update_privilege_revokes(
6613 SystemObjectId::Object(database.id().into()),
6614 database.privileges(),
6615 &role_ids,
6616 &mut privilege_revokes,
6617 );
6618 }
6619
6620 for network_policy in scx.catalog.get_network_policies() {
6622 if role_ids.contains(&network_policy.owner_id()) {
6623 drop_ids.push(ObjectId::NetworkPolicy(network_policy.id()));
6624 }
6625 update_privilege_revokes(
6626 SystemObjectId::Object(ObjectId::NetworkPolicy(network_policy.id())),
6627 network_policy.privileges(),
6628 &role_ids,
6629 &mut privilege_revokes,
6630 );
6631 }
6632
6633 for policy in scx.catalog.get_query_policies() {
6635 if role_ids.contains(&policy.owner_id()) {
6636 drop_ids.push(ObjectId::QueryPolicy(policy.id()));
6637 }
6638 update_privilege_revokes(
6639 SystemObjectId::Object(ObjectId::QueryPolicy(policy.id())),
6640 policy.privileges(),
6641 &role_ids,
6642 &mut privilege_revokes,
6643 );
6644 }
6645
6646 update_privilege_revokes(
6647 SystemObjectId::System,
6648 scx.catalog.get_system_privileges(),
6649 &role_ids,
6650 &mut privilege_revokes,
6651 );
6652
6653 for (default_privilege_object, default_privilege_acl_items) in
6654 scx.catalog.get_default_privileges()
6655 {
6656 for default_privilege_acl_item in default_privilege_acl_items {
6657 if role_ids.contains(&default_privilege_object.role_id)
6658 || role_ids.contains(&default_privilege_acl_item.grantee)
6659 {
6660 default_privilege_revokes.push((
6661 default_privilege_object.clone(),
6662 default_privilege_acl_item.clone(),
6663 ));
6664 }
6665 }
6666 }
6667
6668 let drop_ids = scx.catalog.object_dependents(&drop_ids);
6669
6670 let system_ids: Vec<_> = drop_ids.iter().filter(|id| id.is_system()).collect();
6671 if !system_ids.is_empty() {
6672 let mut owners = system_ids
6673 .into_iter()
6674 .filter_map(|object_id| scx.catalog.get_owner_id(object_id))
6675 .collect::<BTreeSet<_>>()
6676 .into_iter()
6677 .map(|role_id| scx.catalog.get_role(&role_id).name().quoted());
6678 sql_bail!(
6679 "cannot drop objects owned by role {} because they are required by the database system",
6680 owners.join(", "),
6681 );
6682 }
6683
6684 Ok(Plan::DropOwned(DropOwnedPlan {
6685 cascade,
6686 role_ids: role_ids.into_iter().collect(),
6687 drop_ids,
6688 privilege_revokes,
6689 default_privilege_revokes,
6690 }))
6691}
6692
6693fn plan_retain_history_option(
6694 scx: &StatementContext,
6695 retain_history: Option<OptionalDuration>,
6696) -> Result<Option<CompactionWindow>, PlanError> {
6697 if let Some(OptionalDuration(lcw)) = retain_history {
6698 Ok(Some(plan_retain_history(scx, lcw)?))
6699 } else {
6700 Ok(None)
6701 }
6702}
6703
6704fn plan_retain_history(
6710 scx: &StatementContext,
6711 lcw: Option<Duration>,
6712) -> Result<CompactionWindow, PlanError> {
6713 scx.require_feature_flag(&vars::ENABLE_LOGICAL_COMPACTION_WINDOW)?;
6714 match lcw {
6715 Some(Duration::ZERO) => Err(PlanError::InvalidOptionValue {
6720 option_name: "RETAIN HISTORY".to_string(),
6721 err: Box::new(PlanError::Unstructured(
6722 "internal error: unexpectedly zero".to_string(),
6723 )),
6724 }),
6725 Some(duration) => {
6726 if duration < DEFAULT_LOGICAL_COMPACTION_WINDOW_DURATION
6729 && scx
6730 .require_feature_flag(&vars::ENABLE_UNLIMITED_RETAIN_HISTORY)
6731 .is_err()
6732 {
6733 return Err(PlanError::RetainHistoryLow {
6734 limit: DEFAULT_LOGICAL_COMPACTION_WINDOW_DURATION,
6735 });
6736 }
6737 Ok(duration.try_into()?)
6738 }
6739 None => {
6742 if scx
6743 .require_feature_flag(&vars::ENABLE_UNLIMITED_RETAIN_HISTORY)
6744 .is_err()
6745 {
6746 Err(PlanError::RetainHistoryRequired)
6747 } else {
6748 Ok(CompactionWindow::DisableCompaction)
6749 }
6750 }
6751 }
6752}
6753
6754generate_extracted_config!(IndexOption, (RetainHistory, OptionalDuration));
6755
6756fn plan_index_options(
6757 scx: &StatementContext,
6758 with_opts: Vec<IndexOption<Aug>>,
6759) -> Result<Vec<crate::plan::IndexOption>, PlanError> {
6760 if !with_opts.is_empty() {
6761 scx.require_feature_flag(&vars::ENABLE_INDEX_OPTIONS)?;
6763 }
6764
6765 let IndexOptionExtracted { retain_history, .. }: IndexOptionExtracted = with_opts.try_into()?;
6766
6767 let mut out = Vec::with_capacity(1);
6768 if let Some(cw) = plan_retain_history_option(scx, retain_history)? {
6769 out.push(crate::plan::IndexOption::RetainHistory(cw));
6770 }
6771 Ok(out)
6772}
6773
6774generate_extracted_config!(
6775 TableOption,
6776 (PartitionBy, Vec<Ident>),
6777 (RetainHistory, OptionalDuration),
6778 (RedactedTest, String)
6779);
6780
6781fn plan_table_options(
6782 scx: &StatementContext,
6783 desc: &RelationDesc,
6784 with_opts: Vec<TableOption<Aug>>,
6785) -> Result<Vec<crate::plan::TableOption>, PlanError> {
6786 let TableOptionExtracted {
6787 partition_by,
6788 retain_history,
6789 redacted_test,
6790 ..
6791 }: TableOptionExtracted = with_opts.try_into()?;
6792
6793 if let Some(partition_by) = partition_by {
6794 scx.require_feature_flag(&ENABLE_COLLECTION_PARTITION_BY)?;
6795 check_partition_by(desc, partition_by)?;
6796 }
6797
6798 if redacted_test.is_some() {
6799 scx.require_feature_flag(&vars::ENABLE_REDACTED_TEST_OPTION)?;
6800 }
6801
6802 let mut out = Vec::with_capacity(1);
6803 if let Some(cw) = plan_retain_history_option(scx, retain_history)? {
6804 out.push(crate::plan::TableOption::RetainHistory(cw));
6805 }
6806 Ok(out)
6807}
6808
6809pub fn plan_alter_index_options(
6810 scx: &mut StatementContext,
6811 AlterIndexStatement {
6812 index_name,
6813 if_exists,
6814 action,
6815 }: AlterIndexStatement<Aug>,
6816) -> Result<Plan, PlanError> {
6817 let object_type = ObjectType::Index;
6818 match action {
6819 AlterIndexAction::ResetOptions(options) => {
6820 let mut options = options.into_iter();
6821 if let Some(opt) = options.next() {
6822 match opt {
6823 IndexOptionName::RetainHistory => {
6824 if options.next().is_some() {
6825 sql_bail!("RETAIN HISTORY must be only option");
6826 }
6827 return alter_retain_history(
6828 scx,
6829 object_type,
6830 if_exists,
6831 UnresolvedObjectName::Item(index_name),
6832 None,
6833 );
6834 }
6835 }
6836 }
6837 sql_bail!("expected option");
6838 }
6839 AlterIndexAction::SetOptions(options) => {
6840 let mut options = options.into_iter();
6841 if let Some(opt) = options.next() {
6842 match opt.name {
6843 IndexOptionName::RetainHistory => {
6844 if options.next().is_some() {
6845 sql_bail!("RETAIN HISTORY must be only option");
6846 }
6847 return alter_retain_history(
6848 scx,
6849 object_type,
6850 if_exists,
6851 UnresolvedObjectName::Item(index_name),
6852 opt.value,
6853 );
6854 }
6855 }
6856 }
6857 sql_bail!("expected option");
6858 }
6859 }
6860}
6861
6862pub fn describe_alter_cluster_set_options(
6863 _: &StatementContext,
6864 _: AlterClusterStatement<Aug>,
6865) -> Result<StatementDesc, PlanError> {
6866 Ok(StatementDesc::new(None))
6867}
6868
6869pub fn plan_alter_cluster(
6870 scx: &mut StatementContext,
6871 AlterClusterStatement {
6872 name,
6873 action,
6874 if_exists,
6875 }: AlterClusterStatement<Aug>,
6876) -> Result<Plan, PlanError> {
6877 let cluster = match resolve_cluster(scx, &name, if_exists)? {
6878 Some(entry) => entry,
6879 None => {
6880 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
6881 name: name.to_ast_string_simple(),
6882 object_type: ObjectType::Cluster,
6883 });
6884
6885 return Ok(Plan::AlterNoop(AlterNoopPlan {
6886 object_type: ObjectType::Cluster,
6887 }));
6888 }
6889 };
6890
6891 let mut options: PlanClusterOption = Default::default();
6892 let mut alter_strategy: AlterClusterPlanStrategy = AlterClusterPlanStrategy::None;
6893
6894 match action {
6895 AlterClusterAction::SetOptions {
6896 options: set_options,
6897 with_options,
6898 } => {
6899 let ClusterOptionExtracted {
6900 auto_scaling_strategy,
6901 availability_zones,
6902 experimental_arrangement_compression,
6903 introspection_debugging,
6904 introspection_interval,
6905 managed,
6906 replicas: replica_defs,
6907 replication_factor,
6908 seen: _,
6909 size,
6910 disk,
6911 schedule,
6912 workload_class,
6913 query_policy,
6914 }: ClusterOptionExtracted = set_options.try_into()?;
6915
6916 if !scx.catalog.active_role_id().is_system() {
6917 if workload_class.is_some() {
6918 sql_bail!("WORKLOAD CLASS not supported for non-system users");
6919 }
6920 }
6921
6922 match managed.unwrap_or_else(|| cluster.is_managed()) {
6923 true => {
6924 let alter_strategy_extracted =
6925 ClusterAlterOptionExtracted::try_from(with_options)?;
6926 alter_strategy = AlterClusterPlanStrategy::try_from(alter_strategy_extracted)?;
6927
6928 if !matches!(alter_strategy, AlterClusterPlanStrategy::None)
6932 && size.is_none()
6933 && replication_factor.is_none()
6934 && availability_zones.is_none()
6935 && introspection_debugging.is_none()
6936 && introspection_interval.is_none()
6937 && experimental_arrangement_compression.is_none()
6938 {
6939 sql_bail!(
6940 "WAIT can only be used together with a SIZE, REPLICATION FACTOR, \
6941 AVAILABILITY ZONES, INTROSPECTION, or EXPERIMENTAL ARRANGEMENT COMPRESSION change"
6942 );
6943 }
6944
6945 if replica_defs.is_some() {
6946 sql_bail!("REPLICAS not supported for managed clusters");
6947 }
6948 if schedule.is_some()
6949 && !matches!(schedule, Some(ClusterScheduleOptionValue::Manual))
6950 {
6951 scx.require_feature_flag(&ENABLE_CLUSTER_SCHEDULE_REFRESH)?;
6952
6953 if replication_factor.is_none()
6962 && cluster.replication_factor().is_some_and(|rf| rf > 1)
6963 {
6964 sql_bail!(
6965 "SCHEDULE cannot be set to anything other than MANUAL while the \
6966 cluster's REPLICATION FACTOR is greater than 1; \
6967 set the REPLICATION FACTOR to 1 first"
6968 );
6969 }
6970 }
6971
6972 if replication_factor.is_some() {
6973 if schedule.is_some()
6974 && !matches!(schedule, Some(ClusterScheduleOptionValue::Manual))
6975 {
6976 sql_bail!(
6977 "REPLICATION FACTOR cannot be given together with any SCHEDULE other than MANUAL"
6978 );
6979 }
6980 if let Some(current_schedule) = cluster.schedule() {
6981 if !matches!(current_schedule, ClusterSchedule::Manual) {
6982 sql_bail!(
6983 "REPLICATION FACTOR cannot be set if the cluster SCHEDULE is anything other than MANUAL"
6984 );
6985 }
6986 }
6987 }
6988
6989 if let Some(value) = auto_scaling_strategy {
6990 scx.require_feature_flag(&ENABLE_AUTO_SCALING_STRATEGY)?;
6991 let strategy = plan_auto_scaling_strategy(value)?;
6992 options.auto_scaling_strategy = AlterOptionParameter::Set(strategy);
6993 }
6994
6995 let effective_strategy = match &options.auto_scaling_strategy {
6999 AlterOptionParameter::Set(s) => s.clone(),
7000 AlterOptionParameter::Reset => None,
7001 AlterOptionParameter::Unchanged => cluster.auto_scaling_strategy().cloned(),
7002 };
7003 if let Some(effective_strategy) = &effective_strategy {
7004 let effective_size = size.as_deref().or_else(|| cluster.managed_size());
7005 let schedule_non_manual = match &schedule {
7006 Some(s) => !matches!(s, ClusterScheduleOptionValue::Manual),
7007 None => cluster
7008 .schedule()
7009 .is_some_and(|s| !matches!(s, ClusterSchedule::Manual)),
7010 };
7011 validate_auto_scaling_strategy(
7012 effective_strategy,
7013 effective_size,
7014 schedule_non_manual,
7015 )?;
7016 }
7017 }
7018 false => {
7019 if !with_options.is_empty() {
7020 sql_bail!("ALTER... WITH not supported for unmanaged clusters");
7021 }
7022 if auto_scaling_strategy.is_some() {
7023 sql_bail!("AUTO SCALING STRATEGY not supported for unmanaged clusters");
7024 }
7025 if availability_zones.is_some() {
7026 sql_bail!("AVAILABILITY ZONES not supported for unmanaged clusters");
7027 }
7028 if replication_factor.is_some() {
7029 sql_bail!("REPLICATION FACTOR not supported for unmanaged clusters");
7030 }
7031 if introspection_debugging.is_some() {
7032 sql_bail!("INTROSPECTION DEBUGGING not supported for unmanaged clusters");
7033 }
7034 if introspection_interval.is_some() {
7035 sql_bail!("INTROSPECTION INTERVAL not supported for unmanaged clusters");
7036 }
7037 if experimental_arrangement_compression.is_some() {
7038 sql_bail!(
7039 "EXPERIMENTAL ARRANGEMENT COMPRESSION not supported for unmanaged clusters"
7040 );
7041 }
7042 if size.is_some() {
7043 sql_bail!("SIZE not supported for unmanaged clusters");
7044 }
7045 if disk.is_some() {
7046 sql_bail!("DISK not supported for unmanaged clusters");
7047 }
7048 if schedule.is_some()
7049 && !matches!(schedule, Some(ClusterScheduleOptionValue::Manual))
7050 {
7051 sql_bail!(
7052 "cluster schedules other than MANUAL are not supported for unmanaged clusters"
7053 );
7054 }
7055 if let Some(current_schedule) = cluster.schedule() {
7056 if !matches!(current_schedule, ClusterSchedule::Manual)
7057 && schedule.is_none()
7058 {
7059 sql_bail!(
7060 "when switching a cluster to unmanaged, if the managed \
7061 cluster's SCHEDULE is anything other than MANUAL, you have to \
7062 explicitly set the SCHEDULE to MANUAL"
7063 );
7064 }
7065 }
7066 }
7067 }
7068
7069 let mut replicas = vec![];
7070 for ReplicaDefinition { name, options } in
7071 replica_defs.into_iter().flat_map(Vec::into_iter)
7072 {
7073 replicas.push((normalize::ident(name), plan_replica_config(scx, options)?));
7074 }
7075
7076 if let Some(managed) = managed {
7077 options.managed = AlterOptionParameter::Set(managed);
7078 }
7079 if let Some(replication_factor) = replication_factor {
7080 options.replication_factor = AlterOptionParameter::Set(replication_factor);
7081 } else if schedule
7082 .as_ref()
7083 .is_some_and(|s| !matches!(s, ClusterScheduleOptionValue::Manual))
7084 && managed != Some(true)
7085 {
7086 options.replication_factor = AlterOptionParameter::Set(0);
7099 }
7100 if let Some(size) = &size {
7101 options.size = AlterOptionParameter::Set(size.clone());
7102 }
7103 if let Some(availability_zones) = availability_zones {
7104 options.availability_zones = AlterOptionParameter::Set(availability_zones);
7105 }
7106 if let Some(introspection_debugging) = introspection_debugging {
7107 options.introspection_debugging =
7108 AlterOptionParameter::Set(introspection_debugging);
7109 }
7110 if let Some(introspection_interval) = introspection_interval {
7111 options.introspection_interval = AlterOptionParameter::Set(introspection_interval);
7112 }
7113 if let Some(experimental_arrangement_compression) = experimental_arrangement_compression
7114 {
7115 options.arrangement_compression =
7116 AlterOptionParameter::Set(experimental_arrangement_compression);
7117 }
7118 if disk.is_some() {
7119 let size = match size.as_deref() {
7123 Some(s) => s,
7124 None => cluster
7125 .managed_size()
7126 .ok_or_else(|| sql_err!("cluster is not managed"))?,
7127 };
7128 if scx.catalog.is_cluster_size_cc(size) {
7129 sql_bail!(
7130 "DISK option not supported for modern cluster sizes because disk is always enabled"
7131 );
7132 }
7133
7134 scx.catalog
7135 .add_notice(PlanNotice::ReplicaDiskOptionDeprecated);
7136 }
7137 if !replicas.is_empty() {
7138 options.replicas = AlterOptionParameter::Set(replicas);
7139 }
7140 if let Some(schedule) = schedule {
7141 options.schedule = AlterOptionParameter::Set(plan_cluster_schedule(schedule)?);
7142 }
7143 if let Some(workload_class) = workload_class {
7144 options.workload_class = AlterOptionParameter::Set(workload_class.0);
7145 }
7146 if let Some(query_policy) = query_policy {
7147 if query_policy.0.is_some() {
7149 scx.require_feature_flag(&vars::ENABLE_QUERY_POLICIES)?;
7150 }
7151 options.query_policy = AlterOptionParameter::Set(
7152 query_policy
7153 .0
7154 .map(|name| scx.catalog.resolve_query_policy(&name).map(|p| p.id()))
7155 .transpose()?,
7156 );
7157 }
7158 }
7159 AlterClusterAction::ResetOptions(reset_options) => {
7160 use AlterOptionParameter::Reset;
7161 use ClusterOptionName::*;
7162
7163 if !scx.catalog.active_role_id().is_system() {
7164 if reset_options.contains(&WorkloadClass) {
7165 sql_bail!("WORKLOAD CLASS not supported for non-system users");
7166 }
7167 }
7168
7169 for option in reset_options {
7175 match option {
7176 AutoScalingStrategy => options.auto_scaling_strategy = Reset,
7177 AvailabilityZones => options.availability_zones = Reset,
7178 Disk => scx
7179 .catalog
7180 .add_notice(PlanNotice::ReplicaDiskOptionDeprecated),
7181 IntrospectionInterval => options.introspection_interval = Reset,
7182 IntrospectionDebugging => options.introspection_debugging = Reset,
7183 ExperimentalArrangementCompression => options.arrangement_compression = Reset,
7184 Managed => options.managed = Reset,
7185 Replicas => options.replicas = Reset,
7186 ReplicationFactor => options.replication_factor = Reset,
7187 Size => options.size = Reset,
7188 Schedule => options.schedule = Reset,
7189 WorkloadClass => options.workload_class = Reset,
7190 QueryPolicy => options.query_policy = Reset,
7191 }
7192 }
7193 }
7194 }
7195 Ok(Plan::AlterCluster(AlterClusterPlan {
7196 id: cluster.id(),
7197 name: cluster.name().to_string(),
7198 options,
7199 strategy: alter_strategy,
7200 }))
7201}
7202
7203pub fn describe_alter_set_cluster(
7204 _: &StatementContext,
7205 _: AlterSetClusterStatement<Aug>,
7206) -> Result<StatementDesc, PlanError> {
7207 Ok(StatementDesc::new(None))
7208}
7209
7210pub fn plan_alter_item_set_cluster(
7211 scx: &StatementContext,
7212 AlterSetClusterStatement {
7213 if_exists,
7214 set_cluster: in_cluster_name,
7215 name,
7216 object_type,
7217 }: AlterSetClusterStatement<Aug>,
7218) -> Result<Plan, PlanError> {
7219 scx.require_feature_flag(&vars::ENABLE_ALTER_SET_CLUSTER)?;
7220
7221 let object_type = object_type.into();
7222
7223 match object_type {
7225 ObjectType::MaterializedView => {}
7226 ObjectType::Index | ObjectType::Sink | ObjectType::MetricSink | ObjectType::Source => {
7227 bail_unsupported!(29606, format!("ALTER {object_type} SET CLUSTER"))
7228 }
7229 ObjectType::Table
7230 | ObjectType::View
7231 | ObjectType::Type
7232 | ObjectType::Role
7233 | ObjectType::Cluster
7234 | ObjectType::ClusterReplica
7235 | ObjectType::Secret
7236 | ObjectType::Connection
7237 | ObjectType::Database
7238 | ObjectType::Schema
7239 | ObjectType::Func
7240 | ObjectType::NetworkPolicy
7241 | ObjectType::QueryPolicy => {
7242 bail_never_supported!(
7243 format!("ALTER {object_type} SET CLUSTER"),
7244 "sql/alter-set-cluster/",
7245 format!("{object_type} has no associated cluster")
7246 )
7247 }
7248 }
7249
7250 let in_cluster = scx.catalog.get_cluster(in_cluster_name.id);
7251
7252 match resolve_item_or_type(scx, object_type, name.clone(), if_exists)? {
7253 Some(entry) => {
7254 let current_cluster = entry.cluster_id();
7255 let Some(current_cluster) = current_cluster else {
7256 sql_bail!("No cluster associated with {name}");
7257 };
7258
7259 if current_cluster == in_cluster.id() {
7260 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7261 } else {
7262 Ok(Plan::AlterSetCluster(AlterSetClusterPlan {
7263 id: entry.id(),
7264 set_cluster: in_cluster.id(),
7265 }))
7266 }
7267 }
7268 None => {
7269 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7270 name: name.to_ast_string_simple(),
7271 object_type,
7272 });
7273
7274 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7275 }
7276 }
7277}
7278
7279pub fn describe_alter_object_rename(
7280 _: &StatementContext,
7281 _: AlterObjectRenameStatement,
7282) -> Result<StatementDesc, PlanError> {
7283 Ok(StatementDesc::new(None))
7284}
7285
7286pub fn plan_alter_object_rename(
7287 scx: &mut StatementContext,
7288 AlterObjectRenameStatement {
7289 name,
7290 object_type,
7291 to_item_name,
7292 if_exists,
7293 }: AlterObjectRenameStatement,
7294) -> Result<Plan, PlanError> {
7295 let object_type = object_type.into();
7296 match (object_type, name) {
7297 (
7298 ObjectType::View
7299 | ObjectType::MaterializedView
7300 | ObjectType::Table
7301 | ObjectType::Source
7302 | ObjectType::Index
7303 | ObjectType::Sink
7304 | ObjectType::Secret
7305 | ObjectType::Connection,
7306 UnresolvedObjectName::Item(name),
7307 ) => plan_alter_item_rename(scx, object_type, name, to_item_name, if_exists),
7308 (ObjectType::Cluster, UnresolvedObjectName::Cluster(name)) => {
7309 plan_alter_cluster_rename(scx, object_type, name, to_item_name, if_exists)
7310 }
7311 (ObjectType::ClusterReplica, UnresolvedObjectName::ClusterReplica(name)) => {
7312 plan_alter_cluster_replica_rename(scx, object_type, name, to_item_name, if_exists)
7313 }
7314 (ObjectType::Schema, UnresolvedObjectName::Schema(name)) => {
7315 plan_alter_schema_rename(scx, name, to_item_name, if_exists)
7316 }
7317 (object_type, name) => {
7318 bail_internal!("invalid object type '{object_type}' for ALTER RENAME with name {name}")
7321 }
7322 }
7323}
7324
7325pub fn plan_alter_schema_rename(
7326 scx: &mut StatementContext,
7327 name: UnresolvedSchemaName,
7328 to_schema_name: Ident,
7329 if_exists: bool,
7330) -> Result<Plan, PlanError> {
7331 let normalized = normalize::unresolved_schema_name(name.clone())?;
7335 if normalized.database.is_none() && normalized.schema == mz_repr::namespaces::MZ_TEMP_SCHEMA {
7336 sql_bail!(
7337 "cannot rename schemas in the ambient database: {:?}",
7338 mz_repr::namespaces::MZ_TEMP_SCHEMA
7339 );
7340 }
7341
7342 let Some((db_spec, schema_spec)) = resolve_schema(scx, name.clone(), if_exists)? else {
7343 let object_type = ObjectType::Schema;
7344 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7345 name: name.to_ast_string_simple(),
7346 object_type,
7347 });
7348 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
7349 };
7350
7351 if scx
7353 .resolve_schema_in_database(&db_spec, &to_schema_name)
7354 .is_ok()
7355 {
7356 return Err(PlanError::Catalog(CatalogError::SchemaAlreadyExists(
7357 to_schema_name.clone().into_string(),
7358 )));
7359 }
7360
7361 let schema = scx.catalog.get_schema(&db_spec, &schema_spec);
7363 if schema.id().is_system() {
7364 bail_never_supported!(format!("renaming the {} schema", schema.name().schema))
7365 }
7366
7367 Ok(Plan::AlterSchemaRename(AlterSchemaRenamePlan {
7368 cur_schema_spec: (db_spec, schema_spec),
7369 new_schema_name: to_schema_name.into_string(),
7370 }))
7371}
7372
7373pub fn plan_alter_schema_swap<F>(
7374 scx: &mut StatementContext,
7375 name_a: UnresolvedSchemaName,
7376 name_b: Ident,
7377 if_exists: bool,
7378 gen_temp_suffix: F,
7379) -> Result<Plan, PlanError>
7380where
7381 F: Fn(&dyn Fn(&str) -> bool) -> Result<String, PlanError>,
7382{
7383 let normalized_a = normalize::unresolved_schema_name(name_a.clone())?;
7387 if normalized_a.database.is_none() && normalized_a.schema == mz_repr::namespaces::MZ_TEMP_SCHEMA
7388 {
7389 sql_bail!("cannot swap schemas that are in the ambient database");
7390 }
7391 let name_b_str = normalize::ident_ref(&name_b);
7393 if name_b_str == mz_repr::namespaces::MZ_TEMP_SCHEMA {
7394 sql_bail!("cannot swap schemas that are in the ambient database");
7395 }
7396
7397 let schema_a = match scx.resolve_schema(name_a.clone()) {
7398 Ok(schema) => schema,
7399 Err(_) if if_exists => {
7400 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7401 name: name_a.to_ast_string_simple(),
7402 object_type: ObjectType::Schema,
7403 });
7404 return Ok(Plan::AlterNoop(AlterNoopPlan {
7405 object_type: ObjectType::Schema,
7406 }));
7407 }
7408 Err(e) => return Err(e),
7409 };
7410
7411 let db_spec = schema_a.database().clone();
7412 if matches!(db_spec, ResolvedDatabaseSpecifier::Ambient) {
7413 sql_bail!("cannot swap schemas that are in the ambient database");
7414 };
7415 let schema_b = scx.resolve_schema_in_database(&db_spec, &name_b)?;
7416
7417 if schema_a.id().is_system() || schema_b.id().is_system() {
7419 bail_never_supported!("swapping a system schema".to_string())
7420 }
7421
7422 const SCHEMA_SWAP_PREFIX: &str = "mz_schema_swap_";
7426 let check = |temp_suffix: &str| {
7427 let mut temp_name = ident!(SCHEMA_SWAP_PREFIX);
7428 temp_name.append_lossy(temp_suffix);
7429 scx.resolve_schema_in_database(&db_spec, &temp_name)
7430 .is_err()
7431 };
7432 let temp_suffix = gen_temp_suffix(&check)?;
7433 let name_temp = format!("{SCHEMA_SWAP_PREFIX}{temp_suffix}");
7434
7435 Ok(Plan::AlterSchemaSwap(AlterSchemaSwapPlan {
7436 schema_a_spec: (*schema_a.database(), *schema_a.id()),
7437 schema_a_name: schema_a.name().schema.to_string(),
7438 schema_b_spec: (*schema_b.database(), *schema_b.id()),
7439 schema_b_name: schema_b.name().schema.to_string(),
7440 name_temp,
7441 }))
7442}
7443
7444pub fn plan_alter_item_rename(
7445 scx: &mut StatementContext,
7446 object_type: ObjectType,
7447 name: UnresolvedItemName,
7448 to_item_name: Ident,
7449 if_exists: bool,
7450) -> Result<Plan, PlanError> {
7451 let resolved = match resolve_item_or_type(scx, object_type, name.clone(), if_exists) {
7452 Ok(r) => r,
7453 Err(PlanError::MismatchedObjectType {
7455 name,
7456 is_type: ObjectType::MaterializedView,
7457 expected_type: ObjectType::View,
7458 }) => {
7459 return Err(PlanError::AlterViewOnMaterializedView(name.to_string()));
7460 }
7461 e => e?,
7462 };
7463
7464 match resolved {
7465 Some(entry) => {
7466 let full_name = scx.catalog.resolve_full_name(entry.name());
7467 let item_type = entry.item_type();
7468
7469 let proposed_name = QualifiedItemName {
7470 qualifiers: entry.name().qualifiers.clone(),
7471 item: to_item_name.clone().into_string(),
7472 };
7473
7474 let conflicting_type_exists;
7478 let conflicting_item_exists;
7479 if item_type == CatalogItemType::Type {
7480 conflicting_type_exists = scx.catalog.get_type_by_name(&proposed_name).is_some();
7481 conflicting_item_exists = scx
7482 .catalog
7483 .get_item_by_name(&proposed_name)
7484 .map(|item| item.item_type().conflicts_with_type())
7485 .unwrap_or(false);
7486 } else {
7487 conflicting_type_exists = item_type.conflicts_with_type()
7488 && scx.catalog.get_type_by_name(&proposed_name).is_some();
7489 conflicting_item_exists = scx.catalog.get_item_by_name(&proposed_name).is_some();
7490 };
7491 if conflicting_type_exists || conflicting_item_exists {
7492 sql_bail!("catalog item '{}' already exists", to_item_name);
7493 }
7494
7495 Ok(Plan::AlterItemRename(AlterItemRenamePlan {
7496 id: entry.id(),
7497 current_full_name: full_name,
7498 to_name: normalize::ident(to_item_name),
7499 object_type,
7500 }))
7501 }
7502 None => {
7503 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7504 name: name.to_ast_string_simple(),
7505 object_type,
7506 });
7507
7508 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7509 }
7510 }
7511}
7512
7513pub fn plan_alter_cluster_rename(
7514 scx: &mut StatementContext,
7515 object_type: ObjectType,
7516 name: Ident,
7517 to_name: Ident,
7518 if_exists: bool,
7519) -> Result<Plan, PlanError> {
7520 match resolve_cluster(scx, &name, if_exists)? {
7521 Some(entry) => Ok(Plan::AlterClusterRename(AlterClusterRenamePlan {
7522 id: entry.id(),
7523 name: entry.name().to_string(),
7524 to_name: ident(to_name),
7525 })),
7526 None => {
7527 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7528 name: name.to_ast_string_simple(),
7529 object_type,
7530 });
7531
7532 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7533 }
7534 }
7535}
7536
7537pub fn plan_alter_cluster_swap<F>(
7538 scx: &mut StatementContext,
7539 name_a: Ident,
7540 name_b: Ident,
7541 if_exists: bool,
7542 gen_temp_suffix: F,
7543) -> Result<Plan, PlanError>
7544where
7545 F: Fn(&dyn Fn(&str) -> bool) -> Result<String, PlanError>,
7546{
7547 let cluster_a = match scx.resolve_cluster(Some(&name_a)) {
7548 Ok(cluster) => cluster,
7549 Err(_) if if_exists => {
7550 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7551 name: name_a.to_ast_string_simple(),
7552 object_type: ObjectType::Cluster,
7553 });
7554 return Ok(Plan::AlterNoop(AlterNoopPlan {
7555 object_type: ObjectType::Cluster,
7556 }));
7557 }
7558 Err(e) => return Err(e),
7559 };
7560 let cluster_b = scx.resolve_cluster(Some(&name_b))?;
7561
7562 const CLUSTER_SWAP_PREFIX: &str = "mz_cluster_swap_";
7563 let check = |temp_suffix: &str| {
7564 let mut temp_name = ident!(CLUSTER_SWAP_PREFIX);
7565 temp_name.append_lossy(temp_suffix);
7566 match scx.catalog.resolve_cluster(Some(temp_name.as_str())) {
7567 Err(CatalogError::UnknownCluster(_)) => true,
7569 Ok(_) | Err(_) => false,
7571 }
7572 };
7573 let temp_suffix = gen_temp_suffix(&check)?;
7574 let name_temp = format!("{CLUSTER_SWAP_PREFIX}{temp_suffix}");
7575
7576 Ok(Plan::AlterClusterSwap(AlterClusterSwapPlan {
7577 id_a: cluster_a.id(),
7578 id_b: cluster_b.id(),
7579 name_a: name_a.into_string(),
7580 name_b: name_b.into_string(),
7581 name_temp,
7582 }))
7583}
7584
7585pub fn plan_alter_cluster_replica_rename(
7586 scx: &mut StatementContext,
7587 object_type: ObjectType,
7588 name: QualifiedReplica,
7589 to_item_name: Ident,
7590 if_exists: bool,
7591) -> Result<Plan, PlanError> {
7592 match resolve_cluster_replica(scx, &name, if_exists)? {
7593 Some((cluster, replica)) => {
7594 ensure_cluster_is_not_managed(scx, cluster.id())?;
7595 Ok(Plan::AlterClusterReplicaRename(
7596 AlterClusterReplicaRenamePlan {
7597 cluster_id: cluster.id(),
7598 replica_id: replica,
7599 name: QualifiedReplica {
7600 cluster: Ident::new(cluster.name())?,
7601 replica: name.replica,
7602 },
7603 to_name: normalize::ident(to_item_name),
7604 },
7605 ))
7606 }
7607 None => {
7608 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7609 name: name.to_ast_string_simple(),
7610 object_type,
7611 });
7612
7613 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7614 }
7615 }
7616}
7617
7618pub fn describe_alter_object_swap(
7619 _: &StatementContext,
7620 _: AlterObjectSwapStatement,
7621) -> Result<StatementDesc, PlanError> {
7622 Ok(StatementDesc::new(None))
7623}
7624
7625pub fn plan_alter_object_swap(
7626 scx: &mut StatementContext,
7627 stmt: AlterObjectSwapStatement,
7628) -> Result<Plan, PlanError> {
7629 scx.require_feature_flag(&vars::ENABLE_ALTER_SWAP)?;
7630
7631 let AlterObjectSwapStatement {
7632 object_type,
7633 if_exists,
7634 name_a,
7635 name_b,
7636 } = stmt;
7637 let object_type = object_type.into();
7638
7639 let gen_temp_suffix = |check_fn: &dyn Fn(&str) -> bool| {
7641 let mut attempts = 0;
7642 let name_temp = loop {
7643 attempts += 1;
7644 if attempts > 10 {
7645 tracing::warn!("Unable to generate temp id for swapping");
7646 sql_bail!("unable to swap!");
7647 }
7648
7649 let short_id = mz_ore::id_gen::temp_id();
7651 if check_fn(&short_id) {
7652 break short_id;
7653 }
7654 };
7655
7656 Ok(name_temp)
7657 };
7658
7659 match (object_type, name_a, name_b) {
7660 (ObjectType::Schema, UnresolvedObjectName::Schema(name_a), name_b) => {
7661 plan_alter_schema_swap(scx, name_a, name_b, if_exists, gen_temp_suffix)
7662 }
7663 (ObjectType::Cluster, UnresolvedObjectName::Cluster(name_a), name_b) => {
7664 plan_alter_cluster_swap(scx, name_a, name_b, if_exists, gen_temp_suffix)
7665 }
7666 (ObjectType::Schema | ObjectType::Cluster, _, _) => {
7667 bail_internal!("name type does not match object type for ALTER SWAP")
7668 }
7669 (
7670 ObjectType::Table
7671 | ObjectType::View
7672 | ObjectType::MaterializedView
7673 | ObjectType::Source
7674 | ObjectType::Sink
7675 | ObjectType::MetricSink
7676 | ObjectType::Index
7677 | ObjectType::Type
7678 | ObjectType::Role
7679 | ObjectType::ClusterReplica
7680 | ObjectType::Secret
7681 | ObjectType::Connection
7682 | ObjectType::Database
7683 | ObjectType::Func
7684 | ObjectType::NetworkPolicy
7685 | ObjectType::QueryPolicy,
7686 _,
7687 _,
7688 ) => Err(PlanError::Unsupported {
7689 feature: format!("ALTER {object_type} .. SWAP WITH ..."),
7690 discussion_no: None,
7691 }),
7692 }
7693}
7694
7695pub fn describe_alter_retain_history(
7696 _: &StatementContext,
7697 _: AlterRetainHistoryStatement<Aug>,
7698) -> Result<StatementDesc, PlanError> {
7699 Ok(StatementDesc::new(None))
7700}
7701
7702pub fn plan_alter_retain_history(
7703 scx: &StatementContext,
7704 AlterRetainHistoryStatement {
7705 object_type,
7706 if_exists,
7707 name,
7708 history,
7709 }: AlterRetainHistoryStatement<Aug>,
7710) -> Result<Plan, PlanError> {
7711 alter_retain_history(scx, object_type.into(), if_exists, name, history)
7712}
7713
7714fn alter_retain_history(
7715 scx: &StatementContext,
7716 object_type: ObjectType,
7717 if_exists: bool,
7718 name: UnresolvedObjectName,
7719 history: Option<WithOptionValue<Aug>>,
7720) -> Result<Plan, PlanError> {
7721 let name = match (object_type, name) {
7722 (
7723 ObjectType::View
7725 | ObjectType::MaterializedView
7726 | ObjectType::Table
7727 | ObjectType::Source
7728 | ObjectType::Index,
7729 UnresolvedObjectName::Item(name),
7730 ) => name,
7731 (object_type, _) => {
7732 bail_unsupported!(format!("RETAIN HISTORY on {object_type}"))
7733 }
7734 };
7735 match resolve_item_or_type(scx, object_type, name.clone(), if_exists)? {
7736 Some(entry) => {
7737 let full_name = scx.catalog.resolve_full_name(entry.name());
7738 let item_type = entry.item_type();
7739
7740 if object_type == ObjectType::View && item_type == CatalogItemType::MaterializedView {
7742 return Err(PlanError::AlterViewOnMaterializedView(
7743 full_name.to_string(),
7744 ));
7745 } else if object_type == ObjectType::View {
7746 sql_bail!("{object_type} does not support RETAIN HISTORY")
7747 } else if object_type != item_type {
7748 sql_bail!(
7749 "\"{}\" is a {} not a {}",
7750 full_name,
7751 entry.item_type(),
7752 format!("{object_type}").to_lowercase()
7753 )
7754 }
7755
7756 let (value, lcw) = match &history {
7758 Some(WithOptionValue::RetainHistoryFor(value)) => {
7759 let window = OptionalDuration::try_from_value(value.clone())?;
7760 (Some(value.clone()), window.0)
7761 }
7762 None => (None, Some(DEFAULT_LOGICAL_COMPACTION_WINDOW_DURATION)),
7764 _ => sql_bail!("unexpected value type for RETAIN HISTORY"),
7765 };
7766 let window = plan_retain_history(scx, lcw)?;
7767
7768 Ok(Plan::AlterRetainHistory(AlterRetainHistoryPlan {
7769 id: entry.id(),
7770 value,
7771 window,
7772 object_type,
7773 }))
7774 }
7775 None => {
7776 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7777 name: name.to_ast_string_simple(),
7778 object_type,
7779 });
7780
7781 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7782 }
7783 }
7784}
7785
7786fn alter_source_timestamp_interval(
7787 scx: &StatementContext,
7788 if_exists: bool,
7789 source_name: UnresolvedItemName,
7790 value: Option<WithOptionValue<Aug>>,
7791) -> Result<Plan, PlanError> {
7792 let object_type = ObjectType::Source;
7793 match resolve_item_or_type(scx, object_type, source_name.clone(), if_exists)? {
7794 Some(entry) => {
7795 let full_name = scx.catalog.resolve_full_name(entry.name());
7796 if entry.item_type() != CatalogItemType::Source {
7797 sql_bail!(
7798 "\"{}\" is a {} not a {}",
7799 full_name,
7800 entry.item_type(),
7801 format!("{object_type}").to_lowercase()
7802 )
7803 }
7804
7805 match value {
7806 Some(val) => {
7807 let val = match val {
7808 WithOptionValue::Value(v) => v,
7809 _ => sql_bail!("TIMESTAMP INTERVAL requires an interval value"),
7810 };
7811 let duration = Duration::try_from_value(val.clone())?;
7812
7813 let min = scx.catalog.system_vars().min_timestamp_interval();
7814 let max = scx.catalog.system_vars().max_timestamp_interval();
7815 if duration < min || duration > max {
7816 return Err(PlanError::InvalidTimestampInterval {
7817 min,
7818 max,
7819 requested: duration,
7820 });
7821 }
7822
7823 Ok(Plan::AlterSourceTimestampInterval(
7824 AlterSourceTimestampIntervalPlan {
7825 id: entry.id(),
7826 value: Some(val),
7827 interval: duration,
7828 },
7829 ))
7830 }
7831 None => {
7832 let interval = scx.catalog.system_vars().default_timestamp_interval();
7833 Ok(Plan::AlterSourceTimestampInterval(
7834 AlterSourceTimestampIntervalPlan {
7835 id: entry.id(),
7836 value: None,
7837 interval,
7838 },
7839 ))
7840 }
7841 }
7842 }
7843 None => {
7844 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7845 name: source_name.to_ast_string_simple(),
7846 object_type,
7847 });
7848
7849 Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
7850 }
7851 }
7852}
7853
7854pub fn describe_alter_secret_options(
7855 _: &StatementContext,
7856 _: AlterSecretStatement<Aug>,
7857) -> Result<StatementDesc, PlanError> {
7858 Ok(StatementDesc::new(None))
7859}
7860
7861pub fn plan_alter_secret(
7862 scx: &mut StatementContext,
7863 stmt: AlterSecretStatement<Aug>,
7864) -> Result<Plan, PlanError> {
7865 let AlterSecretStatement {
7866 name,
7867 if_exists,
7868 value,
7869 } = stmt;
7870 let object_type = ObjectType::Secret;
7871 let id = match resolve_item_or_type(scx, object_type, name.clone(), if_exists)? {
7872 Some(entry) => entry.id(),
7873 None => {
7874 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7875 name: name.to_string(),
7876 object_type,
7877 });
7878
7879 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
7880 }
7881 };
7882
7883 let secret_as = query::plan_secret_as(scx, value)?;
7884
7885 Ok(Plan::AlterSecret(AlterSecretPlan { id, secret_as }))
7886}
7887
7888pub fn describe_alter_connection(
7889 _: &StatementContext,
7890 _: AlterConnectionStatement<Aug>,
7891) -> Result<StatementDesc, PlanError> {
7892 Ok(StatementDesc::new(None))
7893}
7894
7895generate_extracted_config!(AlterConnectionOption, (Validate, bool));
7896
7897pub fn plan_alter_connection(
7898 scx: &StatementContext,
7899 stmt: AlterConnectionStatement<Aug>,
7900) -> Result<Plan, PlanError> {
7901 let AlterConnectionStatement {
7902 name,
7903 if_exists,
7904 actions,
7905 with_options,
7906 } = stmt;
7907 let conn_name = normalize::unresolved_item_name(name)?;
7908 let entry = match scx.catalog.resolve_item(&conn_name) {
7909 Ok(entry) => entry,
7910 Err(_) if if_exists => {
7911 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
7912 name: conn_name.to_string(),
7913 object_type: ObjectType::Connection,
7914 });
7915
7916 return Ok(Plan::AlterNoop(AlterNoopPlan {
7917 object_type: ObjectType::Connection,
7918 }));
7919 }
7920 Err(e) => return Err(e.into()),
7921 };
7922
7923 let connection = entry.connection()?;
7924
7925 if actions
7926 .iter()
7927 .any(|action| matches!(action, AlterConnectionAction::RotateKeys))
7928 {
7929 if actions.len() > 1 {
7930 sql_bail!("cannot specify any other actions alongside ALTER CONNECTION...ROTATE KEYS");
7931 }
7932
7933 if !with_options.is_empty() {
7934 sql_bail!(
7935 "ALTER CONNECTION...ROTATE KEYS does not support WITH ({})",
7936 with_options
7937 .iter()
7938 .map(|o| o.to_ast_string_simple())
7939 .join(", ")
7940 );
7941 }
7942
7943 if !matches!(connection, Connection::Ssh(_)) {
7944 sql_bail!(
7945 "{} is not an SSH connection",
7946 scx.catalog.resolve_full_name(entry.name())
7947 )
7948 }
7949
7950 return Ok(Plan::AlterConnection(AlterConnectionPlan {
7951 id: entry.id(),
7952 action: crate::plan::AlterConnectionAction::RotateKeys,
7953 }));
7954 }
7955
7956 let options = AlterConnectionOptionExtracted::try_from(with_options)?;
7957 if options.validate.is_some() {
7958 scx.require_feature_flag(&vars::ENABLE_CONNECTION_VALIDATION_SYNTAX)?;
7959 }
7960
7961 let validate = match options.validate {
7962 Some(val) => val,
7963 None => {
7964 scx.catalog
7965 .system_vars()
7966 .enable_default_connection_validation()
7967 && connection.validate_by_default()
7968 }
7969 };
7970
7971 let connection_type = match connection {
7972 Connection::Aws(_) => CreateConnectionType::Aws,
7973 Connection::AwsPrivatelink(_) => CreateConnectionType::AwsPrivatelink,
7974 Connection::Gcp(_) => CreateConnectionType::Gcp,
7975 Connection::Kafka(_) => CreateConnectionType::Kafka,
7976 Connection::Csr(_) => CreateConnectionType::Csr,
7977 Connection::GlueSchemaRegistry(_) => CreateConnectionType::GlueSchemaRegistry,
7978 Connection::Postgres(_) => CreateConnectionType::Postgres,
7979 Connection::Ssh(_) => CreateConnectionType::Ssh,
7980 Connection::MySql(_) => CreateConnectionType::MySql,
7981 Connection::SqlServer(_) => CreateConnectionType::SqlServer,
7982 Connection::IcebergCatalog(_) => CreateConnectionType::IcebergCatalog,
7983 };
7984
7985 let specified_options: BTreeSet<_> = actions
7987 .iter()
7988 .map(|action: &AlterConnectionAction<Aug>| match action {
7989 AlterConnectionAction::SetOption(option) => Ok(option.name.clone()),
7990 AlterConnectionAction::DropOption(name) => Ok(name.clone()),
7991 AlterConnectionAction::RotateKeys => {
7992 Err(internal_err!("RotateKeys is handled separately above"))
7993 }
7994 })
7995 .collect::<Result<_, PlanError>>()?;
7996
7997 for invalid in INALTERABLE_OPTIONS {
7998 if specified_options.contains(invalid) {
7999 sql_bail!("cannot ALTER {} option {}", connection_type, invalid);
8000 }
8001 }
8002
8003 connection::validate_options_per_connection_type(connection_type, specified_options)?;
8004
8005 let mut set_options_vec: Vec<_> = Vec::new();
8007 let mut drop_options: BTreeSet<_> = BTreeSet::new();
8008 for action in actions {
8009 match action {
8010 AlterConnectionAction::SetOption(option) => set_options_vec.push(option),
8011 AlterConnectionAction::DropOption(name) => {
8012 drop_options.insert(name);
8013 }
8014 AlterConnectionAction::RotateKeys => {
8015 bail_internal!("RotateKeys is handled separately above")
8016 }
8017 }
8018 }
8019
8020 let set_options: BTreeMap<_, _> = set_options_vec
8021 .clone()
8022 .into_iter()
8023 .map(|option| (option.name, option.value))
8024 .collect();
8025
8026 let connection_options_extracted =
8030 connection::ConnectionOptionExtracted::try_from(set_options_vec)?;
8031
8032 let duplicates: Vec<_> = connection_options_extracted
8033 .seen
8034 .intersection(&drop_options)
8035 .collect();
8036
8037 if !duplicates.is_empty() {
8038 sql_bail!(
8039 "cannot both SET and DROP/RESET options {}",
8040 duplicates
8041 .iter()
8042 .map(|option| option.to_string())
8043 .join(", ")
8044 )
8045 }
8046
8047 for mutually_exclusive_options in MUTUALLY_EXCLUSIVE_SETS {
8048 let set_options_count = mutually_exclusive_options
8049 .iter()
8050 .filter(|o| set_options.contains_key(o))
8051 .count();
8052 let drop_options_count = mutually_exclusive_options
8053 .iter()
8054 .filter(|o| drop_options.contains(o))
8055 .count();
8056
8057 if set_options_count > 0 && drop_options_count > 0 {
8059 sql_bail!(
8060 "cannot both SET and DROP/RESET mutually exclusive {} options {}",
8061 connection_type,
8062 mutually_exclusive_options
8063 .iter()
8064 .map(|option| option.to_string())
8065 .join(", ")
8066 )
8067 }
8068
8069 if set_options_count > 0 || drop_options_count > 0 {
8074 drop_options.extend(mutually_exclusive_options.iter().cloned());
8075 }
8076
8077 }
8080
8081 Ok(Plan::AlterConnection(AlterConnectionPlan {
8082 id: entry.id(),
8083 action: crate::plan::AlterConnectionAction::AlterOptions {
8084 set_options,
8085 drop_options,
8086 validate,
8087 },
8088 }))
8089}
8090
8091pub fn describe_alter_sink(
8092 _: &StatementContext,
8093 _: AlterSinkStatement<Aug>,
8094) -> Result<StatementDesc, PlanError> {
8095 Ok(StatementDesc::new(None))
8096}
8097
8098pub fn plan_alter_sink(
8099 scx: &mut StatementContext,
8100 stmt: AlterSinkStatement<Aug>,
8101) -> Result<Plan, PlanError> {
8102 let AlterSinkStatement {
8103 sink_name,
8104 if_exists,
8105 action,
8106 } = stmt;
8107
8108 let object_type = ObjectType::Sink;
8109 let item = resolve_item_or_type(scx, object_type, sink_name.clone(), if_exists)?;
8110
8111 let Some(item) = item else {
8112 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
8113 name: sink_name.to_string(),
8114 object_type,
8115 });
8116
8117 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
8118 };
8119 let item = item.at_version(RelationVersionSelector::Latest);
8121
8122 let create_sql = item.create_sql();
8124 let stmts = mz_sql_parser::parser::parse_statements(create_sql)?;
8125 let [stmt]: [StatementParseResult; 1] = stmts
8126 .try_into()
8127 .map_err(|_| internal_err!("create SQL of sink was not exactly one statement"))?;
8128 let Statement::CreateSink(stmt) = stmt.ast else {
8129 bail_internal!("create SQL of sink is not a CREATE SINK statement");
8130 };
8131 let (mut stmt, _) = crate::names::resolve(scx.catalog, stmt)?;
8132
8133 let mut set_options = vec![];
8135 let mut reset_options = vec![];
8136 match action {
8137 AlterSinkAction::ChangeRelation(new_from) => {
8138 stmt.from = new_from;
8139 }
8140 AlterSinkAction::SetOptions(options) => {
8141 for option in &options {
8142 match &option.name {
8143 CreateSinkOptionName::CommitInterval => {}
8144 name => bail_unsupported!(format!(
8145 "ALTER SINK ... SET ({})",
8146 name.to_ast_string_simple()
8147 )),
8148 }
8149 }
8150 if options.iter().all(|o| stmt.with_options.contains(o)) {
8166 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
8167 }
8168 set_options = options;
8169 }
8170 AlterSinkAction::ResetOptions(names) => {
8171 for name in &names {
8172 match name {
8173 CreateSinkOptionName::CommitInterval => {}
8174 name => bail_unsupported!(format!(
8175 "ALTER SINK ... RESET ({})",
8176 name.to_ast_string_simple()
8177 )),
8178 }
8179 if !stmt.with_options.iter().any(|o| o.name == *name) {
8182 sql_bail!(
8183 "cannot RESET {}: option is not set",
8184 name.to_ast_string_simple()
8185 );
8186 }
8187 }
8188 reset_options = names;
8189 }
8190 }
8191 crate::plan::apply_sink_option_edits(&mut stmt.with_options, &set_options, &reset_options);
8192
8193 let Plan::CreateSink(mut plan) = plan_sink(scx, stmt)? else {
8195 bail_internal!("plan_sink did not produce a CreateSink plan");
8196 };
8197
8198 plan.sink.version += 1;
8199
8200 Ok(Plan::AlterSink(AlterSinkPlan {
8201 item_id: item.id(),
8202 global_id: item.global_id(),
8203 sink: plan.sink,
8204 with_snapshot: plan.with_snapshot,
8205 in_cluster: plan.in_cluster,
8206 set_options,
8207 reset_options,
8208 }))
8209}
8210
8211pub fn describe_alter_source(
8212 _: &StatementContext,
8213 _: AlterSourceStatement<Aug>,
8214) -> Result<StatementDesc, PlanError> {
8215 Ok(StatementDesc::new(None))
8217}
8218
8219generate_extracted_config!(
8220 AlterSourceAddSubsourceOption,
8221 (TextColumns, Vec::<UnresolvedItemName>, Default(vec![])),
8222 (ExcludeColumns, Vec::<UnresolvedItemName>, Default(vec![])),
8223 (Details, String)
8224);
8225
8226pub fn plan_alter_source(
8227 scx: &mut StatementContext,
8228 stmt: AlterSourceStatement<Aug>,
8229) -> Result<Plan, PlanError> {
8230 let AlterSourceStatement {
8231 source_name,
8232 if_exists,
8233 action,
8234 } = stmt;
8235 let object_type = ObjectType::Source;
8236
8237 if resolve_item_or_type(scx, object_type, source_name.clone(), if_exists)?.is_none() {
8238 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
8239 name: source_name.to_string(),
8240 object_type,
8241 });
8242
8243 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
8244 }
8245
8246 match action {
8247 AlterSourceAction::SetOptions(options) => {
8248 let mut options = options.into_iter();
8249 let option = options
8250 .next()
8251 .ok_or_else(|| sql_err!("ALTER SOURCE SET requires at least one option"))?;
8252 if option.name == CreateSourceOptionName::RetainHistory {
8253 if options.next().is_some() {
8254 sql_bail!("RETAIN HISTORY must be only option");
8255 }
8256 return alter_retain_history(
8257 scx,
8258 object_type,
8259 if_exists,
8260 UnresolvedObjectName::Item(source_name),
8261 option.value,
8262 );
8263 }
8264 if option.name == CreateSourceOptionName::TimestampInterval {
8265 if options.next().is_some() {
8266 sql_bail!("TIMESTAMP INTERVAL must be only option");
8267 }
8268 return alter_source_timestamp_interval(scx, if_exists, source_name, option.value);
8269 }
8270 sql_bail!(
8273 "Cannot modify the {} of a SOURCE.",
8274 option.name.to_ast_string_simple()
8275 );
8276 }
8277 AlterSourceAction::ResetOptions(reset) => {
8278 let mut options = reset.into_iter();
8279 let option = options
8280 .next()
8281 .ok_or_else(|| sql_err!("ALTER SOURCE RESET requires at least one option"))?;
8282 if option == CreateSourceOptionName::RetainHistory {
8283 if options.next().is_some() {
8284 sql_bail!("RETAIN HISTORY must be only option");
8285 }
8286 return alter_retain_history(
8287 scx,
8288 object_type,
8289 if_exists,
8290 UnresolvedObjectName::Item(source_name),
8291 None,
8292 );
8293 }
8294 if option == CreateSourceOptionName::TimestampInterval {
8295 if options.next().is_some() {
8296 sql_bail!("TIMESTAMP INTERVAL must be only option");
8297 }
8298 return alter_source_timestamp_interval(scx, if_exists, source_name, None);
8299 }
8300 sql_bail!(
8301 "Cannot modify the {} of a SOURCE.",
8302 option.to_ast_string_simple()
8303 );
8304 }
8305 AlterSourceAction::DropSubsources { .. } => {
8306 sql_bail!("ALTER SOURCE...DROP SUBSOURCE no longer supported; use DROP SOURCE")
8307 }
8308 AlterSourceAction::AddSubsources { .. } => {
8309 sql_bail!("ALTER SOURCE...ADD SUBSOURCE must be purified before planning")
8310 }
8311 AlterSourceAction::RefreshReferences => {
8312 sql_bail!("ALTER SOURCE...REFRESH REFERENCES must be purified before planning")
8313 }
8314 };
8315}
8316
8317pub fn describe_alter_system_set(
8318 _: &StatementContext,
8319 _: AlterSystemSetStatement,
8320) -> Result<StatementDesc, PlanError> {
8321 Ok(StatementDesc::new(None))
8322}
8323
8324pub fn plan_alter_system_set(
8325 _: &StatementContext,
8326 AlterSystemSetStatement { name, to }: AlterSystemSetStatement,
8327) -> Result<Plan, PlanError> {
8328 let name = name.to_string();
8329 Ok(Plan::AlterSystemSet(AlterSystemSetPlan {
8330 name,
8331 value: scl::plan_set_variable_to(to)?,
8332 }))
8333}
8334
8335pub fn describe_alter_system_reset(
8336 _: &StatementContext,
8337 _: AlterSystemResetStatement,
8338) -> Result<StatementDesc, PlanError> {
8339 Ok(StatementDesc::new(None))
8340}
8341
8342pub fn plan_alter_system_reset(
8343 _: &StatementContext,
8344 AlterSystemResetStatement { name }: AlterSystemResetStatement,
8345) -> Result<Plan, PlanError> {
8346 let name = name.to_string();
8347 Ok(Plan::AlterSystemReset(AlterSystemResetPlan { name }))
8348}
8349
8350pub fn describe_alter_system_reset_all(
8351 _: &StatementContext,
8352 _: AlterSystemResetAllStatement,
8353) -> Result<StatementDesc, PlanError> {
8354 Ok(StatementDesc::new(None))
8355}
8356
8357pub fn plan_alter_system_reset_all(
8358 _: &StatementContext,
8359 _: AlterSystemResetAllStatement,
8360) -> Result<Plan, PlanError> {
8361 Ok(Plan::AlterSystemResetAll(AlterSystemResetAllPlan {}))
8362}
8363
8364pub fn describe_alter_role(
8365 _: &StatementContext,
8366 _: AlterRoleStatement<Aug>,
8367) -> Result<StatementDesc, PlanError> {
8368 Ok(StatementDesc::new(None))
8369}
8370
8371pub fn plan_alter_role(
8372 scx: &StatementContext,
8373 AlterRoleStatement { name, option }: AlterRoleStatement<Aug>,
8374) -> Result<Plan, PlanError> {
8375 let option = match option {
8376 AlterRoleOption::Attributes(attrs) => {
8377 let attrs = plan_role_attributes(attrs, scx)?;
8378 PlannedAlterRoleOption::Attributes(attrs)
8379 }
8380 AlterRoleOption::Variable(variable) => {
8381 PlannedAlterRoleOption::Variable(plan_role_variable(scx, variable)?)
8382 }
8383 };
8384
8385 Ok(Plan::AlterRole(AlterRolePlan {
8386 id: name.id,
8387 name: name.name,
8388 option,
8389 }))
8390}
8391
8392pub fn describe_alter_table_add_column(
8393 _: &StatementContext,
8394 _: AlterTableAddColumnStatement<Aug>,
8395) -> Result<StatementDesc, PlanError> {
8396 Ok(StatementDesc::new(None))
8397}
8398
8399pub fn plan_alter_table_add_column(
8400 scx: &StatementContext,
8401 stmt: AlterTableAddColumnStatement<Aug>,
8402) -> Result<Plan, PlanError> {
8403 let AlterTableAddColumnStatement {
8404 if_exists,
8405 name,
8406 if_col_not_exist,
8407 column_name,
8408 data_type,
8409 } = stmt;
8410 let object_type = ObjectType::Table;
8411
8412 scx.require_feature_flag(&vars::ENABLE_ALTER_TABLE_ADD_COLUMN)?;
8413
8414 let (relation_id, item_name, desc) =
8415 match resolve_item_or_type(scx, object_type, name.clone(), if_exists)? {
8416 Some(item) => {
8417 let item_name = scx.catalog.resolve_full_name(item.name());
8419 let item = item.at_version(RelationVersionSelector::Latest);
8420 let desc = item
8421 .relation_desc()
8422 .ok_or_else(|| sql_err!("item does not have a relation description"))?
8423 .into_owned();
8424 (item.id(), item_name, desc)
8425 }
8426 None => {
8427 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
8428 name: name.to_ast_string_simple(),
8429 object_type,
8430 });
8431 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
8432 }
8433 };
8434
8435 let column_name = ColumnName::from(column_name.as_str());
8436 if desc.get_by_name(&column_name).is_some() {
8437 if if_col_not_exist {
8438 scx.catalog.add_notice(PlanNotice::ColumnAlreadyExists {
8439 column_name: column_name.to_string(),
8440 object_name: item_name.item,
8441 });
8442 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
8443 } else {
8444 return Err(PlanError::ColumnAlreadyExists {
8445 column_name,
8446 object_name: item_name.item,
8447 });
8448 }
8449 }
8450
8451 let scalar_type = scalar_type_from_sql(scx, &data_type)?;
8452 let column_type = scalar_type.nullable(true);
8454 let raw_sql_type = mz_sql_parser::parser::parse_data_type(&data_type.to_ast_string_stable())?;
8456
8457 Ok(Plan::AlterTableAddColumn(AlterTablePlan {
8458 relation_id,
8459 column_name,
8460 column_type,
8461 raw_sql_type,
8462 }))
8463}
8464
8465pub fn describe_alter_materialized_view_apply_replacement(
8466 _: &StatementContext,
8467 _: AlterMaterializedViewApplyReplacementStatement,
8468) -> Result<StatementDesc, PlanError> {
8469 Ok(StatementDesc::new(None))
8470}
8471
8472pub fn plan_alter_materialized_view_apply_replacement(
8473 scx: &StatementContext,
8474 stmt: AlterMaterializedViewApplyReplacementStatement,
8475) -> Result<Plan, PlanError> {
8476 let AlterMaterializedViewApplyReplacementStatement {
8477 if_exists,
8478 name,
8479 replacement_name,
8480 } = stmt;
8481
8482 scx.require_feature_flag(&vars::ENABLE_REPLACEMENT_MATERIALIZED_VIEWS)?;
8483
8484 let object_type = ObjectType::MaterializedView;
8485 let Some(mv) = resolve_item_or_type(scx, object_type, name.clone(), if_exists)? else {
8486 scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
8487 name: name.to_ast_string_simple(),
8488 object_type,
8489 });
8490 return Ok(Plan::AlterNoop(AlterNoopPlan { object_type }));
8491 };
8492
8493 let replacement = resolve_item_or_type(scx, object_type, replacement_name, false)?
8494 .ok_or_else(|| sql_err!("replacement materialized view does not exist"))?;
8495
8496 if replacement.replacement_target() != Some(mv.id()) {
8497 return Err(PlanError::InvalidReplacement {
8498 item_type: mv.item_type(),
8499 item_name: scx.catalog.minimal_qualification(mv.name()),
8500 replacement_type: replacement.item_type(),
8501 replacement_name: scx.catalog.minimal_qualification(replacement.name()),
8502 });
8503 }
8504
8505 Ok(Plan::AlterMaterializedViewApplyReplacement(
8506 AlterMaterializedViewApplyReplacementPlan {
8507 id: mv.id(),
8508 replacement_id: replacement.id(),
8509 },
8510 ))
8511}
8512
8513pub fn describe_comment(
8514 _: &StatementContext,
8515 _: CommentStatement<Aug>,
8516) -> Result<StatementDesc, PlanError> {
8517 Ok(StatementDesc::new(None))
8518}
8519
8520pub fn plan_comment(
8521 scx: &mut StatementContext,
8522 stmt: CommentStatement<Aug>,
8523) -> Result<Plan, PlanError> {
8524 const MAX_COMMENT_LENGTH: usize = 1024;
8525
8526 let CommentStatement { object, comment } = stmt;
8527
8528 if let Some(c) = &comment {
8530 if c.len() > 1024 {
8531 return Err(PlanError::CommentTooLong {
8532 length: c.len(),
8533 max_size: MAX_COMMENT_LENGTH,
8534 });
8535 }
8536 }
8537
8538 let (object_id, column_pos) = match &object {
8539 com_ty @ CommentObjectType::Table { name }
8540 | com_ty @ CommentObjectType::View { name }
8541 | com_ty @ CommentObjectType::MaterializedView { name }
8542 | com_ty @ CommentObjectType::Index { name }
8543 | com_ty @ CommentObjectType::Func { name }
8544 | com_ty @ CommentObjectType::Connection { name }
8545 | com_ty @ CommentObjectType::Source { name }
8546 | com_ty @ CommentObjectType::Sink { name }
8547 | com_ty @ CommentObjectType::Secret { name } => {
8548 let item = scx.get_item_by_resolved_name(name)?;
8549 match (com_ty, item.item_type()) {
8550 (CommentObjectType::Table { .. }, CatalogItemType::Table) => {
8551 (CommentObjectId::Table(item.id()), None)
8552 }
8553 (CommentObjectType::View { .. }, CatalogItemType::View) => {
8554 (CommentObjectId::View(item.id()), None)
8555 }
8556 (CommentObjectType::MaterializedView { .. }, CatalogItemType::MaterializedView) => {
8557 (CommentObjectId::MaterializedView(item.id()), None)
8558 }
8559 (CommentObjectType::Index { .. }, CatalogItemType::Index) => {
8560 (CommentObjectId::Index(item.id()), None)
8561 }
8562 (CommentObjectType::Func { .. }, CatalogItemType::Func) => {
8563 (CommentObjectId::Func(item.id()), None)
8564 }
8565 (CommentObjectType::Connection { .. }, CatalogItemType::Connection) => {
8566 (CommentObjectId::Connection(item.id()), None)
8567 }
8568 (CommentObjectType::Source { .. }, CatalogItemType::Source) => {
8569 (CommentObjectId::Source(item.id()), None)
8570 }
8571 (CommentObjectType::Sink { .. }, CatalogItemType::Sink) => {
8572 (CommentObjectId::Sink(item.id()), None)
8573 }
8574 (CommentObjectType::Secret { .. }, CatalogItemType::Secret) => {
8575 (CommentObjectId::Secret(item.id()), None)
8576 }
8577 (com_ty, cat_ty) => {
8578 let expected_type = match com_ty {
8579 CommentObjectType::Table { .. } => ObjectType::Table,
8580 CommentObjectType::View { .. } => ObjectType::View,
8581 CommentObjectType::MaterializedView { .. } => ObjectType::MaterializedView,
8582 CommentObjectType::Index { .. } => ObjectType::Index,
8583 CommentObjectType::Func { .. } => ObjectType::Func,
8584 CommentObjectType::Connection { .. } => ObjectType::Connection,
8585 CommentObjectType::Source { .. } => ObjectType::Source,
8586 CommentObjectType::Sink { .. } => ObjectType::Sink,
8587 CommentObjectType::Secret { .. } => ObjectType::Secret,
8588 _ => sql_bail!("cannot comment on this object type"),
8589 };
8590
8591 return Err(PlanError::InvalidObjectType {
8592 expected_type: SystemObjectType::Object(expected_type),
8593 actual_type: SystemObjectType::Object(cat_ty.into()),
8594 object_name: item.name().item.clone(),
8595 });
8596 }
8597 }
8598 }
8599 CommentObjectType::Type { ty } => match ty {
8600 ResolvedDataType::AnonymousList(_) | ResolvedDataType::AnonymousMap { .. } => {
8601 sql_bail!("cannot comment on anonymous list or map type");
8602 }
8603 ResolvedDataType::Named { id, modifiers, .. } => {
8604 if !modifiers.is_empty() {
8605 sql_bail!("cannot comment on type with modifiers");
8606 }
8607 (CommentObjectId::Type(*id), None)
8608 }
8609 ResolvedDataType::Error => bail_internal!("unresolved data type"),
8610 },
8611 CommentObjectType::Column { name } => {
8612 let (item, pos) = scx.get_column_by_resolved_name(name)?;
8613 match item.item_type() {
8614 CatalogItemType::Table => (CommentObjectId::Table(item.id()), Some(pos + 1)),
8615 CatalogItemType::Source => (CommentObjectId::Source(item.id()), Some(pos + 1)),
8616 CatalogItemType::View => (CommentObjectId::View(item.id()), Some(pos + 1)),
8617 CatalogItemType::MaterializedView => {
8618 (CommentObjectId::MaterializedView(item.id()), Some(pos + 1))
8619 }
8620 CatalogItemType::Type => (CommentObjectId::Type(item.id()), Some(pos + 1)),
8621 r => {
8622 return Err(PlanError::Unsupported {
8623 feature: format!("Specifying comments on a column of {r}"),
8624 discussion_no: None,
8625 });
8626 }
8627 }
8628 }
8629 CommentObjectType::Role { name } => (CommentObjectId::Role(name.id), None),
8630 CommentObjectType::Database { name } => {
8631 (CommentObjectId::Database(*name.database_id()), None)
8632 }
8633 CommentObjectType::Schema { name } => {
8634 if matches!(name.schema_spec(), SchemaSpecifier::Temporary) {
8638 sql_bail!(
8639 "cannot comment on schema {} because it is a temporary schema",
8640 mz_repr::namespaces::MZ_TEMP_SCHEMA
8641 );
8642 }
8643 (
8644 CommentObjectId::Schema((*name.database_spec(), *name.schema_spec())),
8645 None,
8646 )
8647 }
8648 CommentObjectType::Cluster { name } => (CommentObjectId::Cluster(name.id), None),
8649 CommentObjectType::ClusterReplica { name } => {
8650 let replica = scx.catalog.resolve_cluster_replica(name)?;
8651 (
8652 CommentObjectId::ClusterReplica((replica.cluster_id(), replica.replica_id())),
8653 None,
8654 )
8655 }
8656 CommentObjectType::NetworkPolicy { name } => {
8657 (CommentObjectId::NetworkPolicy(name.id), None)
8658 }
8659 CommentObjectType::QueryPolicy { name } => {
8660 scx.require_feature_flag(&vars::ENABLE_QUERY_POLICIES)?;
8661 (
8662 CommentObjectId::QueryPolicy(scx.catalog.resolve_query_policy(name.as_str())?.id()),
8663 None,
8664 )
8665 }
8666 };
8667
8668 if let Some(p) = column_pos {
8674 i32::try_from(p).map_err(|_| PlanError::TooManyColumns {
8675 max_num_columns: MAX_NUM_COLUMNS,
8676 req_num_columns: p,
8677 })?;
8678 }
8679
8680 Ok(Plan::Comment(CommentPlan {
8681 object_id,
8682 sub_component: column_pos,
8683 comment,
8684 }))
8685}
8686
8687pub(crate) fn resolve_cluster<'a>(
8688 scx: &'a StatementContext,
8689 name: &'a Ident,
8690 if_exists: bool,
8691) -> Result<Option<&'a dyn CatalogCluster<'a>>, PlanError> {
8692 match scx.resolve_cluster(Some(name)) {
8693 Ok(cluster) => Ok(Some(cluster)),
8694 Err(_) if if_exists => Ok(None),
8695 Err(e) => Err(e),
8696 }
8697}
8698
8699pub(crate) fn resolve_cluster_replica<'a>(
8700 scx: &'a StatementContext,
8701 name: &QualifiedReplica,
8702 if_exists: bool,
8703) -> Result<Option<(&'a dyn CatalogCluster<'a>, ReplicaId)>, PlanError> {
8704 match scx.resolve_cluster(Some(&name.cluster)) {
8705 Ok(cluster) => match cluster.replica_ids().get(name.replica.as_str()) {
8706 Some(replica_id) => Ok(Some((cluster, *replica_id))),
8707 None if if_exists => Ok(None),
8708 None => Err(sql_err!(
8709 "CLUSTER {} has no CLUSTER REPLICA named {}",
8710 cluster.name(),
8711 name.replica.as_str().quoted(),
8712 )),
8713 },
8714 Err(_) if if_exists => Ok(None),
8715 Err(e) => Err(e),
8716 }
8717}
8718
8719pub(crate) fn resolve_database<'a>(
8720 scx: &'a StatementContext,
8721 name: &'a UnresolvedDatabaseName,
8722 if_exists: bool,
8723) -> Result<Option<&'a dyn CatalogDatabase>, PlanError> {
8724 match scx.resolve_database(name) {
8725 Ok(database) => Ok(Some(database)),
8726 Err(_) if if_exists => Ok(None),
8727 Err(e) => Err(e),
8728 }
8729}
8730
8731pub(crate) fn resolve_schema<'a>(
8732 scx: &'a StatementContext,
8733 name: UnresolvedSchemaName,
8734 if_exists: bool,
8735) -> Result<Option<(ResolvedDatabaseSpecifier, SchemaSpecifier)>, PlanError> {
8736 match scx.resolve_schema(name) {
8737 Ok(schema) => Ok(Some((schema.database().clone(), schema.id().clone()))),
8738 Err(_) if if_exists => Ok(None),
8739 Err(e) => Err(e),
8740 }
8741}
8742
8743pub(crate) fn resolve_network_policy<'a>(
8744 scx: &'a StatementContext,
8745 name: Ident,
8746 if_exists: bool,
8747) -> Result<Option<ResolvedNetworkPolicyName>, PlanError> {
8748 match scx
8749 .catalog
8750 .resolve_network_policy(normalize::ident_ref(&name))
8751 {
8752 Ok(policy) => Ok(Some(ResolvedNetworkPolicyName {
8753 id: policy.id(),
8754 name: policy.name().to_string(),
8755 })),
8756 Err(_) if if_exists => Ok(None),
8757 Err(e) => Err(e.into()),
8758 }
8759}
8760
8761pub(crate) fn resolve_item_or_type<'a>(
8762 scx: &'a StatementContext,
8763 object_type: ObjectType,
8764 name: UnresolvedItemName,
8765 if_exists: bool,
8766) -> Result<Option<&'a dyn CatalogItem>, PlanError> {
8767 let name = normalize::unresolved_item_name(name)?;
8768 let catalog_item = match object_type {
8769 ObjectType::Type => scx.catalog.resolve_type(&name),
8770 ObjectType::Table
8771 | ObjectType::View
8772 | ObjectType::MaterializedView
8773 | ObjectType::Source
8774 | ObjectType::Sink
8775 | ObjectType::MetricSink
8776 | ObjectType::Index
8777 | ObjectType::Role
8778 | ObjectType::Cluster
8779 | ObjectType::ClusterReplica
8780 | ObjectType::Secret
8781 | ObjectType::Connection
8782 | ObjectType::Database
8783 | ObjectType::Schema
8784 | ObjectType::Func
8785 | ObjectType::NetworkPolicy
8786 | ObjectType::QueryPolicy => scx.catalog.resolve_item(&name),
8787 };
8788
8789 match catalog_item {
8790 Ok(item) => {
8791 let is_type = ObjectType::from(item.item_type());
8792 if object_type == is_type {
8793 Ok(Some(item))
8794 } else {
8795 Err(PlanError::MismatchedObjectType {
8796 name: scx.catalog.minimal_qualification(item.name()),
8797 is_type,
8798 expected_type: object_type,
8799 })
8800 }
8801 }
8802 Err(_) if if_exists => Ok(None),
8803 Err(e) => Err(e.into()),
8804 }
8805}
8806
8807fn ensure_cluster_is_not_managed(
8809 scx: &StatementContext,
8810 cluster_id: ClusterId,
8811) -> Result<(), PlanError> {
8812 let cluster = scx.catalog.get_cluster(cluster_id);
8813 if cluster.is_managed() {
8814 Err(PlanError::ManagedCluster {
8815 cluster_name: cluster.name().to_string(),
8816 })
8817 } else {
8818 Ok(())
8819 }
8820}
8821
8822#[cfg(test)]
8823mod tests {
8824 use super::{
8825 METRIC_SINK_CURATED_PREFIX_MARKER, METRIC_SINK_PREFIX_MARKER,
8826 validate_user_metric_sink_prefix,
8827 };
8828
8829 #[mz_ore::test]
8830 fn user_metric_sink_prefix_cannot_reach_the_curated_prefix() {
8831 assert!(validate_user_metric_sink_prefix(METRIC_SINK_CURATED_PREFIX_MARKER).is_err());
8833 assert!(validate_user_metric_sink_prefix("mz_metric_sink_curated_x").is_err());
8834 assert!(validate_user_metric_sink_prefix(METRIC_SINK_PREFIX_MARKER).is_err());
8836 assert!(validate_user_metric_sink_prefix("mz_metric_sink_cur").is_err());
8837 assert!(validate_user_metric_sink_prefix("myapp_").is_err());
8839 assert!(validate_user_metric_sink_prefix("mz_metric_sink_myapp_").is_ok());
8842 assert!(validate_user_metric_sink_prefix("mz_metric_sink_curatex_").is_ok());
8843 assert!(validate_user_metric_sink_prefix("mz_metric_sink_my_curated_").is_ok());
8844 }
8845}