Skip to main content

mz_sql/ast/
transform.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//! Provides a publicly available interface to transform our SQL ASTs.
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use mz_ore::str::StrExt;
15use mz_repr::CatalogItemId;
16use mz_sql_parser::ast::CreateTableFromSourceStatement;
17
18use crate::ast::visit::{self, Visit};
19use crate::ast::visit_mut::{self, VisitMut};
20use crate::ast::{
21    AstInfo, CreateConnectionStatement, CreateIndexStatement, CreateMaterializedViewStatement,
22    CreateMetricSinkStatement, CreateSecretStatement, CreateSinkStatement, CreateSourceStatement,
23    CreateSubsourceStatement, CreateTableStatement, CreateViewStatement,
24    CreateWebhookSourceStatement, Expr, Ident, Query, Raw, RawDataType, RawItemName, Statement,
25    UnresolvedItemName, ViewDefinition,
26};
27use crate::names::FullItemName;
28
29/// Given a [`Statement`] rewrites all references of the schema name `cur_schema_name` to
30/// `new_schema_name`.
31pub fn create_stmt_rename_schema_refs(
32    create_stmt: &mut Statement<Raw>,
33    database: &str,
34    cur_schema: &str,
35    new_schema: &str,
36) -> Result<(), (String, String)> {
37    match create_stmt {
38        stmt @ Statement::CreateConnection(_)
39        | stmt @ Statement::CreateDatabase(_)
40        | stmt @ Statement::CreateSchema(_)
41        | stmt @ Statement::CreateWebhookSource(_)
42        | stmt @ Statement::CreateSource(_)
43        | stmt @ Statement::CreateSubsource(_)
44        | stmt @ Statement::CreateSink(_)
45        | stmt @ Statement::CreateMetricSink(_)
46        | stmt @ Statement::CreateView(_)
47        | stmt @ Statement::CreateMaterializedView(_)
48        | stmt @ Statement::CreateTable(_)
49        | stmt @ Statement::CreateTableFromSource(_)
50        | stmt @ Statement::CreateIndex(_)
51        | stmt @ Statement::CreateType(_)
52        | stmt @ Statement::CreateSecret(_) => {
53            let mut visitor = CreateSqlRewriteSchema {
54                database,
55                cur_schema,
56                new_schema,
57                error: None,
58            };
59            visitor.visit_statement_mut(stmt);
60
61            if let Some(e) = visitor.error.take() {
62                Err(e)
63            } else {
64                Ok(())
65            }
66        }
67        stmt => {
68            unreachable!("Internal error: only catalog items need to update item refs. {stmt:?}")
69        }
70    }
71}
72
73struct CreateSqlRewriteSchema<'a> {
74    database: &'a str,
75    cur_schema: &'a str,
76    new_schema: &'a str,
77    error: Option<(String, String)>,
78}
79
80impl<'a> CreateSqlRewriteSchema<'a> {
81    fn maybe_rewrite_idents(&mut self, name: &mut [Ident]) {
82        match name {
83            [schema, item] if schema.as_str() == self.cur_schema => {
84                // TODO(parkmycar): I _think_ when the database component is not specified we can
85                // always infer we're using the current database. But I'm not positive, so for now
86                // we'll bail in this case.
87                if self.error.is_none() {
88                    self.error = Some((schema.to_string(), item.to_string()));
89                }
90            }
91            [database, schema, _item] => {
92                if database.as_str() == self.database && schema.as_str() == self.cur_schema {
93                    *schema = Ident::new_unchecked(self.new_schema);
94                }
95            }
96            _ => (),
97        }
98    }
99}
100
101impl<'a, 'ast> VisitMut<'ast, Raw> for CreateSqlRewriteSchema<'a> {
102    fn visit_expr_mut(&mut self, e: &'ast mut Expr<Raw>) {
103        match e {
104            Expr::Identifier(id) => {
105                // The last ID component is a column name that should not be
106                // considered in the rewrite.
107                let i = id.len() - 1;
108                self.maybe_rewrite_idents(&mut id[..i]);
109            }
110            Expr::QualifiedWildcard(id) => {
111                self.maybe_rewrite_idents(id);
112            }
113            _ => visit_mut::visit_expr_mut(self, e),
114        }
115    }
116
117    fn visit_unresolved_item_name_mut(
118        &mut self,
119        unresolved_item_name: &'ast mut UnresolvedItemName,
120    ) {
121        self.maybe_rewrite_idents(&mut unresolved_item_name.0);
122    }
123
124    fn visit_data_type_mut(&mut self, data_type: &'ast mut RawDataType) {
125        // The generated `visit_data_type_mut` is a no-op because `DataType` is an
126        // associated type the generic visitor treats opaquely, so we must descend
127        // by hand. A type is referenced by a schema-qualified name precisely in
128        // these data type positions (a cast, a column type, or a nested element
129        // type), so without this a schema rename leaves stale references in any
130        // dependent that uses one of the schema's types.
131        match data_type {
132            RawDataType::Array(element_type) | RawDataType::List(element_type) => {
133                self.visit_data_type_mut(element_type)
134            }
135            RawDataType::Map {
136                key_type,
137                value_type,
138            } => {
139                self.visit_data_type_mut(key_type);
140                self.visit_data_type_mut(value_type);
141            }
142            RawDataType::Other { name, .. } => self.visit_item_name_mut(name),
143        }
144    }
145
146    fn visit_item_name_mut(
147        &mut self,
148        item_name: &'ast mut <mz_sql_parser::ast::Raw as AstInfo>::ItemName,
149    ) {
150        match item_name {
151            RawItemName::Name(n) | RawItemName::Id(_, n, _) => self.maybe_rewrite_idents(&mut n.0),
152        }
153    }
154}
155
156/// Changes the `name` used in an item's `CREATE` statement. To complete a
157/// rename operation, you must also call `create_stmt_rename_refs` on all dependent
158/// items.
159pub fn create_stmt_rename(create_stmt: &mut Statement<Raw>, to_item_name: String) {
160    // TODO(sploiselle): Support renaming schemas and databases.
161    match create_stmt {
162        Statement::CreateIndex(CreateIndexStatement { name, .. }) => {
163            *name = Some(Ident::new_unchecked(to_item_name));
164        }
165        Statement::CreateSink(CreateSinkStatement {
166            name: Some(name), ..
167        })
168        | Statement::CreateSource(CreateSourceStatement { name, .. })
169        | Statement::CreateSubsource(CreateSubsourceStatement { name, .. })
170        | Statement::CreateView(CreateViewStatement {
171            definition: ViewDefinition { name, .. },
172            ..
173        })
174        | Statement::CreateMaterializedView(CreateMaterializedViewStatement { name, .. })
175        | Statement::CreateTable(CreateTableStatement { name, .. })
176        | Statement::CreateTableFromSource(CreateTableFromSourceStatement { name, .. })
177        | Statement::CreateSecret(CreateSecretStatement { name, .. })
178        | Statement::CreateConnection(CreateConnectionStatement { name, .. })
179        | Statement::CreateWebhookSource(CreateWebhookSourceStatement { name, .. }) => {
180            // The last name in an ItemName is the item name. The item name
181            // does not have a fixed index.
182            // TODO: https://github.com/MaterializeInc/database-issues/issues/1721
183            let item_name_len = name.0.len() - 1;
184            name.0[item_name_len] = Ident::new_unchecked(to_item_name);
185        }
186        item => unreachable!("Internal error: only catalog items can be renamed {item:?}"),
187    }
188}
189
190/// Updates all references of `from_name` in `create_stmt` to `to_name` or
191/// errors if request is ambiguous.
192///
193/// Requests are considered ambiguous if `create_stmt` is a
194/// `Statement::CreateView`, and any of the following apply to its `query`:
195/// - `to_name.item` is used as an [`Ident`] in `query`.
196/// - `from_name.item` does not unambiguously refer to an item in the query,
197///   e.g. it is also used as a schema, or not all references to the item are
198///   sufficiently qualified.
199/// - `to_name.item` does not unambiguously refer to an item in the query after
200///   the rename. Right now, given the first condition, this is just a coherence
201///   check, but will be more meaningful once the first restriction is lifted.
202pub fn create_stmt_rename_refs(
203    create_stmt: &mut Statement<Raw>,
204    from_name: FullItemName,
205    to_item_name: String,
206) -> Result<(), String> {
207    let from_item = UnresolvedItemName::from(from_name.clone());
208    let maybe_update_item_name = |item_name: &mut UnresolvedItemName| {
209        if item_name.0 == from_item.0 {
210            // The last name in an ItemName is the item name. The item name
211            // does not have a fixed index.
212            // TODO: https://github.com/MaterializeInc/database-issues/issues/1721
213            let item_name_len = item_name.0.len() - 1;
214            item_name.0[item_name_len] = Ident::new_unchecked(to_item_name.clone());
215        }
216    };
217
218    // TODO(sploiselle): Support renaming schemas and databases.
219    match create_stmt {
220        Statement::CreateIndex(CreateIndexStatement { on_name, .. }) => {
221            maybe_update_item_name(on_name.name_mut());
222        }
223        Statement::CreateSink(CreateSinkStatement { from, .. }) => {
224            maybe_update_item_name(from.name_mut());
225        }
226        Statement::CreateMetricSink(CreateMetricSinkStatement { from, .. }) => {
227            maybe_update_item_name(from.name_mut());
228        }
229        Statement::CreateTableFromSource(CreateTableFromSourceStatement { source, .. }) => {
230            maybe_update_item_name(source.name_mut());
231        }
232        Statement::CreateView(CreateViewStatement {
233            definition: ViewDefinition { query, .. },
234            ..
235        }) => {
236            rewrite_query(from_name, to_item_name, query)?;
237        }
238        Statement::CreateMaterializedView(CreateMaterializedViewStatement {
239            replacement_for,
240            query,
241            ..
242        }) => {
243            match replacement_for {
244                // The planner rejects replacement queries that depend on their
245                // target. Only the FOR clause refers to the renamed item.
246                Some(target) if target.name() == &from_item => {
247                    maybe_update_item_name(target.name_mut());
248                }
249                _ => rewrite_query(from_name, to_item_name, query)?,
250            }
251        }
252        Statement::CreateSource(_)
253        | Statement::CreateSubsource(_)
254        | Statement::CreateTable(_)
255        | Statement::CreateSecret(_)
256        | Statement::CreateConnection(_)
257        | Statement::CreateWebhookSource(_) => {}
258        item => {
259            unreachable!("Internal error: only catalog items need to update item refs {item:?}")
260        }
261    }
262
263    Ok(())
264}
265
266/// Rewrites `query`'s references of `from` to `to` or errors if too ambiguous.
267fn rewrite_query(from: FullItemName, to: String, query: &mut Query<Raw>) -> Result<(), String> {
268    let from_ident = Ident::new_unchecked(from.item.clone());
269    let to_ident = Ident::new_unchecked(to);
270    let qual_depth =
271        QueryIdentAgg::determine_qual_depth(&from_ident, Some(to_ident.clone()), query)?;
272    CreateSqlRewriter::rewrite_query_with_qual_depth(from, to_ident.clone(), qual_depth, query);
273    // Ensure that our rewrite didn't didn't introduce ambiguous
274    // references to `to_name`.
275    match QueryIdentAgg::determine_qual_depth(&to_ident, None, query) {
276        Ok(_) => Ok(()),
277        Err(e) => Err(e),
278    }
279}
280
281fn ambiguous_err(n: &Ident, t: &str) -> String {
282    format!(
283        "{} potentially used ambiguously as item and {}",
284        n.as_str().quoted(),
285        t
286    )
287}
288
289/// Visits a [`Query`], assessing catalog item [`Ident`]s' use of a specified `Ident`.
290struct QueryIdentAgg<'a> {
291    /// The name whose usage you want to assess.
292    name: &'a Ident,
293    /// Tracks all second-level qualifiers used on `name` in a `BTreeMap`, as
294    /// well as any third-level qualifiers used on those second-level qualifiers
295    /// in a `BTreeSet`.
296    qualifiers: BTreeMap<Ident, BTreeSet<Ident>>,
297    /// Tracks the least qualified instance of `name` seen.
298    min_qual_depth: usize,
299    /// Provides an option to fail the visit if encounters a specified `Ident`.
300    fail_on: Option<Ident>,
301    err: Option<String>,
302}
303
304impl<'a> QueryIdentAgg<'a> {
305    /// Determines the depth of qualification needed to unambiguously reference
306    /// catalog items in a [`Query`].
307    ///
308    /// Includes an option to fail if a given `Ident` is encountered.
309    ///
310    /// `Result`s of `Ok(usize)` indicate that `name` can be unambiguously
311    /// referred to with `usize` parts, e.g. 2 requires schema and item name
312    /// qualification.
313    ///
314    /// `Result`s of `Err` indicate that we cannot unambiguously reference
315    /// `name` or encountered `fail_on`, if it's provided.
316    fn determine_qual_depth(
317        name: &Ident,
318        fail_on: Option<Ident>,
319        query: &Query<Raw>,
320    ) -> Result<usize, String> {
321        let mut v = QueryIdentAgg {
322            qualifiers: BTreeMap::new(),
323            min_qual_depth: usize::MAX,
324            err: None,
325            name,
326            fail_on,
327        };
328
329        // Aggregate identities in `v`.
330        v.visit_query(query);
331        // Not possible to have a qualification depth of 0;
332        assert!(v.min_qual_depth > 0);
333
334        if let Some(e) = v.err {
335            return Err(e);
336        }
337
338        // Check if there was more than one 3rd-level (e.g.
339        // database) qualification used for any reference to `name`.
340        let req_depth = if v.qualifiers.values().any(|v| v.len() > 1) {
341            3
342        // Check if there was more than one 2nd-level (e.g. schema)
343        // qualification used for any reference to `name`.
344        } else if v.qualifiers.len() > 1 {
345            2
346        } else {
347            1
348        };
349
350        if v.min_qual_depth < req_depth {
351            Err(format!(
352                "{} is not sufficiently qualified to support renaming",
353                name.as_str().quoted()
354            ))
355        } else {
356            Ok(req_depth)
357        }
358    }
359
360    // Assesses `v` for uses of `self.name` and `self.fail_on`.
361    fn check_failure(&mut self, v: &[Ident]) {
362        // Fail if we encounter `self.fail_on`.
363        if let Some(f) = &self.fail_on {
364            if v.iter().any(|i| i == f) {
365                self.err = Some(format!(
366                    "found reference to {}; cannot rename {} to any identity \
367                    used in any existing view definitions",
368                    f.as_str().quoted(),
369                    self.name.as_str().quoted()
370                ));
371            }
372        }
373    }
374}
375
376impl<'a, 'ast> Visit<'ast, Raw> for QueryIdentAgg<'a> {
377    fn visit_expr(&mut self, e: &'ast Expr<Raw>) {
378        match e {
379            Expr::Identifier(i) => {
380                self.check_failure(i);
381                if let Some(p) = i.iter().rposition(|e| e == self.name) {
382                    if p == i.len() - 1 {
383                        // `self.name` used as a column if it's in the final
384                        // position here, e.g. `SELECT view.col FROM ...`
385                        self.err = Some(ambiguous_err(self.name, "column"));
386                        return;
387                    }
388                    self.min_qual_depth = std::cmp::min(p + 1, self.min_qual_depth);
389                }
390            }
391            Expr::QualifiedWildcard(i) => {
392                self.check_failure(i);
393                if let Some(p) = i.iter().rposition(|e| e == self.name) {
394                    self.min_qual_depth = std::cmp::min(p + 1, self.min_qual_depth);
395                }
396            }
397            _ => visit::visit_expr(self, e),
398        }
399    }
400
401    fn visit_ident(&mut self, ident: &'ast Ident) {
402        self.check_failure(std::slice::from_ref(ident));
403        // This is an unqualified item using `self.name`, e.g. an alias, which
404        // we cannot unambiguously resolve.
405        if ident == self.name {
406            self.err = Some(ambiguous_err(self.name, "alias or column"));
407        }
408    }
409
410    fn visit_unresolved_item_name(&mut self, unresolved_item_name: &'ast UnresolvedItemName) {
411        let names = &unresolved_item_name.0;
412        self.check_failure(names);
413        // Every item is used as an `ItemName` at least once, which
414        // lets use track all items named `self.name`.
415        if let Some(p) = names.iter().rposition(|e| e == self.name) {
416            // Name used as last element of `<db>.<schema>.<item>`
417            if p == names.len() - 1 && names.len() == 3 {
418                self.qualifiers
419                    .entry(names[1].clone())
420                    .or_default()
421                    .insert(names[0].clone());
422                self.min_qual_depth = std::cmp::min(3, self.min_qual_depth);
423            } else {
424                // Any other use is a database or schema
425                self.err = Some(ambiguous_err(self.name, "database, schema, or function"))
426            }
427        }
428    }
429
430    fn visit_item_name(&mut self, item_name: &'ast <Raw as AstInfo>::ItemName) {
431        match item_name {
432            RawItemName::Name(n) | RawItemName::Id(_, n, _) => self.visit_unresolved_item_name(n),
433        }
434    }
435}
436
437struct CreateSqlRewriter {
438    from: Vec<Ident>,
439    to: Ident,
440}
441
442impl CreateSqlRewriter {
443    fn rewrite_query_with_qual_depth(
444        from_name: FullItemName,
445        to_name: Ident,
446        qual_depth: usize,
447        query: &mut Query<Raw>,
448    ) {
449        let from = match qual_depth {
450            1 => vec![Ident::new_unchecked(from_name.item)],
451            2 => vec![
452                Ident::new_unchecked(from_name.schema),
453                Ident::new_unchecked(from_name.item),
454            ],
455            3 => vec![
456                Ident::new_unchecked(from_name.database.to_string()),
457                Ident::new_unchecked(from_name.schema),
458                Ident::new_unchecked(from_name.item),
459            ],
460            _ => unreachable!(),
461        };
462        let mut v = CreateSqlRewriter { from, to: to_name };
463        v.visit_query_mut(query);
464    }
465
466    fn maybe_rewrite_idents(&self, name: &mut [Ident]) {
467        if name.len() > 0 && name.ends_with(&self.from) {
468            name[name.len() - 1] = self.to.clone();
469        }
470    }
471}
472
473impl<'ast> VisitMut<'ast, Raw> for CreateSqlRewriter {
474    fn visit_expr_mut(&mut self, e: &'ast mut Expr<Raw>) {
475        match e {
476            Expr::Identifier(id) => {
477                // The last ID component is a column name that should not be
478                // considered in the rewrite.
479                let i = id.len() - 1;
480                self.maybe_rewrite_idents(&mut id[..i]);
481            }
482            Expr::QualifiedWildcard(id) => {
483                self.maybe_rewrite_idents(id);
484            }
485            _ => visit_mut::visit_expr_mut(self, e),
486        }
487    }
488    fn visit_unresolved_item_name_mut(
489        &mut self,
490        unresolved_item_name: &'ast mut UnresolvedItemName,
491    ) {
492        self.maybe_rewrite_idents(&mut unresolved_item_name.0);
493    }
494    fn visit_item_name_mut(
495        &mut self,
496        item_name: &'ast mut <mz_sql_parser::ast::Raw as AstInfo>::ItemName,
497    ) {
498        match item_name {
499            RawItemName::Name(n) | RawItemName::Id(_, n, _) => self.maybe_rewrite_idents(&mut n.0),
500        }
501    }
502}
503
504/// Updates all `CatalogItemId`s from the keys of `ids` to the values of `ids` within `create_stmt`.
505pub fn create_stmt_replace_ids(
506    create_stmt: &mut Statement<Raw>,
507    ids: &BTreeMap<CatalogItemId, CatalogItemId>,
508) {
509    let mut id_replacer = CreateSqlIdReplacer { ids };
510    id_replacer.visit_statement_mut(create_stmt);
511}
512
513struct CreateSqlIdReplacer<'a> {
514    ids: &'a BTreeMap<CatalogItemId, CatalogItemId>,
515}
516
517impl<'ast> VisitMut<'ast, Raw> for CreateSqlIdReplacer<'_> {
518    fn visit_item_name_mut(
519        &mut self,
520        item_name: &'ast mut <mz_sql_parser::ast::Raw as AstInfo>::ItemName,
521    ) {
522        match item_name {
523            RawItemName::Id(id, _, _) => {
524                let old_id = match id.parse() {
525                    Ok(old_id) => old_id,
526                    Err(e) => panic!("invalid persisted global id {id}: {e}"),
527                };
528                if let Some(new_id) = self.ids.get(&old_id) {
529                    *id = new_id.to_string();
530                }
531            }
532            RawItemName::Name(_) => {}
533        }
534    }
535}