Skip to main content

mz_deploy/project/compiler/
mod_statements.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//! Validation for database and schema mod file statements.
11//!
12//! Validates that mod files (database-level and schema-level) contain only
13//! permitted statement types: comments, grants, and alter default privileges
14//! targeting the correct database or schema.
15
16use crate::project::error::{ValidationError, ValidationErrorKind};
17use mz_sql_parser::ast::*;
18
19/// Get a human-readable name for a CommentObjectType variant.
20fn comment_object_type_name(obj: &CommentObjectType<Raw>) -> &'static str {
21    match obj {
22        CommentObjectType::Table { .. } => "TABLE",
23        CommentObjectType::View { .. } => "VIEW",
24        CommentObjectType::MaterializedView { .. } => "MATERIALIZED VIEW",
25        CommentObjectType::Source { .. } => "SOURCE",
26        CommentObjectType::Sink { .. } => "SINK",
27        CommentObjectType::Connection { .. } => "CONNECTION",
28        CommentObjectType::Secret { .. } => "SECRET",
29        CommentObjectType::Schema { .. } => "SCHEMA",
30        CommentObjectType::Database { .. } => "DATABASE",
31        CommentObjectType::Column { .. } => "COLUMN",
32        CommentObjectType::Index { .. } => "INDEX",
33        CommentObjectType::Func { .. } => "FUNCTION",
34        CommentObjectType::Type { .. } => "TYPE",
35        CommentObjectType::Role { .. } => "ROLE",
36        CommentObjectType::Cluster { .. } => "CLUSTER",
37        CommentObjectType::ClusterReplica { .. } => "CLUSTER REPLICA",
38        CommentObjectType::NetworkPolicy { .. } => "NETWORK POLICY",
39        CommentObjectType::QueryPolicy { .. } => "QUERY POLICY",
40    }
41}
42
43/// Validate database mod file statements.
44///
45/// Database mod files can only contain:
46/// - COMMENT ON DATABASE (targeting the database itself)
47/// - GRANT ON DATABASE (targeting the database itself)
48/// - ALTER DEFAULT PRIVILEGES
49pub(crate) fn validate_database_mod_statements(
50    database_name: &str,
51    database_path: &std::path::Path,
52    statements: &[Statement<Raw>],
53    errors: &mut Vec<ValidationError>,
54) {
55    use mz_sql_parser::ast::Statement as MzStatement;
56
57    for stmt in statements {
58        let stmt_sql = format!("{};", stmt);
59
60        match stmt {
61            MzStatement::Comment(comment_stmt) => {
62                // Must be COMMENT ON DATABASE targeting this database
63                match &comment_stmt.object {
64                    CommentObjectType::Database { name } => {
65                        // Check if it targets this database
66                        let target_db = name.to_string();
67                        if target_db != database_name {
68                            errors.push(ValidationError::with_file_and_sql(
69                                ValidationErrorKind::DatabaseModCommentTargetMismatch {
70                                    target: format!("DATABASE {}", target_db),
71                                    database_name: database_name.to_string(),
72                                },
73                                database_path.to_path_buf(),
74                                stmt_sql,
75                            ));
76                        }
77                    }
78                    _ => {
79                        errors.push(ValidationError::with_file_and_sql(
80                            ValidationErrorKind::DatabaseModCommentTargetMismatch {
81                                target: comment_object_type_name(&comment_stmt.object).to_string(),
82                                database_name: database_name.to_string(),
83                            },
84                            database_path.to_path_buf(),
85                            stmt_sql,
86                        ));
87                    }
88                }
89            }
90            MzStatement::GrantPrivileges(grant_stmt) => {
91                // Must be GRANT ON DATABASE targeting this database
92                match &grant_stmt.target {
93                    GrantTargetSpecification::Object {
94                        object_type,
95                        object_spec_inner,
96                        ..
97                    } => {
98                        if object_type != &ObjectType::Database {
99                            errors.push(ValidationError::with_file_and_sql(
100                                ValidationErrorKind::DatabaseModGrantTargetMismatch {
101                                    target: format!("{}", object_type),
102                                    database_name: database_name.to_string(),
103                                },
104                                database_path.to_path_buf(),
105                                stmt_sql.clone(),
106                            ));
107                        }
108
109                        // Check that it targets this specific database
110                        if let GrantTargetSpecificationInner::Objects { names } = object_spec_inner
111                        {
112                            for name in names {
113                                if let UnresolvedObjectName::Item(item_name) = name {
114                                    let target_db = item_name.to_string();
115                                    if target_db != database_name {
116                                        errors.push(ValidationError::with_file_and_sql(
117                                            ValidationErrorKind::DatabaseModGrantTargetMismatch {
118                                                target: format!("DATABASE {}", target_db),
119                                                database_name: database_name.to_string(),
120                                            },
121                                            database_path.to_path_buf(),
122                                            stmt_sql.clone(),
123                                        ));
124                                    }
125                                }
126                            }
127                        }
128                    }
129                    GrantTargetSpecification::System => {
130                        errors.push(ValidationError::with_file_and_sql(
131                            ValidationErrorKind::DatabaseModGrantTargetMismatch {
132                                target: "SYSTEM or other".to_string(),
133                                database_name: database_name.to_string(),
134                            },
135                            database_path.to_path_buf(),
136                            stmt_sql,
137                        ));
138                    }
139                }
140            }
141            MzStatement::AlterDefaultPrivileges(alter_stmt) => {
142                // Must specify IN DATABASE targeting this database
143                match &alter_stmt.target_objects {
144                    GrantTargetAllSpecification::AllDatabases { databases } => {
145                        // Validate all databases reference the current database
146                        for db_name in databases {
147                            let db_str = db_name.to_string();
148                            if db_str != database_name {
149                                errors.push(ValidationError::with_file_and_sql(
150                                    ValidationErrorKind::AlterDefaultPrivilegesDatabaseMismatch {
151                                        referenced: db_str,
152                                        expected: database_name.to_string(),
153                                    },
154                                    database_path.to_path_buf(),
155                                    stmt_sql.clone(),
156                                ));
157                            }
158                        }
159                    }
160                    GrantTargetAllSpecification::AllSchemas { .. } => {
161                        // Reject: IN SCHEMA not allowed in database mod files
162                        errors.push(ValidationError::with_file_and_sql(
163                            ValidationErrorKind::AlterDefaultPrivilegesSchemaNotAllowed {
164                                database_name: database_name.to_string(),
165                            },
166                            database_path.to_path_buf(),
167                            stmt_sql.clone(),
168                        ));
169                    }
170                    GrantTargetAllSpecification::All => {
171                        // Reject: Must specify IN DATABASE
172                        errors.push(ValidationError::with_file_and_sql(
173                            ValidationErrorKind::AlterDefaultPrivilegesRequiresDatabaseScope {
174                                database_name: database_name.to_string(),
175                            },
176                            database_path.to_path_buf(),
177                            stmt_sql.clone(),
178                        ));
179                    }
180                }
181            }
182            _ => {
183                // Reject all other statement types
184                errors.push(ValidationError::with_file_and_sql(
185                    ValidationErrorKind::InvalidDatabaseModStatement {
186                        statement_type: format!("{:?}", stmt)
187                            .split('(')
188                            .next()
189                            .unwrap_or("unknown")
190                            .to_string(),
191                        database_name: database_name.to_string(),
192                    },
193                    database_path.to_path_buf(),
194                    stmt_sql,
195                ));
196            }
197        }
198    }
199}
200
201/// Validate schema mod file statements and normalize names.
202///
203/// Schema mod files can only contain:
204/// - COMMENT ON SCHEMA (targeting the schema itself)
205/// - GRANT ON SCHEMA (targeting the schema itself)
206/// - ALTER DEFAULT PRIVILEGES
207///
208/// Names are normalized to include the database qualifier.
209pub(crate) fn validate_schema_mod_statements(
210    database_name: &str,
211    schema_name: &str,
212    schema_path: &std::path::Path,
213    statements: &mut [Statement<Raw>],
214    errors: &mut Vec<ValidationError>,
215) {
216    use mz_sql_parser::ast::Statement as MzStatement;
217
218    // Helper function to normalize unqualified schema names
219    let normalize_schema_name = |name: &mut UnresolvedSchemaName| {
220        if name.0.len() == 1 {
221            // Unqualified: prepend database to make database.schema
222            let schema = name.0[0].clone();
223            let database = Ident::new(database_name).expect("valid database identifier");
224            name.0 = vec![database, schema];
225        }
226        // Already qualified or invalid - leave as-is
227    };
228
229    for stmt in statements.iter_mut() {
230        let stmt_sql = format!("{};", stmt);
231
232        match stmt {
233            MzStatement::Comment(comment_stmt) => {
234                // Must be COMMENT ON SCHEMA targeting this schema
235                match &mut comment_stmt.object {
236                    CommentObjectType::Schema { name } => {
237                        // Check if it targets this schema (can be qualified or unqualified)
238                        let target_schema = name.to_string();
239                        let is_match =
240                            schema_name_matches(&target_schema, database_name, schema_name);
241
242                        if !is_match {
243                            errors.push(ValidationError::with_file_and_sql(
244                                ValidationErrorKind::SchemaModCommentTargetMismatch {
245                                    target: format!("SCHEMA {}", target_schema),
246                                    schema_name: format!("{}.{}", database_name, schema_name),
247                                },
248                                schema_path.to_path_buf(),
249                                stmt_sql,
250                            ));
251                        } else {
252                            // Normalize the schema name to be fully qualified
253                            normalize_schema_name(name);
254                        }
255                    }
256                    _ => {
257                        errors.push(ValidationError::with_file_and_sql(
258                            ValidationErrorKind::SchemaModCommentTargetMismatch {
259                                target: comment_object_type_name(&comment_stmt.object).to_string(),
260                                schema_name: format!("{}.{}", database_name, schema_name),
261                            },
262                            schema_path.to_path_buf(),
263                            stmt_sql,
264                        ));
265                    }
266                }
267            }
268            MzStatement::GrantPrivileges(grant_stmt) => {
269                // Must be GRANT ON SCHEMA targeting this schema
270                match &mut grant_stmt.target {
271                    GrantTargetSpecification::Object {
272                        object_type,
273                        object_spec_inner,
274                        ..
275                    } => {
276                        if object_type != &ObjectType::Schema {
277                            errors.push(ValidationError::with_file_and_sql(
278                                ValidationErrorKind::SchemaModGrantTargetMismatch {
279                                    target: format!("{}", object_type),
280                                    schema_name: format!("{}.{}", database_name, schema_name),
281                                },
282                                schema_path.to_path_buf(),
283                                stmt_sql.clone(),
284                            ));
285                        }
286
287                        // Check that it targets this specific schema
288                        if let GrantTargetSpecificationInner::Objects { names } = object_spec_inner
289                        {
290                            for name in names {
291                                if let UnresolvedObjectName::Schema(schema_name_obj) = name {
292                                    let target_schema = schema_name_obj.to_string();
293                                    let is_match = schema_name_matches(
294                                        &target_schema,
295                                        database_name,
296                                        schema_name,
297                                    );
298
299                                    if !is_match {
300                                        errors.push(ValidationError::with_file_and_sql(
301                                            ValidationErrorKind::SchemaModGrantTargetMismatch {
302                                                target: format!("SCHEMA {}", target_schema),
303                                                schema_name: format!(
304                                                    "{}.{}",
305                                                    database_name, schema_name
306                                                ),
307                                            },
308                                            schema_path.to_path_buf(),
309                                            stmt_sql.clone(),
310                                        ));
311                                    } else {
312                                        // Normalize the schema name to be fully qualified
313                                        normalize_schema_name(schema_name_obj);
314                                    }
315                                }
316                            }
317                        }
318                    }
319                    GrantTargetSpecification::System => {
320                        errors.push(ValidationError::with_file_and_sql(
321                            ValidationErrorKind::SchemaModGrantTargetMismatch {
322                                target: "SYSTEM or other".to_string(),
323                                schema_name: format!("{}.{}", database_name, schema_name),
324                            },
325                            schema_path.to_path_buf(),
326                            stmt_sql,
327                        ));
328                    }
329                }
330            }
331            MzStatement::SetVariable(set_stmt) => {
332                if set_stmt.variable.as_str().eq_ignore_ascii_case("api") {
333                    // SET api = stable is a valid schema mod directive
334                    let is_valid = match &set_stmt.to {
335                        SetVariableTo::Values(values) => {
336                            values.len() == 1
337                                && match &values[0] {
338                                    SetVariableValue::Ident(ident) => {
339                                        ident.as_str().eq_ignore_ascii_case("stable")
340                                    }
341                                    SetVariableValue::Literal(Value::String(s)) => {
342                                        s.eq_ignore_ascii_case("stable")
343                                    }
344                                    SetVariableValue::Literal(_) => false,
345                                }
346                        }
347                        SetVariableTo::Default => false,
348                    };
349
350                    if !is_valid {
351                        errors.push(ValidationError::with_file_and_sql(
352                            ValidationErrorKind::InvalidSetVariable {
353                                variable: set_stmt.variable.as_str().to_string(),
354                                value: set_stmt.to.to_string(),
355                            },
356                            schema_path.to_path_buf(),
357                            stmt_sql,
358                        ));
359                    }
360                } else {
361                    errors.push(ValidationError::with_file_and_sql(
362                        ValidationErrorKind::InvalidSchemaModStatement {
363                            statement_type: "SET".to_string(),
364                            schema_name: format!("{}.{}", database_name, schema_name),
365                        },
366                        schema_path.to_path_buf(),
367                        stmt_sql,
368                    ));
369                }
370            }
371            MzStatement::AlterDefaultPrivileges(alter_stmt) => {
372                // Must specify IN SCHEMA targeting this schema
373                match &mut alter_stmt.target_objects {
374                    GrantTargetAllSpecification::AllSchemas { schemas } => {
375                        // Validate each schema reference
376                        for schema_name_obj in schemas {
377                            let schema_str = schema_name_obj.to_string();
378
379                            // Check if it matches the current schema (qualified or unqualified)
380                            let is_match =
381                                schema_name_matches(&schema_str, database_name, schema_name);
382
383                            if !is_match {
384                                errors.push(ValidationError::with_file_and_sql(
385                                    ValidationErrorKind::AlterDefaultPrivilegesSchemaMismatch {
386                                        referenced: schema_str,
387                                        expected: format!("{}.{}", database_name, schema_name),
388                                    },
389                                    schema_path.to_path_buf(),
390                                    stmt_sql.clone(),
391                                ));
392                            } else {
393                                // Normalize the schema name to be fully qualified
394                                normalize_schema_name(schema_name_obj);
395                            }
396                        }
397                    }
398                    GrantTargetAllSpecification::AllDatabases { .. } => {
399                        // Reject: IN DATABASE not allowed in schema mod files
400                        errors.push(ValidationError::with_file_and_sql(
401                            ValidationErrorKind::AlterDefaultPrivilegesDatabaseNotAllowed {
402                                schema_name: format!("{}.{}", database_name, schema_name),
403                            },
404                            schema_path.to_path_buf(),
405                            stmt_sql.clone(),
406                        ));
407                    }
408                    GrantTargetAllSpecification::All => {
409                        // Reject: Must specify IN SCHEMA
410                        errors.push(ValidationError::with_file_and_sql(
411                            ValidationErrorKind::AlterDefaultPrivilegesRequiresSchemaScope {
412                                schema_name: format!("{}.{}", database_name, schema_name),
413                            },
414                            schema_path.to_path_buf(),
415                            stmt_sql.clone(),
416                        ));
417                    }
418                }
419            }
420            _ => {
421                // Reject all other statement types
422                errors.push(ValidationError::with_file_and_sql(
423                    ValidationErrorKind::InvalidSchemaModStatement {
424                        statement_type: format!("{:?}", stmt)
425                            .split('(')
426                            .next()
427                            .unwrap_or("unknown")
428                            .to_string(),
429                        schema_name: format!("{}.{}", database_name, schema_name),
430                    },
431                    schema_path.to_path_buf(),
432                    stmt_sql,
433                ));
434            }
435        }
436    }
437}
438
439/// Returns true if `target` matches `schema_name` either unqualified or as `database.schema`.
440fn schema_name_matches(target: &str, database_name: &str, schema_name: &str) -> bool {
441    target == schema_name || target == format!("{}.{}", database_name, schema_name)
442}