Skip to main content

mz_sql/plan/statement/
ddl.rs

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