mz_deploy/client.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//! Database client layer for communicating with a Materialize region.
11//!
12//! All interaction with the live database flows through this module. The
13//! `Client` type (defined in `connection`) holds a `tokio_postgres`
14//! connection and exposes scoped sub-clients that group related operations:
15//!
16//! - **`introspection`** — Read-only catalog queries: schema/cluster/object
17//! existence checks, dependency lookups, and batch metadata retrieval.
18//! - **`provisioning`** — DDL operations that create or alter databases,
19//! schemas, and clusters to match the project definition.
20//! - **`deployment_ops`** — Blue/green deployment lifecycle: staging,
21//! hydration monitoring, cutover, and abort.
22//! - **`validation`** — Pre-deployment validation: checks that the target
23//! environment matches expected state before applying changes.
24//! - **`type_info`** — `SHOW COLUMNS` queries used to generate and refresh
25//! the `types.lock` data-contract file.
26//!
27//! ## Supporting Submodules
28//!
29//! - **`models`** — Data structures shared across sub-clients (deployment
30//! records, cluster configs, conflict records, etc.).
31//! - **`errors`** — Error types: `ConnectionError` for transport/query
32//! failures, `DatabaseValidationError` for semantic mismatches.
33//!
34//! Most sub-client types are internal; this module re-exports the key public
35//! types so that consumers only need `use crate::client::*`.
36
37pub(crate) mod auto_scaling;
38mod connection;
39mod deployment_ops;
40mod dev_overlays;
41mod errors;
42mod introspection;
43mod models;
44mod provisioning;
45mod type_info;
46mod validation;
47
48/// Name of the dedicated cluster mz-deploy creates during `setup` and
49/// pins every connection to via libpq options.
50pub const SERVER_CLUSTER_NAME: &str = "_mz_deploy_server";
51
52pub use crate::config::Profile;
53pub use connection::{Client, DevOverlaysClient};
54pub(crate) use connection::{build_options_string, default_sslmode, is_loopback_host};
55
56/// Double-quote a SQL identifier, escaping any embedded double quotes.
57pub fn quote_identifier(name: &str) -> String {
58 format!("\"{}\"", name.replace('"', "\"\""))
59}
60
61/// Build a comma-separated `$1, $2, …, $n` placeholder string for parameterized queries.
62pub fn sql_placeholders(n: usize) -> String {
63 (1..=n)
64 .map(|i| format!("${}", i))
65 .collect::<Vec<_>>()
66 .join(", ")
67}
68
69/// Build a `LIKE` pattern (used with `ESCAPE '\'`) matching any name that ends
70/// in the staging suffix `_<deploy_id>`.
71///
72/// The suffix is matched *literally*: `_`, `%`, and the escape character `\` are
73/// LIKE metacharacters, so they are escaped. Only the leading `%` stays a
74/// wildcard. Without escaping, the `_` separating the suffix would act as a
75/// single-character wildcard — pattern `%_prod` would match any name ending in
76/// `<any char>prod` (e.g. a production schema `fooprod` or cluster `dataprod`),
77/// and a `deploy_id` containing `%` would match nearly everything. Used by both
78/// the staging-discovery queries (which feed `DROP ... CASCADE`) and the
79/// hydration-status / `wait` readiness queries.
80pub(crate) fn staging_suffix_like_pattern(deploy_id: &str) -> String {
81 let mut pattern = String::from("%");
82 // The literal suffix is the separating underscore followed by the deploy id.
83 for ch in std::iter::once('_').chain(deploy_id.chars()) {
84 if matches!(ch, '\\' | '_' | '%') {
85 pattern.push('\\');
86 }
87 pattern.push(ch);
88 }
89 pattern
90}
91
92#[cfg(test)]
93mod tests {
94 use super::staging_suffix_like_pattern;
95
96 #[mz_ore::test]
97 fn test_staging_suffix_like_pattern_escapes_separator() {
98 // Regression test for QA Finding 3.
99 //
100 // The `_` separating the staging suffix must be escaped so it matches a
101 // literal underscore, not a single-character wildcard. With deploy id
102 // `prod` the pattern must be `%\_prod` (used with `ESCAPE '\'`), which
103 // matches only names ending in the literal `_prod` — NOT `fooprod` or any
104 // other `<char>prod`, which the unescaped `%_prod` would have matched.
105 assert_eq!(staging_suffix_like_pattern("prod"), r"%\_prod");
106 }
107
108 #[mz_ore::test]
109 fn test_staging_suffix_like_pattern_escapes_metacharacters() {
110 // A deploy id containing LIKE metacharacters must not inject wildcards.
111 // `%` and `_` inside the id are escaped to literals; the only wildcard is
112 // the leading `%`.
113 assert_eq!(staging_suffix_like_pattern("a%b_c"), r"%\_a\%b\_c");
114 // Backslashes (the escape char itself) are also escaped.
115 assert_eq!(staging_suffix_like_pattern(r"a\b"), r"%\_a\\b");
116 }
117
118 #[mz_ore::test]
119 fn test_staging_suffix_like_pattern_plain_id() {
120 // A plain alphanumeric id only escapes the separating underscore.
121 assert_eq!(staging_suffix_like_pattern("deploy123"), r"%\_deploy123");
122 }
123}
124pub use deployment_ops::{
125 ClusterDeploymentStatus, ClusterStatusContext, DEFAULT_ALLOWED_LAG_SECS, FailureReason,
126 HydrationStatusUpdate,
127};
128pub use errors::{ConnectionError, DatabaseValidationError, format_relative_path};
129pub use introspection::DependentSink;
130pub use models::{
131 ApplyState, Cluster, ClusterConfig, ClusterOptions, ClusterReplica, ConflictRecord,
132 DeploymentDetails, DeploymentHistoryEntry, DeploymentKind, DeploymentMetadata, DeploymentMode,
133 DeploymentObjectRecord, ObjectGrant, PendingStatement, ProductionClusterRecord,
134 ReplacementMvRecord, SchemaDeploymentRecord, StagingDeployment,
135};