Skip to main content

mz_sql/
names.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//! Structured name types for SQL objects.
11
12use std::borrow::Cow;
13use std::collections::{BTreeMap, BTreeSet};
14use std::fmt;
15use std::str::FromStr;
16use std::sync::LazyLock;
17
18use anyhow::anyhow;
19use mz_controller_types::{ClusterId, ReplicaId};
20use mz_expr::LocalId;
21use mz_ore::str::StrExt;
22use mz_repr::network_policy_id::NetworkPolicyId;
23use mz_repr::query_policy_id::QueryPolicyId;
24use mz_repr::role_id::RoleId;
25use mz_repr::{CatalogItemId, GlobalId};
26use mz_repr::{ColumnName, RelationVersionSelector};
27use mz_sql_parser::ast::visit_mut::VisitMutNode;
28use mz_sql_parser::ast::{Expr, RawNetworkPolicyName, Version};
29use mz_sql_parser::ident;
30use proptest_derive::Arbitrary;
31use serde::{Deserialize, Serialize};
32use uncased::UncasedStr;
33
34use crate::ast::display::{AstDisplay, AstFormatter};
35use crate::ast::fold::{Fold, FoldNode};
36use crate::ast::visit::{Visit, VisitNode};
37use crate::ast::visit_mut::VisitMut;
38use crate::ast::{
39    self, AstInfo, Cte, CteBlock, CteMutRec, DocOnIdentifier, GrantTargetSpecification,
40    GrantTargetSpecificationInner, Ident, MutRecBlock, ObjectType, Query, Raw, RawClusterName,
41    RawDataType, RawItemName, Statement, UnresolvedItemName, UnresolvedObjectName,
42};
43use crate::catalog::{
44    CatalogError, CatalogItem, CatalogItemType, CatalogTypeDetails, SessionCatalog,
45};
46use crate::normalize;
47use crate::plan::PlanError;
48
49/// A fully-qualified human readable name of an item in the catalog.
50///
51/// Catalog names compare case sensitively. Use
52/// [`normalize::unresolved_item_name`] to
53/// perform proper case folding if converting an [`UnresolvedItemName`] to a
54/// `FullItemName`.
55///
56/// [`normalize::unresolved_item_name`]: crate::normalize::unresolved_item_name
57#[derive(
58    Debug,
59    Clone,
60    Eq,
61    PartialEq,
62    Hash,
63    Ord,
64    PartialOrd,
65    Serialize,
66    Deserialize
67)]
68pub struct FullItemName {
69    /// The database name.
70    pub database: RawDatabaseSpecifier,
71    /// The schema name.
72    pub schema: String,
73    /// The item name.
74    pub item: String,
75}
76
77impl FullItemName {
78    /// Converts the name into a string vector of its constituent parts:
79    /// database (if present), schema, and item.
80    pub fn into_parts(self) -> Vec<String> {
81        let mut parts = vec![];
82        if let RawDatabaseSpecifier::Name(name) = self.database {
83            parts.push(name);
84        }
85        parts.push(self.schema);
86        parts.push(self.item);
87        parts
88    }
89}
90
91impl fmt::Display for FullItemName {
92    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93        if let RawDatabaseSpecifier::Name(database) = &self.database {
94            write!(f, "{}.", database)?;
95        }
96        write!(f, "{}.{}", self.schema, self.item)
97    }
98}
99
100impl From<FullItemName> for UnresolvedItemName {
101    fn from(full_name: FullItemName) -> UnresolvedItemName {
102        // TODO(parkmycar): Change UnresolvedItemName to use `Ident` internally.
103        let mut name_parts = Vec::new();
104        if let RawDatabaseSpecifier::Name(database) = full_name.database {
105            name_parts.push(Ident::new_unchecked(database));
106        }
107        name_parts.push(Ident::new_unchecked(full_name.schema));
108        name_parts.push(Ident::new_unchecked(full_name.item));
109        UnresolvedItemName(name_parts)
110    }
111}
112
113/// A fully-qualified non-human readable name of an item in the catalog using IDs for the database
114/// and schema.
115#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
116pub struct QualifiedItemName {
117    pub qualifiers: ItemQualifiers,
118    pub item: String,
119}
120
121// Do not implement [`Display`] for [`QualifiedItemName`]. [`FullItemName`] should always be
122// displayed instead.
123static_assertions::assert_not_impl_any!(QualifiedItemName: fmt::Display);
124
125/// An optionally-qualified human-readable name of an item in the catalog.
126///
127/// This is like a [`FullItemName`], but either the database or schema name may be
128/// omitted.
129#[derive(
130    Clone,
131    Debug,
132    Serialize,
133    Deserialize,
134    PartialEq,
135    Eq,
136    PartialOrd,
137    Ord,
138    Hash
139)]
140pub struct PartialItemName {
141    pub database: Option<String>,
142    pub schema: Option<String>,
143    pub item: String,
144}
145
146impl PartialItemName {
147    // Whether either self or other might be a (possibly differently qualified)
148    // version of the other.
149    pub fn matches(&self, other: &Self) -> bool {
150        match (&self.database, &other.database) {
151            (Some(d1), Some(d2)) if d1 != d2 => return false,
152            _ => (),
153        }
154        match (&self.schema, &other.schema) {
155            (Some(s1), Some(s2)) if s1 != s2 => return false,
156            _ => (),
157        }
158        self.item == other.item
159    }
160}
161
162impl fmt::Display for PartialItemName {
163    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164        if let Some(database) = &self.database {
165            write!(f, "{}.", database)?;
166        }
167        if let Some(schema) = &self.schema {
168            write!(f, "{}.", schema)?;
169        }
170        write!(f, "{}", self.item)
171    }
172}
173
174impl From<FullItemName> for PartialItemName {
175    fn from(n: FullItemName) -> PartialItemName {
176        let database = match n.database {
177            RawDatabaseSpecifier::Ambient => None,
178            RawDatabaseSpecifier::Name(name) => Some(name),
179        };
180        PartialItemName {
181            database,
182            schema: Some(n.schema),
183            item: n.item,
184        }
185    }
186}
187
188impl From<String> for PartialItemName {
189    fn from(item: String) -> Self {
190        PartialItemName {
191            database: None,
192            schema: None,
193            item,
194        }
195    }
196}
197
198impl From<PartialItemName> for UnresolvedItemName {
199    fn from(partial_name: PartialItemName) -> UnresolvedItemName {
200        // TODO(parkmycar): Change UnresolvedItemName to use `Ident` internally.
201        let mut name_parts = Vec::new();
202        if let Some(database) = partial_name.database {
203            name_parts.push(Ident::new_unchecked(database));
204        }
205        if let Some(schema) = partial_name.schema {
206            name_parts.push(Ident::new_unchecked(schema));
207        }
208        name_parts.push(Ident::new_unchecked(partial_name.item));
209        UnresolvedItemName(name_parts)
210    }
211}
212
213/// A fully-qualified human readable name of a schema in the catalog.
214#[derive(
215    Debug,
216    Clone,
217    Eq,
218    PartialEq,
219    Hash,
220    PartialOrd,
221    Ord,
222    Serialize,
223    Deserialize
224)]
225pub struct FullSchemaName {
226    /// The database name
227    pub database: RawDatabaseSpecifier,
228    /// The schema name
229    pub schema: String,
230}
231
232impl fmt::Display for FullSchemaName {
233    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
234        if let RawDatabaseSpecifier::Name(database) = &self.database {
235            write!(f, "{}.", database)?;
236        }
237        write!(f, "{}", self.schema)
238    }
239}
240
241/// The fully-qualified non-human readable name of a schema in the catalog.
242#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
243pub struct QualifiedSchemaName {
244    pub database: ResolvedDatabaseSpecifier,
245    pub schema: String,
246}
247
248impl fmt::Display for QualifiedSchemaName {
249    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
250        match &self.database {
251            ResolvedDatabaseSpecifier::Ambient => f.write_str(&self.schema),
252            ResolvedDatabaseSpecifier::Id(id) => write!(f, "{}.{}", id, self.schema),
253        }
254    }
255}
256
257/// An optionally-qualified name of an schema in the catalog.
258///
259/// This is like a [`FullSchemaName`], but either the database or schema name may be
260/// omitted.
261#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
262pub struct PartialSchemaName {
263    pub database: Option<String>,
264    pub schema: String,
265}
266
267impl fmt::Display for PartialSchemaName {
268    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
269        if let Some(database) = &self.database {
270            write!(f, "{}.", database)?;
271        }
272        write!(f, "{}", self.schema)
273    }
274}
275
276/// A human readable name of a database.
277#[derive(
278    Debug,
279    Clone,
280    Eq,
281    PartialEq,
282    Ord,
283    PartialOrd,
284    Hash,
285    Serialize,
286    Deserialize
287)]
288pub enum RawDatabaseSpecifier {
289    /// The "ambient" database, which is always present and is not named
290    /// explicitly, but by omission.
291    Ambient,
292    /// A normal database with a name.
293    Name(String),
294}
295
296impl fmt::Display for RawDatabaseSpecifier {
297    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
298        match self {
299            Self::Ambient => f.write_str("<none>"),
300            Self::Name(name) => f.write_str(name),
301        }
302    }
303}
304
305impl From<Option<String>> for RawDatabaseSpecifier {
306    fn from(s: Option<String>) -> RawDatabaseSpecifier {
307        match s {
308            None => Self::Ambient,
309            Some(name) => Self::Name(name),
310        }
311    }
312}
313
314/// An id of a database.
315#[derive(
316    Debug,
317    Clone,
318    Copy,
319    Eq,
320    PartialEq,
321    Hash,
322    PartialOrd,
323    Ord,
324    Serialize,
325    Deserialize,
326    Arbitrary
327)]
328pub enum ResolvedDatabaseSpecifier {
329    /// The "ambient" database, which is always present and is not named
330    /// explicitly, but by omission.
331    Ambient,
332    /// A normal database with a name.
333    Id(DatabaseId),
334}
335
336impl ResolvedDatabaseSpecifier {
337    pub fn id(&self) -> Option<DatabaseId> {
338        match self {
339            ResolvedDatabaseSpecifier::Ambient => None,
340            ResolvedDatabaseSpecifier::Id(id) => Some(*id),
341        }
342    }
343}
344
345impl fmt::Display for ResolvedDatabaseSpecifier {
346    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
347        match self {
348            Self::Ambient => f.write_str("<none>"),
349            Self::Id(id) => write!(f, "{}", id),
350        }
351    }
352}
353
354impl AstDisplay for ResolvedDatabaseSpecifier {
355    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
356        f.write_str(format!("{}", self));
357    }
358}
359
360impl From<DatabaseId> for ResolvedDatabaseSpecifier {
361    fn from(id: DatabaseId) -> Self {
362        Self::Id(id)
363    }
364}
365
366impl From<Option<DatabaseId>> for ResolvedDatabaseSpecifier {
367    fn from(id: Option<DatabaseId>) -> Self {
368        match id {
369            Some(id) => Self::Id(id),
370            None => Self::Ambient,
371        }
372    }
373}
374
375/*
376 * TODO(jkosh44) It's possible that in order to fix
377 * https://github.com/MaterializeInc/database-issues/issues/2689 we will need to assign temporary
378 * schemas unique Ids. If/when that happens we can remove this enum and refer to all schemas by
379 * their Id.
380 */
381/// An id of a schema.
382#[derive(
383    Debug,
384    Clone,
385    Copy,
386    Eq,
387    PartialEq,
388    Hash,
389    PartialOrd,
390    Ord,
391    Serialize,
392    Deserialize
393)]
394pub enum SchemaSpecifier {
395    /// A temporary schema
396    Temporary,
397    /// A normal database with a name.
398    Id(SchemaId),
399}
400
401impl SchemaSpecifier {
402    const TEMPORARY_SCHEMA_ID: u64 = 0;
403
404    pub fn is_system(&self) -> bool {
405        match self {
406            SchemaSpecifier::Temporary => false,
407            SchemaSpecifier::Id(id) => id.is_system(),
408        }
409    }
410
411    pub fn is_user(&self) -> bool {
412        match self {
413            SchemaSpecifier::Temporary => true,
414            SchemaSpecifier::Id(id) => id.is_user(),
415        }
416    }
417
418    pub fn is_temporary(&self) -> bool {
419        matches!(self, SchemaSpecifier::Temporary)
420    }
421}
422
423impl fmt::Display for SchemaSpecifier {
424    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
425        match self {
426            Self::Temporary => f.write_str(format!("{}", Self::TEMPORARY_SCHEMA_ID).as_str()),
427            Self::Id(id) => write!(f, "{}", id),
428        }
429    }
430}
431
432impl AstDisplay for SchemaSpecifier {
433    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
434        f.write_str(format!("{}", self));
435    }
436}
437
438impl From<SchemaId> for SchemaSpecifier {
439    fn from(id: SchemaId) -> SchemaSpecifier {
440        match id {
441            SchemaId::User(id) if id == SchemaSpecifier::TEMPORARY_SCHEMA_ID => {
442                SchemaSpecifier::Temporary
443            }
444            schema_id => SchemaSpecifier::Id(schema_id),
445        }
446    }
447}
448
449impl From<&SchemaSpecifier> for SchemaId {
450    fn from(schema_spec: &SchemaSpecifier) -> Self {
451        match schema_spec {
452            SchemaSpecifier::Temporary => SchemaId::User(SchemaSpecifier::TEMPORARY_SCHEMA_ID),
453            SchemaSpecifier::Id(id) => id.clone(),
454        }
455    }
456}
457
458impl From<SchemaSpecifier> for SchemaId {
459    fn from(schema_spec: SchemaSpecifier) -> Self {
460        match schema_spec {
461            SchemaSpecifier::Temporary => SchemaId::User(SchemaSpecifier::TEMPORARY_SCHEMA_ID),
462            SchemaSpecifier::Id(id) => id,
463        }
464    }
465}
466
467// Aug is the type variable assigned to an AST that has already been
468// name-resolved. An AST in this state has global IDs populated next to table
469// names, and local IDs assigned to CTE definitions and references.
470#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone, Default)]
471pub struct Aug;
472
473#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize)]
474pub struct ItemQualifiers {
475    pub database_spec: ResolvedDatabaseSpecifier,
476    pub schema_spec: SchemaSpecifier,
477}
478
479#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
480pub enum ResolvedItemName {
481    Item {
482        id: CatalogItemId,
483        qualifiers: ItemQualifiers,
484        full_name: FullItemName,
485        // Whether this object, when printed out, should use [id AS name] syntax. We
486        // want this for things like tables and sources, but not for things like
487        // types.
488        print_id: bool,
489        version: RelationVersionSelector,
490    },
491    Cte {
492        id: LocalId,
493        name: String,
494    },
495    Error,
496}
497
498impl ResolvedItemName {
499    pub fn full_name_str(&self) -> String {
500        match self {
501            ResolvedItemName::Item { full_name, .. } => full_name.to_string(),
502            ResolvedItemName::Cte { name, .. } => name.clone(),
503            ResolvedItemName::Error => "error in name resolution".to_string(),
504        }
505    }
506
507    pub fn full_item_name(&self) -> &FullItemName {
508        match self {
509            ResolvedItemName::Item { full_name, .. } => full_name,
510            _ => panic!("cannot call object_full_name on non-object"),
511        }
512    }
513
514    pub fn item_id(&self) -> &CatalogItemId {
515        match self {
516            ResolvedItemName::Item { id, .. } => id,
517            _ => panic!("cannot call item_id on non-object"),
518        }
519    }
520
521    pub fn version(&self) -> &RelationVersionSelector {
522        match self {
523            ResolvedItemName::Item { version, .. } => version,
524            _ => panic!("cannot call version on non-object"),
525        }
526    }
527}
528
529impl AstDisplay for ResolvedItemName {
530    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
531        match self {
532            ResolvedItemName::Item {
533                id,
534                qualifiers: _,
535                full_name,
536                print_id,
537                version,
538            } => {
539                if *print_id {
540                    f.write_str(format!("[{} AS ", id));
541                }
542                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
543                    f.write_node(&Ident::new_unchecked(database));
544                    f.write_str(".");
545                }
546                f.write_node(&Ident::new_unchecked(&full_name.schema));
547                f.write_str(".");
548                f.write_node(&Ident::new_unchecked(&full_name.item));
549
550                if *print_id {
551                    if let RelationVersionSelector::Specific(version) = version {
552                        let version = normalize::ast_version(*version);
553                        f.write_str(" VERSION ");
554                        f.write_node(&version);
555                    }
556                }
557
558                if *print_id {
559                    f.write_str("]");
560                }
561            }
562            ResolvedItemName::Cte { name, .. } => f.write_node(&Ident::new_unchecked(name)),
563            ResolvedItemName::Error => {}
564        }
565    }
566}
567
568impl std::fmt::Display for ResolvedItemName {
569    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
570        f.write_str(self.to_ast_string_simple().as_str())
571    }
572}
573
574#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
575pub enum ResolvedColumnReference {
576    Column { name: ColumnName, index: usize },
577    Error,
578}
579
580impl AstDisplay for ResolvedColumnReference {
581    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
582        match self {
583            ResolvedColumnReference::Column { name, .. } => {
584                f.write_node(&Ident::new_unchecked(name.as_str()));
585            }
586            ResolvedColumnReference::Error => {}
587        }
588    }
589}
590
591impl std::fmt::Display for ResolvedColumnReference {
592    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
593        f.write_str(self.to_ast_string_simple().as_str())
594    }
595}
596
597#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
598pub enum ResolvedSchemaName {
599    Schema {
600        database_spec: ResolvedDatabaseSpecifier,
601        schema_spec: SchemaSpecifier,
602        full_name: FullSchemaName,
603    },
604    Error,
605}
606
607impl ResolvedSchemaName {
608    /// Panics if this is `Self::Error`.
609    pub fn database_spec(&self) -> &ResolvedDatabaseSpecifier {
610        match self {
611            ResolvedSchemaName::Schema { database_spec, .. } => database_spec,
612            ResolvedSchemaName::Error => {
613                unreachable!("should have been handled by name resolution")
614            }
615        }
616    }
617
618    /// Panics if this is `Self::Error`.
619    pub fn schema_spec(&self) -> &SchemaSpecifier {
620        match self {
621            ResolvedSchemaName::Schema { schema_spec, .. } => schema_spec,
622            ResolvedSchemaName::Error => {
623                unreachable!("should have been handled by name resolution")
624            }
625        }
626    }
627}
628
629impl AstDisplay for ResolvedSchemaName {
630    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
631        match self {
632            ResolvedSchemaName::Schema { full_name, .. } => {
633                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
634                    f.write_node(&Ident::new_unchecked(database));
635                    f.write_str(".");
636                }
637                f.write_node(&Ident::new_unchecked(&full_name.schema));
638            }
639            ResolvedSchemaName::Error => {}
640        }
641    }
642}
643
644#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
645pub enum ResolvedDatabaseName {
646    Database { id: DatabaseId, name: String },
647    Error,
648}
649
650impl ResolvedDatabaseName {
651    /// Panics if this is `Self::Error`.
652    pub fn database_id(&self) -> &DatabaseId {
653        match self {
654            ResolvedDatabaseName::Database { id, .. } => id,
655            ResolvedDatabaseName::Error => {
656                unreachable!("should have been handled by name resolution")
657            }
658        }
659    }
660}
661
662impl AstDisplay for ResolvedDatabaseName {
663    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
664        match self {
665            ResolvedDatabaseName::Database { name, .. } => {
666                f.write_node(&Ident::new_unchecked(name))
667            }
668            ResolvedDatabaseName::Error => {}
669        }
670    }
671}
672
673#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
674pub struct ResolvedClusterName {
675    pub id: ClusterId,
676    /// If set, a name to print in the `AstDisplay` implementation instead of
677    /// `None`. This is only meant to be used by the `NameSimplifier`.
678    ///
679    /// NOTE(benesch): it would be much clearer if the `NameSimplifier` folded
680    /// the AST into a different metadata type, to avoid polluting the resolved
681    /// AST with this field.
682    pub print_name: Option<String>,
683}
684
685impl AstDisplay for ResolvedClusterName {
686    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
687        if let Some(print_name) = &self.print_name {
688            f.write_node(&Ident::new_unchecked(print_name))
689        } else {
690            f.write_str(format!("[{}]", self.id))
691        }
692    }
693}
694
695#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
696pub struct ResolvedClusterReplicaName {
697    pub cluster_id: ClusterId,
698    pub replica_id: ReplicaId,
699}
700
701impl AstDisplay for ResolvedClusterReplicaName {
702    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
703        f.write_str(format!("[{}.{}]", self.cluster_id, self.replica_id))
704    }
705}
706
707#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
708pub enum ResolvedDataType {
709    AnonymousList(Box<ResolvedDataType>),
710    AnonymousMap {
711        key_type: Box<ResolvedDataType>,
712        value_type: Box<ResolvedDataType>,
713    },
714    Named {
715        id: CatalogItemId,
716        qualifiers: ItemQualifiers,
717        full_name: FullItemName,
718        modifiers: Vec<i64>,
719        print_id: bool,
720    },
721    Error,
722}
723
724impl AstDisplay for ResolvedDataType {
725    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
726        match self {
727            ResolvedDataType::AnonymousList(element_type) => {
728                element_type.fmt(f);
729                f.write_str(" list");
730            }
731            ResolvedDataType::AnonymousMap {
732                key_type,
733                value_type,
734            } => {
735                f.write_str("map[");
736                key_type.fmt(f);
737                f.write_str("=>");
738                value_type.fmt(f);
739                f.write_str("]");
740            }
741            ResolvedDataType::Named {
742                id,
743                full_name,
744                modifiers,
745                print_id,
746                ..
747            } => {
748                if *print_id {
749                    f.write_str(format!("[{} AS ", id));
750                }
751                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
752                    f.write_node(&Ident::new_unchecked(database));
753                    f.write_str(".");
754                }
755
756                f.write_node(&Ident::new_unchecked(&full_name.schema));
757                f.write_str(".");
758
759                f.write_node(&Ident::new_unchecked(&full_name.item));
760                if *print_id {
761                    f.write_str("]");
762                }
763                if modifiers.len() > 0 {
764                    f.write_str("(");
765                    f.write_node(&ast::display::comma_separated(modifiers));
766                    f.write_str(")");
767                }
768            }
769            ResolvedDataType::Error => {}
770        }
771    }
772}
773
774impl ResolvedDataType {
775    /// Return the name of `self`'s item without qualification or IDs.
776    ///
777    /// This is used to generate default column names for cast operations.
778    pub fn unqualified_item_name(&self) -> String {
779        let mut res = String::new();
780        match self {
781            ResolvedDataType::AnonymousList(element_type) => {
782                res += &element_type.unqualified_item_name();
783                res += " list";
784            }
785            ResolvedDataType::AnonymousMap {
786                key_type,
787                value_type,
788            } => {
789                res += "map[";
790                res += &key_type.unqualified_item_name();
791                res += "=>";
792                res += &value_type.unqualified_item_name();
793                res += "]";
794            }
795            ResolvedDataType::Named { full_name, .. } => {
796                res += &full_name.item;
797            }
798            ResolvedDataType::Error => {}
799        }
800        res
801    }
802
803    /// Return the name of `self`'s without IDs or modifiers.
804    ///
805    /// This is used for error messages.
806    pub fn human_readable_name(&self) -> String {
807        let mut res = String::new();
808        match self {
809            ResolvedDataType::AnonymousList(element_type) => {
810                res += &element_type.human_readable_name();
811                res += " list";
812            }
813            ResolvedDataType::AnonymousMap {
814                key_type,
815                value_type,
816            } => {
817                res += "map[";
818                res += &key_type.human_readable_name();
819                res += "=>";
820                res += &value_type.human_readable_name();
821                res += "]";
822            }
823            ResolvedDataType::Named { full_name, .. } => {
824                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
825                    res += database;
826                    res += ".";
827                }
828                res += &full_name.schema;
829                res += ".";
830                res += &full_name.item;
831            }
832            ResolvedDataType::Error => {}
833        }
834        res
835    }
836}
837
838impl fmt::Display for ResolvedDataType {
839    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
840        f.write_str(self.to_ast_string_simple().as_str())
841    }
842}
843
844#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
845pub struct ResolvedRoleName {
846    pub id: RoleId,
847    pub name: String,
848}
849
850impl AstDisplay for ResolvedRoleName {
851    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
852        f.write_str(format!("[{} AS {}]", self.id, self.name));
853    }
854}
855
856#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
857pub struct ResolvedNetworkPolicyName {
858    pub id: NetworkPolicyId,
859    pub name: String,
860}
861
862impl AstDisplay for ResolvedNetworkPolicyName {
863    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
864        f.write_str(format!("[{} AS {}]", self.id, self.name));
865    }
866}
867
868#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
869pub struct ResolvedQueryPolicyName {
870    pub id: QueryPolicyId,
871    pub name: String,
872}
873
874impl AstDisplay for ResolvedQueryPolicyName {
875    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
876        f.write_str(format!("[{} AS {}]", self.id, self.name));
877    }
878}
879
880#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
881pub enum ResolvedObjectName {
882    Cluster(ResolvedClusterName),
883    ClusterReplica(ResolvedClusterReplicaName),
884    Database(ResolvedDatabaseName),
885    Schema(ResolvedSchemaName),
886    Role(ResolvedRoleName),
887    NetworkPolicy(ResolvedNetworkPolicyName),
888    QueryPolicy(ResolvedQueryPolicyName),
889    Item(ResolvedItemName),
890}
891
892impl AstDisplay for ResolvedObjectName {
893    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
894        match self {
895            ResolvedObjectName::Cluster(n) => f.write_node(n),
896            ResolvedObjectName::ClusterReplica(n) => f.write_node(n),
897            ResolvedObjectName::Database(n) => f.write_node(n),
898            ResolvedObjectName::Schema(n) => f.write_node(n),
899            ResolvedObjectName::Role(n) => f.write_node(n),
900            ResolvedObjectName::Item(n) => f.write_node(n),
901            ResolvedObjectName::NetworkPolicy(n) => f.write_node(n),
902            ResolvedObjectName::QueryPolicy(n) => f.write_node(n),
903        }
904    }
905}
906
907impl AstInfo for Aug {
908    type NestedStatement = Statement<Raw>;
909    type ItemName = ResolvedItemName;
910    type ColumnReference = ResolvedColumnReference;
911    type SchemaName = ResolvedSchemaName;
912    type DatabaseName = ResolvedDatabaseName;
913    type ClusterName = ResolvedClusterName;
914    type DataType = ResolvedDataType;
915    type CteId = LocalId;
916    type RoleName = ResolvedRoleName;
917    type ObjectName = ResolvedObjectName;
918    type NetworkPolicyName = ResolvedNetworkPolicyName;
919}
920
921/// The identifier for a schema.
922#[derive(
923    Clone,
924    Copy,
925    Debug,
926    Eq,
927    PartialEq,
928    Ord,
929    PartialOrd,
930    Hash,
931    Serialize,
932    Deserialize,
933    Arbitrary
934)]
935pub enum SchemaId {
936    User(u64),
937    System(u64),
938}
939
940impl SchemaId {
941    pub fn is_user(&self) -> bool {
942        matches!(self, SchemaId::User(_))
943    }
944
945    pub fn is_system(&self) -> bool {
946        matches!(self, SchemaId::System(_))
947    }
948}
949
950impl fmt::Display for SchemaId {
951    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
952        match self {
953            SchemaId::System(id) => write!(f, "s{}", id),
954            SchemaId::User(id) => write!(f, "u{}", id),
955        }
956    }
957}
958
959impl FromStr for SchemaId {
960    type Err = PlanError;
961
962    fn from_str(s: &str) -> Result<Self, Self::Err> {
963        let err = || PlanError::Unstructured(format!("couldn't parse SchemaId {}", s));
964        // Validate the (single-byte, ASCII) tag before slicing so that a
965        // multi-byte leading character doesn't slice inside a UTF-8 boundary.
966        let variant = match s.chars().next() {
967            Some('s') => SchemaId::System,
968            Some('u') => SchemaId::User,
969            _ => return Err(err()),
970        };
971        let val: u64 = s[1..].parse().map_err(|_| err())?;
972        Ok(variant(val))
973    }
974}
975
976/// The identifier for a database.
977#[derive(
978    Clone,
979    Copy,
980    Debug,
981    Eq,
982    PartialEq,
983    Ord,
984    PartialOrd,
985    Hash,
986    Serialize,
987    Deserialize,
988    Arbitrary
989)]
990pub enum DatabaseId {
991    User(u64),
992    System(u64),
993}
994
995impl DatabaseId {
996    pub fn is_user(&self) -> bool {
997        matches!(self, DatabaseId::User(_))
998    }
999
1000    pub fn is_system(&self) -> bool {
1001        matches!(self, DatabaseId::System(_))
1002    }
1003}
1004
1005impl fmt::Display for DatabaseId {
1006    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1007        match self {
1008            DatabaseId::System(id) => write!(f, "s{}", id),
1009            DatabaseId::User(id) => write!(f, "u{}", id),
1010        }
1011    }
1012}
1013
1014impl FromStr for DatabaseId {
1015    type Err = PlanError;
1016
1017    fn from_str(s: &str) -> Result<Self, Self::Err> {
1018        let err = || PlanError::Unstructured(format!("couldn't parse DatabaseId {}", s));
1019        // Validate the (single-byte, ASCII) tag before slicing so that a
1020        // multi-byte leading character doesn't slice inside a UTF-8 boundary.
1021        let variant = match s.chars().next() {
1022            Some('s') => DatabaseId::System,
1023            Some('u') => DatabaseId::User,
1024            _ => return Err(err()),
1025        };
1026        let val: u64 = s[1..].parse().map_err(|_| err())?;
1027        Ok(variant(val))
1028    }
1029}
1030
1031pub static PUBLIC_ROLE_NAME: LazyLock<&UncasedStr> = LazyLock::new(|| UncasedStr::new("PUBLIC"));
1032
1033#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
1034pub enum ObjectId {
1035    Cluster(ClusterId),
1036    ClusterReplica((ClusterId, ReplicaId)),
1037    Database(DatabaseId),
1038    Schema((ResolvedDatabaseSpecifier, SchemaSpecifier)),
1039    Role(RoleId),
1040    Item(CatalogItemId),
1041    NetworkPolicy(NetworkPolicyId),
1042    QueryPolicy(QueryPolicyId),
1043}
1044
1045impl ObjectId {
1046    pub fn unwrap_cluster_id(self) -> ClusterId {
1047        match self {
1048            ObjectId::Cluster(id) => id,
1049            _ => panic!("ObjectId::unwrap_cluster_id called on {self:?}"),
1050        }
1051    }
1052    pub fn unwrap_cluster_replica_id(self) -> (ClusterId, ReplicaId) {
1053        match self {
1054            ObjectId::ClusterReplica(id) => id,
1055            _ => panic!("ObjectId::unwrap_cluster_replica_id called on {self:?}"),
1056        }
1057    }
1058    pub fn unwrap_database_id(self) -> DatabaseId {
1059        match self {
1060            ObjectId::Database(id) => id,
1061            _ => panic!("ObjectId::unwrap_database_id called on {self:?}"),
1062        }
1063    }
1064    pub fn unwrap_schema_id(self) -> (ResolvedDatabaseSpecifier, SchemaSpecifier) {
1065        match self {
1066            ObjectId::Schema(id) => id,
1067            _ => panic!("ObjectId::unwrap_schema_id called on {self:?}"),
1068        }
1069    }
1070    pub fn unwrap_role_id(self) -> RoleId {
1071        match self {
1072            ObjectId::Role(id) => id,
1073            _ => panic!("ObjectId::unwrap_role_id called on {self:?}"),
1074        }
1075    }
1076    pub fn unwrap_item_id(self) -> CatalogItemId {
1077        match self {
1078            ObjectId::Item(id) => id,
1079            _ => panic!("ObjectId::unwrap_item_id called on {self:?}"),
1080        }
1081    }
1082
1083    pub fn is_system(&self) -> bool {
1084        match self {
1085            ObjectId::Cluster(cluster_id) => cluster_id.is_system(),
1086            ObjectId::ClusterReplica((_cluster_id, replica_id)) => replica_id.is_system(),
1087            ObjectId::Database(database_id) => database_id.is_system(),
1088            ObjectId::Schema((_database_id, schema_id)) => schema_id.is_system(),
1089            ObjectId::Role(role_id) => role_id.is_system(),
1090            ObjectId::Item(global_id) => global_id.is_system(),
1091            ObjectId::NetworkPolicy(network_policy_id) => network_policy_id.is_system(),
1092            ObjectId::QueryPolicy(id) => id.is_system(),
1093        }
1094    }
1095
1096    pub fn is_user(&self) -> bool {
1097        match self {
1098            ObjectId::Cluster(cluster_id) => cluster_id.is_user(),
1099            ObjectId::ClusterReplica((_cluster_id, replica_id)) => replica_id.is_user(),
1100            ObjectId::Database(database_id) => database_id.is_user(),
1101            ObjectId::Schema((_database_id, schema_id)) => schema_id.is_user(),
1102            ObjectId::Role(role_id) => role_id.is_user(),
1103            ObjectId::Item(global_id) => global_id.is_user(),
1104            ObjectId::NetworkPolicy(network_policy_id) => network_policy_id.is_user(),
1105            ObjectId::QueryPolicy(id) => id.is_user(),
1106        }
1107    }
1108}
1109
1110impl fmt::Display for ObjectId {
1111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1112        match self {
1113            ObjectId::Cluster(cluster_id) => write!(f, "C{cluster_id}"),
1114            ObjectId::ClusterReplica((cluster_id, replica_id)) => {
1115                write!(f, "CR{cluster_id}.{replica_id}")
1116            }
1117            ObjectId::Database(database_id) => write!(f, "D{database_id}"),
1118            ObjectId::Schema((database_spec, schema_spec)) => {
1119                let database_id = match database_spec {
1120                    ResolvedDatabaseSpecifier::Ambient => "".to_string(),
1121                    ResolvedDatabaseSpecifier::Id(database_id) => format!("{database_id}."),
1122                };
1123                write!(f, "S{database_id}{schema_spec}")
1124            }
1125            ObjectId::Role(role_id) => write!(f, "R{role_id}"),
1126            ObjectId::Item(item_id) => write!(f, "I{item_id}"),
1127            ObjectId::NetworkPolicy(network_policy_id) => write!(f, "NP{network_policy_id}"),
1128            ObjectId::QueryPolicy(id) => write!(f, "QP{id}"),
1129        }
1130    }
1131}
1132
1133impl TryFrom<ResolvedObjectName> for ObjectId {
1134    type Error = anyhow::Error;
1135
1136    fn try_from(name: ResolvedObjectName) -> Result<ObjectId, Self::Error> {
1137        match name {
1138            ResolvedObjectName::Cluster(name) => Ok(ObjectId::Cluster(name.id)),
1139            ResolvedObjectName::ClusterReplica(name) => {
1140                Ok(ObjectId::ClusterReplica((name.cluster_id, name.replica_id)))
1141            }
1142            ResolvedObjectName::Database(name) => Ok(ObjectId::Database(*name.database_id())),
1143            ResolvedObjectName::Schema(name) => match name {
1144                ResolvedSchemaName::Schema {
1145                    database_spec,
1146                    schema_spec,
1147                    ..
1148                } => Ok(ObjectId::Schema((database_spec, schema_spec))),
1149                ResolvedSchemaName::Error => Err(anyhow!("error in name resolution")),
1150            },
1151            ResolvedObjectName::Role(name) => Ok(ObjectId::Role(name.id)),
1152            ResolvedObjectName::Item(name) => match name {
1153                ResolvedItemName::Item { id, .. } => Ok(ObjectId::Item(id)),
1154                ResolvedItemName::Cte { .. } => Err(anyhow!("CTE does not correspond to object")),
1155                ResolvedItemName::Error => Err(anyhow!("error in name resolution")),
1156            },
1157            ResolvedObjectName::NetworkPolicy(name) => Ok(ObjectId::NetworkPolicy(name.id)),
1158            ResolvedObjectName::QueryPolicy(name) => Ok(ObjectId::QueryPolicy(name.id)),
1159        }
1160    }
1161}
1162
1163impl From<ClusterId> for ObjectId {
1164    fn from(id: ClusterId) -> Self {
1165        ObjectId::Cluster(id)
1166    }
1167}
1168
1169impl From<&ClusterId> for ObjectId {
1170    fn from(id: &ClusterId) -> Self {
1171        ObjectId::Cluster(*id)
1172    }
1173}
1174
1175impl From<(ClusterId, ReplicaId)> for ObjectId {
1176    fn from(id: (ClusterId, ReplicaId)) -> Self {
1177        ObjectId::ClusterReplica(id)
1178    }
1179}
1180
1181impl From<&(ClusterId, ReplicaId)> for ObjectId {
1182    fn from(id: &(ClusterId, ReplicaId)) -> Self {
1183        ObjectId::ClusterReplica(*id)
1184    }
1185}
1186
1187impl From<DatabaseId> for ObjectId {
1188    fn from(id: DatabaseId) -> Self {
1189        ObjectId::Database(id)
1190    }
1191}
1192
1193impl From<&DatabaseId> for ObjectId {
1194    fn from(id: &DatabaseId) -> Self {
1195        ObjectId::Database(*id)
1196    }
1197}
1198
1199impl From<ItemQualifiers> for ObjectId {
1200    fn from(qualifiers: ItemQualifiers) -> Self {
1201        ObjectId::Schema((qualifiers.database_spec, qualifiers.schema_spec))
1202    }
1203}
1204
1205impl From<&ItemQualifiers> for ObjectId {
1206    fn from(qualifiers: &ItemQualifiers) -> Self {
1207        ObjectId::Schema((qualifiers.database_spec, qualifiers.schema_spec))
1208    }
1209}
1210
1211impl From<(ResolvedDatabaseSpecifier, SchemaSpecifier)> for ObjectId {
1212    fn from(id: (ResolvedDatabaseSpecifier, SchemaSpecifier)) -> Self {
1213        ObjectId::Schema(id)
1214    }
1215}
1216
1217impl From<&(ResolvedDatabaseSpecifier, SchemaSpecifier)> for ObjectId {
1218    fn from(id: &(ResolvedDatabaseSpecifier, SchemaSpecifier)) -> Self {
1219        ObjectId::Schema(*id)
1220    }
1221}
1222
1223impl From<RoleId> for ObjectId {
1224    fn from(id: RoleId) -> Self {
1225        ObjectId::Role(id)
1226    }
1227}
1228
1229impl From<&RoleId> for ObjectId {
1230    fn from(id: &RoleId) -> Self {
1231        ObjectId::Role(*id)
1232    }
1233}
1234
1235impl From<CatalogItemId> for ObjectId {
1236    fn from(id: CatalogItemId) -> Self {
1237        ObjectId::Item(id)
1238    }
1239}
1240
1241impl From<&CatalogItemId> for ObjectId {
1242    fn from(id: &CatalogItemId) -> Self {
1243        ObjectId::Item(*id)
1244    }
1245}
1246
1247impl From<CommentObjectId> for ObjectId {
1248    fn from(id: CommentObjectId) -> Self {
1249        match id {
1250            CommentObjectId::Table(item_id)
1251            | CommentObjectId::View(item_id)
1252            | CommentObjectId::MaterializedView(item_id)
1253            | CommentObjectId::Source(item_id)
1254            | CommentObjectId::Sink(item_id)
1255            | CommentObjectId::MetricSink(item_id)
1256            | CommentObjectId::Index(item_id)
1257            | CommentObjectId::Func(item_id)
1258            | CommentObjectId::Connection(item_id)
1259            | CommentObjectId::Type(item_id)
1260            | CommentObjectId::Secret(item_id) => ObjectId::Item(item_id),
1261            CommentObjectId::Role(id) => ObjectId::Role(id),
1262            CommentObjectId::Database(id) => ObjectId::Database(id),
1263            CommentObjectId::Schema(id) => ObjectId::Schema(id),
1264            CommentObjectId::Cluster(id) => ObjectId::Cluster(id),
1265            CommentObjectId::ClusterReplica(id) => ObjectId::ClusterReplica(id),
1266            CommentObjectId::NetworkPolicy(id) => ObjectId::NetworkPolicy(id),
1267            CommentObjectId::QueryPolicy(id) => ObjectId::QueryPolicy(id),
1268        }
1269    }
1270}
1271
1272#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
1273pub enum SystemObjectId {
1274    /// The ID of a specific object.
1275    Object(ObjectId),
1276    /// Identifier for the entire system.
1277    System,
1278}
1279
1280impl SystemObjectId {
1281    pub fn object_id(&self) -> Option<&ObjectId> {
1282        match self {
1283            SystemObjectId::Object(object_id) => Some(object_id),
1284            SystemObjectId::System => None,
1285        }
1286    }
1287
1288    pub fn is_system(&self) -> bool {
1289        matches!(self, SystemObjectId::System)
1290    }
1291}
1292
1293impl From<ObjectId> for SystemObjectId {
1294    fn from(id: ObjectId) -> Self {
1295        SystemObjectId::Object(id)
1296    }
1297}
1298
1299/// Comments can be applied to multiple kinds of objects (e.g. Tables and Role), so we need a way
1300/// to represent these different types and their IDs (e.g. [`CatalogItemId`] and [`RoleId`]), as
1301/// well as the inner kind of object that is represented, e.g. [`CatalogItemId`] is used to
1302/// identify both Tables and Views. No other kind of ID encapsulates all of this, hence this new
1303/// "*Id" type.
1304///
1305/// New variants here also need to be added to the durable counterpart
1306/// `mz_catalog_protos::objects::CommentObject` and to both CASE expressions in
1307/// the `mz_internal.mz_comments` materialized view (`MZ_COMMENTS` in
1308/// `mz-catalog::builtin::mz_internal`). The MV reads `CommentObject` out of
1309/// `mz_catalog_raw` as serde JSON.
1310#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize)]
1311pub enum CommentObjectId {
1312    Table(CatalogItemId),
1313    View(CatalogItemId),
1314    MaterializedView(CatalogItemId),
1315    Source(CatalogItemId),
1316    Sink(CatalogItemId),
1317    MetricSink(CatalogItemId),
1318    Index(CatalogItemId),
1319    Func(CatalogItemId),
1320    Connection(CatalogItemId),
1321    Type(CatalogItemId),
1322    Secret(CatalogItemId),
1323    Role(RoleId),
1324    Database(DatabaseId),
1325    Schema((ResolvedDatabaseSpecifier, SchemaSpecifier)),
1326    Cluster(ClusterId),
1327    ClusterReplica((ClusterId, ReplicaId)),
1328    NetworkPolicy(NetworkPolicyId),
1329    QueryPolicy(QueryPolicyId),
1330}
1331
1332/// Whether to resolve an name in the types namespace, the functions namespace,
1333/// or the relations namespace. It is possible to resolve name in multiple
1334/// namespaces, in which case types are preferred to functions are preferred to
1335/// relations.
1336// NOTE(benesch,sploiselle): The fact that some names are looked up in multiple
1337// namespaces is a bit dubious, and stems from the fact that we don't
1338// automatically create types for relations (see database-issues#7142). It's possible that we
1339// don't allow names to be looked up in multiple namespaces (i.e., this becomes
1340// `enum ItemResolutionNamespace`), but it's also possible that the design of
1341// the `DOC ON TYPE` option means we're forever stuck with this complexity.
1342#[derive(Debug, Clone, Copy)]
1343struct ItemResolutionConfig {
1344    types: bool,
1345    functions: bool,
1346    relations: bool,
1347}
1348
1349#[derive(Debug)]
1350pub struct NameResolver<'a> {
1351    catalog: &'a dyn SessionCatalog,
1352    ctes: BTreeMap<String, LocalId>,
1353    /// The next `LocalId` to allocate for a CTE. Never decremented, so every
1354    /// CTE in the statement gets a unique id, even when CTE names shadow each
1355    /// other. Later phases (e.g., HIR lowering's `CteMap`) key CTEs by
1356    /// `LocalId` and rely on this uniqueness.
1357    next_cte_id: u64,
1358    status: Result<(), PlanError>,
1359    ids: BTreeMap<CatalogItemId, BTreeSet<GlobalId>>,
1360}
1361
1362impl<'a> NameResolver<'a> {
1363    fn new(catalog: &'a dyn SessionCatalog) -> NameResolver<'a> {
1364        NameResolver {
1365            catalog,
1366            ctes: BTreeMap::new(),
1367            next_cte_id: 0,
1368            status: Ok(()),
1369            ids: BTreeMap::new(),
1370        }
1371    }
1372
1373    fn allocate_cte_id(&mut self) -> LocalId {
1374        let id = LocalId::new(self.next_cte_id);
1375        self.next_cte_id += 1;
1376        id
1377    }
1378
1379    fn resolve_data_type(&mut self, data_type: RawDataType) -> Result<ResolvedDataType, PlanError> {
1380        self.resolve_data_type_inner(data_type, true)
1381    }
1382
1383    fn resolve_data_type_inner(
1384        &mut self,
1385        data_type: RawDataType,
1386        should_insert_id: bool,
1387    ) -> Result<ResolvedDataType, PlanError> {
1388        match data_type {
1389            RawDataType::Array(elem_type) => {
1390                let name = elem_type.to_string();
1391                // `T[]` recursively resolves to its element type, but we
1392                // only want to insert its array type `_T` and not its element
1393                // type `T`. Thus we set `should_insert_id` to `false`.
1394                match self.resolve_data_type_inner(*elem_type, false)? {
1395                    ResolvedDataType::AnonymousList(_) | ResolvedDataType::AnonymousMap { .. } => {
1396                        sql_bail!("type \"{}[]\" does not exist", name)
1397                    }
1398                    ResolvedDataType::Named { id, modifiers, .. } => {
1399                        let element_item = self.catalog.get_item(&id);
1400                        let array_item = match element_item.type_details() {
1401                            Some(CatalogTypeDetails {
1402                                array_id: Some(array_id),
1403                                ..
1404                            }) => self.catalog.get_item(array_id),
1405                            Some(_) => sql_bail!("type \"{}[]\" does not exist", name),
1406                            None => {
1407                                // Resolution should never produce a
1408                                // `ResolvedDataType::Named` with an ID of a
1409                                // non-type, but we error gracefully just in
1410                                // case.
1411                                sql_bail!(
1412                                    "internal error: {} does not refer to a type",
1413                                    self.catalog
1414                                        .resolve_full_name(element_item.name())
1415                                        .to_string()
1416                                        .quoted()
1417                                );
1418                            }
1419                        };
1420
1421                        // We don't need to check `should_insert_id` here since we're
1422                        // guaranteed to insert just one array item type for an
1423                        // array. For multi-dimensional arrays, the parser always
1424                        // collapses it into a 1D array.
1425                        self.ids.insert(array_item.id(), BTreeSet::new());
1426                        Ok(ResolvedDataType::Named {
1427                            id: array_item.id(),
1428                            qualifiers: array_item.name().qualifiers.clone(),
1429                            full_name: self.catalog.resolve_full_name(array_item.name()),
1430                            modifiers,
1431                            print_id: true,
1432                        })
1433                    }
1434                    ResolvedDataType::Error => sql_bail!("type \"{}[]\" does not exist", name),
1435                }
1436            }
1437            RawDataType::List(elem_type) => {
1438                let elem_type = self.resolve_data_type_inner(*elem_type, should_insert_id)?;
1439                Ok(ResolvedDataType::AnonymousList(Box::new(elem_type)))
1440            }
1441            RawDataType::Map {
1442                key_type,
1443                value_type,
1444            } => {
1445                let key_type = self.resolve_data_type_inner(*key_type, should_insert_id)?;
1446                let value_type = self.resolve_data_type_inner(*value_type, should_insert_id)?;
1447                Ok(ResolvedDataType::AnonymousMap {
1448                    key_type: Box::new(key_type),
1449                    value_type: Box::new(value_type),
1450                })
1451            }
1452            RawDataType::Other { name, typ_mod } => {
1453                let (full_name, item) = match name {
1454                    RawItemName::Name(name) => {
1455                        let name = normalize::unresolved_item_name(name)?;
1456                        let item = self.catalog.resolve_type(&name)?;
1457                        let full_name = self.catalog.resolve_full_name(item.name());
1458                        (full_name, item)
1459                    }
1460                    RawItemName::Id(id, name, version) => {
1461                        let id: CatalogItemId = id.parse()?;
1462                        let item = match self.catalog.try_get_item(&id) {
1463                            Some(item) => item,
1464                            None => return Err(PlanError::InvalidId(id)),
1465                        };
1466                        let full_name = normalize::full_name(name)?;
1467                        if version.is_some() {
1468                            sql_bail!("specifying a version for a type reference is not supported");
1469                        }
1470
1471                        (full_name, item)
1472                    }
1473                };
1474                if should_insert_id {
1475                    self.ids.insert(item.id(), BTreeSet::new());
1476                }
1477                Ok(ResolvedDataType::Named {
1478                    id: item.id(),
1479                    qualifiers: item.name().qualifiers.clone(),
1480                    full_name,
1481                    modifiers: typ_mod,
1482                    print_id: true,
1483                })
1484            }
1485        }
1486    }
1487
1488    fn resolve_item_name(
1489        &mut self,
1490        item_name: RawItemName,
1491        config: ItemResolutionConfig,
1492    ) -> ResolvedItemName {
1493        match item_name {
1494            RawItemName::Name(name) => self.resolve_item_name_name(name, config),
1495            RawItemName::Id(id, raw_name, version) => {
1496                self.resolve_item_name_id(id, raw_name, version)
1497            }
1498        }
1499    }
1500
1501    fn resolve_item_name_name(
1502        &mut self,
1503        raw_name: UnresolvedItemName,
1504        config: ItemResolutionConfig,
1505    ) -> ResolvedItemName {
1506        let raw_name = match normalize::unresolved_item_name(raw_name) {
1507            Ok(raw_name) => raw_name,
1508            Err(e) => {
1509                if self.status.is_ok() {
1510                    self.status = Err(e);
1511                }
1512                return ResolvedItemName::Error;
1513            }
1514        };
1515
1516        let mut r: Result<&dyn CatalogItem, CatalogError> =
1517            Err(CatalogError::UnknownItem(raw_name.to_string()));
1518
1519        if r.is_err() && config.types {
1520            r = self.catalog.resolve_type(&raw_name);
1521        }
1522
1523        if r.is_err() && config.functions {
1524            r = self.catalog.resolve_function(&raw_name);
1525        }
1526
1527        if r.is_err() && config.relations {
1528            // Check if unqualified name refers to a CTE.
1529            //
1530            // Note that this is done in non-function contexts as CTEs
1531            // are treated as relations.
1532            if raw_name.database.is_none() && raw_name.schema.is_none() {
1533                let norm_name = normalize::ident(Ident::new_unchecked(&raw_name.item));
1534                if let Some(id) = self.ctes.get(&norm_name) {
1535                    return ResolvedItemName::Cte {
1536                        id: *id,
1537                        name: norm_name,
1538                    };
1539                }
1540            }
1541            r = self.catalog.resolve_item(&raw_name);
1542        };
1543
1544        match r {
1545            Ok(item) => {
1546                // Record the item at its current version.
1547                let item = item.at_version(RelationVersionSelector::Latest);
1548                self.ids
1549                    .entry(item.id())
1550                    .or_default()
1551                    .insert(item.global_id());
1552                let print_id = !matches!(
1553                    item.item_type(),
1554                    CatalogItemType::Func | CatalogItemType::Type
1555                );
1556                let alter_table_enabled =
1557                    self.catalog.system_vars().enable_alter_table_add_column();
1558                let version = match item.latest_version() {
1559                    // Only track the version of referenced object if the feature is enabled.
1560                    Some(v) if item.id().is_user() && alter_table_enabled => {
1561                        RelationVersionSelector::Specific(v)
1562                    }
1563                    _ => RelationVersionSelector::Latest,
1564                };
1565
1566                ResolvedItemName::Item {
1567                    id: item.id(),
1568                    qualifiers: item.name().qualifiers.clone(),
1569                    full_name: self.catalog.resolve_full_name(item.name()),
1570                    print_id,
1571                    version,
1572                }
1573            }
1574            Err(mut e) => {
1575                if self.status.is_ok() {
1576                    match &mut e {
1577                        CatalogError::UnknownFunction {
1578                            name: _,
1579                            alternative,
1580                        } => {
1581                            // Suggest using the `jsonb_` version of `json_`
1582                            // functions that do not exist.
1583                            if raw_name.database.is_none()
1584                                && (raw_name.schema.is_none()
1585                                    || raw_name.schema.as_deref() == Some("pg_catalog")
1586                                        && raw_name.item.starts_with("json_"))
1587                            {
1588                                let jsonb_name = PartialItemName {
1589                                    item: raw_name.item.replace("json_", "jsonb_"),
1590                                    ..raw_name
1591                                };
1592                                if self.catalog.resolve_function(&jsonb_name).is_ok() {
1593                                    *alternative = Some(jsonb_name.to_string());
1594                                }
1595                            }
1596                        }
1597                        _ => (),
1598                    }
1599
1600                    self.status = Err(e.into());
1601                }
1602                ResolvedItemName::Error
1603            }
1604        }
1605    }
1606
1607    fn resolve_item_name_id(
1608        &mut self,
1609        id: String,
1610        raw_name: UnresolvedItemName,
1611        version: Option<Version>,
1612    ) -> ResolvedItemName {
1613        let id: CatalogItemId = match id.parse() {
1614            Ok(id) => id,
1615            Err(e) => {
1616                if self.status.is_ok() {
1617                    self.status = Err(e.into());
1618                }
1619                return ResolvedItemName::Error;
1620            }
1621        };
1622        let item = match self.catalog.try_get_item(&id) {
1623            Some(item) => item,
1624            None => {
1625                if self.status.is_ok() {
1626                    self.status = Err(PlanError::InvalidId(id));
1627                }
1628                return ResolvedItemName::Error;
1629            }
1630        };
1631        let alter_table_enabled = self.catalog.system_vars().enable_alter_table_add_column();
1632        let version = match version {
1633            // If there isn't a version specified, and this item supports versioning, track the
1634            // latest.
1635            None => match item.latest_version() {
1636                // Only pin a version for user items, and only with the feature on. Mirrors the
1637                // by-name path in `fold_item_name`. Builtins are not user-versioned, so pinning
1638                // one strands the reference if the builtin is ever converted to an item type
1639                // without versions.
1640                Some(v) if id.is_user() && alter_table_enabled => {
1641                    RelationVersionSelector::Specific(v)
1642                }
1643                _ => RelationVersionSelector::Latest,
1644            },
1645            // Note: Return the specific version if one is specified, even if the feature is off.
1646            Some(v) => {
1647                let specified_version = normalize::relation_version(v);
1648                match item.latest_version() {
1649                    Some(latest) if latest >= specified_version => {
1650                        RelationVersionSelector::Specific(specified_version)
1651                    }
1652                    // A version pin on a builtin is meaningless, since builtins are not
1653                    // user-versioned. Such a pin can still sit in a persisted catalog, and if the
1654                    // builtin has been converted to an item type without versions it no longer
1655                    // validates. Resolve to latest instead of failing catalog open. User items
1656                    // keep the strict check so real out-of-range versions still error.
1657                    _ if !id.is_user() => RelationVersionSelector::Latest,
1658                    _ => {
1659                        if self.status.is_ok() {
1660                            self.status = Err(PlanError::InvalidVersion {
1661                                name: item.name().item.clone(),
1662                                version: v.to_string(),
1663                            })
1664                        }
1665                        return ResolvedItemName::Error;
1666                    }
1667                }
1668            }
1669        };
1670        let item = item.at_version(version);
1671        self.ids
1672            .entry(item.id())
1673            .or_default()
1674            .insert(item.global_id());
1675
1676        let full_name = match normalize::full_name(raw_name) {
1677            Ok(full_name) => full_name,
1678            Err(e) => {
1679                if self.status.is_ok() {
1680                    self.status = Err(e);
1681                }
1682                return ResolvedItemName::Error;
1683            }
1684        };
1685        ResolvedItemName::Item {
1686            id,
1687            qualifiers: item.name().qualifiers.clone(),
1688            full_name,
1689            print_id: true,
1690            version,
1691        }
1692    }
1693
1694    /// Resolves an item name in a `DOC ON` position (`DOC ON TYPE x`,
1695    /// `DOC ON COLUMN x.c`), where the name may denote a type or a relation. Also used for `COMMENT
1696    /// ON COLUMN`.
1697    fn resolve_doc_on_name(&mut self, name: RawItemName) -> ResolvedItemName {
1698        let mut name = self.resolve_item_name(
1699            name,
1700            // The name can refer to either a type or a relation.
1701            //
1702            // It's possible this will get simpler once database-issues#7142 is
1703            // fixed. See the comment on `ItemResolutionConfig` for details.
1704            ItemResolutionConfig {
1705                functions: false,
1706                types: true,
1707                relations: true,
1708            },
1709        );
1710        if let ResolvedItemName::Item { print_id, .. } = &mut name {
1711            // These references persist in a sink's `create_sql`, so the resolved name must print
1712            // its id, otherwise it can't recover it when recreating
1713            *print_id = true;
1714        }
1715        name
1716    }
1717}
1718
1719impl<'a> Fold<Raw, Aug> for NameResolver<'a> {
1720    fn fold_nested_statement(
1721        &mut self,
1722        stmt: <Raw as AstInfo>::NestedStatement,
1723    ) -> <Aug as AstInfo>::NestedStatement {
1724        stmt
1725    }
1726
1727    fn fold_query(&mut self, q: Query<Raw>) -> Query<Aug> {
1728        // Retain the old values of various CTE names so that we can restore them after we're done
1729        // planning this SELECT.
1730        let mut shadowed_cte_ids = Vec::new();
1731
1732        // A reused identifier indicates a reused name.
1733        use itertools::Itertools;
1734        if let Some(ident) = q.ctes.bound_identifiers().duplicates().next() {
1735            self.status = Err(sql_err!(
1736                "WITH query name \"{}\" specified more than once",
1737                normalize::ident_ref(ident),
1738            ));
1739        }
1740
1741        let ctes: CteBlock<Aug> = match q.ctes {
1742            CteBlock::Simple(ctes) => {
1743                let mut result_ctes = Vec::<Cte<Aug>>::new();
1744
1745                for cte in ctes.into_iter() {
1746                    let cte_name = normalize::ident(cte.alias.name.clone());
1747                    let local_id = self.allocate_cte_id();
1748
1749                    result_ctes.push(Cte {
1750                        alias: cte.alias,
1751                        id: local_id,
1752                        query: self.fold_query(cte.query),
1753                    });
1754
1755                    let shadowed_id = self.ctes.insert(cte_name.clone(), local_id);
1756                    shadowed_cte_ids.push((cte_name, shadowed_id));
1757                }
1758                CteBlock::Simple(result_ctes)
1759            }
1760            CteBlock::MutuallyRecursive(MutRecBlock { options, ctes }) => {
1761                let mut result_ctes = Vec::<CteMutRec<Aug>>::new();
1762
1763                // All bindings go into scope before any definition is walked,
1764                // so that the definitions can refer to each other.
1765                let mut local_ids = Vec::with_capacity(ctes.len());
1766                for cte in ctes.iter() {
1767                    let cte_name = normalize::ident(cte.name.clone());
1768                    let local_id = self.allocate_cte_id();
1769                    let shadowed_id = self.ctes.insert(cte_name.clone(), local_id);
1770                    shadowed_cte_ids.push((cte_name, shadowed_id));
1771                    local_ids.push(local_id);
1772                }
1773
1774                for (cte, local_id) in ctes.into_iter().zip_eq(local_ids) {
1775                    let columns = cte
1776                        .columns
1777                        .into_iter()
1778                        .map(|column| self.fold_cte_mut_rec_column_def(column))
1779                        .collect();
1780                    let query = self.fold_query(cte.query);
1781                    result_ctes.push(CteMutRec {
1782                        name: cte.name,
1783                        columns,
1784                        id: local_id,
1785                        query,
1786                    });
1787                }
1788                CteBlock::MutuallyRecursive(MutRecBlock {
1789                    options: options
1790                        .into_iter()
1791                        .map(|option| self.fold_mut_rec_block_option(option))
1792                        .collect(),
1793                    ctes: result_ctes,
1794                })
1795            }
1796        };
1797
1798        let result = Query {
1799            ctes,
1800            // Queries can be recursive, so need the ability to grow the stack.
1801            body: mz_ore::stack::maybe_grow(|| self.fold_set_expr(q.body)),
1802            limit: q.limit.map(|l| self.fold_limit(l)),
1803            offset: q.offset.map(|l| self.fold_expr(l)),
1804            order_by: q
1805                .order_by
1806                .into_iter()
1807                .map(|c| self.fold_order_by_expr(c))
1808                .collect(),
1809        };
1810
1811        // Restore the old values of the CTEs.
1812        for (name, value) in shadowed_cte_ids.iter() {
1813            match value {
1814                Some(value) => {
1815                    self.ctes.insert(name.to_string(), value.clone());
1816                }
1817                None => {
1818                    self.ctes.remove(name);
1819                }
1820            };
1821        }
1822
1823        result
1824    }
1825
1826    fn fold_cte_id(&mut self, _id: <Raw as AstInfo>::CteId) -> <Aug as AstInfo>::CteId {
1827        panic!("this should have been handled when walking the CTE");
1828    }
1829
1830    fn fold_item_name(
1831        &mut self,
1832        item_name: <Raw as AstInfo>::ItemName,
1833    ) -> <Aug as AstInfo>::ItemName {
1834        self.resolve_item_name(
1835            item_name,
1836            // By default, when resolving an item name, we assume only relations
1837            // should be in scope.
1838            ItemResolutionConfig {
1839                functions: false,
1840                types: false,
1841                relations: true,
1842            },
1843        )
1844    }
1845
1846    fn fold_column_name(&mut self, column_name: ast::ColumnName<Raw>) -> ast::ColumnName<Aug> {
1847        let item_name = self.resolve_doc_on_name(column_name.relation);
1848
1849        match &item_name {
1850            ResolvedItemName::Item {
1851                id,
1852                full_name,
1853                version,
1854                qualifiers: _,
1855                print_id: _,
1856            } => {
1857                let item = self.catalog.get_item(id).at_version(*version);
1858                let name = normalize::column_name(column_name.column.clone());
1859
1860                let maybe_desc = match item.type_details() {
1861                    Some(details) => match details.typ.desc(self.catalog) {
1862                        Ok(desc) => desc.map(Cow::Owned),
1863                        Err(e) => {
1864                            if self.status.is_ok() {
1865                                self.status = Err(e);
1866                            }
1867                            return ast::ColumnName {
1868                                relation: ResolvedItemName::Error,
1869                                column: ResolvedColumnReference::Error,
1870                            };
1871                        }
1872                    },
1873                    None => item.relation_desc(),
1874                };
1875                let Some(desc) = maybe_desc else {
1876                    if self.status.is_ok() {
1877                        self.status = Err(PlanError::ItemWithoutColumns {
1878                            name: full_name.to_string(),
1879                            item_type: item.item_type(),
1880                        });
1881                    }
1882                    return ast::ColumnName {
1883                        relation: ResolvedItemName::Error,
1884                        column: ResolvedColumnReference::Error,
1885                    };
1886                };
1887
1888                let Some((index, _typ)) = desc.get_by_name(&name) else {
1889                    if self.status.is_ok() {
1890                        let similar = desc.iter_similar_names(&name).cloned().collect();
1891                        self.status = Err(PlanError::UnknownColumn {
1892                            table: Some(full_name.clone().into()),
1893                            column: name,
1894                            similar,
1895                        })
1896                    }
1897                    return ast::ColumnName {
1898                        relation: ResolvedItemName::Error,
1899                        column: ResolvedColumnReference::Error,
1900                    };
1901                };
1902
1903                ast::ColumnName {
1904                    relation: item_name,
1905                    column: ResolvedColumnReference::Column { name, index },
1906                }
1907            }
1908            ResolvedItemName::Cte { .. } | ResolvedItemName::Error => ast::ColumnName {
1909                relation: ResolvedItemName::Error,
1910                column: ResolvedColumnReference::Error,
1911            },
1912        }
1913    }
1914
1915    fn fold_column_reference(
1916        &mut self,
1917        _node: <Raw as AstInfo>::ColumnReference,
1918    ) -> <Aug as AstInfo>::ColumnReference {
1919        // Do not call this function directly; instead resolve through `fold_column_name`
1920        ResolvedColumnReference::Error
1921    }
1922
1923    fn fold_data_type(
1924        &mut self,
1925        data_type: <Raw as AstInfo>::DataType,
1926    ) -> <Aug as AstInfo>::DataType {
1927        match self.resolve_data_type(data_type) {
1928            Ok(data_type) => data_type,
1929            Err(e) => {
1930                if self.status.is_ok() {
1931                    self.status = Err(e);
1932                }
1933                ResolvedDataType::Error
1934            }
1935        }
1936    }
1937
1938    fn fold_schema_name(
1939        &mut self,
1940        name: <Raw as AstInfo>::SchemaName,
1941    ) -> <Aug as AstInfo>::SchemaName {
1942        let norm_name = match normalize::unresolved_schema_name(name) {
1943            Ok(norm_name) => norm_name,
1944            Err(e) => {
1945                if self.status.is_ok() {
1946                    self.status = Err(e);
1947                }
1948                return ResolvedSchemaName::Error;
1949            }
1950        };
1951
1952        // Special case for mz_temp: with lazy temporary schema creation, the temp
1953        // schema may not exist yet. Return a resolved name with SchemaSpecifier::Temporary
1954        // so that downstream code can handle it appropriately (e.g., return a proper error).
1955        if norm_name.database.is_none() && norm_name.schema == mz_repr::namespaces::MZ_TEMP_SCHEMA {
1956            return ResolvedSchemaName::Schema {
1957                database_spec: ResolvedDatabaseSpecifier::Ambient,
1958                schema_spec: SchemaSpecifier::Temporary,
1959                full_name: FullSchemaName {
1960                    database: RawDatabaseSpecifier::Ambient,
1961                    schema: mz_repr::namespaces::MZ_TEMP_SCHEMA.to_string(),
1962                },
1963            };
1964        }
1965
1966        match self
1967            .catalog
1968            .resolve_schema(norm_name.database.as_deref(), norm_name.schema.as_str())
1969        {
1970            Ok(schema) => {
1971                let raw_database_spec = match schema.database() {
1972                    ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
1973                    ResolvedDatabaseSpecifier::Id(id) => {
1974                        RawDatabaseSpecifier::Name(self.catalog.get_database(id).name().to_string())
1975                    }
1976                };
1977                ResolvedSchemaName::Schema {
1978                    database_spec: schema.database().clone(),
1979                    schema_spec: schema.id().clone(),
1980                    full_name: FullSchemaName {
1981                        database: raw_database_spec,
1982                        schema: schema.name().schema.clone(),
1983                    },
1984                }
1985            }
1986            Err(e) => {
1987                if self.status.is_ok() {
1988                    self.status = Err(e.into());
1989                }
1990                ResolvedSchemaName::Error
1991            }
1992        }
1993    }
1994
1995    fn fold_database_name(
1996        &mut self,
1997        database_name: <Raw as AstInfo>::DatabaseName,
1998    ) -> <Aug as AstInfo>::DatabaseName {
1999        match self.catalog.resolve_database(database_name.0.as_str()) {
2000            Ok(database) => ResolvedDatabaseName::Database {
2001                id: database.id(),
2002                name: database_name.0.into_string(),
2003            },
2004            Err(e) => {
2005                if self.status.is_ok() {
2006                    self.status = Err(e.into());
2007                }
2008                ResolvedDatabaseName::Error
2009            }
2010        }
2011    }
2012
2013    fn fold_cluster_name(
2014        &mut self,
2015        cluster_name: <Raw as AstInfo>::ClusterName,
2016    ) -> <Aug as AstInfo>::ClusterName {
2017        match cluster_name {
2018            RawClusterName::Unresolved(ident) => {
2019                match self.catalog.resolve_cluster(Some(ident.as_str())) {
2020                    Ok(cluster) => ResolvedClusterName {
2021                        id: cluster.id(),
2022                        print_name: None,
2023                    },
2024                    Err(e) => {
2025                        self.status = Err(e.into());
2026                        ResolvedClusterName {
2027                            // The ID is arbitrary here; we just need some dummy
2028                            // value to return.
2029                            id: ClusterId::system(0).expect("0 is a valid ID"),
2030                            print_name: None,
2031                        }
2032                    }
2033                }
2034            }
2035            RawClusterName::Resolved(ident) => match ident.parse() {
2036                Ok(id) => ResolvedClusterName {
2037                    id,
2038                    print_name: None,
2039                },
2040                Err(e) => {
2041                    self.status = Err(e.into());
2042                    ResolvedClusterName {
2043                        // The ID is arbitrary here; we just need some dummy
2044                        // value to return.
2045                        id: ClusterId::system(0).expect("0 is a valid ID"),
2046                        print_name: None,
2047                    }
2048                }
2049            },
2050        }
2051    }
2052
2053    fn fold_with_option_value(
2054        &mut self,
2055        node: mz_sql_parser::ast::WithOptionValue<Raw>,
2056    ) -> mz_sql_parser::ast::WithOptionValue<Aug> {
2057        use mz_sql_parser::ast::WithOptionValue::*;
2058        match node {
2059            Sequence(vs) => Sequence(
2060                vs.into_iter()
2061                    .map(|v| self.fold_with_option_value(v))
2062                    .collect(),
2063            ),
2064            Map(map) => Map(map
2065                .into_iter()
2066                .map(|(k, v)| (k, self.fold_with_option_value(v)))
2067                .collect()),
2068            Value(v) => Value(self.fold_value(v)),
2069            DataType(dt) => DataType(self.fold_data_type(dt)),
2070            Secret(secret) => {
2071                let item_name = self.fold_item_name(secret);
2072                match &item_name {
2073                    ResolvedItemName::Item { id, .. } => {
2074                        let item = self.catalog.get_item(id);
2075                        if item.item_type() != CatalogItemType::Secret {
2076                            self.status =
2077                                Err(PlanError::InvalidSecret(Box::new(item_name.clone())));
2078                        }
2079                    }
2080                    ResolvedItemName::Cte { .. } => {
2081                        self.status = Err(PlanError::InvalidSecret(Box::new(item_name.clone())));
2082                    }
2083                    ResolvedItemName::Error => {}
2084                }
2085                Secret(item_name)
2086            }
2087            Item(obj) => {
2088                let item_name = self.fold_item_name(obj);
2089                match &item_name {
2090                    ResolvedItemName::Item { .. } => {}
2091                    ResolvedItemName::Cte { .. } => {
2092                        self.status = Err(PlanError::InvalidObject(Box::new(item_name.clone())));
2093                    }
2094                    ResolvedItemName::Error => {}
2095                }
2096                Item(item_name)
2097            }
2098            UnresolvedItemName(name) => UnresolvedItemName(self.fold_unresolved_item_name(name)),
2099            Ident(name) => Ident(self.fold_ident(name)),
2100            Expr(e) => Expr(self.fold_expr(e)),
2101            ClusterReplicas(replicas) => ClusterReplicas(
2102                replicas
2103                    .into_iter()
2104                    .map(|r| self.fold_replica_definition(r))
2105                    .collect(),
2106            ),
2107            ConnectionKafkaBroker(broker) => ConnectionKafkaBroker(self.fold_kafka_broker(broker)),
2108            ConnectionAwsPrivatelink(privatelink) => {
2109                ConnectionAwsPrivatelink(self.fold_connection_default_aws_privatelink(privatelink))
2110            }
2111            KafkaMatchingBrokerRule(x) => {
2112                KafkaMatchingBrokerRule(self.fold_kafka_matching_broker_rule(x))
2113            }
2114            RetainHistoryFor(value) => RetainHistoryFor(self.fold_value(value)),
2115            Refresh(refresh) => Refresh(self.fold_refresh_option_value(refresh)),
2116            ClusterScheduleOptionValue(value) => ClusterScheduleOptionValue(value),
2117            ClusterAutoScalingStrategyOptionValue(value) => {
2118                ClusterAutoScalingStrategyOptionValue(value)
2119            }
2120            ClusterAlterStrategy(value) => {
2121                ClusterAlterStrategy(self.fold_cluster_alter_option_value(value))
2122            }
2123            NetworkPolicyRules(rules) => NetworkPolicyRules(
2124                rules
2125                    .into_iter()
2126                    .map(|r| self.fold_network_policy_rule_definition(r))
2127                    .collect(),
2128            ),
2129        }
2130    }
2131
2132    fn fold_role_name(&mut self, name: <Raw as AstInfo>::RoleName) -> <Aug as AstInfo>::RoleName {
2133        match self.catalog.resolve_role(name.as_str()) {
2134            Ok(role) => ResolvedRoleName {
2135                id: role.id(),
2136                name: role.name().to_string(),
2137            },
2138            Err(e) => {
2139                if self.status.is_ok() {
2140                    self.status = Err(e.into());
2141                }
2142                // garbage value that will be ignored since there's an error.
2143                ResolvedRoleName {
2144                    id: RoleId::User(0),
2145                    name: "".to_string(),
2146                }
2147            }
2148        }
2149    }
2150
2151    fn fold_network_policy_name(
2152        &mut self,
2153        name: <Raw as AstInfo>::NetworkPolicyName,
2154    ) -> <Aug as AstInfo>::NetworkPolicyName {
2155        let name_str = match &name {
2156            RawNetworkPolicyName::Unresolved(ident) => ident.as_str(),
2157            RawNetworkPolicyName::Resolved(s) => s.as_str(),
2158        };
2159        match self.catalog.resolve_network_policy(name_str) {
2160            Ok(policy) => ResolvedNetworkPolicyName {
2161                id: policy.id(),
2162                name: policy.name().to_string(),
2163            },
2164            Err(e) => {
2165                if self.status.is_ok() {
2166                    self.status = Err(e.into());
2167                }
2168                // garbage value that will be ignored since there's an error.
2169                ResolvedNetworkPolicyName {
2170                    id: NetworkPolicyId::User(0),
2171                    name: "".to_string(),
2172                }
2173            }
2174        }
2175    }
2176
2177    fn fold_object_name(
2178        &mut self,
2179        name: <Raw as AstInfo>::ObjectName,
2180    ) -> <Aug as AstInfo>::ObjectName {
2181        match name {
2182            UnresolvedObjectName::Cluster(name) => ResolvedObjectName::Cluster(
2183                self.fold_cluster_name(RawClusterName::Unresolved(name)),
2184            ),
2185            UnresolvedObjectName::ClusterReplica(name) => {
2186                match self.catalog.resolve_cluster_replica(&name) {
2187                    Ok(cluster_replica) => {
2188                        ResolvedObjectName::ClusterReplica(ResolvedClusterReplicaName {
2189                            cluster_id: cluster_replica.cluster_id(),
2190                            replica_id: cluster_replica.replica_id(),
2191                        })
2192                    }
2193                    Err(e) => {
2194                        self.status = Err(e.into());
2195                        ResolvedObjectName::ClusterReplica(ResolvedClusterReplicaName {
2196                            // The ID is arbitrary here; we just need some dummy
2197                            // value to return.
2198                            cluster_id: ClusterId::system(0).expect("0 is a valid ID"),
2199                            replica_id: ReplicaId::System(0),
2200                        })
2201                    }
2202                }
2203            }
2204            UnresolvedObjectName::Database(name) => {
2205                ResolvedObjectName::Database(self.fold_database_name(name))
2206            }
2207            UnresolvedObjectName::Schema(name) => {
2208                ResolvedObjectName::Schema(self.fold_schema_name(name))
2209            }
2210            UnresolvedObjectName::Role(name) => ResolvedObjectName::Role(self.fold_role_name(name)),
2211            UnresolvedObjectName::Item(name) => {
2212                ResolvedObjectName::Item(self.fold_item_name(RawItemName::Name(name)))
2213            }
2214            UnresolvedObjectName::NetworkPolicy(name) => ResolvedObjectName::NetworkPolicy(
2215                self.fold_network_policy_name(RawNetworkPolicyName::Unresolved(name)),
2216            ),
2217            UnresolvedObjectName::QueryPolicy(name) => {
2218                let name = name.as_str().to_string();
2219                let id = match self.catalog.resolve_query_policy(&name) {
2220                    Ok(policy) => policy.id(),
2221                    Err(error) => {
2222                        self.status = Err(error.into());
2223                        QueryPolicyId::User(0)
2224                    }
2225                };
2226                ResolvedObjectName::QueryPolicy(ResolvedQueryPolicyName { id, name })
2227            }
2228        }
2229    }
2230
2231    fn fold_function(
2232        &mut self,
2233        node: mz_sql_parser::ast::Function<Raw>,
2234    ) -> mz_sql_parser::ast::Function<Aug> {
2235        // Functions implemented as SQL statements can have very deeply nested
2236        // and recursive structures, so need the ability to grow the stack.
2237        mz_ore::stack::maybe_grow(|| {
2238            mz_sql_parser::ast::Function {
2239                name: self.resolve_item_name(
2240                    node.name,
2241                    // When resolving a function name, only function items should be
2242                    // considered.
2243                    ItemResolutionConfig {
2244                        functions: true,
2245                        types: false,
2246                        relations: false,
2247                    },
2248                ),
2249                args: self.fold_function_args(node.args),
2250                filter: node.filter.map(|expr| Box::new(self.fold_expr(*expr))),
2251                over: node.over.map(|over| Box::new(self.fold_window_spec(*over))),
2252                distinct: node.distinct,
2253            }
2254        })
2255    }
2256
2257    fn fold_table_factor(
2258        &mut self,
2259        node: mz_sql_parser::ast::TableFactor<Raw>,
2260    ) -> mz_sql_parser::ast::TableFactor<Aug> {
2261        use mz_sql_parser::ast::TableFactor::*;
2262        match node {
2263            Table { name, alias } => Table {
2264                name: self.fold_item_name(name),
2265                alias: alias.map(|alias| self.fold_table_alias(alias)),
2266            },
2267            Function {
2268                function,
2269                alias,
2270                with_ordinality,
2271            } => {
2272                match &function.name {
2273                    RawItemName::Name(name) => {
2274                        if *name == UnresolvedItemName::unqualified(ident!("values"))
2275                            && self.status.is_ok()
2276                        {
2277                            self.status = Err(PlanError::FromValueRequiresParen);
2278                        }
2279                    }
2280                    RawItemName::Id(..) => {}
2281                }
2282
2283                Function {
2284                    function: self.fold_function(function),
2285                    alias: alias.map(|alias| self.fold_table_alias(alias)),
2286                    with_ordinality,
2287                }
2288            }
2289            RowsFrom {
2290                functions,
2291                alias,
2292                with_ordinality,
2293            } => RowsFrom {
2294                functions: functions
2295                    .into_iter()
2296                    .map(|f| self.fold_function(f))
2297                    .collect(),
2298                alias: alias.map(|alias| self.fold_table_alias(alias)),
2299                with_ordinality,
2300            },
2301            Derived {
2302                lateral,
2303                subquery,
2304                alias,
2305            } => Derived {
2306                lateral,
2307                subquery: Box::new(self.fold_query(*subquery)),
2308                alias: alias.map(|alias| self.fold_table_alias(alias)),
2309            },
2310            NestedJoin { join, alias } => NestedJoin {
2311                join: Box::new(self.fold_table_with_joins(*join)),
2312                alias: alias.map(|alias| self.fold_table_alias(alias)),
2313            },
2314        }
2315    }
2316
2317    fn fold_grant_target_specification(
2318        &mut self,
2319        node: GrantTargetSpecification<Raw>,
2320    ) -> GrantTargetSpecification<Aug> {
2321        match node {
2322            GrantTargetSpecification::Object {
2323                object_type: ObjectType::Type,
2324                object_spec_inner: GrantTargetSpecificationInner::Objects { names },
2325            } => GrantTargetSpecification::Object {
2326                object_type: ObjectType::Type,
2327                object_spec_inner: GrantTargetSpecificationInner::Objects {
2328                    names: names
2329                        .into_iter()
2330                        .map(|name| match name {
2331                            UnresolvedObjectName::Item(name) => {
2332                                ResolvedObjectName::Item(self.resolve_item_name_name(
2333                                    name,
2334                                    // `{GRANT|REVOKE} ... ON TYPE ...` can only
2335                                    // refer to type names.
2336                                    ItemResolutionConfig {
2337                                        functions: false,
2338                                        types: true,
2339                                        relations: false,
2340                                    },
2341                                ))
2342                            }
2343                            _ => self.fold_object_name(name),
2344                        })
2345                        .collect(),
2346                },
2347            },
2348            _ => mz_sql_parser::ast::fold::fold_grant_target_specification(self, node),
2349        }
2350    }
2351
2352    fn fold_doc_on_identifier(&mut self, node: DocOnIdentifier<Raw>) -> DocOnIdentifier<Aug> {
2353        match node {
2354            DocOnIdentifier::Column(name) => DocOnIdentifier::Column(self.fold_column_name(name)),
2355            DocOnIdentifier::Type(name) => DocOnIdentifier::Type(self.resolve_doc_on_name(name)),
2356        }
2357    }
2358
2359    fn fold_expr(&mut self, node: Expr<Raw>) -> Expr<Aug> {
2360        // Exprs can be recursive, so need the ability to grow the stack.
2361        mz_ore::stack::maybe_grow(|| mz_sql_parser::ast::fold::fold_expr(self, node))
2362    }
2363}
2364
2365/// Resolves names in an AST node using the provided catalog.
2366#[mz_ore::instrument(target = "compiler", level = "trace", name = "ast_resolve_names")]
2367pub fn resolve<N>(
2368    catalog: &dyn SessionCatalog,
2369    node: N,
2370) -> Result<(N::Folded, ResolvedIds), PlanError>
2371where
2372    N: FoldNode<Raw, Aug>,
2373{
2374    let mut resolver = NameResolver::new(catalog);
2375    let result = node.fold(&mut resolver);
2376    resolver.status?;
2377    Ok((result, ResolvedIds::new(resolver.ids)))
2378}
2379
2380/// A set of items and their corresponding collections resolved by name resolution.
2381///
2382/// This is a newtype of a [`BTreeMap`] that is provided to make it harder to confuse a set of
2383/// resolved IDs with other collections of [`CatalogItemId`].
2384#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2385pub struct ResolvedIds {
2386    #[serde(serialize_with = "mz_ore::serde::map_key_to_string")]
2387    entries: BTreeMap<CatalogItemId, BTreeSet<GlobalId>>,
2388}
2389
2390impl ResolvedIds {
2391    fn new(entries: BTreeMap<CatalogItemId, BTreeSet<GlobalId>>) -> Self {
2392        ResolvedIds { entries }
2393    }
2394
2395    /// Returns an emptry [`ResolvedIds`].
2396    pub fn empty() -> Self {
2397        ResolvedIds {
2398            entries: BTreeMap::new(),
2399        }
2400    }
2401
2402    /// Returns if the set of IDs is empty.
2403    pub fn is_empty(&self) -> bool {
2404        self.entries.is_empty()
2405    }
2406
2407    /// Returns all of the [`GlobalId`]s in this set.
2408    pub fn collections(&self) -> impl Iterator<Item = &GlobalId> {
2409        self.entries.values().flat_map(|gids| gids.into_iter())
2410    }
2411
2412    /// Returns all of the [`CatalogItemId`]s in this set.
2413    pub fn items(&self) -> impl Iterator<Item = &CatalogItemId> {
2414        self.entries.keys()
2415    }
2416
2417    /// Returns if this set of IDs contains the provided [`CatalogItemId`].
2418    pub fn contains_item(&self, item: &CatalogItemId) -> bool {
2419        self.entries.contains_key(item)
2420    }
2421
2422    pub fn add_item(&mut self, item: CatalogItemId) {
2423        self.entries.insert(item, BTreeSet::new());
2424    }
2425
2426    pub fn remove_item(&mut self, item: &CatalogItemId) {
2427        self.entries.remove(item);
2428    }
2429
2430    /// Merges all entries from `other` into `self`.
2431    pub fn extend_from(&mut self, other: &ResolvedIds) {
2432        for (id, gids) in &other.entries {
2433            self.entries
2434                .entry(*id)
2435                .or_default()
2436                .extend(gids.iter().copied());
2437        }
2438    }
2439
2440    /// Create a new [`ResolvedIds`] that contains the elements from `self`
2441    /// where `predicate` returns `true`.
2442    pub fn retain_items<F>(&self, predicate: F) -> Self
2443    where
2444        F: Fn(&CatalogItemId) -> bool,
2445    {
2446        let mut new_ids = self.clone();
2447        new_ids
2448            .entries
2449            .retain(|item_id, _global_ids| predicate(item_id));
2450        new_ids
2451    }
2452}
2453
2454impl FromIterator<(CatalogItemId, GlobalId)> for ResolvedIds {
2455    fn from_iter<T: IntoIterator<Item = (CatalogItemId, GlobalId)>>(iter: T) -> Self {
2456        let mut ids = ResolvedIds::empty();
2457        ids.extend(iter);
2458        ids
2459    }
2460}
2461
2462impl Extend<(CatalogItemId, GlobalId)> for ResolvedIds {
2463    fn extend<T: IntoIterator<Item = (CatalogItemId, GlobalId)>>(&mut self, iter: T) {
2464        for (item_id, global_id) in iter {
2465            self.entries.entry(item_id).or_default().insert(global_id);
2466        }
2467    }
2468}
2469
2470/// A set of IDs references by the `HirRelationExpr` of an object.
2471#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2472pub struct DependencyIds(pub BTreeSet<CatalogItemId>);
2473
2474impl FromIterator<CatalogItemId> for DependencyIds {
2475    fn from_iter<T: IntoIterator<Item = CatalogItemId>>(iter: T) -> Self {
2476        DependencyIds(iter.into_iter().collect())
2477    }
2478}
2479
2480#[derive(Debug)]
2481pub struct DependencyVisitor<'a> {
2482    catalog: &'a dyn SessionCatalog,
2483    ids: BTreeMap<CatalogItemId, BTreeSet<GlobalId>>,
2484}
2485
2486impl<'a> DependencyVisitor<'a> {
2487    pub fn new(catalog: &'a dyn SessionCatalog) -> Self {
2488        DependencyVisitor {
2489            catalog,
2490            ids: Default::default(),
2491        }
2492    }
2493}
2494
2495impl<'a, 'ast> Visit<'ast, Aug> for DependencyVisitor<'a> {
2496    fn visit_item_name(&mut self, item_name: &'ast <Aug as AstInfo>::ItemName) {
2497        if let ResolvedItemName::Item { id, version, .. } = item_name {
2498            let global_ids = self.ids.entry(*id).or_default();
2499            if let Some(item) = self.catalog.try_get_item(id) {
2500                global_ids.insert(item.at_version(*version).global_id());
2501            }
2502        }
2503    }
2504
2505    fn visit_data_type(&mut self, data_type: &'ast <Aug as AstInfo>::DataType) {
2506        match data_type {
2507            ResolvedDataType::AnonymousList(data_type) => self.visit_data_type(data_type),
2508            ResolvedDataType::AnonymousMap {
2509                key_type,
2510                value_type,
2511            } => {
2512                self.visit_data_type(key_type);
2513                self.visit_data_type(value_type);
2514            }
2515            ResolvedDataType::Named { id, .. } => {
2516                self.ids.entry(*id).or_default();
2517            }
2518            ResolvedDataType::Error => {}
2519        }
2520    }
2521}
2522
2523pub fn visit_dependencies<'ast, N>(catalog: &dyn SessionCatalog, node: &'ast N) -> ResolvedIds
2524where
2525    N: VisitNode<'ast, Aug> + 'ast,
2526{
2527    let mut visitor = DependencyVisitor::new(catalog);
2528    node.visit(&mut visitor);
2529    ResolvedIds::new(visitor.ids)
2530}
2531
2532#[derive(Debug)]
2533pub struct ItemDependencyModifier<'a> {
2534    pub modified: bool,
2535    pub id_map: &'a BTreeMap<CatalogItemId, CatalogItemId>,
2536}
2537
2538impl<'ast, 'a> VisitMut<'ast, Raw> for ItemDependencyModifier<'a> {
2539    fn visit_item_name_mut(&mut self, item_name: &mut RawItemName) {
2540        if let RawItemName::Id(id, _, _) = item_name {
2541            let parsed_id = id.parse::<CatalogItemId>().unwrap();
2542            if let Some(new_id) = self.id_map.get(&parsed_id) {
2543                *id = new_id.to_string();
2544                self.modified = true;
2545            }
2546        }
2547    }
2548}
2549
2550/// Updates any references in the provided AST node that are keys in `id_map`.
2551/// If an id is found it will be updated to the value of the key in `id_map`.
2552/// This assumes the names of the reference(s) are unmodified (e.g. each pair of
2553/// ids refer to an item of the same name, whose id has changed).
2554pub fn modify_dependency_item_ids<'ast, N>(
2555    node: &'ast mut N,
2556    id_map: &BTreeMap<CatalogItemId, CatalogItemId>,
2557) -> bool
2558where
2559    N: VisitMutNode<'ast, Raw>,
2560{
2561    let mut modifier = ItemDependencyModifier {
2562        id_map,
2563        modified: false,
2564    };
2565    node.visit_mut(&mut modifier);
2566
2567    modifier.modified
2568}
2569
2570// Used when displaying a view's source for human creation. If the name
2571// specified is the same as the name in the catalog, we don't use the ID format.
2572#[derive(Debug)]
2573pub struct NameSimplifier<'a> {
2574    pub catalog: &'a dyn SessionCatalog,
2575}
2576
2577impl<'ast, 'a> VisitMut<'ast, Aug> for NameSimplifier<'a> {
2578    fn visit_cluster_name_mut(&mut self, node: &mut ResolvedClusterName) {
2579        node.print_name = Some(self.catalog.get_cluster(node.id).name().into());
2580    }
2581
2582    fn visit_item_name_mut(&mut self, name: &mut ResolvedItemName) {
2583        if let ResolvedItemName::Item {
2584            id,
2585            full_name,
2586            print_id,
2587            ..
2588        } = name
2589        {
2590            let item = self.catalog.get_item(id);
2591            let catalog_full_name = self.catalog.resolve_full_name(item.name());
2592            if catalog_full_name == *full_name {
2593                *print_id = false;
2594            }
2595        }
2596    }
2597
2598    fn visit_data_type_mut(&mut self, name: &mut ResolvedDataType) {
2599        if let ResolvedDataType::Named {
2600            id,
2601            full_name,
2602            print_id,
2603            ..
2604        } = name
2605        {
2606            let item = self.catalog.get_item(id);
2607            let catalog_full_name = self.catalog.resolve_full_name(item.name());
2608            if catalog_full_name == *full_name {
2609                *print_id = false;
2610            }
2611        }
2612    }
2613}
2614
2615/// Returns the [`CatalogItemId`] dependencies the provided `node` has.
2616///
2617/// _DOES NOT_ resolve names, simply does a recursive walk through an object to
2618/// find all of the IDs.
2619pub fn dependencies<'ast, N>(node: &'ast N) -> Result<BTreeSet<CatalogItemId>, anyhow::Error>
2620where
2621    N: VisitNode<'ast, Raw>,
2622{
2623    let mut visitor = IdDependencVisitor::default();
2624    node.visit(&mut visitor);
2625    match visitor.error {
2626        Some(error) => Err(error),
2627        None => Ok(visitor.ids),
2628    }
2629}
2630
2631#[derive(Debug, Default)]
2632struct IdDependencVisitor {
2633    ids: BTreeSet<CatalogItemId>,
2634    error: Option<anyhow::Error>,
2635}
2636
2637impl<'ast> Visit<'ast, Raw> for IdDependencVisitor {
2638    fn visit_item_name(&mut self, node: &'ast <Raw as AstInfo>::ItemName) {
2639        // Bail early if we're already in an error state.
2640        if self.error.is_some() {
2641            return;
2642        }
2643
2644        match node {
2645            // Nothing to do! We don't lookup names.
2646            RawItemName::Name(_) => (),
2647            RawItemName::Id(id, _name, _version) => match id.parse::<CatalogItemId>() {
2648                Ok(id) => {
2649                    self.ids.insert(id);
2650                }
2651                Err(e) => {
2652                    self.error = Some(e);
2653                }
2654            },
2655        }
2656    }
2657}
2658
2659#[cfg(test)]
2660mod tests {
2661    use proptest::prelude::*;
2662
2663    use super::*;
2664
2665    #[mz_ore::test]
2666    fn proptest_schema_id_roundtrips() {
2667        fn testcase(og: SchemaId) {
2668            let s = og.to_string();
2669            let rnd: SchemaId = s.parse().unwrap();
2670            assert_eq!(og, rnd);
2671        }
2672
2673        proptest!(|(id in any::<SchemaId>())| {
2674            testcase(id);
2675        })
2676    }
2677
2678    #[mz_ore::test]
2679    fn proptest_database_id_roundtrips() {
2680        fn testcase(og: DatabaseId) {
2681            let s = og.to_string();
2682            let rnd: DatabaseId = s.parse().unwrap();
2683            assert_eq!(og, rnd);
2684        }
2685
2686        proptest!(|(id in any::<DatabaseId>())| {
2687            testcase(id);
2688        })
2689    }
2690
2691    #[mz_ore::test]
2692    fn test_schema_id_from_str() {
2693        assert_eq!("s5".parse::<SchemaId>().unwrap(), SchemaId::System(5));
2694        assert_eq!("u5".parse::<SchemaId>().unwrap(), SchemaId::User(5));
2695
2696        // Regression test for a panic on multi-byte leading characters, where
2697        // slicing off a single byte landed inside a UTF-8 char boundary (SQL-195).
2698        for invalid in ["ü1", "ü", "é42", "🦀7", "", "x1", "s"] {
2699            assert!(
2700                invalid.parse::<SchemaId>().is_err(),
2701                "expected {invalid:?} to fail to parse"
2702            );
2703        }
2704    }
2705
2706    #[mz_ore::test]
2707    fn test_database_id_from_str() {
2708        assert_eq!("s5".parse::<DatabaseId>().unwrap(), DatabaseId::System(5));
2709        assert_eq!("u5".parse::<DatabaseId>().unwrap(), DatabaseId::User(5));
2710
2711        // Regression test for a panic on multi-byte leading characters, where
2712        // slicing off a single byte landed inside a UTF-8 char boundary (SQL-195).
2713        for invalid in ["ü1", "ü", "é42", "🦀7", "", "x1", "u"] {
2714            assert!(
2715                invalid.parse::<DatabaseId>().is_err(),
2716                "expected {invalid:?} to fail to parse"
2717            );
2718        }
2719    }
2720}