1use crate::client::connection::{Client, IntrospectionClient};
18use crate::client::errors::ConnectionError;
19use crate::client::models::{Cluster, ClusterConfig, ClusterReplica, ObjectGrant};
20use crate::client::sql_placeholders;
21use crate::client::staging_suffix_like_pattern;
22use crate::client::{parse_create_cluster, quote_identifier};
23use crate::project::SchemaQualifier;
24use crate::project::ir::object_id::ObjectId;
25use itertools::Itertools;
26use std::collections::{BTreeMap, BTreeSet};
27use tokio_postgres::types::ToSql;
28
29#[derive(Debug, Clone, serde::Serialize)]
34pub struct DependentSink {
35 pub sink_database: String,
36 pub sink_schema: String,
37 pub sink_name: String,
38 pub dependency_database: String,
39 pub dependency_schema: String,
40 pub dependency_name: String,
41 pub dependency_type: String,
42}
43
44pub(super) async fn schema_exists(
46 client: &Client,
47 database: &str,
48 schema: &str,
49) -> Result<bool, ConnectionError> {
50 let query = r#"
51 SELECT EXISTS(
52 SELECT 1
53 FROM mz_catalog.mz_schemas s
54 JOIN mz_catalog.mz_databases d ON s.database_id = d.id
55 WHERE s.name = $1 AND d.name = $2
56 ) AS exists
57 "#;
58
59 let row = client.query_one(query, &[&schema, &database]).await?;
60
61 Ok(row.get("exists"))
62}
63
64pub(super) async fn cluster_exists(client: &Client, name: &str) -> Result<bool, ConnectionError> {
66 let query = r#"
67 SELECT EXISTS(
68 SELECT 1 FROM mz_catalog.mz_clusters WHERE name = $1
69 ) AS exists
70 "#;
71
72 let row = client.query_one(query, &[&name]).await?;
73
74 Ok(row.get("exists"))
75}
76
77pub(super) async fn get_cluster(
79 client: &Client,
80 name: &str,
81) -> Result<Option<Cluster>, ConnectionError> {
82 let query = r#"
83 SELECT
84 c.id,
85 c.name,
86 c.managed,
87 c.size,
88 c.replication_factor::bigint AS replication_factor
89 FROM mz_catalog.mz_clusters c
90 WHERE c.name = $1
91 "#;
92
93 let rows = client.query(query, &[&name]).await?;
94
95 if rows.is_empty() {
96 return Ok(None);
97 }
98
99 let row = &rows[0];
100 Ok(Some(Cluster {
101 id: row.get("id"),
102 name: row.get("name"),
103 managed: row.get("managed"),
104 size: row.get("size"),
105 replication_factor: row.get("replication_factor"),
106 }))
107}
108
109pub(super) async fn get_cluster_create_sql(
114 client: &Client,
115 name: &str,
116) -> Result<Option<String>, ConnectionError> {
117 let query = format!("SHOW CREATE CLUSTER {}", quote_identifier(name));
118 let rows = client.query(&query, &[]).await?;
119 Ok(rows.first().map(|row| row.get("create_sql")))
120}
121
122pub(super) async fn list_clusters(client: &Client) -> Result<Vec<Cluster>, ConnectionError> {
124 let query = r#"
125 SELECT
126 c.id,
127 c.name,
128 c.managed,
129 c.size,
130 c.replication_factor::bigint AS replication_factor
131 FROM mz_catalog.mz_clusters c
132 ORDER BY c.name
133 "#;
134
135 let rows = client.query(query, &[]).await?;
136
137 Ok(rows
138 .iter()
139 .map(|row| Cluster {
140 id: row.get("id"),
141 name: row.get("name"),
142 managed: row.get("managed"),
143 size: row.get("size"),
144 replication_factor: row.get("replication_factor"),
145 })
146 .collect())
147}
148
149pub(super) async fn get_cluster_config(
156 client: &Client,
157 name: &str,
158) -> Result<Option<ClusterConfig>, ConnectionError> {
159 let cluster_query = r#"
161 SELECT
162 c.managed,
163 r.name AS replica_name,
164 r.size AS replica_size,
165 r.availability_zone
166 FROM mz_catalog.mz_clusters c
167 LEFT JOIN mz_catalog.mz_cluster_replicas r ON c.id = r.cluster_id
168 WHERE c.name = $1
169 ORDER BY r.name
170 "#;
171
172 let cluster_rows = client.query(cluster_query, &[&name]).await?;
173
174 if cluster_rows.is_empty() {
175 return Ok(None);
176 }
177
178 let managed: bool = cluster_rows[0].get("managed");
179
180 let grants_query = r#"
182 WITH cluster_privilege AS (
183 SELECT mz_internal.mz_aclexplode(privileges).*, owner_id
184 FROM mz_clusters
185 WHERE name = $1
186 )
187 SELECT
188 grantee.name AS grantee,
189 c.privilege_type
190 FROM cluster_privilege AS c
191 JOIN mz_roles AS grantee ON c.grantee = grantee.id
192 WHERE grantee.name NOT IN ('none', 'mz_system', 'mz_support')
193 AND c.grantee != c.owner_id
194 "#;
195
196 let grant_rows = client.query(grants_query, &[&name]).await?;
197
198 let grants: Vec<ObjectGrant> = grant_rows
199 .iter()
200 .map(|row| ObjectGrant {
201 grantee: row.get("grantee"),
202 privilege_type: row.get("privilege_type"),
203 })
204 .collect();
205
206 if managed {
207 let create_sql = get_cluster_create_sql(client, name).await?.ok_or_else(|| {
208 ConnectionError::Message(format!("Cluster '{}' has no CREATE statement", name))
209 })?;
210 let create_stmt = parse_create_cluster(&create_sql)
211 .map_err(|e| ConnectionError::Message(format!("cluster '{}': {}", name, e)))?;
212
213 Ok(Some(ClusterConfig::Managed {
214 create_stmt,
215 grants,
216 }))
217 } else {
218 let mut replicas = Vec::new();
220 for row in &cluster_rows {
221 let replica_name: Option<String> = row.get("replica_name");
222 if let Some(replica_name) = replica_name {
223 replicas.push(ClusterReplica {
224 name: replica_name,
225 size: row.get("replica_size"),
226 availability_zone: row.get("availability_zone"),
227 });
228 }
229 }
230
231 let query_policy = get_cluster_query_policy(client, name).await?;
232 Ok(Some(ClusterConfig::Unmanaged {
233 replicas,
234 grants,
235 query_policy,
236 }))
237 }
238}
239
240async fn get_cluster_query_policy(
242 client: &Client,
243 name: &str,
244) -> Result<Option<String>, ConnectionError> {
245 let exists = client
246 .query_one(
247 "SELECT EXISTS (
248 SELECT 1 FROM mz_catalog.mz_objects o
249 JOIN mz_catalog.mz_schemas s ON o.schema_id = s.id
250 WHERE s.name = 'mz_internal' AND o.name = 'mz_query_policy_attachments'
251 )",
252 &[],
253 )
254 .await?;
255 if !exists.get::<_, bool>(0) {
256 return Ok(None);
257 }
258
259 let rows = client
260 .query(
261 "SELECT p.name
262 FROM mz_internal.mz_query_policy_attachments a
263 JOIN mz_catalog.mz_clusters c ON c.id = a.object_id
264 LEFT JOIN mz_internal.mz_query_policies p ON p.id = a.policy_id
265 WHERE a.object_type = 'cluster' AND c.name = $1",
266 &[&name],
267 )
268 .await?;
269 match rows.as_slice() {
270 [] => Ok(None),
271 [row] => row.get::<_, Option<String>>(0).map(Some).ok_or_else(|| {
272 ConnectionError::Message(format!(
273 "Cannot resolve query policy for cluster '{}'",
274 name
275 ))
276 }),
277 _ => Err(ConnectionError::Message(format!(
278 "Multiple query policies for cluster '{}'",
279 name
280 ))),
281 }
282}
283
284pub(super) async fn network_policy_exists(
286 client: &Client,
287 name: &str,
288) -> Result<bool, ConnectionError> {
289 let query = r#"
290 SELECT EXISTS(
291 SELECT 1 FROM mz_catalog.mz_network_policies WHERE name = $1
292 ) AS exists
293 "#;
294
295 let row = client.query_one(query, &[&name]).await?;
296
297 Ok(row.get("exists"))
298}
299
300pub(super) async fn role_exists(client: &Client, name: &str) -> Result<bool, ConnectionError> {
302 let query = r#"
303 SELECT EXISTS(
304 SELECT 1 FROM mz_catalog.mz_roles WHERE name = $1
305 ) AS exists
306 "#;
307
308 let row = client.query_one(query, &[&name]).await?;
309
310 Ok(row.get("exists"))
311}
312
313pub(super) async fn get_role_members(
315 client: &Client,
316 role_name: &str,
317) -> Result<Vec<String>, ConnectionError> {
318 let query = r#"
319 SELECT m.name AS member
320 FROM mz_catalog.mz_role_members rm
321 JOIN mz_catalog.mz_roles r ON r.id = rm.role_id
322 JOIN mz_catalog.mz_roles m ON m.id = rm.member
323 WHERE r.name = $1
324 ORDER BY m.name
325 "#;
326
327 let rows = client.query(query, &[&role_name]).await?;
328
329 Ok(rows.iter().map(|row| row.get("member")).collect())
330}
331
332pub(super) async fn get_role_parameters(
334 client: &Client,
335 role_name: &str,
336) -> Result<Vec<String>, ConnectionError> {
337 let query = r#"
338 SELECT rp.parameter_name
339 FROM mz_catalog.mz_role_parameters rp
340 JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
341 WHERE r.name = $1
342 ORDER BY rp.parameter_name
343 "#;
344
345 let rows = client.query(query, &[&role_name]).await?;
346
347 Ok(rows.iter().map(|row| row.get("parameter_name")).collect())
348}
349
350pub(super) async fn get_current_user(client: &Client) -> Result<String, ConnectionError> {
352 let row = client.query_one("SELECT current_user()", &[]).await?;
353
354 Ok(row.get(0))
355}
356
357pub(super) async fn check_schemas_exist(
361 client: &Client,
362 schemas: &[(String, String)],
363) -> Result<BTreeSet<(String, String)>, ConnectionError> {
364 if schemas.is_empty() {
365 return Ok(BTreeSet::new());
366 }
367
368 let fqns: Vec<String> = schemas
370 .iter()
371 .map(|(db, schema)| format!("{}.{}", db, schema))
372 .collect();
373
374 let fqn_map: BTreeMap<&str, &(String, String)> = fqns
375 .iter()
376 .zip_eq(schemas.iter())
377 .map(|(fqn, pair)| (fqn.as_str(), pair))
378 .collect();
379
380 let placeholders_str = sql_placeholders(fqns.len());
381
382 let query = format!(
383 r#"
384 SELECT d.name || '.' || s.name as fqn
385 FROM mz_catalog.mz_schemas s
386 JOIN mz_catalog.mz_databases d ON s.database_id = d.id
387 WHERE d.name || '.' || s.name IN ({})
388 ORDER BY fqn
389 "#,
390 placeholders_str
391 );
392
393 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
394 for fqn in &fqns {
395 params.push(fqn);
396 }
397
398 let rows = client.query(&query, ¶ms).await?;
399
400 let mut existing = BTreeSet::new();
401 for row in rows {
402 let fqn: String = row.get("fqn");
403 if let Some(pair) = fqn_map.get(fqn.as_str()) {
404 existing.insert((*pair).clone());
405 }
406 }
407
408 Ok(existing)
409}
410
411pub(super) async fn check_clusters_exist(
415 client: &Client,
416 clusters: &[String],
417) -> Result<BTreeSet<String>, ConnectionError> {
418 if clusters.is_empty() {
419 return Ok(BTreeSet::new());
420 }
421
422 let placeholders_str = sql_placeholders(clusters.len());
423
424 let query = format!(
425 r#"
426 SELECT name FROM mz_catalog.mz_clusters
427 WHERE name IN ({})
428 ORDER BY name
429 "#,
430 placeholders_str
431 );
432
433 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
434 for name in clusters {
435 params.push(name);
436 }
437
438 let rows = client.query(&query, ¶ms).await?;
439
440 Ok(rows.iter().map(|row| row.get("name")).collect())
441}
442
443pub(super) async fn check_objects_exist(
445 client: &Client,
446 objects: &BTreeSet<ObjectId>,
447) -> Result<BTreeSet<ObjectId>, ConnectionError> {
448 if objects.is_empty() {
449 return Ok(BTreeSet::new());
450 }
451
452 let fqn_map: BTreeMap<String, &ObjectId> = objects.iter().map(|o| (o.to_string(), o)).collect();
453 let fqns: Vec<&String> = fqn_map.keys().collect();
454
455 let placeholders_str = sql_placeholders(fqns.len());
456
457 let query = format!(
458 r#"
459 SELECT d.name || '.' || s.name || '.' || mo.name as fqn
460 FROM mz_objects mo
461 JOIN mz_schemas s ON mo.schema_id = s.id
462 JOIN mz_databases d ON s.database_id = d.id
463 WHERE d.name || '.' || s.name || '.' || mo.name IN ({})
464 AND mo.type IN ('table', 'view', 'materialized-view', 'source', 'sink')
465 ORDER BY fqn
466 "#,
467 placeholders_str
468 );
469
470 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
471 for fqn in &fqns {
472 params.push(fqn);
473 }
474
475 let rows = client.query(&query, ¶ms).await?;
476
477 Ok(rows
478 .iter()
479 .filter_map(|row| {
480 let fqn: String = row.get("fqn");
481 fqn_map.get(&fqn).map(|id| (*id).clone())
482 })
483 .collect())
484}
485
486async fn check_catalog_objects_exist(
490 client: &Client,
491 objects: &BTreeSet<ObjectId>,
492 catalog_table: &str,
493) -> Result<BTreeSet<ObjectId>, ConnectionError> {
494 if objects.is_empty() {
495 return Ok(BTreeSet::new());
496 }
497
498 let fqn_map: BTreeMap<String, &ObjectId> = objects.iter().map(|o| (o.to_string(), o)).collect();
500 let fqns: Vec<&String> = fqn_map.keys().collect();
501
502 let placeholders_str = sql_placeholders(fqns.len());
503
504 let query = format!(
505 r#"
506 SELECT d.name || '.' || s.name || '.' || t.name as fqn
507 FROM {} t
508 JOIN mz_schemas s ON t.schema_id = s.id
509 JOIN mz_databases d ON s.database_id = d.id
510 WHERE d.name || '.' || s.name || '.' || t.name IN ({})
511 ORDER BY fqn
512 "#,
513 catalog_table, placeholders_str
514 );
515
516 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
517 for fqn in &fqns {
518 params.push(*fqn);
519 }
520
521 let rows = client.query(&query, ¶ms).await?;
522
523 let mut existing = BTreeSet::new();
524 for row in rows {
525 let fqn: String = row.get("fqn");
526 if let Some(obj_id) = fqn_map.get(&fqn) {
527 existing.insert((*obj_id).clone());
528 }
529 }
530
531 Ok(existing)
532}
533
534pub(super) async fn check_tables_exist(
538 client: &Client,
539 tables: &BTreeSet<ObjectId>,
540) -> Result<BTreeSet<ObjectId>, ConnectionError> {
541 check_catalog_objects_exist(client, tables, "mz_tables").await
542}
543
544pub(super) async fn check_sources_exist(
548 client: &Client,
549 sources: &BTreeSet<ObjectId>,
550) -> Result<BTreeSet<ObjectId>, ConnectionError> {
551 check_catalog_objects_exist(client, sources, "mz_sources").await
552}
553
554pub(super) async fn check_secrets_exist(
558 client: &Client,
559 secrets: &BTreeSet<ObjectId>,
560) -> Result<BTreeSet<ObjectId>, ConnectionError> {
561 check_catalog_objects_exist(client, secrets, "mz_secrets").await
562}
563
564pub(super) async fn check_connections_exist(
568 client: &Client,
569 connections: &BTreeSet<ObjectId>,
570) -> Result<BTreeSet<ObjectId>, ConnectionError> {
571 check_catalog_objects_exist(client, connections, "mz_connections").await
572}
573
574pub(super) async fn check_sinks_exist(
579 client: &Client,
580 sinks: &BTreeSet<ObjectId>,
581) -> Result<BTreeSet<ObjectId>, ConnectionError> {
582 check_catalog_objects_exist(client, sinks, "mz_sinks").await
583}
584
585pub(super) async fn find_sinks_depending_on_schemas(
591 client: &Client,
592 schemas: &[SchemaQualifier],
593) -> Result<Vec<DependentSink>, ConnectionError> {
594 if schemas.is_empty() {
595 return Ok(Vec::new());
596 }
597
598 let mut conditions = Vec::new();
600 let mut param_idx = 1;
601
602 for _ in schemas {
603 conditions.push(format!(
604 "(dep_db.name = ${} AND dep_schema.name = ${})",
605 param_idx,
606 param_idx + 1
607 ));
608 param_idx += 2;
609 }
610
611 let where_clause = conditions.join(" OR ");
612
613 let query = format!(
614 r#"
615 SELECT
616 sink_db.name as sink_database,
617 sink_schema.name as sink_schema,
618 sinks.name as sink_name,
619 dep_db.name as dependency_database,
620 dep_schema.name as dependency_schema,
621 dep_obj.name as dependency_name,
622 dep_obj.type as dependency_type
623 FROM mz_sinks sinks
624 JOIN mz_schemas sink_schema ON sinks.schema_id = sink_schema.id
625 JOIN mz_databases sink_db ON sink_schema.database_id = sink_db.id
626 JOIN mz_internal.mz_object_dependencies deps ON sinks.id = deps.object_id
627 JOIN mz_objects dep_obj ON deps.referenced_object_id = dep_obj.id
628 JOIN mz_schemas dep_schema ON dep_obj.schema_id = dep_schema.id
629 JOIN mz_databases dep_db ON dep_schema.database_id = dep_db.id
630 WHERE ({})
631 AND dep_obj.type IN ('materialized-view', 'table', 'source')
632 ORDER BY sink_db.name, sink_schema.name, sinks.name
633 "#,
634 where_clause
635 );
636
637 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
639 for sq in schemas {
640 params.push(&sq.database);
641 params.push(&sq.schema);
642 }
643
644 let rows = client.query(&query, ¶ms).await?;
645
646 Ok(rows
647 .iter()
648 .map(|row| DependentSink {
649 sink_database: row.get("sink_database"),
650 sink_schema: row.get("sink_schema"),
651 sink_name: row.get("sink_name"),
652 dependency_database: row.get("dependency_database"),
653 dependency_schema: row.get("dependency_schema"),
654 dependency_name: row.get("dependency_name"),
655 dependency_type: row.get("dependency_type"),
656 })
657 .collect())
658}
659
660pub(super) async fn check_connection_exists(
662 client: &Client,
663 database: &str,
664 schema: &str,
665 name: &str,
666) -> Result<bool, ConnectionError> {
667 let query = r#"
668 SELECT EXISTS(
669 SELECT 1
670 FROM mz_catalog.mz_connections c
671 JOIN mz_catalog.mz_schemas s ON c.schema_id = s.id
672 JOIN mz_catalog.mz_databases d ON s.database_id = d.id
673 WHERE d.name = $1 AND s.name = $2 AND c.name = $3
674 ) AS exists
675 "#;
676 let row = client
677 .query_one(query, &[&database, &schema, &name])
678 .await?;
679 Ok(row.get("exists"))
680}
681
682pub(super) async fn object_exists(
686 client: &Client,
687 database: &str,
688 schema: &str,
689 object: &str,
690) -> Result<bool, ConnectionError> {
691 let query = r#"
692 SELECT EXISTS(
693 SELECT 1 FROM mz_objects o
694 JOIN mz_schemas s ON o.schema_id = s.id
695 JOIN mz_databases d ON s.database_id = d.id
696 WHERE d.name = $1 AND s.name = $2 AND o.name = $3
697 AND o.type IN ('materialized-view', 'table', 'source')
698 ) AS exists
699 "#;
700
701 let row = client
702 .query_one(query, &[&database, &schema, &object])
703 .await?;
704
705 Ok(row.get("exists"))
706}
707
708pub(super) async fn get_staging_schemas(
710 client: &Client,
711 deploy_id: &str,
712) -> Result<Vec<SchemaQualifier>, ConnectionError> {
713 let pattern = staging_suffix_like_pattern(deploy_id);
714
715 let query = r#"
716 SELECT d.name as database, s.name as schema
717 FROM mz_schemas s
718 JOIN mz_databases d ON s.database_id = d.id
719 WHERE s.name LIKE $1 ESCAPE '\'
720 "#;
721
722 let rows = client.query(query, &[&pattern]).await?;
723
724 Ok(rows
725 .iter()
726 .map(|row| {
727 let database: String = row.get("database");
728 let schema: String = row.get("schema");
729 SchemaQualifier::new(database, schema)
730 })
731 .collect())
732}
733
734pub(super) async fn get_staging_clusters(
736 client: &Client,
737 deploy_id: &str,
738) -> Result<Vec<String>, ConnectionError> {
739 let pattern = staging_suffix_like_pattern(deploy_id);
740
741 let query = r#"
742 SELECT name
743 FROM mz_clusters
744 WHERE name LIKE $1 ESCAPE '\'
745 "#;
746
747 let rows = client.query(query, &[&pattern]).await?;
748
749 Ok(rows.iter().map(|row| row.get("name")).collect())
750}
751
752fn mz_type_to_drop_keyword(obj_type: &str) -> Option<&'static str> {
754 match obj_type {
755 "table" => Some("TABLE"),
756 "view" => Some("VIEW"),
757 "materialized-view" => Some("MATERIALIZED VIEW"),
758 "source" => Some("SOURCE"),
759 "sink" => Some("SINK"),
760 _ => None,
761 }
762}
763
764pub(super) async fn drop_schema_objects(
768 client: &Client,
769 database: &str,
770 schema: &str,
771) -> Result<Vec<String>, ConnectionError> {
772 let query = r#"
773 SELECT mo.name, mo.type
774 FROM mz_objects mo
775 JOIN mz_schemas s ON mo.schema_id = s.id
776 JOIN mz_databases d ON s.database_id = d.id
777 WHERE d.name = $1 AND s.name = $2
778 AND mo.type IN ('table', 'view', 'materialized-view', 'source', 'sink')
779 ORDER BY mo.id DESC
780 "#;
781
782 let rows = client.query(query, &[&database, &schema]).await?;
783
784 let mut dropped = Vec::new();
785 for row in rows {
786 let name: String = row.get("name");
787 let obj_type: String = row.get("type");
788
789 let fqn = format!(
790 "{}.{}.{}",
791 quote_identifier(database),
792 quote_identifier(schema),
793 quote_identifier(&name)
794 );
795 let Some(drop_type) = mz_type_to_drop_keyword(obj_type.as_str()) else {
796 continue;
797 };
798
799 let drop_sql = format!("DROP {} IF EXISTS {} CASCADE", drop_type, fqn);
800 client.execute(&drop_sql, &[]).await?;
801
802 dropped.push(fqn);
803 }
804
805 Ok(dropped)
806}
807
808pub(super) async fn drop_objects(
812 client: &Client,
813 objects: &BTreeSet<ObjectId>,
814) -> Result<Vec<String>, ConnectionError> {
815 let mut dropped = Vec::new();
816
817 if objects.is_empty() {
818 return Ok(dropped);
819 }
820
821 let placeholders_str = sql_placeholders(objects.len());
822
823 let query = format!(
824 r#"
825 SELECT mo.name, s.name as schema_name, d.name as database_name, mo.type
826 FROM mz_objects mo
827 JOIN mz_schemas s ON mo.schema_id = s.id
828 JOIN mz_databases d ON s.database_id = d.id
829 WHERE d.name || '.' || s.name || '.' || mo.name IN ({})
830 AND mo.type IN ('table', 'view', 'materialized-view', 'source', 'sink')
831 ORDER BY mo.id DESC
832 "#,
833 placeholders_str
834 );
835
836 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
837 let fqns: Vec<_> = objects.iter().map(|object| object.to_string()).collect();
838 for fqn in &fqns {
839 params.push(fqn);
840 }
841
842 let rows = client.query(&query, ¶ms).await?;
843
844 for row in rows {
845 let name: String = row.get("name");
846 let schema: String = row.get("schema_name");
847 let database: String = row.get("database_name");
848 let obj_type: String = row.get("type");
849
850 let fqn = format!(
851 "{}.{}.{}",
852 quote_identifier(&database),
853 quote_identifier(&schema),
854 quote_identifier(&name)
855 );
856 let Some(drop_type) = mz_type_to_drop_keyword(obj_type.as_str()) else {
857 continue;
858 };
859
860 let drop_sql = format!("DROP {} IF EXISTS {} CASCADE", drop_type, fqn);
861 client.execute(&drop_sql, &[]).await?;
862
863 dropped.push(fqn);
864 }
865
866 Ok(dropped)
867}
868
869pub(super) async fn drop_staging_schemas(
871 client: &Client,
872 schemas: &[SchemaQualifier],
873) -> Result<(), ConnectionError> {
874 for sq in schemas {
875 let drop_sql = format!(
876 "DROP SCHEMA IF EXISTS {}.{} CASCADE",
877 quote_identifier(&sq.database),
878 quote_identifier(&sq.schema)
879 );
880 client.execute(&drop_sql, &[]).await?;
881 }
882
883 Ok(())
884}
885
886pub(super) async fn drop_staging_clusters(
888 client: &Client,
889 clusters: &[String],
890) -> Result<(), ConnectionError> {
891 for cluster in clusters {
892 let drop_sql = format!(
893 "DROP CLUSTER IF EXISTS {} CASCADE",
894 quote_identifier(cluster)
895 );
896 client.execute(&drop_sql, &[]).await?;
897 }
898
899 Ok(())
900}
901
902async fn get_named_object_grants(
908 client: &Client,
909 catalog_table: &str,
910 name: &str,
911) -> Result<Vec<ObjectGrant>, ConnectionError> {
912 let query = format!(
913 r#"
914 -- Explode the ACL bitmap into individual (grantee, privilege_type) rows.
915 -- Each object stores privileges as a compact bitmap; mz_aclexplode unpacks it.
916 WITH privilege AS (
917 SELECT mz_internal.mz_aclexplode(privileges).*, owner_id
918 FROM {}
919 WHERE name = $1
920 )
921 SELECT
922 grantee.name AS grantee,
923 p.privilege_type
924 FROM privilege AS p
925 -- Resolve grantee role IDs to human-readable names.
926 JOIN mz_roles AS grantee ON p.grantee = grantee.id
927 -- Exclude system roles that are not user-manageable.
928 WHERE grantee.name NOT IN ('none', 'mz_system', 'mz_support')
929 -- Owners implicitly have all privileges; don't surface those as explicit grants.
930 AND p.grantee != p.owner_id
931 "#,
932 catalog_table
933 );
934
935 let rows = client.query(&query, &[&name]).await?;
936
937 Ok(rows
938 .iter()
939 .map(|row| ObjectGrant {
940 grantee: row.get("grantee"),
941 privilege_type: row.get("privilege_type"),
942 })
943 .collect())
944}
945
946pub(super) async fn get_cluster_grants(
948 client: &Client,
949 name: &str,
950) -> Result<Vec<ObjectGrant>, ConnectionError> {
951 get_named_object_grants(client, "mz_clusters", name).await
952}
953
954pub(super) async fn get_network_policy_grants(
956 client: &Client,
957 name: &str,
958) -> Result<Vec<ObjectGrant>, ConnectionError> {
959 get_named_object_grants(client, "mz_network_policies", name).await
960}
961
962pub(super) async fn get_database_object_grants(
966 client: &Client,
967 catalog_table: &str,
968 database: &str,
969 schema: &str,
970 name: &str,
971) -> Result<Vec<ObjectGrant>, ConnectionError> {
972 let query = format!(
973 r#"
974 -- Locate the object by its fully-qualified name (database.schema.object)
975 -- using a 3-table join chain: catalog_table -> mz_schemas -> mz_databases.
976 -- Then explode the ACL bitmap into individual privilege rows.
977 WITH privilege AS (
978 SELECT mz_internal.mz_aclexplode(t.privileges).*, t.owner_id
979 FROM {} t
980 JOIN mz_schemas s ON t.schema_id = s.id
981 JOIN mz_databases d ON s.database_id = d.id
982 WHERE d.name = $1 AND s.name = $2 AND t.name = $3
983 )
984 SELECT
985 grantee.name AS grantee,
986 p.privilege_type
987 FROM privilege AS p
988 JOIN mz_roles AS grantee ON p.grantee = grantee.id
989 WHERE grantee.name NOT IN ('none', 'mz_system', 'mz_support')
990 AND p.grantee != p.owner_id
991 "#,
992 catalog_table
993 );
994
995 let rows = client.query(&query, &[&database, &schema, &name]).await?;
996
997 Ok(rows
998 .iter()
999 .map(|row| ObjectGrant {
1000 grantee: row.get("grantee"),
1001 privilege_type: row.get("privilege_type"),
1002 })
1003 .collect())
1004}
1005
1006async fn get_default_privilege_grants_for_named_object(
1012 client: &Client,
1013 catalog_table: &str,
1014 name: &str,
1015 object_type: &str,
1016) -> Result<Vec<ObjectGrant>, ConnectionError> {
1017 let query = format!(
1018 r#"
1019 -- Query default privileges from ALTER DEFAULT PRIVILEGES rules.
1020 -- These are auto-applied grants that should be protected from revocation.
1021 SELECT
1022 grantee_role.name AS grantee,
1023 dp_priv.privilege_type
1024 FROM mz_default_privileges dp
1025 -- Expand the privilege bitmap into individual privilege type strings.
1026 CROSS JOIN LATERAL unnest(
1027 mz_internal.mz_format_privileges(dp.privileges)
1028 ) AS dp_priv(privilege_type)
1029 JOIN {} obj ON obj.name = $1
1030 JOIN mz_roles AS grantee_role ON dp.grantee = grantee_role.id
1031 WHERE dp.object_type = $2
1032 -- Match rules targeting the object's owner, or PUBLIC ('p') rules
1033 -- that apply to all owners.
1034 AND (dp.role_id = obj.owner_id OR dp.role_id = 'p')
1035 -- Named objects (clusters, network policies) are not schema-scoped,
1036 -- so only global default privileges (both NULL) apply.
1037 AND dp.database_id IS NULL
1038 AND dp.schema_id IS NULL
1039 AND grantee_role.name NOT IN ('none', 'mz_system', 'mz_support')
1040 "#,
1041 catalog_table
1042 );
1043
1044 let rows = client.query(&query, &[&name, &object_type]).await?;
1045
1046 Ok(rows
1047 .iter()
1048 .map(|row| ObjectGrant {
1049 grantee: row.get("grantee"),
1050 privilege_type: row.get("privilege_type"),
1051 })
1052 .collect())
1053}
1054
1055pub(super) async fn get_default_privilege_grants_for_cluster(
1057 client: &Client,
1058 name: &str,
1059) -> Result<Vec<ObjectGrant>, ConnectionError> {
1060 get_default_privilege_grants_for_named_object(client, "mz_clusters", name, "cluster").await
1061}
1062
1063pub(super) async fn get_default_privilege_grants_for_network_policy(
1065 client: &Client,
1066 name: &str,
1067) -> Result<Vec<ObjectGrant>, ConnectionError> {
1068 get_default_privilege_grants_for_named_object(client, "mz_network_policies", name, "type").await
1069}
1070
1071pub(super) async fn get_default_privilege_grants_for_database_object(
1077 client: &Client,
1078 catalog_table: &str,
1079 database: &str,
1080 schema: &str,
1081 name: &str,
1082 object_type: &str,
1083) -> Result<Vec<ObjectGrant>, ConnectionError> {
1084 let query = format!(
1085 r#"
1086 -- Query default privileges from ALTER DEFAULT PRIVILEGES rules
1087 -- for a schema-qualified database object.
1088 SELECT
1089 grantee_role.name AS grantee,
1090 dp_priv.privilege_type
1091 FROM mz_default_privileges dp
1092 -- Expand the privilege bitmap into individual privilege type strings.
1093 CROSS JOIN LATERAL unnest(
1094 mz_internal.mz_format_privileges(dp.privileges)
1095 ) AS dp_priv(privilege_type)
1096 -- Locate the object by FQN to determine its owner, database, and schema.
1097 JOIN {} obj ON obj.name = $3
1098 JOIN mz_schemas s ON obj.schema_id = s.id
1099 JOIN mz_databases d ON s.database_id = d.id
1100 JOIN mz_roles AS grantee_role ON dp.grantee = grantee_role.id
1101 WHERE d.name = $1 AND s.name = $2
1102 AND dp.object_type = $4
1103 -- Match rules targeting the object's owner, or PUBLIC ('p') rules.
1104 AND (dp.role_id = obj.owner_id OR dp.role_id = 'p')
1105 -- Match both global rules (database_id IS NULL) and rules scoped to
1106 -- this specific database. Global rules apply to all databases.
1107 AND (dp.database_id IS NULL OR dp.database_id = d.id)
1108 -- Same for schema: global or scoped to this specific schema.
1109 AND (dp.schema_id IS NULL OR dp.schema_id = s.id)
1110 AND grantee_role.name NOT IN ('none', 'mz_system', 'mz_support')
1111 "#,
1112 catalog_table
1113 );
1114
1115 let rows = client
1116 .query(&query, &[&database, &schema, &name, &object_type])
1117 .await?;
1118
1119 Ok(rows
1120 .iter()
1121 .map(|row| ObjectGrant {
1122 grantee: row.get("grantee"),
1123 privilege_type: row.get("privilege_type"),
1124 })
1125 .collect())
1126}
1127
1128pub(super) async fn get_connection_create_sql(
1134 client: &Client,
1135 database: &str,
1136 schema: &str,
1137 name: &str,
1138) -> Result<Option<String>, ConnectionError> {
1139 let fqn = format!(
1140 "{}.{}.{}",
1141 quote_identifier(database),
1142 quote_identifier(schema),
1143 quote_identifier(name)
1144 );
1145 let query = format!("SHOW CREATE CONNECTION {}", fqn);
1146 let rows = client.query(&query, &[]).await?;
1147 Ok(rows.first().map(|row| row.get("create_sql")))
1148}
1149
1150impl IntrospectionClient<'_> {
1151 pub async fn get_current_user(&self) -> Result<String, ConnectionError> {
1153 get_current_user(self.client).await
1154 }
1155
1156 pub async fn check_objects_exist(
1158 &self,
1159 objects: &BTreeSet<ObjectId>,
1160 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1161 check_objects_exist(self.client, objects).await
1162 }
1163
1164 pub async fn check_catalog_objects_exist(
1166 &self,
1167 objects: &BTreeSet<ObjectId>,
1168 catalog_table: &str,
1169 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1170 check_catalog_objects_exist(self.client, objects, catalog_table).await
1171 }
1172
1173 pub async fn check_tables_exist(
1175 &self,
1176 tables: &BTreeSet<ObjectId>,
1177 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1178 check_tables_exist(self.client, tables).await
1179 }
1180
1181 pub async fn check_sources_exist(
1183 &self,
1184 sources: &BTreeSet<ObjectId>,
1185 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1186 check_sources_exist(self.client, sources).await
1187 }
1188
1189 pub async fn check_secrets_exist(
1191 &self,
1192 secrets: &BTreeSet<ObjectId>,
1193 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1194 check_secrets_exist(self.client, secrets).await
1195 }
1196
1197 pub async fn check_connections_exist(
1199 &self,
1200 connections: &BTreeSet<ObjectId>,
1201 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1202 check_connections_exist(self.client, connections).await
1203 }
1204
1205 pub async fn check_sinks_exist(
1207 &self,
1208 sinks: &BTreeSet<ObjectId>,
1209 ) -> Result<BTreeSet<ObjectId>, ConnectionError> {
1210 check_sinks_exist(self.client, sinks).await
1211 }
1212
1213 pub async fn check_schemas_exist(
1215 &self,
1216 schemas: &[(String, String)],
1217 ) -> Result<BTreeSet<(String, String)>, ConnectionError> {
1218 check_schemas_exist(self.client, schemas).await
1219 }
1220
1221 pub async fn check_clusters_exist(
1223 &self,
1224 clusters: &[String],
1225 ) -> Result<BTreeSet<String>, ConnectionError> {
1226 check_clusters_exist(self.client, clusters).await
1227 }
1228
1229 pub async fn find_sinks_depending_on_schemas(
1231 &self,
1232 schemas: &[SchemaQualifier],
1233 ) -> Result<Vec<DependentSink>, ConnectionError> {
1234 find_sinks_depending_on_schemas(self.client, schemas).await
1235 }
1236
1237 pub async fn check_connection_exists(
1239 &self,
1240 database: &str,
1241 schema: &str,
1242 name: &str,
1243 ) -> Result<bool, ConnectionError> {
1244 check_connection_exists(self.client, database, schema, name).await
1245 }
1246
1247 pub async fn object_exists(
1249 &self,
1250 database: &str,
1251 schema: &str,
1252 object: &str,
1253 ) -> Result<bool, ConnectionError> {
1254 object_exists(self.client, database, schema, object).await
1255 }
1256
1257 pub async fn get_staging_schemas(
1259 &self,
1260 deploy_id: &str,
1261 ) -> Result<Vec<SchemaQualifier>, ConnectionError> {
1262 get_staging_schemas(self.client, deploy_id).await
1263 }
1264
1265 pub async fn get_staging_clusters(
1267 &self,
1268 deploy_id: &str,
1269 ) -> Result<Vec<String>, ConnectionError> {
1270 get_staging_clusters(self.client, deploy_id).await
1271 }
1272
1273 pub async fn drop_schema_objects(
1275 &self,
1276 database: &str,
1277 schema: &str,
1278 ) -> Result<Vec<String>, ConnectionError> {
1279 drop_schema_objects(self.client, database, schema).await
1280 }
1281
1282 pub async fn drop_objects(
1284 &self,
1285 objects: &BTreeSet<ObjectId>,
1286 ) -> Result<Vec<String>, ConnectionError> {
1287 drop_objects(self.client, objects).await
1288 }
1289
1290 pub async fn drop_staging_schemas(
1292 &self,
1293 schemas: &[SchemaQualifier],
1294 ) -> Result<(), ConnectionError> {
1295 drop_staging_schemas(self.client, schemas).await
1296 }
1297
1298 pub async fn drop_staging_clusters(&self, clusters: &[String]) -> Result<(), ConnectionError> {
1300 drop_staging_clusters(self.client, clusters).await
1301 }
1302
1303 pub async fn schema_exists(
1305 &self,
1306 database: &str,
1307 schema: &str,
1308 ) -> Result<bool, ConnectionError> {
1309 schema_exists(self.client, database, schema).await
1310 }
1311
1312 pub async fn network_policy_exists(&self, name: &str) -> Result<bool, ConnectionError> {
1314 network_policy_exists(self.client, name).await
1315 }
1316
1317 pub async fn role_exists(&self, name: &str) -> Result<bool, ConnectionError> {
1319 role_exists(self.client, name).await
1320 }
1321
1322 pub async fn get_role_members(&self, name: &str) -> Result<Vec<String>, ConnectionError> {
1324 get_role_members(self.client, name).await
1325 }
1326
1327 pub async fn get_role_parameters(&self, name: &str) -> Result<Vec<String>, ConnectionError> {
1329 get_role_parameters(self.client, name).await
1330 }
1331
1332 pub async fn cluster_exists(&self, name: &str) -> Result<bool, ConnectionError> {
1334 cluster_exists(self.client, name).await
1335 }
1336
1337 pub async fn get_cluster(&self, name: &str) -> Result<Option<Cluster>, ConnectionError> {
1339 get_cluster(self.client, name).await
1340 }
1341
1342 pub async fn get_cluster_create_sql(
1344 &self,
1345 name: &str,
1346 ) -> Result<Option<String>, ConnectionError> {
1347 get_cluster_create_sql(self.client, name).await
1348 }
1349
1350 pub async fn list_clusters(&self) -> Result<Vec<Cluster>, ConnectionError> {
1352 list_clusters(self.client).await
1353 }
1354
1355 pub async fn get_cluster_config(
1357 &self,
1358 name: &str,
1359 ) -> Result<Option<ClusterConfig>, ConnectionError> {
1360 get_cluster_config(self.client, name).await
1361 }
1362
1363 pub async fn get_cluster_grants(
1365 &self,
1366 name: &str,
1367 ) -> Result<Vec<ObjectGrant>, ConnectionError> {
1368 get_cluster_grants(self.client, name).await
1369 }
1370
1371 pub async fn get_network_policy_grants(
1373 &self,
1374 name: &str,
1375 ) -> Result<Vec<ObjectGrant>, ConnectionError> {
1376 get_network_policy_grants(self.client, name).await
1377 }
1378
1379 pub async fn get_database_object_grants(
1381 &self,
1382 catalog_table: &str,
1383 database: &str,
1384 schema: &str,
1385 name: &str,
1386 ) -> Result<Vec<ObjectGrant>, ConnectionError> {
1387 get_database_object_grants(self.client, catalog_table, database, schema, name).await
1388 }
1389
1390 pub async fn get_connection_create_sql(
1392 &self,
1393 database: &str,
1394 schema: &str,
1395 name: &str,
1396 ) -> Result<Option<String>, ConnectionError> {
1397 get_connection_create_sql(self.client, database, schema, name).await
1398 }
1399
1400 pub async fn get_default_privilege_grants_for_cluster(
1402 &self,
1403 name: &str,
1404 ) -> Result<Vec<ObjectGrant>, ConnectionError> {
1405 get_default_privilege_grants_for_cluster(self.client, name).await
1406 }
1407
1408 pub async fn get_default_privilege_grants_for_network_policy(
1410 &self,
1411 name: &str,
1412 ) -> Result<Vec<ObjectGrant>, ConnectionError> {
1413 get_default_privilege_grants_for_network_policy(self.client, name).await
1414 }
1415
1416 pub async fn get_default_privilege_grants_for_database_object(
1418 &self,
1419 catalog_table: &str,
1420 database: &str,
1421 schema: &str,
1422 name: &str,
1423 object_type: &str,
1424 ) -> Result<Vec<ObjectGrant>, ConnectionError> {
1425 get_default_privilege_grants_for_database_object(
1426 self.client,
1427 catalog_table,
1428 database,
1429 schema,
1430 name,
1431 object_type,
1432 )
1433 .await
1434 }
1435}