Skip to main content

mz_deploy/cli/commands/
stage.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//! Stage command - deploy to staging environment with renamed schemas and clusters.
11//!
12//! Runs the standard blue/green deployment pipeline that can later be promoted
13//! to production via [`super::promote`].
14
15use super::ObjectRef;
16use crate::cli::CliError;
17use crate::cli::executor::{self, DeploymentExecutor};
18use crate::cli::{git, progress};
19use crate::client::DeploymentMode;
20use crate::client::{Client, ClusterConfig, DeploymentKind, PendingStatement, ReplacementMvRecord};
21use crate::config::Settings;
22use crate::log;
23use crate::project::SchemaQualifier;
24use crate::project::analysis::changeset::ChangeSet;
25use crate::project::analysis::deployment_snapshot::{self, DeploymentSnapshot};
26use crate::project::analysis::deps::extract_external_indexes;
27use crate::project::ast::Statement;
28use crate::project::ir::compiled::{DatabaseObject, FullyQualifiedName};
29use crate::project::ir::graph::Project;
30use crate::project::ir::object_id::ObjectId;
31use crate::project::resolve::normalize::{self, NormalizingVisitor};
32use crate::verbose;
33use mz_ore::option::OptionExt;
34use mz_sql_parser::ast::display::AstDisplay;
35use mz_sql_parser::ast::{CreateClusterStatement, Ident};
36use std::collections::BTreeSet;
37
38/// Reject a stage name long enough that appending the staging suffix
39/// `_<stage_name>` to a schema or cluster identifier would exceed the
40/// identifier length limit and panic during deploy.
41fn validate_stage_name(stage_name: &str) -> Result<(), CliError> {
42    // The suffix is appended to existing identifiers, so reserve headroom for
43    // the base name rather than letting the suffix consume the whole limit.
44    if stage_name.len() + 1 > Ident::MAX_LENGTH / 2 {
45        return Err(CliError::InvalidEnvironmentName {
46            name: stage_name.to_string(),
47        });
48    }
49    Ok(())
50}
51use std::fmt;
52use std::path::Path;
53use std::time::Instant;
54
55/// Planning output produced once and consumed by all stage execution phases.
56///
57/// Keeps stage deterministic by passing one analyzed view of objects/resources through
58/// validation, metadata recording, and resource creation.
59struct StageAnalysis<'a> {
60    objects: Vec<ObjectRef<'a>>,
61    sinks: Vec<ObjectRef<'a>>,
62    replacement_mvs: Vec<ObjectRef<'a>>,
63    schema_set: BTreeSet<SchemaQualifier>,
64    cluster_set: BTreeSet<String>,
65}
66
67/// Classification result for objects considered during staging.
68///
69/// Separates deploy-now objects from deferred/special-case categories that apply handles later.
70struct PartitionedObjects<'a> {
71    objects: Vec<ObjectRef<'a>>,
72    sinks: Vec<ObjectRef<'a>>,
73    replacement_mvs: Vec<ObjectRef<'a>>,
74    table_count: usize,
75}
76
77/// Summary returned after a successful stage run, used for terminal output
78/// and `--json`.
79#[derive(serde::Serialize)]
80struct StageResult {
81    deploy_id: String,
82    objects_deployed: usize,
83    #[serde(skip)]
84    duration: std::time::Duration,
85}
86
87impl fmt::Display for StageResult {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        write!(
90            f,
91            "  \u{2713} Successfully deployed {} objects to '{}' staging environment ({:.1}s)",
92            self.objects_deployed,
93            self.deploy_id,
94            self.duration.as_secs_f64()
95        )
96    }
97}
98
99#[derive(serde::Serialize)]
100struct StagePlan {
101    deploy_id: String,
102    schemas: Vec<StagePlanSchema>,
103    clusters: Vec<StagePlanCluster>,
104    objects: Vec<StagePlanObject>,
105    sinks: Vec<StagePlanObject>,
106    replacement_mvs: Vec<StagePlanObject>,
107}
108
109#[derive(serde::Serialize)]
110struct StagePlanSchema {
111    database: String,
112    schema: String,
113    staging_schema: String,
114}
115
116#[derive(serde::Serialize)]
117struct StagePlanCluster {
118    production_cluster: String,
119    staging_cluster: String,
120}
121
122#[derive(serde::Serialize)]
123struct StagePlanObject {
124    database: String,
125    schema: String,
126    object: String,
127}
128
129impl fmt::Display for StagePlan {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        writeln!(f, "Stage plan for '{}':", self.deploy_id)?;
132
133        if !self.schemas.is_empty() {
134            writeln!(f, "\nSchemas ({}):", self.schemas.len())?;
135            for s in &self.schemas {
136                writeln!(
137                    f,
138                    "    {}.{} \u{2192} {}",
139                    s.database, s.schema, s.staging_schema
140                )?;
141            }
142        }
143
144        if !self.clusters.is_empty() {
145            writeln!(f, "\nClusters ({}):", self.clusters.len())?;
146            for c in &self.clusters {
147                writeln!(
148                    f,
149                    "    {} \u{2192} {}",
150                    c.production_cluster, c.staging_cluster
151                )?;
152            }
153        }
154
155        if !self.objects.is_empty() {
156            writeln!(f, "\nObjects ({}):", self.objects.len())?;
157            for o in &self.objects {
158                writeln!(f, "    {}.{}.{}", o.database, o.schema, o.object)?;
159            }
160        }
161
162        if !self.sinks.is_empty() {
163            writeln!(f, "\nSinks ({}):", self.sinks.len())?;
164            for s in &self.sinks {
165                writeln!(f, "    {}.{}.{}", s.database, s.schema, s.object)?;
166            }
167        }
168
169        if !self.replacement_mvs.is_empty() {
170            writeln!(f, "\nReplacement MVs ({}):", self.replacement_mvs.len())?;
171            for m in &self.replacement_mvs {
172                writeln!(f, "    {}.{}.{}", m.database, m.schema, m.object)?;
173            }
174        }
175
176        Ok(())
177    }
178}
179
180/// Deploy the project to a staging environment.
181///
182/// Creates renamed schemas and clusters alongside production, deploys the
183/// project onto them, and records metadata so a later `apply` can atomically
184/// swap staging into production.
185///
186/// # Arguments
187/// * `settings` - Resolved CLI settings (project directory, profile, etc.)
188/// * `stage_name` - Optional environment name; defaults to a git-derived or
189///   random identifier
190/// * `allow_dirty` - Allow deploying with uncommitted changes
191/// * `no_rollback` - Skip automatic rollback on failure (for debugging)
192/// * `dry_run` - Print SQL instead of executing it
193///
194/// # Returns
195/// `Ok(())` if the deployment succeeds.
196///
197/// # Errors
198/// Surfaces `CliError` variants from git checks, project compilation, and
199/// database execution.
200pub async fn run(
201    settings: &Settings,
202    stage_name: Option<&str>,
203    allow_dirty: bool,
204    no_rollback: bool,
205    dry_run: bool,
206    redeploy_schemas: &[String],
207    redeploy_all: bool,
208) -> Result<(), CliError> {
209    let profile = settings.connection();
210    let directory = &settings.directory;
211    let start_time = Instant::now();
212
213    if !allow_dirty && git::is_dirty(directory) {
214        return Err(CliError::GitDirty);
215    }
216
217    let stage_name = stage_name
218        .owned()
219        .or_else(|| git::get_git_commit(directory).map(|sha| sha.chars().take(7).collect()))
220        .unwrap_or_else(executor::generate_random_env_name);
221    validate_stage_name(&stage_name)?;
222
223    let planned_project = super::compile::run(settings, true).await?;
224    let staging_suffix = format!("_{}", stage_name);
225
226    let client = Client::connect_with_profile(profile.clone())
227        .await
228        .map_err(CliError::Connection)?;
229
230    crate::cli::commands::setup::verify(&client, settings.emulator()).await?;
231    let role =
232        crate::cli::commands::setup::validate_connection(&client, settings.emulator()).await?;
233    crate::cli::commands::setup::require_deployer(role)?;
234
235    let forced_dirty_schemas = resolve_redeploy_schemas(&planned_project, redeploy_schemas)?;
236
237    let Some(analysis) = analyze_project_changes(
238        &client,
239        &planned_project,
240        &stage_name,
241        forced_dirty_schemas,
242        redeploy_all,
243    )
244    .await?
245    else {
246        return Ok(());
247    };
248
249    validate_project_for_stage(
250        &client,
251        &planned_project,
252        directory,
253        &analysis.schema_set,
254        &analysis.cluster_set,
255    )
256    .await?;
257
258    if !dry_run {
259        // Metadata is written before any resources are created, so a failure
260        // partway through can leave deployment rows behind that block
261        // re-staging under the same name. Roll them back on failure, unless
262        // --no-rollback asks to preserve state for debugging. The rollback runs
263        // a suffix-matching CASCADE drop, so honoring the flag here also avoids
264        // dropping resources the operator asked to keep.
265        if let Err(e) = record_stage_metadata(
266            &client,
267            directory,
268            &stage_name,
269            &staging_suffix,
270            &analysis.objects,
271            &analysis.sinks,
272            &analysis.replacement_mvs,
273            &planned_project.replacement_schemas,
274        )
275        .await
276        {
277            if no_rollback {
278                progress::error("Deployment failed (skipping rollback due to --no-rollback flag)");
279            } else {
280                progress::error("Deployment failed, rolling back...");
281                rollback_staging_resources(&client, &stage_name).await;
282            }
283            return Err(e);
284        }
285    }
286
287    if dry_run {
288        let plan = StagePlan {
289            deploy_id: stage_name.to_string(),
290            schemas: analysis
291                .schema_set
292                .iter()
293                .map(|sq| StagePlanSchema {
294                    database: sq.database.clone(),
295                    schema: sq.schema.clone(),
296                    staging_schema: format!("{}{}", sq.schema, staging_suffix),
297                })
298                .collect(),
299            clusters: analysis
300                .cluster_set
301                .iter()
302                .map(|c| StagePlanCluster {
303                    production_cluster: c.clone(),
304                    staging_cluster: format!("{}{}", c, staging_suffix),
305                })
306                .collect(),
307            objects: analysis
308                .objects
309                .iter()
310                .map(|(id, _)| StagePlanObject {
311                    database: id.expect_database().to_string(),
312                    schema: id.schema().to_string(),
313                    object: id.object().to_string(),
314                })
315                .collect(),
316            sinks: analysis
317                .sinks
318                .iter()
319                .map(|(id, _)| StagePlanObject {
320                    database: id.expect_database().to_string(),
321                    schema: id.schema().to_string(),
322                    object: id.object().to_string(),
323                })
324                .collect(),
325            replacement_mvs: analysis
326                .replacement_mvs
327                .iter()
328                .map(|(id, _)| StagePlanObject {
329                    database: id.expect_database().to_string(),
330                    schema: id.schema().to_string(),
331                    object: id.object().to_string(),
332                })
333                .collect(),
334        };
335        log::output(&plan);
336        return Ok(());
337    }
338
339    let success_count = create_resources_with_rollback(
340        &client,
341        &stage_name,
342        &staging_suffix,
343        &analysis.schema_set,
344        &analysis.cluster_set,
345        &planned_project,
346        &analysis.objects,
347        &analysis.replacement_mvs,
348        no_rollback,
349        dry_run,
350    )
351    .await?;
352
353    let result = StageResult {
354        deploy_id: stage_name.to_string(),
355        objects_deployed: success_count,
356        duration: start_time.elapsed(),
357    };
358    log::output(&result);
359    log::print_deploy_id(&stage_name);
360    Ok(())
361}
362
363/// Parse one `--redeploy-schema` value, which must be fully qualified as
364/// `database.schema`. Reuses the SQL parser so reserved-word components quote
365/// correctly.
366fn parse_qualified_schema(raw: &str) -> Result<SchemaQualifier, CliError> {
367    let unqualified = || {
368        CliError::Message(format!(
369            "invalid --redeploy-schema '{}': expected a qualified 'database.schema' name",
370            raw
371        ))
372    };
373    let name = mz_sql_parser::parser::parse_item_name(raw).map_err(|_| unqualified())?;
374    let [database, schema] = name.0.as_slice() else {
375        return Err(unqualified());
376    };
377    Ok(SchemaQualifier::new(
378        database.as_str().to_string(),
379        schema.as_str().to_string(),
380    ))
381}
382
383/// Resolve `--redeploy-schema` values into `SchemaQualifier`s, validating each
384/// against the project's schemas.
385fn resolve_redeploy_schemas(
386    planned_project: &Project,
387    redeploy_schemas: &[String],
388) -> Result<BTreeSet<SchemaQualifier>, CliError> {
389    if redeploy_schemas.is_empty() {
390        return Ok(BTreeSet::new());
391    }
392
393    let objects: Vec<_> = planned_project.iter_objects().collect();
394    let project_schemas = SchemaQualifier::collect_from(&objects);
395
396    let mut resolved = BTreeSet::new();
397    for raw in redeploy_schemas {
398        let sq = parse_qualified_schema(raw)?;
399        if !project_schemas.contains(&sq) {
400            let available = project_schemas
401                .iter()
402                .map(|s| format!("{}.{}", s.database, s.schema))
403                .collect::<Vec<_>>()
404                .join(", ");
405            return Err(CliError::Message(format!(
406                "--redeploy-schema '{}.{}' is not a schema in this project; available: {}",
407                sq.database, sq.schema, available
408            )));
409        }
410        resolved.insert(sq);
411    }
412    Ok(resolved)
413}
414
415/// Produces the stage deployment plan by diffing against current production snapshot.
416///
417/// Handles incremental-vs-full mode, applies stage-specific object filtering,
418/// validates table dependencies, and returns resource sets required for execution.
419async fn analyze_project_changes<'a>(
420    client: &Client,
421    planned_project: &'a Project,
422    stage_name: &str,
423    forced_dirty_schemas: BTreeSet<SchemaQualifier>,
424    redeploy_all: bool,
425) -> Result<Option<StageAnalysis<'a>>, CliError> {
426    progress::stage_start("Analyzing project changes");
427    let analyze_start = Instant::now();
428
429    if client
430        .deployments()
431        .get_deployment_metadata(stage_name)
432        .await?
433        .is_some()
434    {
435        return Err(CliError::InvalidEnvironmentName {
436            name: format!("deployment '{}' already exists", stage_name),
437        });
438    }
439
440    let new_snapshot = deployment_snapshot::build_snapshot_from_planned(planned_project)?;
441    let production_snapshot = deployment_snapshot::load_from_database(client, None).await?;
442
443    let dirty_schemas = if redeploy_all {
444        new_snapshot.schemas.keys().cloned().collect()
445    } else {
446        forced_dirty_schemas
447    };
448
449    let change_set = if production_snapshot.objects.is_empty() {
450        None
451    } else {
452        Some(ChangeSet::from_deployment_snapshot_comparison(
453            &production_snapshot,
454            &new_snapshot,
455            planned_project,
456            &dirty_schemas,
457        ))
458    };
459
460    // Reject adding brand-new objects to a schema that already has production objects.
461    // During incremental deployment:
462    //
463    //   1. The changeset correctly classifies these as `new_replacement_objects`
464    //   2. But `new_replacement_objects` is never consumed by `partition_objects` —
465    //      only `changed_replacement_objects` feeds into it
466    //   3. The new MV ends up in the regular `objects` partition and deploys to the
467    //      staging schema (e.g. `core_v3`)
468    //   4. Metadata for the production schema (`core`) gets overwritten to
469    //      `DeploymentKind::Replacement` by the changed MVs
470    //   5. During promote, the staging schema is skipped from swap and dropped CASCADE
471    //      — the new MV is lost
472    //
473    // The proper long-term fix is to support `ALTER MATERIALIZED VIEW ... SET SCHEMA`.
474    // With that, new MVs could be deployed to the staging schema alongside changed MVs,
475    // then moved into the production schema during promote via `SET SCHEMA` instead of
476    // relying on schema swap. This would eliminate the need for mixed deployment kinds
477    // or special-casing in `partition_objects` — new objects simply deploy to staging
478    // and get relocated on promote, just like changed objects get swapped.
479    //
480    // A brand-new stable schema (no prior production objects) deploys fine via normal
481    // blue-green swap — only schemas with existing production objects are affected.
482    if let Some(ref cs) = change_set {
483        validate_no_new_objects_in_existing_stable_schemas(cs, &production_snapshot)?;
484    }
485
486    let objects = select_stage_objects(planned_project, change_set.as_ref())?;
487    if objects.is_empty() && change_set.as_ref().is_some_and(ChangeSet::is_empty) {
488        progress::success("No changes detected compared to production, skipping deployment");
489        return Ok(None);
490    }
491
492    let replacement_object_ids = change_set
493        .as_ref()
494        .map(|cs| cs.changed_replacement_objects.clone())
495        .unwrap_or_default();
496    let partitioned = partition_objects(objects, &replacement_object_ids);
497    log_partition_summary(&partitioned);
498
499    let object_ids: BTreeSet<_> = partitioned
500        .objects
501        .iter()
502        .map(|(id, _)| id.clone())
503        .collect();
504    client
505        .validation()
506        .validate_table_dependencies(planned_project, &object_ids)
507        .await?;
508
509    let (schema_set, cluster_set) =
510        collect_stage_resources(&partitioned.objects, &partitioned.replacement_mvs);
511
512    let analyze_duration = analyze_start.elapsed();
513    progress::stage_success(
514        &format!(
515            "Ready to deploy {} view(s)/materialized view(s)",
516            partitioned.objects.len()
517        ),
518        analyze_duration,
519    );
520
521    Ok(Some(StageAnalysis {
522        objects: partitioned.objects,
523        sinks: partitioned.sinks,
524        replacement_mvs: partitioned.replacement_mvs,
525        schema_set,
526        cluster_set,
527    }))
528}
529
530/// Chooses the initial object set for stage before stage-specific partitioning.
531///
532/// Incremental mode uses the change set; full mode uses all sorted project objects.
533fn select_stage_objects<'a>(
534    planned_project: &'a Project,
535    change_set: Option<&ChangeSet>,
536) -> Result<Vec<ObjectRef<'a>>, CliError> {
537    if let Some(cs) = change_set {
538        if cs.is_empty() {
539            return Ok(Vec::new());
540        }
541        verbose!("{}", cs);
542        Ok(planned_project.get_sorted_objects_filtered(&cs.objects_to_deploy)?)
543    } else {
544        verbose!("Full deployment: no production deployment found");
545        Ok(planned_project.get_sorted_objects()?)
546    }
547}
548
549/// Splits objects into stage execution categories.
550///
551/// Tables/sources are excluded, sinks are deferred to apply, and changed replacement MVs
552/// are tracked for special replacement handling.
553fn partition_objects<'a>(
554    objects: Vec<ObjectRef<'a>>,
555    replacement_object_ids: &BTreeSet<ObjectId>,
556) -> PartitionedObjects<'a> {
557    let mut kept = Vec::new();
558    let mut sinks = Vec::new();
559    let mut replacement_mvs = Vec::new();
560    let mut table_count = 0;
561
562    for (object_id, typed_obj) in objects {
563        match &typed_obj.stmt {
564            Statement::CreateTable(_)
565            | Statement::CreateTableFromSource(_)
566            | Statement::CreateSource(_)
567            | Statement::CreateSecret(_)
568            | Statement::CreateConnection(_) => {
569                table_count += 1;
570            }
571            Statement::CreateSink(_) => sinks.push((object_id, typed_obj)),
572            Statement::CreateMaterializedView(_) if replacement_object_ids.contains(&object_id) => {
573                replacement_mvs.push((object_id, typed_obj));
574            }
575            _ => kept.push((object_id, typed_obj)),
576        }
577    }
578
579    PartitionedObjects {
580        objects: kept,
581        sinks,
582        replacement_mvs,
583        table_count,
584    }
585}
586
587/// Reports the partitioning decisions visible to users in verbose mode.
588fn log_partition_summary(partitioned: &PartitionedObjects<'_>) {
589    if partitioned.table_count > 0 {
590        verbose!(
591            "Skipped {} table(s)/source(s) - use 'mz-deploy apply' for those",
592            partitioned.table_count
593        );
594    }
595    if !partitioned.sinks.is_empty() {
596        verbose!(
597            "Found {} sink(s) - will be created during apply after swap",
598            partitioned.sinks.len()
599        );
600    }
601    if !partitioned.replacement_mvs.is_empty() {
602        verbose!(
603            "Found {} replacement MV(s) - will use CREATE REPLACEMENT protocol",
604            partitioned.replacement_mvs.len()
605        );
606    }
607}
608
609/// Derives schema/cluster prerequisites for resource creation.
610///
611/// Builds schema and cluster sets solely from the objects being staged.
612/// Apply-managed objects (sources, tables, secrets, connections) are excluded
613/// by `partition_objects`, so their schemas and clusters are never staged.
614fn collect_stage_resources(
615    objects: &[ObjectRef<'_>],
616    replacement_mvs: &[ObjectRef<'_>],
617) -> (BTreeSet<SchemaQualifier>, BTreeSet<String>) {
618    let mut schema_set = BTreeSet::new();
619    let mut cluster_set = BTreeSet::new();
620
621    for (object_id, typed_obj) in objects.iter().chain(replacement_mvs.iter()) {
622        schema_set.insert(SchemaQualifier::new(
623            object_id.expect_database().to_string(),
624            object_id.schema().to_string(),
625        ));
626        cluster_set.extend(typed_obj.clusters());
627    }
628
629    (schema_set, cluster_set)
630}
631
632/// Runs all preflight database validations required before mutating deployment state.
633///
634/// This is intentionally isolated so stage fails before any metadata/resource writes.
635async fn validate_project_for_stage(
636    client: &Client,
637    planned_project: &Project,
638    directory: &Path,
639    schema_set: &BTreeSet<SchemaQualifier>,
640    cluster_set: &BTreeSet<String>,
641) -> Result<(), CliError> {
642    progress::stage_start("Validating project");
643    let validate_start = Instant::now();
644    client
645        .validation()
646        .validate_project(planned_project, directory)
647        .await?;
648    client
649        .validation()
650        .validate_cluster_isolation(planned_project)
651        .await?;
652    client
653        .validation()
654        .validate_privileges(planned_project)
655        .await?;
656    client
657        .validation()
658        .validate_schema_ownership(schema_set)
659        .await?;
660    client
661        .validation()
662        .validate_cluster_ownership(cluster_set)
663        .await?;
664    client
665        .validation()
666        .validate_sink_connections_exist(planned_project)
667        .await?;
668    let validate_duration = validate_start.elapsed();
669    progress::stage_success("All validations passed", validate_duration);
670    Ok(())
671}
672
673/// Persists stage deployment state and deferred apply actions.
674///
675/// Records object hashes plus schema deployment kinds, then stores sink/replacement
676/// records that the `apply` command consumes after swap.
677async fn record_stage_metadata(
678    client: &Client,
679    directory: &Path,
680    stage_name: &str,
681    staging_suffix: &str,
682    objects: &[ObjectRef<'_>],
683    sinks: &[ObjectRef<'_>],
684    replacement_mvs: &[ObjectRef<'_>],
685    replacement_schemas: &BTreeSet<SchemaQualifier>,
686) -> Result<(), CliError> {
687    progress::stage_start("Recording deployment metadata");
688    let metadata_start = Instant::now();
689    let metadata = executor::collect_deployment_metadata(client, directory).await;
690
691    let mut staging_snapshot = DeploymentSnapshot::default();
692
693    for (object_id, typed_obj) in objects {
694        let hash = deployment_snapshot::compute_typed_hash(typed_obj);
695        staging_snapshot.objects.insert(object_id.clone(), hash);
696        staging_snapshot.schemas.insert(
697            SchemaQualifier::new(
698                object_id.expect_database().to_string(),
699                object_id.schema().to_string(),
700            ),
701            DeploymentKind::Objects,
702        );
703    }
704
705    for (object_id, typed_obj) in sinks {
706        let hash = deployment_snapshot::compute_typed_hash(typed_obj);
707        staging_snapshot.objects.insert(object_id.clone(), hash);
708        staging_snapshot
709            .schemas
710            .entry(SchemaQualifier::new(
711                object_id.expect_database().to_string(),
712                object_id.schema().to_string(),
713            ))
714            .or_insert(DeploymentKind::Sinks);
715    }
716
717    for (object_id, typed_obj) in replacement_mvs {
718        let hash = deployment_snapshot::compute_typed_hash(typed_obj);
719        staging_snapshot.objects.insert(object_id.clone(), hash);
720        staging_snapshot.schemas.insert(
721            SchemaQualifier::new(
722                object_id.expect_database().to_string(),
723                object_id.schema().to_string(),
724            ),
725            DeploymentKind::Replacement,
726        );
727    }
728
729    // Ensure replacement schemas record the correct kind.
730    // During Objects→Replacement transitions, MVs go through the regular objects
731    // path (for blue-green swap), but the metadata must reflect the final kind
732    // so future deploys know to use CREATE REPLACEMENT.
733    for sq in replacement_schemas {
734        if staging_snapshot.schemas.contains_key(sq) {
735            staging_snapshot
736                .schemas
737                .insert(sq.clone(), DeploymentKind::Replacement);
738        }
739    }
740
741    deployment_snapshot::write_to_database(
742        client,
743        &staging_snapshot,
744        stage_name,
745        &metadata,
746        None,
747        DeploymentMode::Stage,
748    )
749    .await?;
750
751    if !sinks.is_empty() {
752        let pending_statements: Vec<PendingStatement> = sinks
753            .iter()
754            .enumerate()
755            .map(|(idx, (object_id, typed_obj))| {
756                let original_fqn: FullyQualifiedName = object_id.clone().into();
757                let mut visitor = NormalizingVisitor::fully_qualifying(&original_fqn);
758                let stmt = typed_obj
759                    .stmt
760                    .clone()
761                    .normalize_name_with(&visitor, &original_fqn.to_item_name())
762                    .normalize_dependencies_with(&mut visitor);
763                let hash = deployment_snapshot::compute_typed_hash(typed_obj);
764                #[allow(clippy::as_conversions)]
765                PendingStatement {
766                    deploy_id: stage_name.to_string(),
767                    sequence_num: idx as i32,
768                    database: object_id.expect_database().to_string(),
769                    schema: object_id.schema().to_string(),
770                    object: object_id.object().to_string(),
771                    object_hash: hash,
772                    statement_sql: stmt.to_string(),
773                    statement_kind: "sink".to_string(),
774                    executed_at: None,
775                }
776            })
777            .collect();
778
779        client
780            .deployments()
781            .insert_pending_statements(&pending_statements)
782            .await?;
783        verbose!(
784            "Stored {} pending sink statement(s)",
785            pending_statements.len()
786        );
787    }
788
789    if !replacement_mvs.is_empty() {
790        let records: Vec<ReplacementMvRecord> = replacement_mvs
791            .iter()
792            .map(|(object_id, _)| ReplacementMvRecord {
793                deploy_id: stage_name.to_string(),
794                target_database: object_id.expect_database().to_string(),
795                target_schema: object_id.schema().to_string(),
796                target_name: object_id.object().to_string(),
797                replacement_schema: format!("{}{}", object_id.schema(), staging_suffix),
798            })
799            .collect();
800        client
801            .deployments()
802            .insert_replacement_mvs(&records)
803            .await?;
804        verbose!("Stored {} replacement MV record(s)", records.len());
805    }
806
807    let metadata_duration = metadata_start.elapsed();
808    progress::stage_success("Deployment metadata recorded", metadata_duration);
809    Ok(())
810}
811
812/// Top-level orchestrator for the staging deployment pipeline.
813///
814/// Provisions all databases, schemas, clusters, and objects needed for a blue-green
815/// deployment. On failure, automatically rolls back every resource created during
816/// this invocation unless the `no_rollback` flag is set.
817#[allow(clippy::too_many_arguments)]
818async fn create_resources_with_rollback<'a>(
819    client: &Client,
820    stage_name: &str,
821    staging_suffix: &str,
822    schema_set: &BTreeSet<SchemaQualifier>,
823    cluster_set: &BTreeSet<String>,
824    planned_project: &'a Project,
825    objects: &'a [(ObjectId, &'a DatabaseObject)],
826    replacement_mvs: &'a [(ObjectId, &'a DatabaseObject)],
827    no_rollback: bool,
828    dry_run: bool,
829) -> Result<usize, CliError> {
830    let executor = DeploymentExecutor::with_dry_run(client, dry_run);
831
832    let result = async {
833        create_databases_and_schemas(&executor, planned_project, schema_set, staging_suffix)
834            .await?;
835        create_staging_clusters(&executor, client, stage_name, cluster_set, staging_suffix).await?;
836        deploy_objects_to_staging(
837            &executor,
838            objects,
839            replacement_mvs,
840            planned_project,
841            cluster_set,
842            staging_suffix,
843        )
844        .await
845    }
846    .await;
847
848    match result {
849        Ok(count) => Ok(count),
850        Err(e) if dry_run || no_rollback => {
851            if !dry_run {
852                progress::error("Deployment failed (skipping rollback due to --no-rollback flag)");
853            }
854            Err(e)
855        }
856        Err(e) => {
857            progress::error("Deployment failed, rolling back...");
858            let (schemas, clusters) = rollback_staging_resources(client, stage_name).await;
859
860            if schemas > 0 || clusters > 0 {
861                progress::success(&format!(
862                    "Rolled back: {} schema(s), {} cluster(s)",
863                    schemas, clusters
864                ));
865            }
866
867            Err(e)
868        }
869    }
870}
871
872/// Provision all database and schema infrastructure required for a staged deployment.
873///
874/// After this completes, both the suffixed staging schemas (where new objects will be
875/// created) and the production schemas (swap targets) are guaranteed to exist.
876async fn create_databases_and_schemas(
877    executor: &DeploymentExecutor<'_>,
878    planned_project: &Project,
879    schema_set: &BTreeSet<SchemaQualifier>,
880    staging_suffix: &str,
881) -> Result<(), CliError> {
882    // Create project databases that aren't in schema_set
883    // (schema_set databases will be created by prepare_databases_and_schemas)
884    let schema_set_dbs: BTreeSet<&str> = schema_set.iter().map(|sq| sq.database.as_str()).collect();
885    for db in &planned_project.databases {
886        if !schema_set_dbs.contains(db.name.as_str()) {
887            executor.ensure_database(&db.name).await?;
888            verbose!("  Ensured database {} exists", db.name);
889        }
890    }
891
892    // Create staging schemas + apply mod_statements
893    progress::stage_start("Creating staging schemas and applying setup statements");
894    let schema_start = Instant::now();
895    executor
896        .prepare_databases_and_schemas(planned_project, schema_set, Some(staging_suffix))
897        .await?;
898    let schema_duration = schema_start.elapsed();
899    progress::stage_success(
900        &format!(
901            "Created {} staging schema(s) with setup statements",
902            schema_set.len()
903        ),
904        schema_duration,
905    );
906
907    // Create production schemas for swap
908    if !executor.is_dry_run() {
909        for sq in schema_set {
910            executor.ensure_schema(&sq.database, &sq.schema).await?;
911            verbose!("  Ensured schema {}.{} exists", sq.database, sq.schema);
912        }
913    }
914
915    Ok(())
916}
917
918/// Provision staging clusters that mirror the size and configuration of their
919/// production counterparts.
920///
921/// Clusters that already exist are skipped. Cluster names are recorded for rollback
922/// tracking before any cluster is created, so partial failures can be cleaned up.
923async fn create_staging_clusters(
924    executor: &DeploymentExecutor<'_>,
925    client: &Client,
926    stage_name: &str,
927    cluster_set: &BTreeSet<String>,
928    staging_suffix: &str,
929) -> Result<(), CliError> {
930    // Write cluster mappings BEFORE creating clusters so abort can clean up on failure
931    let cluster_names: Vec<String> = cluster_set.iter().cloned().collect();
932    executor
933        .record_deployment_clusters(stage_name, &cluster_names)
934        .await?;
935
936    progress::stage_start("Creating staging clusters");
937    let cluster_start = Instant::now();
938    let mut created_clusters = 0;
939
940    // Batch check which staging clusters already exist (skip in dry-run mode)
941    let existing_staging_clusters = if !executor.is_dry_run() {
942        let staging_cluster_names: Vec<String> = cluster_set
943            .iter()
944            .map(|name| format!("{}{}", name, staging_suffix))
945            .collect();
946        client
947            .introspection()
948            .check_clusters_exist(&staging_cluster_names)
949            .await?
950    } else {
951        BTreeSet::new()
952    };
953
954    for prod_cluster in cluster_set {
955        let staging_cluster = format!("{}{}", prod_cluster, staging_suffix);
956
957        if executor.is_dry_run() {
958            // Config is unused in dry-run mode; provide a placeholder.
959            let placeholder = ClusterConfig::Managed {
960                create_stmt: CreateClusterStatement {
961                    name: Ident::new_unchecked(""),
962                    options: Vec::new(),
963                    features: Vec::new(),
964                    if_not_exists: false,
965                },
966                grants: Vec::new(),
967            };
968            executor
969                .create_cluster(&staging_cluster, prod_cluster, &placeholder)
970                .await?;
971            created_clusters += 1;
972            continue;
973        }
974
975        // Check if staging cluster already exists using batch result
976        if existing_staging_clusters.contains(&staging_cluster) {
977            verbose!("  Cluster '{}' already exists, skipping", staging_cluster);
978            continue;
979        }
980
981        // Get production cluster configuration (handles both managed and unmanaged)
982        let config = client
983            .introspection()
984            .get_cluster_config(prod_cluster)
985            .await?;
986
987        let config = match config {
988            Some(config) => config,
989            None => {
990                return Err(CliError::ClusterNotFound {
991                    name: prod_cluster.clone(),
992                });
993            }
994        };
995
996        executor
997            .create_cluster(&staging_cluster, prod_cluster, &config)
998            .await?;
999        created_clusters += 1;
1000
1001        log_cluster_creation(&staging_cluster, prod_cluster, &config);
1002    }
1003
1004    let cluster_duration = cluster_start.elapsed();
1005    progress::stage_success(
1006        &format!("Created {} cluster(s)", created_clusters),
1007        cluster_duration,
1008    );
1009
1010    Ok(())
1011}
1012
1013/// Log verbose details about a newly created staging cluster.
1014fn log_cluster_creation(staging_cluster: &str, prod_cluster: &str, config: &ClusterConfig) {
1015    match config {
1016        ClusterConfig::Managed {
1017            create_stmt,
1018            grants,
1019        } => {
1020            verbose!(
1021                "  Created managed cluster '{}' ({}, {} grant(s), cloned from '{}')",
1022                staging_cluster,
1023                create_stmt.to_ast_string_simple(),
1024                grants.len(),
1025                prod_cluster
1026            );
1027        }
1028        ClusterConfig::Unmanaged {
1029            replicas, grants, ..
1030        } => {
1031            verbose!(
1032                "  Created unmanaged cluster '{}' with {} replica(s), {} grant(s) (cloned from '{}')",
1033                staging_cluster,
1034                replicas.len(),
1035                grants.len(),
1036                prod_cluster
1037            );
1038            for replica in replicas {
1039                verbose!(
1040                    "    - {} (size: {}{})",
1041                    replica.name,
1042                    replica.size,
1043                    replica
1044                        .availability_zone
1045                        .as_ref()
1046                        .map(|az| format!(", az: {}", az))
1047                        .unwrap_or_default()
1048                );
1049            }
1050        }
1051    }
1052}
1053
1054/// Execute all object definitions (views, materialized views, indexes) into the
1055/// staging schemas.
1056///
1057/// Regular objects are created with suffixed names; replacement materialized views
1058/// are linked to their production targets via `CREATE REPLACEMENT MATERIALIZED VIEW
1059/// ... FOR`. Returns the total number of successfully deployed objects.
1060async fn deploy_objects_to_staging<'a>(
1061    executor: &DeploymentExecutor<'_>,
1062    objects: &'a [(ObjectId, &'a DatabaseObject)],
1063    replacement_mvs: &'a [(ObjectId, &'a DatabaseObject)],
1064    planned_project: &'a Project,
1065    cluster_set: &BTreeSet<String>,
1066    staging_suffix: &str,
1067) -> Result<usize, CliError> {
1068    progress::stage_start("Deploying objects to staging");
1069    let deploy_start = Instant::now();
1070
1071    // Collect ObjectIds from objects being deployed for the staging transformer
1072    // Include both regular objects and replacement MVs
1073    let objects_to_deploy_set: BTreeSet<_> = objects
1074        .iter()
1075        .chain(replacement_mvs.iter())
1076        .map(|(oid, _)| oid.clone())
1077        .collect();
1078
1079    // Deploy external indexes
1080    let mut external_indexes: Vec<_> = planned_project
1081        .iter_objects()
1082        .filter(|object| !objects_to_deploy_set.contains(&object.id))
1083        .flat_map(extract_external_indexes)
1084        .filter_map(|(cluster, index)| cluster_set.contains(&cluster.name).then_some(index))
1085        .collect();
1086
1087    // Transform cluster names in external indexes for staging
1088    normalize::transform_cluster_names_for_staging(&mut external_indexes, staging_suffix);
1089    for index in external_indexes {
1090        verbose!("Creating external index {}", index);
1091        executor.execute_sql(&index).await?;
1092    }
1093
1094    // Build the set of replacement object IDs from the replacement MVs slice.
1095    // Only these specific objects have their references left unsuffixed.
1096    let replacement_object_ids: BTreeSet<ObjectId> =
1097        replacement_mvs.iter().map(|(oid, _)| oid.clone()).collect();
1098
1099    let mut success_count = 0;
1100
1101    // Deploy regular objects
1102    for (idx, (object_id, typed_obj)) in objects.iter().enumerate() {
1103        verbose!(
1104            "Applying {}/{}: {}{} (to schema {}{})",
1105            idx + 1,
1106            objects.len(),
1107            object_id.object(),
1108            staging_suffix,
1109            object_id.schema(),
1110            staging_suffix
1111        );
1112
1113        deploy_single_object(
1114            executor,
1115            object_id,
1116            typed_obj,
1117            staging_suffix,
1118            planned_project,
1119            &objects_to_deploy_set,
1120            &replacement_object_ids,
1121            |stmt| stmt,
1122        )
1123        .await?;
1124        success_count += 1;
1125    }
1126
1127    // Deploy replacement MVs using CREATE REPLACEMENT MATERIALIZED VIEW ... FOR
1128    for (idx, (object_id, typed_obj)) in replacement_mvs.iter().enumerate() {
1129        verbose!(
1130            "Applying replacement MV {}/{}: {} FOR {}",
1131            idx + 1,
1132            replacement_mvs.len(),
1133            object_id.object(),
1134            object_id
1135        );
1136
1137        let production_target = object_id.to_unresolved_item_name();
1138        deploy_single_object(
1139            executor,
1140            object_id,
1141            typed_obj,
1142            staging_suffix,
1143            planned_project,
1144            &objects_to_deploy_set,
1145            &replacement_object_ids,
1146            |stmt| match stmt {
1147                Statement::CreateMaterializedView(mut mv) => {
1148                    mv.replacement_for =
1149                        Some(mz_sql_parser::ast::RawItemName::Name(production_target));
1150                    Statement::CreateMaterializedView(mv)
1151                }
1152                other => other,
1153            },
1154        )
1155        .await?;
1156        success_count += 1;
1157    }
1158
1159    let deploy_duration = deploy_start.elapsed();
1160    progress::stage_success(
1161        &format!("Deployed {} view(s)/materialized view(s)", success_count),
1162        deploy_duration,
1163    );
1164
1165    Ok(success_count)
1166}
1167
1168/// Rollback staging resources on deployment failure.
1169///
1170/// This function performs best-effort cleanup of staging resources created during
1171/// a failed deployment. It mirrors the abort command logic but uses a best-effort
1172/// approach where cleanup failures are logged rather than returning errors.
1173///
1174/// # Arguments
1175/// * `client` - Database client
1176/// * `environment` - Staging environment name
1177///
1178/// # Returns
1179/// Number of schemas and clusters that were cleaned up (for summary message)
1180async fn rollback_staging_resources(client: &Client, environment: &str) -> (usize, usize) {
1181    let staging_schemas = best_effort_fetch(
1182        client
1183            .introspection()
1184            .get_staging_schemas(environment)
1185            .await,
1186        "query staging schemas",
1187    );
1188    let staging_clusters = best_effort_fetch(
1189        client
1190            .introspection()
1191            .get_staging_clusters(environment)
1192            .await,
1193        "query staging clusters",
1194    );
1195
1196    let schema_count = staging_schemas.len();
1197    let cluster_count = staging_clusters.len();
1198
1199    if !staging_schemas.is_empty() {
1200        verbose!("Dropping staging schemas...");
1201        if let Err(e) = client
1202            .introspection()
1203            .drop_staging_schemas(&staging_schemas)
1204            .await
1205        {
1206            verbose!("Warning: Failed to drop some schemas: {}", e);
1207        } else {
1208            for sq in &staging_schemas {
1209                verbose!("  Dropped {}.{}", sq.database, sq.schema);
1210            }
1211        }
1212    }
1213
1214    if !staging_clusters.is_empty() {
1215        verbose!("Dropping staging clusters...");
1216        if let Err(e) = client
1217            .introspection()
1218            .drop_staging_clusters(&staging_clusters)
1219            .await
1220        {
1221            verbose!("Warning: Failed to drop some clusters: {}", e);
1222        } else {
1223            for cluster in &staging_clusters {
1224                verbose!("  Dropped {}", cluster);
1225            }
1226        }
1227    }
1228
1229    verbose!("Deleting deployment records...");
1230    best_effort_delete(
1231        client
1232            .deployments()
1233            .delete_deployment_clusters(environment)
1234            .await,
1235        "delete cluster records",
1236    );
1237    best_effort_delete(
1238        client
1239            .deployments()
1240            .delete_pending_statements(environment)
1241            .await,
1242        "delete pending statements",
1243    );
1244    best_effort_delete(
1245        client
1246            .deployments()
1247            .delete_replacement_mvs(environment)
1248            .await,
1249        "delete replacement MV records",
1250    );
1251    best_effort_delete(
1252        client.deployments().delete_deployment(environment).await,
1253        "delete deployment records",
1254    );
1255
1256    (schema_count, cluster_count)
1257}
1258
1259/// Best-effort fetch wrapper used by rollback.
1260///
1261/// Converts query failures into empty results so cleanup can continue and report
1262/// as much progress as possible instead of aborting midway.
1263fn best_effort_fetch<T, E: fmt::Display>(result: Result<Vec<T>, E>, action: &str) -> Vec<T> {
1264    match result {
1265        Ok(values) => values,
1266        Err(e) => {
1267            verbose!("Warning: Failed to {}: {}", action, e);
1268            vec![]
1269        }
1270    }
1271}
1272
1273/// Best-effort delete wrapper used by rollback metadata cleanup.
1274fn best_effort_delete<E: fmt::Display>(result: Result<(), E>, action: &str) {
1275    if let Err(e) = result {
1276        verbose!("Warning: Failed to {}: {}", action, e);
1277    }
1278}
1279
1280/// Deploy a single object to the staging environment.
1281///
1282/// Handles normalization, execution, and deployment of indexes/grants/comments.
1283/// The `transform` callback allows the caller to modify the normalized statement
1284/// before execution (e.g., to set `replacement_for` on replacement MVs).
1285///
1286/// `replacement_objects` is the set of specific object IDs being updated
1287/// in-place via replacement MVs. References to these objects are left
1288/// unsuffixed (pointing to production). During full deployment the set is
1289/// empty, so every reference is suffixed to point at the staging schemas.
1290async fn deploy_single_object(
1291    executor: &DeploymentExecutor<'_>,
1292    object_id: &ObjectId,
1293    typed_obj: &DatabaseObject,
1294    staging_suffix: &str,
1295    planned_project: &Project,
1296    objects_to_deploy_set: &BTreeSet<ObjectId>,
1297    replacement_objects: &BTreeSet<ObjectId>,
1298    transform: impl FnOnce(Statement) -> Statement,
1299) -> Result<(), CliError> {
1300    let original_fqn: FullyQualifiedName = object_id.clone().into();
1301
1302    let mut visitor = NormalizingVisitor::staging(
1303        &original_fqn,
1304        staging_suffix.to_string(),
1305        &planned_project.external_dependencies,
1306        Some(objects_to_deploy_set),
1307        replacement_objects,
1308    );
1309
1310    let stmt = typed_obj
1311        .stmt
1312        .clone()
1313        .normalize_name_with(&visitor, &original_fqn.to_item_name())
1314        .normalize_dependencies_with(&mut visitor)
1315        .normalize_cluster_with(&visitor);
1316
1317    let stmt = transform(stmt);
1318    executor.execute_sql(&stmt).await?;
1319
1320    // Deploy indexes, grants, and comments
1321    let mut indexes = typed_obj.indexes.clone();
1322    let mut grants = typed_obj.grants.clone();
1323    let mut comments = typed_obj.comments.clone();
1324
1325    visitor.normalize_index_references(&mut indexes);
1326    visitor.normalize_index_clusters(&mut indexes);
1327    visitor.normalize_grant_references(&mut grants);
1328    visitor.normalize_comment_references(&mut comments);
1329
1330    for index in &indexes {
1331        executor.execute_sql(index).await?;
1332    }
1333
1334    for grant in &grants {
1335        executor.execute_sql(grant).await?;
1336    }
1337
1338    for comment in &comments {
1339        executor.execute_sql(comment).await?;
1340    }
1341
1342    Ok(())
1343}
1344
1345/// Check that no new replacement objects are being added to schemas that already
1346/// have production objects.
1347fn validate_no_new_objects_in_existing_stable_schemas(
1348    change_set: &ChangeSet,
1349    production_snapshot: &DeploymentSnapshot,
1350) -> Result<(), CliError> {
1351    let blocked: Vec<_> = change_set
1352        .new_replacement_objects
1353        .iter()
1354        .filter(|obj| {
1355            !production_snapshot.objects.contains_key(obj)
1356                && production_snapshot
1357                    .objects
1358                    .keys()
1359                    .any(|prod| prod.database() == obj.database() && prod.schema() == obj.schema())
1360        })
1361        .collect();
1362
1363    if blocked.is_empty() {
1364        return Ok(());
1365    }
1366
1367    let first = blocked[0];
1368    Err(CliError::NewObjectInExistingStableSchema {
1369        database: first.expect_database().to_string(),
1370        schema: first.schema().to_string(),
1371        objects: blocked.iter().map(|o| o.object().to_string()).collect(),
1372    })
1373}
1374
1375#[cfg(test)]
1376mod tests {
1377    use super::*;
1378    use crate::project::analysis::deployment_snapshot::build_snapshot_from_planned;
1379    use crate::project::ir::compiled;
1380    use crate::project::ir::object_id::ObjectId;
1381    use std::collections::{BTreeMap, BTreeSet};
1382
1383    #[mz_ore::test]
1384    fn parse_qualified_schema_requires_two_parts() {
1385        // Fully qualified parses to (database, schema).
1386        let sq = parse_qualified_schema("app.core").expect("qualified name parses");
1387        assert_eq!(
1388            sq,
1389            SchemaQualifier::new("app".to_string(), "core".to_string())
1390        );
1391
1392        // A reserved-word component is handled via the SQL parser.
1393        let sq = parse_qualified_schema("app.\"select\"").expect("quoted keyword parses");
1394        assert_eq!(
1395            sq,
1396            SchemaQualifier::new("app".to_string(), "select".to_string())
1397        );
1398
1399        // Unqualified (1-part) and over-qualified (3-part) are rejected.
1400        assert!(parse_qualified_schema("core").is_err());
1401        assert!(parse_qualified_schema("app.core.orders").is_err());
1402    }
1403
1404    /// Parse SQL strings into a compiled::DatabaseObject.
1405    ///
1406    /// The first CREATE statement becomes the main statement.
1407    /// Any CREATE INDEX statements become entries in the indexes vec.
1408    fn make_typed_object(sqls: &[&str]) -> DatabaseObject {
1409        let mut stmt = None;
1410        let mut indexes = Vec::new();
1411
1412        for sql in sqls {
1413            let parsed = mz_sql_parser::parser::parse_statements(sql).unwrap();
1414            for p in parsed {
1415                match p.ast {
1416                    mz_sql_parser::ast::Statement::CreateView(s) => {
1417                        stmt = Some(Statement::CreateView(s));
1418                    }
1419                    mz_sql_parser::ast::Statement::CreateMaterializedView(s) => {
1420                        stmt = Some(Statement::CreateMaterializedView(s));
1421                    }
1422                    mz_sql_parser::ast::Statement::CreateTable(s) => {
1423                        stmt = Some(Statement::CreateTable(s));
1424                    }
1425                    mz_sql_parser::ast::Statement::CreateSource(s) => {
1426                        stmt = Some(Statement::CreateSource(s));
1427                    }
1428                    mz_sql_parser::ast::Statement::CreateConnection(s) => {
1429                        stmt = Some(Statement::CreateConnection(s));
1430                    }
1431                    mz_sql_parser::ast::Statement::CreateSecret(s) => {
1432                        stmt = Some(Statement::CreateSecret(s));
1433                    }
1434                    mz_sql_parser::ast::Statement::CreateIndex(s) => {
1435                        indexes.push(s);
1436                    }
1437                    other => panic!("Unexpected statement type: {:?}", other),
1438                }
1439            }
1440        }
1441
1442        DatabaseObject {
1443            path: std::path::PathBuf::from("test.sql"),
1444            stmt: stmt.expect("Expected at least one CREATE statement"),
1445            indexes,
1446            grants: vec![],
1447            comments: vec![],
1448            tests: vec![],
1449        }
1450    }
1451
1452    /// Build a graph::Project from a list of (database, schema, object_name, typed_obj) tuples.
1453    fn make_planned_project(objects: Vec<(&str, &str, &str, DatabaseObject)>) -> Project {
1454        // Group into databases -> schemas -> objects
1455        let mut db_map: BTreeMap<String, BTreeMap<String, Vec<DatabaseObject>>> = BTreeMap::new();
1456
1457        for (database, schema, _name, typed_obj) in objects {
1458            db_map
1459                .entry(database.to_string())
1460                .or_default()
1461                .entry(schema.to_string())
1462                .or_default()
1463                .push(typed_obj);
1464        }
1465
1466        let databases: Vec<compiled::Database> = db_map
1467            .into_iter()
1468            .map(|(db_name, schemas)| compiled::Database {
1469                name: db_name,
1470                schemas: schemas
1471                    .into_iter()
1472                    .map(|(schema_name, objs)| compiled::Schema {
1473                        name: schema_name,
1474                        objects: objs,
1475                        mod_statements: None,
1476                    })
1477                    .collect(),
1478                mod_statements: None,
1479            })
1480            .collect();
1481
1482        let typed_project = compiled::Project {
1483            databases,
1484            replacement_schemas: BTreeSet::new(),
1485        };
1486
1487        Project::from(typed_project)
1488    }
1489
1490    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1491    #[mz_ore::test]
1492    fn test_full_deploy_view_not_indexed_mixed_types() {
1493        let view_obj = make_typed_object(&["CREATE VIEW my_view AS SELECT 1"]);
1494        let table_obj = make_typed_object(&["CREATE TABLE my_table (id INT)"]);
1495        let source_obj = make_typed_object(&[
1496            "CREATE SOURCE my_source IN CLUSTER source_cluster FROM LOAD GENERATOR COUNTER",
1497        ]);
1498        let conn_obj =
1499            make_typed_object(&["CREATE CONNECTION my_conn TO KAFKA (BROKER 'localhost:9092')"]);
1500        let secret_obj = make_typed_object(&["CREATE SECRET my_secret AS 'hunter2'"]);
1501
1502        let objects: Vec<ObjectRef> = vec![
1503            (
1504                ObjectId::new("db".into(), "public".into(), "my_view".into()),
1505                &view_obj,
1506            ),
1507            (
1508                ObjectId::new("db".into(), "public".into(), "my_table".into()),
1509                &table_obj,
1510            ),
1511            (
1512                ObjectId::new("db".into(), "public".into(), "my_source".into()),
1513                &source_obj,
1514            ),
1515            (
1516                ObjectId::new("db".into(), "public".into(), "my_conn".into()),
1517                &conn_obj,
1518            ),
1519            (
1520                ObjectId::new("db".into(), "public".into(), "my_secret".into()),
1521                &secret_obj,
1522            ),
1523        ];
1524
1525        let replacement_ids = BTreeSet::new();
1526        let partitioned = partition_objects(objects, &replacement_ids);
1527
1528        // Only the view should be in staged objects
1529        assert_eq!(
1530            partitioned.objects.len(),
1531            1,
1532            "Only the view should be staged"
1533        );
1534        assert_eq!(partitioned.objects[0].0.object(), "my_view");
1535
1536        // Table, source, connection, secret should be counted as skipped
1537        assert_eq!(
1538            partitioned.table_count, 4,
1539            "Table, source, connection, and secret should all be skipped"
1540        );
1541
1542        // No sinks or replacement MVs
1543        assert!(partitioned.sinks.is_empty());
1544        assert!(partitioned.replacement_mvs.is_empty());
1545
1546        // Collect stage resources
1547        let (schema_set, cluster_set) =
1548            collect_stage_resources(&partitioned.objects, &partitioned.replacement_mvs);
1549
1550        // Should have the view's schema
1551        assert_eq!(schema_set.len(), 1);
1552        assert!(schema_set.contains(&SchemaQualifier::new("db".into(), "public".into())));
1553
1554        // View has no cluster, so cluster_set should be empty
1555        assert!(
1556            cluster_set.is_empty(),
1557            "View without index should not require any clusters"
1558        );
1559    }
1560
1561    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1562    #[mz_ore::test]
1563    fn test_full_deploy_view_indexed_different_cluster() {
1564        let view_obj = make_typed_object(&[
1565            "CREATE VIEW my_view AS SELECT 1",
1566            "CREATE INDEX my_idx IN CLUSTER index_cluster ON my_view (column1)",
1567        ]);
1568        let table_obj = make_typed_object(&["CREATE TABLE my_table (id INT)"]);
1569        let source_obj = make_typed_object(&[
1570            "CREATE SOURCE my_source IN CLUSTER source_cluster FROM LOAD GENERATOR COUNTER",
1571        ]);
1572        let conn_obj =
1573            make_typed_object(&["CREATE CONNECTION my_conn TO KAFKA (BROKER 'localhost:9092')"]);
1574        let secret_obj = make_typed_object(&["CREATE SECRET my_secret AS 'hunter2'"]);
1575
1576        let objects: Vec<ObjectRef> = vec![
1577            (
1578                ObjectId::new("db".into(), "public".into(), "my_view".into()),
1579                &view_obj,
1580            ),
1581            (
1582                ObjectId::new("db".into(), "public".into(), "my_table".into()),
1583                &table_obj,
1584            ),
1585            (
1586                ObjectId::new("db".into(), "public".into(), "my_source".into()),
1587                &source_obj,
1588            ),
1589            (
1590                ObjectId::new("db".into(), "public".into(), "my_conn".into()),
1591                &conn_obj,
1592            ),
1593            (
1594                ObjectId::new("db".into(), "public".into(), "my_secret".into()),
1595                &secret_obj,
1596            ),
1597        ];
1598
1599        let replacement_ids = BTreeSet::new();
1600        let partitioned = partition_objects(objects, &replacement_ids);
1601
1602        // Only the view should be staged
1603        assert_eq!(partitioned.objects.len(), 1);
1604        assert_eq!(partitioned.objects[0].0.object(), "my_view");
1605        assert_eq!(partitioned.table_count, 4);
1606
1607        // Collect stage resources
1608        let (schema_set, cluster_set) =
1609            collect_stage_resources(&partitioned.objects, &partitioned.replacement_mvs);
1610
1611        // Should have view's schema
1612        assert_eq!(schema_set.len(), 1);
1613        assert!(schema_set.contains(&SchemaQualifier::new("db".into(), "public".into())));
1614
1615        // Should stage index_cluster (from the view's index), NOT source_cluster
1616        assert_eq!(
1617            cluster_set.len(),
1618            1,
1619            "Should only have index_cluster, got: {:?}",
1620            cluster_set
1621        );
1622        assert!(
1623            cluster_set.contains("index_cluster"),
1624            "Should stage index_cluster from the view's index"
1625        );
1626        assert!(
1627            !cluster_set.contains("source_cluster"),
1628            "Should NOT stage source_cluster (source is not staged)"
1629        );
1630    }
1631
1632    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1633    #[mz_ore::test]
1634    fn test_incremental_deploy_view_updated_not_indexed() {
1635        // Build planned project with all object types
1636        let view_obj = make_typed_object(&["CREATE VIEW my_view AS SELECT 1"]);
1637        let table_obj = make_typed_object(&["CREATE TABLE my_table (id INT)"]);
1638        let source_obj = make_typed_object(&[
1639            "CREATE SOURCE my_source IN CLUSTER source_cluster FROM LOAD GENERATOR COUNTER",
1640        ]);
1641        let conn_obj =
1642            make_typed_object(&["CREATE CONNECTION my_conn TO KAFKA (BROKER 'localhost:9092')"]);
1643        let secret_obj = make_typed_object(&["CREATE SECRET my_secret AS 'hunter2'"]);
1644
1645        let planned_project = make_planned_project(vec![
1646            ("db", "public", "my_view", view_obj),
1647            ("db", "storage", "my_table", table_obj),
1648            ("db", "storage", "my_source", source_obj),
1649            ("db", "storage", "my_conn", conn_obj),
1650            ("db", "storage", "my_secret", secret_obj),
1651        ]);
1652
1653        // Build new snapshot from planned project
1654        let new_snapshot = build_snapshot_from_planned(&planned_project).unwrap();
1655
1656        // Build old snapshot: same hashes for everything EXCEPT the view
1657        let mut old_snapshot = DeploymentSnapshot::default();
1658        for (object_id, hash) in &new_snapshot.objects {
1659            if object_id.object() == "my_view" {
1660                // Different hash to simulate the view having changed
1661                old_snapshot
1662                    .objects
1663                    .insert(object_id.clone(), "old_hash".to_string());
1664            } else {
1665                old_snapshot.objects.insert(object_id.clone(), hash.clone());
1666            }
1667        }
1668
1669        // Compute changeset
1670        let change_set = ChangeSet::from_deployment_snapshot_comparison(
1671            &old_snapshot,
1672            &new_snapshot,
1673            &planned_project,
1674            &BTreeSet::new(),
1675        );
1676
1677        // The view should be in objects_to_deploy
1678        assert!(
1679            change_set.objects_to_deploy.contains(&ObjectId::new(
1680                "db".into(),
1681                "public".into(),
1682                "my_view".into()
1683            )),
1684            "Changed view should be in objects_to_deploy"
1685        );
1686
1687        // Get filtered objects and partition
1688        let objects = planned_project
1689            .get_sorted_objects_filtered(&change_set.objects_to_deploy)
1690            .unwrap();
1691
1692        let partitioned = partition_objects(objects, &change_set.changed_replacement_objects);
1693
1694        // Only the view should be staged
1695        assert_eq!(
1696            partitioned.objects.len(),
1697            1,
1698            "Only the changed view should be staged, got: {:?}",
1699            partitioned
1700                .objects
1701                .iter()
1702                .map(|(id, _)| id.object())
1703                .collect::<Vec<_>>()
1704        );
1705        assert_eq!(partitioned.objects[0].0.object(), "my_view");
1706
1707        let (schema_set, cluster_set) =
1708            collect_stage_resources(&partitioned.objects, &partitioned.replacement_mvs);
1709
1710        assert_eq!(schema_set.len(), 1);
1711        assert!(schema_set.contains(&SchemaQualifier::new("db".into(), "public".into())));
1712        assert!(
1713            cluster_set.is_empty(),
1714            "View without index should not require any clusters"
1715        );
1716    }
1717
1718    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1719    #[mz_ore::test]
1720    fn test_incremental_deploy_view_updated_indexed_different_cluster() {
1721        // Build planned project with indexed view and other object types
1722        let view_obj = make_typed_object(&[
1723            "CREATE VIEW my_view AS SELECT 1",
1724            "CREATE INDEX my_idx IN CLUSTER index_cluster ON my_view (column1)",
1725        ]);
1726        let table_obj = make_typed_object(&["CREATE TABLE my_table (id INT)"]);
1727        let source_obj = make_typed_object(&[
1728            "CREATE SOURCE my_source IN CLUSTER source_cluster FROM LOAD GENERATOR COUNTER",
1729        ]);
1730        let conn_obj =
1731            make_typed_object(&["CREATE CONNECTION my_conn TO KAFKA (BROKER 'localhost:9092')"]);
1732        let secret_obj = make_typed_object(&["CREATE SECRET my_secret AS 'hunter2'"]);
1733
1734        let planned_project = make_planned_project(vec![
1735            ("db", "public", "my_view", view_obj),
1736            ("db", "storage", "my_table", table_obj),
1737            ("db", "storage", "my_source", source_obj),
1738            ("db", "storage", "my_conn", conn_obj),
1739            ("db", "storage", "my_secret", secret_obj),
1740        ]);
1741
1742        // Build new snapshot from planned project
1743        let new_snapshot = build_snapshot_from_planned(&planned_project).unwrap();
1744
1745        // Build old snapshot: same hashes except the view
1746        let mut old_snapshot = DeploymentSnapshot::default();
1747        for (object_id, hash) in &new_snapshot.objects {
1748            if object_id.object() == "my_view" {
1749                old_snapshot
1750                    .objects
1751                    .insert(object_id.clone(), "old_hash".to_string());
1752            } else {
1753                old_snapshot.objects.insert(object_id.clone(), hash.clone());
1754            }
1755        }
1756
1757        // Compute changeset
1758        let change_set = ChangeSet::from_deployment_snapshot_comparison(
1759            &old_snapshot,
1760            &new_snapshot,
1761            &planned_project,
1762            &BTreeSet::new(),
1763        );
1764
1765        assert!(
1766            change_set.objects_to_deploy.contains(&ObjectId::new(
1767                "db".into(),
1768                "public".into(),
1769                "my_view".into()
1770            )),
1771            "Changed view should be in objects_to_deploy"
1772        );
1773
1774        // Get filtered objects and partition
1775        let objects = planned_project
1776            .get_sorted_objects_filtered(&change_set.objects_to_deploy)
1777            .unwrap();
1778
1779        let partitioned = partition_objects(objects, &change_set.changed_replacement_objects);
1780
1781        // Only the view should be staged
1782        assert_eq!(
1783            partitioned.objects.len(),
1784            1,
1785            "Only the changed view should be staged, got: {:?}",
1786            partitioned
1787                .objects
1788                .iter()
1789                .map(|(id, _)| id.object())
1790                .collect::<Vec<_>>()
1791        );
1792        assert_eq!(partitioned.objects[0].0.object(), "my_view");
1793
1794        let (schema_set, cluster_set) =
1795            collect_stage_resources(&partitioned.objects, &partitioned.replacement_mvs);
1796
1797        assert_eq!(schema_set.len(), 1);
1798        assert!(schema_set.contains(&SchemaQualifier::new("db".into(), "public".into())));
1799
1800        // Should stage index_cluster only, NOT source_cluster
1801        assert_eq!(
1802            cluster_set.len(),
1803            1,
1804            "Should only have index_cluster, got: {:?}",
1805            cluster_set
1806        );
1807        assert!(
1808            cluster_set.contains("index_cluster"),
1809            "Should stage index_cluster from the view's index"
1810        );
1811        assert!(
1812            !cluster_set.contains("source_cluster"),
1813            "Should NOT stage source_cluster"
1814        );
1815    }
1816
1817    fn make_empty_change_set() -> ChangeSet {
1818        ChangeSet {
1819            changed_objects: BTreeSet::new(),
1820            dirty_schemas: BTreeSet::new(),
1821            dirty_clusters: BTreeSet::new(),
1822            objects_to_deploy: BTreeSet::new(),
1823            new_replacement_objects: BTreeSet::new(),
1824            changed_replacement_objects: BTreeSet::new(),
1825        }
1826    }
1827
1828    #[mz_ore::test]
1829    fn test_validate_no_new_replacement_objects_first_deploy() {
1830        let cs = make_empty_change_set();
1831        let snapshot = DeploymentSnapshot::default();
1832        assert!(validate_no_new_objects_in_existing_stable_schemas(&cs, &snapshot).is_ok());
1833    }
1834
1835    #[mz_ore::test]
1836    fn test_validate_new_replacement_objects_in_brand_new_schema() {
1837        let mut cs = make_empty_change_set();
1838        cs.new_replacement_objects.insert(ObjectId::new(
1839            "db".into(),
1840            "analytics".into(),
1841            "new_mv".into(),
1842        ));
1843
1844        // Production has objects in a *different* schema, not analytics
1845        let mut snapshot = DeploymentSnapshot::default();
1846        snapshot.objects.insert(
1847            ObjectId::new("db".into(), "public".into(), "existing_mv".into()),
1848            "hash1".into(),
1849        );
1850
1851        assert!(validate_no_new_objects_in_existing_stable_schemas(&cs, &snapshot).is_ok());
1852    }
1853
1854    #[mz_ore::test]
1855    fn test_validate_new_replacement_objects_in_existing_production_schema() {
1856        let mut cs = make_empty_change_set();
1857        cs.new_replacement_objects.insert(ObjectId::new(
1858            "db".into(),
1859            "analytics".into(),
1860            "new_mv".into(),
1861        ));
1862
1863        // Production already has objects in analytics
1864        let mut snapshot = DeploymentSnapshot::default();
1865        snapshot.objects.insert(
1866            ObjectId::new("db".into(), "analytics".into(), "existing_mv".into()),
1867            "hash1".into(),
1868        );
1869
1870        let result = validate_no_new_objects_in_existing_stable_schemas(&cs, &snapshot);
1871        assert!(result.is_err());
1872        match result.unwrap_err() {
1873            CliError::NewObjectInExistingStableSchema {
1874                database,
1875                schema,
1876                objects,
1877            } => {
1878                assert_eq!(database, "db");
1879                assert_eq!(schema, "analytics");
1880                assert_eq!(objects, vec!["new_mv"]);
1881            }
1882            other => panic!("Expected NewObjectInExistingStableSchema, got: {:?}", other),
1883        }
1884    }
1885
1886    #[mz_ore::test]
1887    fn test_validate_changed_replacement_objects_only() {
1888        let mut cs = make_empty_change_set();
1889        // Only changed objects, no new ones
1890        cs.changed_replacement_objects.insert(ObjectId::new(
1891            "db".into(),
1892            "analytics".into(),
1893            "changed_mv".into(),
1894        ));
1895
1896        let mut snapshot = DeploymentSnapshot::default();
1897        snapshot.objects.insert(
1898            ObjectId::new("db".into(), "analytics".into(), "changed_mv".into()),
1899            "hash1".into(),
1900        );
1901
1902        assert!(validate_no_new_objects_in_existing_stable_schemas(&cs, &snapshot).is_ok());
1903    }
1904
1905    #[mz_ore::test]
1906    fn test_validate_mixed_new_in_new_schema_changed_in_existing() {
1907        let mut cs = make_empty_change_set();
1908        // New object in a brand-new schema
1909        cs.new_replacement_objects.insert(ObjectId::new(
1910            "db".into(),
1911            "new_schema".into(),
1912            "new_mv".into(),
1913        ));
1914        // Changed object in an existing schema
1915        cs.changed_replacement_objects.insert(ObjectId::new(
1916            "db".into(),
1917            "existing_schema".into(),
1918            "changed_mv".into(),
1919        ));
1920
1921        // Production has objects only in existing_schema
1922        let mut snapshot = DeploymentSnapshot::default();
1923        snapshot.objects.insert(
1924            ObjectId::new("db".into(), "existing_schema".into(), "changed_mv".into()),
1925            "hash1".into(),
1926        );
1927
1928        // Should pass: the new object is in a schema with no production objects
1929        assert!(validate_no_new_objects_in_existing_stable_schemas(&cs, &snapshot).is_ok());
1930    }
1931
1932    #[mz_ore::test]
1933    fn test_validate_transitioning_objects_in_existing_schema_allowed() {
1934        let mut cs = make_empty_change_set();
1935        // Object transitioning from Objects→Replacement lands in new_replacement_objects
1936        cs.new_replacement_objects.insert(ObjectId::new(
1937            "db".into(),
1938            "analytics".into(),
1939            "existing_mv".into(),
1940        ));
1941
1942        // The same object already exists in production (it's transitioning, not new)
1943        let mut snapshot = DeploymentSnapshot::default();
1944        snapshot.objects.insert(
1945            ObjectId::new("db".into(), "analytics".into(), "existing_mv".into()),
1946            "hash1".into(),
1947        );
1948
1949        // Should pass: the object already exists in production, it's just changing schema kind
1950        assert!(validate_no_new_objects_in_existing_stable_schemas(&cs, &snapshot).is_ok());
1951    }
1952
1953    fn make_planned_project_with_replacement_schemas(
1954        objects: Vec<(&str, &str, &str, DatabaseObject)>,
1955        replacement_schemas: BTreeSet<SchemaQualifier>,
1956    ) -> Project {
1957        let mut db_map: BTreeMap<String, BTreeMap<String, Vec<DatabaseObject>>> = BTreeMap::new();
1958
1959        for (database, schema, _name, typed_obj) in objects {
1960            db_map
1961                .entry(database.to_string())
1962                .or_default()
1963                .entry(schema.to_string())
1964                .or_default()
1965                .push(typed_obj);
1966        }
1967
1968        let databases: Vec<compiled::Database> = db_map
1969            .into_iter()
1970            .map(|(db_name, schemas)| compiled::Database {
1971                name: db_name,
1972                schemas: schemas
1973                    .into_iter()
1974                    .map(|(schema_name, objs)| compiled::Schema {
1975                        name: schema_name,
1976                        objects: objs,
1977                        mod_statements: None,
1978                    })
1979                    .collect(),
1980                mod_statements: None,
1981            })
1982            .collect();
1983
1984        let typed_project = compiled::Project {
1985            databases,
1986            replacement_schemas,
1987        };
1988
1989        Project::from(typed_project)
1990    }
1991
1992    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1993    #[mz_ore::test]
1994    fn test_build_snapshot_replacement_schema_kind() {
1995        let mv_obj =
1996            make_typed_object(&["CREATE MATERIALIZED VIEW my_mv IN CLUSTER compute AS SELECT 1"]);
1997        let view_obj = make_typed_object(&["CREATE VIEW my_view AS SELECT 1"]);
1998
1999        let mut replacement_schemas = BTreeSet::new();
2000        replacement_schemas.insert(SchemaQualifier::new("db".into(), "stable".into()));
2001
2002        let planned_project = make_planned_project_with_replacement_schemas(
2003            vec![
2004                ("db", "stable", "my_mv", mv_obj),
2005                ("db", "regular", "my_view", view_obj),
2006            ],
2007            replacement_schemas,
2008        );
2009
2010        let snapshot = build_snapshot_from_planned(&planned_project).unwrap();
2011
2012        // The stable schema should be Replacement
2013        assert_eq!(
2014            snapshot
2015                .schemas
2016                .get(&SchemaQualifier::new("db".into(), "stable".into())),
2017            Some(&DeploymentKind::Replacement),
2018            "Replacement schema should have Replacement kind in snapshot"
2019        );
2020
2021        // The regular schema should be Objects
2022        assert_eq!(
2023            snapshot
2024                .schemas
2025                .get(&SchemaQualifier::new("db".into(), "regular".into())),
2026            Some(&DeploymentKind::Objects),
2027            "Regular schema should have Objects kind in snapshot"
2028        );
2029    }
2030
2031    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2032    #[mz_ore::test]
2033    fn test_build_snapshot_no_replacement_schemas_all_objects() {
2034        let mv_obj =
2035            make_typed_object(&["CREATE MATERIALIZED VIEW my_mv IN CLUSTER compute AS SELECT 1"]);
2036        let view_obj = make_typed_object(&["CREATE VIEW my_view AS SELECT 1"]);
2037
2038        let planned_project = make_planned_project(vec![
2039            ("db", "stable", "my_mv", mv_obj),
2040            ("db", "regular", "my_view", view_obj),
2041        ]);
2042
2043        let snapshot = build_snapshot_from_planned(&planned_project).unwrap();
2044
2045        // Both should be Objects when no replacement_schemas configured
2046        assert_eq!(
2047            snapshot
2048                .schemas
2049                .get(&SchemaQualifier::new("db".into(), "stable".into())),
2050            Some(&DeploymentKind::Objects),
2051        );
2052        assert_eq!(
2053            snapshot
2054                .schemas
2055                .get(&SchemaQualifier::new("db".into(), "regular".into())),
2056            Some(&DeploymentKind::Objects),
2057        );
2058    }
2059
2060    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2061    #[mz_ore::test]
2062    fn test_record_stage_metadata_transition_override() {
2063        // During an Objects→Replacement transition, MVs go through the regular
2064        // objects path (not replacement_mvs), but the metadata must still record
2065        // the schema as Replacement.
2066        let mv_obj =
2067            make_typed_object(&["CREATE MATERIALIZED VIEW my_mv IN CLUSTER compute AS SELECT 1"]);
2068
2069        // Objects path (transition — MV is NOT in replacement_mvs)
2070        let objects: Vec<ObjectRef> = vec![(
2071            ObjectId::new("db".into(), "stable".into(), "my_mv".into()),
2072            &mv_obj,
2073        )];
2074        let sinks: Vec<ObjectRef> = vec![];
2075        let replacement_mvs: Vec<ObjectRef> = vec![];
2076
2077        // The project declares "stable" as a replacement schema
2078        let mut replacement_schemas = BTreeSet::new();
2079        replacement_schemas.insert(SchemaQualifier::new("db".into(), "stable".into()));
2080
2081        // Simulate what record_stage_metadata does (without DB calls)
2082        let mut staging_snapshot = DeploymentSnapshot::default();
2083
2084        for (object_id, typed_obj) in &objects {
2085            let hash = deployment_snapshot::compute_typed_hash(typed_obj);
2086            staging_snapshot.objects.insert(object_id.clone(), hash);
2087            staging_snapshot.schemas.insert(
2088                SchemaQualifier::new(
2089                    object_id.expect_database().to_string(),
2090                    object_id.schema().to_string(),
2091                ),
2092                DeploymentKind::Objects,
2093            );
2094        }
2095
2096        for (object_id, typed_obj) in &sinks {
2097            let hash = deployment_snapshot::compute_typed_hash(typed_obj);
2098            staging_snapshot.objects.insert(object_id.clone(), hash);
2099            staging_snapshot
2100                .schemas
2101                .entry(SchemaQualifier::new(
2102                    object_id.expect_database().to_string(),
2103                    object_id.schema().to_string(),
2104                ))
2105                .or_insert(DeploymentKind::Sinks);
2106        }
2107
2108        for (object_id, typed_obj) in &replacement_mvs {
2109            let hash = deployment_snapshot::compute_typed_hash(typed_obj);
2110            staging_snapshot.objects.insert(object_id.clone(), hash);
2111            staging_snapshot.schemas.insert(
2112                SchemaQualifier::new(
2113                    object_id.expect_database().to_string(),
2114                    object_id.schema().to_string(),
2115                ),
2116                DeploymentKind::Replacement,
2117            );
2118        }
2119
2120        // Before the fix, the schema would remain Objects here.
2121        assert_eq!(
2122            staging_snapshot
2123                .schemas
2124                .get(&SchemaQualifier::new("db".into(), "stable".into())),
2125            Some(&DeploymentKind::Objects),
2126            "Before override, schema should be Objects (from regular objects path)"
2127        );
2128
2129        // Apply the replacement_schemas override (the fix)
2130        for sq in &replacement_schemas {
2131            if staging_snapshot.schemas.contains_key(sq) {
2132                staging_snapshot
2133                    .schemas
2134                    .insert(sq.clone(), DeploymentKind::Replacement);
2135            }
2136        }
2137
2138        // After the fix, the schema should be Replacement
2139        assert_eq!(
2140            staging_snapshot
2141                .schemas
2142                .get(&SchemaQualifier::new("db".into(), "stable".into())),
2143            Some(&DeploymentKind::Replacement),
2144            "After override, schema should be Replacement"
2145        );
2146    }
2147
2148    #[mz_ore::test]
2149    fn test_record_stage_metadata_override_only_applies_to_existing_schemas() {
2150        // The override should NOT create new schema entries — it only applies to
2151        // schemas that already have objects in the staging snapshot.
2152        let replacement_schemas =
2153            BTreeSet::from([SchemaQualifier::new("db".into(), "nonexistent".into())]);
2154
2155        let mut staging_snapshot = DeploymentSnapshot::default();
2156
2157        // Apply the replacement_schemas override
2158        for sq in &replacement_schemas {
2159            if staging_snapshot.schemas.contains_key(sq) {
2160                staging_snapshot
2161                    .schemas
2162                    .insert(sq.clone(), DeploymentKind::Replacement);
2163            }
2164        }
2165
2166        // Should NOT have created a new entry
2167        assert!(
2168            staging_snapshot.schemas.is_empty(),
2169            "Override should not create entries for schemas with no objects"
2170        );
2171    }
2172
2173    #[mz_ore::test]
2174    fn test_validate_stage_name_length() {
2175        assert!(validate_stage_name("prod").is_ok());
2176        assert!(validate_stage_name(&"a".repeat(Ident::MAX_LENGTH / 2 - 1)).is_ok());
2177        assert!(validate_stage_name(&"a".repeat(Ident::MAX_LENGTH)).is_err());
2178    }
2179}