Skip to main content

mz_deploy/client/
models.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//! Domain models for Materialize catalog objects.
11//!
12//! These types represent objects in the Materialize system catalog and provide
13//! a type-safe interface over raw database rows.
14
15use chrono::{DateTime, Utc};
16use mz_sql_parser::ast::{CreateClusterStatement, Raw};
17use std::fmt;
18use std::str::FromStr;
19
20use crate::project::SchemaQualifier;
21
22/// The type of deployment - either tables-only or full objects.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum DeploymentKind {
26    /// Table creation deployment (apply tables command)
27    Tables,
28    /// Full object deployment (stage, apply commands)
29    Objects,
30    /// Contains sinks
31    Sinks,
32    /// Contains replacement materialized views (drop after apply, not swap)
33    Replacement,
34}
35
36impl fmt::Display for DeploymentKind {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            DeploymentKind::Tables => write!(f, "tables"),
40            DeploymentKind::Objects => write!(f, "objects"),
41            DeploymentKind::Sinks => write!(f, "sinks"),
42            DeploymentKind::Replacement => write!(f, "replacement"),
43        }
44    }
45}
46
47impl FromStr for DeploymentKind {
48    type Err = String;
49
50    fn from_str(s: &str) -> Result<Self, Self::Err> {
51        match s {
52            "tables" => Ok(DeploymentKind::Tables),
53            "objects" => Ok(DeploymentKind::Objects),
54            "sinks" => Ok(DeploymentKind::Sinks),
55            "replacement" => Ok(DeploymentKind::Replacement),
56            _ => Err(format!("Invalid deployment kind: {}", s)),
57        }
58    }
59}
60
61/// Deployment mode tag stored alongside each deployment.
62///
63/// Currently only `Stage` exists; kept as an enum for schema compatibility
64/// with the `mode` column in `_mz_deploy.tables.deployments`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
66#[serde(rename_all = "snake_case")]
67pub enum DeploymentMode {
68    /// Full staging deployment that can be promoted to production.
69    Stage,
70}
71
72impl fmt::Display for DeploymentMode {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match self {
75            DeploymentMode::Stage => write!(f, "stage"),
76        }
77    }
78}
79
80impl FromStr for DeploymentMode {
81    type Err = String;
82
83    fn from_str(s: &str) -> Result<Self, Self::Err> {
84        match s {
85            "stage" => Ok(DeploymentMode::Stage),
86            _ => Err(format!("Invalid deployment mode: {}", s)),
87        }
88    }
89}
90
91/// A compute cluster in Materialize.
92///
93/// Clusters provide the compute resources for materialized views, indexes, and sinks.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct Cluster {
96    /// Materialize's unique identifier for the cluster
97    pub id: String,
98    /// Cluster name (e.g., "quickstart")
99    pub name: String,
100    /// Whether the cluster is managed
101    pub managed: bool,
102    /// Cluster size (e.g., "M.1-large"), None for unmanaged clusters
103    pub size: Option<String>,
104    /// Number of replicas for fault tolerance (stored as i64 to handle postgres uint4 type)
105    pub replication_factor: Option<i64>,
106}
107
108/// Configuration for a cluster replica (used for unmanaged clusters).
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct ClusterReplica {
111    /// Replica name (e.g., "r1", "r2")
112    pub name: String,
113    /// Replica size (e.g., "25cc")
114    pub size: String,
115    /// Optional availability zone
116    pub availability_zone: Option<String>,
117}
118
119/// A privilege grant on a cluster.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct ObjectGrant {
122    /// Role name that receives the grant
123    pub grantee: String,
124    /// Privilege type (e.g., "USAGE", "CREATE")
125    pub privilege_type: String,
126}
127
128/// Configuration for creating a cluster (managed or unmanaged).
129///
130/// This captures all the information needed to clone a cluster's configuration
131/// including its replicas (for unmanaged clusters) and privilege grants.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub enum ClusterConfig {
134    /// Managed cluster, captured as the canonical `CREATE CLUSTER` statement the
135    /// server renders for it. Cloning replays it under a new name.
136    Managed {
137        /// The production cluster's `CREATE CLUSTER` statement
138        create_stmt: CreateClusterStatement<Raw>,
139        /// Privilege grants on the cluster
140        grants: Vec<ObjectGrant>,
141    },
142    /// Unmanaged cluster with explicit replicas
143    Unmanaged {
144        /// The attached policy's unquoted catalog name, if any.
145        query_policy: Option<String>,
146        /// Replica configurations
147        replicas: Vec<ClusterReplica>,
148        /// Privilege grants on the cluster
149        grants: Vec<ObjectGrant>,
150    },
151}
152
153impl ClusterConfig {
154    /// Get the grants for this cluster configuration.
155    pub fn grants(&self) -> &[ObjectGrant] {
156        match self {
157            ClusterConfig::Managed { grants, .. } => grants,
158            ClusterConfig::Unmanaged { grants, .. } => grants,
159        }
160    }
161}
162
163/// A schema deployment record tracking when and how a schema was deployed.
164///
165/// Stored in the `deploy.deployments` table. Schemas are deployed
166/// atomically - all objects in a dirty schema are redeployed together.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct SchemaDeploymentRecord {
169    /// Deploy ID (e.g., `"<init>"` for direct deploy, `"staging"` for staged deploy)
170    pub deploy_id: String,
171    /// Database name (e.g., "materialize")
172    pub database: String,
173    /// Schema name (e.g., "public")
174    pub schema: String,
175    /// When this schema was deployed
176    pub deployed_at: DateTime<Utc>,
177    /// Which Materialize user/role deployed this schema
178    pub deployed_by: String,
179    /// When this schema was promoted to production (NULL for staging, set on promotion)
180    pub promoted_at: Option<DateTime<Utc>>,
181    /// Git commit hash if available
182    pub git_commit: Option<String>,
183    /// Type of deployment (tables or objects)
184    pub kind: DeploymentKind,
185    /// Whether this is a stage or preview deployment
186    pub mode: DeploymentMode,
187}
188
189/// An object deployment record tracking object-level deployment history.
190///
191/// Stored in the `deploy.objects` table (append-only).
192/// Each row records that an object with a specific hash was deployed
193/// to a deployment at a point in time.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct DeploymentObjectRecord {
196    /// Deploy ID (e.g., `"<init>"` for direct deploy, `"staging"` for staged deploy)
197    pub deploy_id: String,
198    /// Database name (e.g., "materialize")
199    pub database: String,
200    /// Schema name (e.g., "public")
201    pub schema: String,
202    /// Object name (e.g., "my_view")
203    pub object: String,
204    /// Hash of the HIR DatabaseObject (semantic content hash)
205    pub object_hash: String,
206    /// When this object was deployed
207    pub deployed_at: DateTime<Utc>,
208}
209
210/// Metadata about a deployment.
211///
212/// Used for validation before operations like apply or abort.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct DeploymentMetadata {
215    /// Deploy ID
216    pub deploy_id: String,
217    /// When this deployment was promoted (NULL if not promoted)
218    pub promoted_at: Option<DateTime<Utc>>,
219    /// Whether this is a stage or preview deployment
220    pub mode: DeploymentMode,
221    /// List of (database, schema) tuples in this deployment
222    pub schemas: Vec<SchemaQualifier>,
223}
224
225/// A conflict record indicating a schema was updated after deployment started.
226///
227/// Used for git-merge-style conflict detection when promoting deployments.
228/// Returned by conflict detection queries that check if production schemas
229/// were modified since the staging deployment began.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct ConflictRecord {
232    /// Database name containing the conflicting schema
233    pub database: String,
234    /// Schema name that has a conflict
235    pub schema: String,
236    /// Deploy ID that last promoted this schema
237    pub deploy_id: String,
238    /// When the schema was last promoted to production
239    pub promoted_at: DateTime<Utc>,
240}
241
242/// A cluster known to host at least one promoted deployment.
243///
244/// Returned by `list_production_clusters()` and used by `dev` to refuse
245/// overlay deployments that would land on production compute. Each record
246/// carries one representative protected deployment so the error message
247/// can explain why the cluster is considered production.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct ProductionClusterRecord {
250    /// Cluster name as it appears in `mz_clusters` (resolved from cluster_id).
251    pub cluster_name: String,
252    /// Database of one promoted deployment hosted on this cluster.
253    pub database: String,
254    /// Schema of one promoted deployment hosted on this cluster.
255    pub schema: String,
256    /// When that deployment was promoted.
257    pub promoted_at: DateTime<Utc>,
258}
259
260/// Details about a specific deployment.
261///
262/// Returned by `get_deployment_details()` for the describe command.
263#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
264pub struct DeploymentDetails {
265    /// When this deployment was created
266    pub deployed_at: DateTime<Utc>,
267    /// When this deployment was promoted (None if still staging)
268    pub promoted_at: Option<DateTime<Utc>>,
269    /// Which Materialize user/role deployed this
270    pub deployed_by: String,
271    /// Git commit hash if available
272    pub git_commit: Option<String>,
273    /// Type of deployment (tables or objects)
274    pub kind: DeploymentKind,
275    /// Whether this is a stage or preview deployment
276    pub mode: DeploymentMode,
277    /// List of (database, schema) tuples in this deployment
278    pub schemas: Vec<SchemaQualifier>,
279}
280
281/// Summary of a staging deployment.
282///
283/// Used by `list_staging_deployments()` for the deployments command.
284#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
285pub struct StagingDeployment {
286    /// When this deployment was created
287    pub deployed_at: DateTime<Utc>,
288    /// Which Materialize user/role deployed this
289    pub deployed_by: String,
290    /// Git commit hash if available
291    pub git_commit: Option<String>,
292    /// Type of deployment (tables or objects)
293    pub kind: DeploymentKind,
294    /// Whether this is a stage or preview deployment
295    pub mode: DeploymentMode,
296    /// List of (database, schema) tuples in this deployment
297    pub schemas: Vec<SchemaQualifier>,
298}
299
300/// A promoted deployment in history.
301///
302/// Returned by `list_deployment_history()` for the history command.
303#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
304pub struct DeploymentHistoryEntry {
305    /// Deploy ID for this deployment
306    pub deploy_id: String,
307    /// When this deployment was promoted
308    pub promoted_at: DateTime<Utc>,
309    /// Which Materialize user/role deployed this
310    pub deployed_by: String,
311    /// Git commit hash if available
312    pub git_commit: Option<String>,
313    /// Type of deployment (tables or objects)
314    pub kind: DeploymentKind,
315    /// List of (database, schema) tuples in this deployment
316    pub schemas: Vec<SchemaQualifier>,
317}
318
319/// State of an apply operation for resumable apply.
320///
321/// This is determined by checking the existence and comments of the
322/// `_mz_deploy.apply_<deploy_id>_pre` and `_mz_deploy.apply_<deploy_id>_post` schemas.
323/// Comments are set when creating the schemas; the swap transaction exchanges which
324/// schema has which comment.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum ApplyState {
327    /// No apply state schemas exist - fresh apply or completed.
328    NotStarted,
329    /// State schemas exist but swap hasn't happened yet.
330    /// The `_pre` schema has comment 'swapped=false'.
331    PreSwap,
332    /// Swap has completed.
333    /// After the swap, `_pre` schema has comment 'swapped=true' (it was `_post` before).
334    PostSwap,
335}
336
337/// A replacement materialized view record tracking the mapping between
338/// the replacement MV (in staging schema) and its production target.
339///
340/// The replacement MV lives in a staging schema (`target_schema` + staging suffix)
341/// within the same database, and has the same object name as the target.
342///
343/// Stored in `_mz_deploy.public.replacement_mvs` table.
344#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
345pub struct ReplacementMvRecord {
346    /// Deploy ID this replacement belongs to
347    pub deploy_id: String,
348    /// Database of the target (and replacement) MV
349    pub target_database: String,
350    /// Schema of the production target MV
351    pub target_schema: String,
352    /// Name of the target (and replacement) MV
353    pub target_name: String,
354    /// Schema of the replacement MV (staging) — typically `target_schema` + staging suffix
355    pub replacement_schema: String,
356}
357
358/// A pending statement to be executed after the swap.
359///
360/// Used for deferred execution of statements like sinks that cannot
361/// be created in staging (they write to external systems immediately).
362/// Stored in `_mz_deploy.public.pending_statements` table.
363#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
364pub struct PendingStatement {
365    /// Deploy ID this statement belongs to
366    pub deploy_id: String,
367    /// Sequence number for ordering execution
368    pub sequence_num: i32,
369    /// Database containing the object
370    pub database: String,
371    /// Schema containing the object
372    pub schema: String,
373    /// Object name
374    pub object: String,
375    /// Hash of the object definition
376    pub object_hash: String,
377    /// SQL statement to execute
378    pub statement_sql: String,
379    /// Kind of statement (e.g., "sink")
380    pub statement_kind: String,
381    /// When this statement was executed (None if not yet executed)
382    pub executed_at: Option<DateTime<Utc>>,
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use mz_sql_parser::ast::Statement;
389    use mz_sql_parser::parser::parse_statements;
390
391    fn create_cluster(sql: &str) -> CreateClusterStatement<Raw> {
392        match parse_statements(sql).unwrap().pop().unwrap().ast {
393            Statement::CreateCluster(stmt) => stmt,
394            other => panic!("expected CREATE CLUSTER, got {:?}", other),
395        }
396    }
397
398    #[mz_ore::test]
399    fn test_deployment_kind_display() {
400        assert_eq!(DeploymentKind::Tables.to_string(), "tables");
401        assert_eq!(DeploymentKind::Objects.to_string(), "objects");
402    }
403
404    #[mz_ore::test]
405    fn test_deployment_kind_from_str_valid() {
406        assert_eq!(
407            "tables".parse::<DeploymentKind>().unwrap(),
408            DeploymentKind::Tables
409        );
410        assert_eq!(
411            "objects".parse::<DeploymentKind>().unwrap(),
412            DeploymentKind::Objects
413        );
414    }
415
416    #[mz_ore::test]
417    fn test_deployment_kind_from_str_invalid() {
418        let result = "invalid".parse::<DeploymentKind>();
419        assert!(result.is_err());
420        assert_eq!(result.unwrap_err(), "Invalid deployment kind: invalid");
421    }
422
423    #[mz_ore::test]
424    fn test_deployment_kind_roundtrip() {
425        // Verify that Display and FromStr are consistent
426        for kind in [
427            DeploymentKind::Tables,
428            DeploymentKind::Objects,
429            DeploymentKind::Sinks,
430            DeploymentKind::Replacement,
431        ] {
432            let s = kind.to_string();
433            let parsed: DeploymentKind = s.parse().unwrap();
434            assert_eq!(kind, parsed);
435        }
436    }
437
438    #[mz_ore::test]
439    fn test_cluster_equality() {
440        let cluster1 = Cluster {
441            id: "u1".to_string(),
442            name: "test".to_string(),
443            managed: true,
444            size: Some("25cc".to_string()),
445            replication_factor: Some(1),
446        };
447
448        let cluster2 = Cluster {
449            id: "u1".to_string(),
450            name: "test".to_string(),
451            managed: true,
452            size: Some("25cc".to_string()),
453            replication_factor: Some(1),
454        };
455
456        let cluster3 = Cluster {
457            id: "u2".to_string(), // Different ID
458            name: "test".to_string(),
459            managed: true,
460            size: Some("25cc".to_string()),
461            replication_factor: Some(1),
462        };
463
464        assert_eq!(cluster1, cluster2);
465        assert_ne!(cluster1, cluster3);
466    }
467
468    #[mz_ore::test]
469    fn test_cluster_replica_equality() {
470        let r1 = ClusterReplica {
471            name: "r1".to_string(),
472            size: "25cc".to_string(),
473            availability_zone: Some("use1-az1".to_string()),
474        };
475
476        let r2 = ClusterReplica {
477            name: "r1".to_string(),
478            size: "25cc".to_string(),
479            availability_zone: Some("use1-az1".to_string()),
480        };
481
482        let r3 = ClusterReplica {
483            name: "r2".to_string(),
484            size: "25cc".to_string(),
485            availability_zone: None,
486        };
487
488        assert_eq!(r1, r2);
489        assert_ne!(r1, r3);
490    }
491
492    #[mz_ore::test]
493    fn test_cluster_grant_equality() {
494        let g1 = ObjectGrant {
495            grantee: "reader".to_string(),
496            privilege_type: "USAGE".to_string(),
497        };
498
499        let g2 = ObjectGrant {
500            grantee: "reader".to_string(),
501            privilege_type: "USAGE".to_string(),
502        };
503
504        let g3 = ObjectGrant {
505            grantee: "writer".to_string(),
506            privilege_type: "CREATE".to_string(),
507        };
508
509        assert_eq!(g1, g2);
510        assert_ne!(g1, g3);
511    }
512
513    #[mz_ore::test]
514    fn test_cluster_config_managed() {
515        let config = ClusterConfig::Managed {
516            create_stmt: create_cluster("CREATE CLUSTER c (SIZE = '25cc')"),
517            grants: vec![ObjectGrant {
518                grantee: "reader".to_string(),
519                privilege_type: "USAGE".to_string(),
520            }],
521        };
522
523        assert_eq!(config.grants().len(), 1);
524        assert_eq!(config.grants()[0].grantee, "reader");
525    }
526
527    #[mz_ore::test]
528    fn test_cluster_config_unmanaged() {
529        let config = ClusterConfig::Unmanaged {
530            query_policy: None,
531            replicas: vec![
532                ClusterReplica {
533                    name: "r1".to_string(),
534                    size: "25cc".to_string(),
535                    availability_zone: None,
536                },
537                ClusterReplica {
538                    name: "r2".to_string(),
539                    size: "50cc".to_string(),
540                    availability_zone: Some("use1-az1".to_string()),
541                },
542            ],
543            grants: vec![],
544        };
545
546        if let ClusterConfig::Unmanaged {
547            replicas, grants, ..
548        } = &config
549        {
550            assert_eq!(replicas.len(), 2);
551            assert_eq!(replicas[0].name, "r1");
552            assert_eq!(replicas[1].availability_zone, Some("use1-az1".to_string()));
553            assert!(grants.is_empty());
554        } else {
555            panic!("Expected Unmanaged config");
556        }
557    }
558
559    #[mz_ore::test]
560    fn test_cluster_config_unmanaged_empty_replicas() {
561        // Unmanaged clusters with 0 replicas are valid
562        let config = ClusterConfig::Unmanaged {
563            query_policy: None,
564            replicas: vec![],
565            grants: vec![ObjectGrant {
566                grantee: "admin".to_string(),
567                privilege_type: "CREATE".to_string(),
568            }],
569        };
570
571        if let ClusterConfig::Unmanaged {
572            replicas, grants, ..
573        } = &config
574        {
575            assert!(replicas.is_empty());
576            assert_eq!(grants.len(), 1);
577        } else {
578            panic!("Expected Unmanaged config");
579        }
580    }
581}