Skip to main content

uqa_sql/catalog/
resolution.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Relation namespace inputs for static SQL analysis.
8
9use crate::catalog::roles::RoleReference;
10use crate::SQLError;
11
12mod production;
13
14/// The usable namespace order and creation target of one analysis. An explicitly placed `pg_catalog` can leave the lookup order unchanged while changing the creation namespace, which `SearchPathMatchesCurrentEnvironment` also compares.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct EffectiveSearchPath {
17    pub schemas: Vec<String>,
18    pub creation_namespace: Option<String>,
19}
20
21/// Immutable session inputs used to resolve unqualified relation names during one statement.
22#[derive(Clone)]
23pub struct RelationNameResolution {
24    pub search_path: Vec<String>,
25    pub temporary_schema: String,
26    pub temporary_namespace_allocated: bool,
27    pub current_user: RoleReference,
28    pub lookup_mode: RelationLookupMode,
29}
30
31/// Whether a query resolves session-visible names or follows catalog identities captured when a stored expression was defined.
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub enum RelationLookupMode {
34    Dynamic,
35    Bound,
36}
37
38impl RelationNameResolution {
39    pub fn search_path(&self) -> &[String] {
40        &self.search_path
41    }
42
43    pub fn search_path_contains(&self, schema: &str) -> bool {
44        self.search_path.iter().any(|candidate| candidate == schema)
45    }
46
47    pub fn current_user(&self) -> &RoleReference {
48        &self.current_user
49    }
50
51    pub fn lookup_mode(&self) -> RelationLookupMode {
52        self.lookup_mode
53    }
54
55    pub fn qualified_schema(&self, name: &str) -> Result<Option<(String, String)>, SQLError> {
56        let (schema, _) = uqa_core::RelationIdentity::parse_reference(name).map_err(|error| {
57            SQLError::Internal(format!("resolve catalog relation `{name}`: {error}"))
58        })?;
59        Ok(schema.map(|schema| {
60            let resolved = if schema == "pg_temp" {
61                self.temporary_schema.clone()
62            } else {
63                schema.clone()
64            };
65            (schema, resolved)
66        }))
67    }
68
69    pub fn set_lookup_mode(&mut self, lookup_mode: RelationLookupMode) -> RelationLookupMode {
70        std::mem::replace(&mut self.lookup_mode, lookup_mode)
71    }
72
73    pub fn raw_relation_lookup_candidates(
74        &self,
75        name: &str,
76    ) -> Result<Vec<uqa_core::RelationIdentity>, SQLError> {
77        let (schema, relation) =
78            uqa_core::RelationIdentity::parse_reference(name).map_err(|error| {
79                SQLError::Internal(format!("resolve catalog relation `{name}`: {error}"))
80            })?;
81        if let Some(schema) = schema {
82            let schema = if schema == "pg_temp" {
83                self.temporary_schema.clone()
84            } else {
85                schema
86            };
87            return Ok(vec![uqa_core::RelationIdentity::new(schema, relation)]);
88        }
89        Ok(candidates::unqualified_candidates(
90            &self.temporary_schema,
91            &self.search_path,
92            &relation,
93        ))
94    }
95}
96
97/// Complete outcome of resolving one relation reference through a statement namespace.
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub enum RelationResolution {
100    Found(String, &'static str),
101    MissingRelation,
102    MissingSchema(String),
103}
104
105impl RelationResolution {
106    /// Collapse namespace absence only for SQL boundaries whose contract reports an undefined relation for either absence outcome.
107    pub fn into_found(self) -> Option<(String, &'static str)> {
108        match self {
109            Self::Found(name, kind) => Some((name, kind)),
110            Self::MissingRelation | Self::MissingSchema(_) => None,
111        }
112    }
113}
114
115pub fn missing_relation_notice(name: &str) -> Result<String, crate::SQLError> {
116    let (_, local_name) =
117        uqa_core::RelationIdentity::parse_reference(name).map_err(crate::SQLError::Internal)?;
118    Ok(format!(
119        "relation \"{local_name}\" does not exist, skipping"
120    ))
121}
122
123/// Bind rename-source diagnostics without losing the distinction between missing schemas and relations.
124pub fn resolve_relation_rename_source(
125    resolution: RelationResolution,
126    name: &str,
127    if_exists: bool,
128    notice: &mut dyn FnMut(&str),
129) -> Result<Option<(String, &'static str)>, crate::SQLError> {
130    match resolution {
131        RelationResolution::Found(canonical, kind) => Ok(Some((canonical, kind))),
132        RelationResolution::MissingSchema(_) | RelationResolution::MissingRelation if if_exists => {
133            notice(&missing_relation_notice(name)?);
134            Ok(None)
135        }
136        RelationResolution::MissingSchema(schema) => Err(crate::SQLError::Routine {
137            sqlstate: "3F000".into(),
138            message: format!("schema \"{schema}\" does not exist"),
139        }),
140        RelationResolution::MissingRelation => Err(crate::SQLError::Routine {
141            sqlstate: "42P01".into(),
142            message: format!("relation \"{name}\" does not exist"),
143        }),
144    }
145}
146
147pub mod candidates;
148
149pub mod creation;
150
151/// The name `PostgreSQL`'s object descriptions give `relation`: its own name, quoted as an identifier needs, when the search path finds that relation by it, and its schema-qualified name otherwise.
152pub fn described_relation_name(
153    relation: &uqa_core::RelationIdentity,
154    resolve: impl FnOnce(&str) -> Result<RelationResolution, SQLError>,
155) -> Result<String, SQLError> {
156    let local = crate::expr::quote_ident(&relation.name);
157    let visible = match resolve(&local)? {
158        RelationResolution::Found(found, _) => uqa_core::RelationIdentity::from_legacy_name(&found)
159            .is_ok_and(|found| found == *relation),
160        RelationResolution::MissingRelation | RelationResolution::MissingSchema(_) => false,
161    };
162    Ok(if visible {
163        local
164    } else {
165        format!("{}.{local}", crate::expr::quote_ident(&relation.schema))
166    })
167}
168
169/// Decode a relation identity already selected by binding. A stored identity must name its schema and must never resolve through the current search path or temporary-schema alias.
170pub fn bound_relation_identity(name: &str) -> Result<uqa_core::RelationIdentity, SQLError> {
171    let (schema, relation) = uqa_core::RelationIdentity::parse_reference(name)
172        .map_err(|error| SQLError::Internal(format!("decode bound relation `{name}`: {error}")))?;
173    let schema = schema.ok_or_else(|| {
174        SQLError::Internal(format!(
175            "bound query contains non-canonical relation reference `{name}`"
176        ))
177    })?;
178    Ok(uqa_core::RelationIdentity::new(schema, relation))
179}
180
181#[cfg(test)]
182mod bound_identity_tests {
183    #[test]
184    fn bound_identity_requires_a_schema_and_keeps_quoted_names_and_schema_aliases() {
185        for (input, schema, name) in [
186            ("public.items", "public", "items"),
187            ("pg_temp.items", "pg_temp", "items"),
188            (
189                "\"other.schema\".\"odd.table\"",
190                "other.schema",
191                "odd.table",
192            ),
193        ] {
194            assert_eq!(
195                super::bound_relation_identity(input).unwrap(),
196                uqa_core::RelationIdentity::new(schema, name)
197            );
198        }
199        let error = super::bound_relation_identity("items").unwrap_err();
200        assert_eq!(
201            error.to_string(),
202            "internal error: bound query contains non-canonical relation reference `items`"
203        );
204        assert!(super::bound_relation_identity("a.b.c").is_err());
205    }
206}