Skip to main content

uqa_sql/schema/dependencies/
oid_alias.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read OID alias constants at analysis as the `reg*` input functions read them: a `regclass`, `regtype`, `regproc`, `regprocedure` or `regnamespace` cast of a string literal, or a cast to an array of one of them, stores the OIDs the names resolve to, as parse analysis stores the constant, so a stored expression follows the objects through renames and a name no object has is reported where the expression is analyzed.
8
9use super::walk_schema_expr_mut;
10use crate::ast::{ColumnType, Expr};
11use crate::expr::EngineHook;
12use crate::plan::{QueryPlan, UnifiedPlan};
13use crate::{SQLError, ScalarExpr};
14use uqa_core::{ArrayValue, Value};
15
16/// A catalog that reads OID alias input: the object a name denotes for one alias type, resolved as the type's input function resolves it through the search path, with the input function's errors. `None` says the catalog has no such object; the reader then reports the input function's missing-object error.
17pub trait OidAliasInput {
18    fn resolve_oid_alias_input(&self, ty: &ColumnType, name: &str)
19        -> Result<Option<i64>, SQLError>;
20}
21
22impl<T: EngineHook + ?Sized> OidAliasInput for T {
23    fn resolve_oid_alias_input(
24        &self,
25        ty: &ColumnType,
26        name: &str,
27    ) -> Result<Option<i64>, SQLError> {
28        match ty {
29            ColumnType::Regclass => EngineHook::resolve_regclass_input(self, name),
30            ColumnType::Regtype => EngineHook::resolve_regtype_input(self, name),
31            ColumnType::Regproc => EngineHook::resolve_regproc(self, name),
32            ColumnType::Regprocedure => EngineHook::resolve_regprocedure_input(self, name),
33            ColumnType::Regnamespace => EngineHook::resolve_regnamespace(self, name),
34            ColumnType::Regcollation => EngineHook::resolve_regcollation(self, name),
35            ColumnType::Regrole => EngineHook::resolve_regrole(self, name),
36            other => Err(SQLError::Internal(format!(
37                "{} is not an OID alias type read at analysis",
38                other.sql_name()
39            ))),
40        }
41    }
42}
43
44/// Whether `ty` is an OID alias type whose input function reads a catalog name at analysis.
45fn is_alias(ty: &ColumnType) -> bool {
46    matches!(
47        ty,
48        ColumnType::Regclass
49            | ColumnType::Regtype
50            | ColumnType::Regproc
51            | ColumnType::Regprocedure
52            | ColumnType::Regcollation
53            | ColumnType::Regnamespace
54    )
55}
56
57/// The OID alias type a cast's type name denotes, and whether the cast is to an array of it.
58fn alias_type(ty: &str) -> Option<(ColumnType, bool)> {
59    if !ty
60        .as_bytes()
61        .windows(3)
62        .any(|window| window.eq_ignore_ascii_case(b"reg"))
63    {
64        return None;
65    }
66    match ColumnType::from_sql_name(ty).ok()? {
67        ColumnType::Array(element) if is_alias(&element) => Some((*element, true)),
68        element if is_alias(&element) => Some((element, false)),
69        _ => None,
70    }
71}
72
73/// The error the alias type's input function reports for a name no object has.
74fn missing_object(ty: &ColumnType, name: &str) -> SQLError {
75    if matches!(ty, ColumnType::Regcollation) {
76        return SQLError::Routine {
77            sqlstate: "42704".into(),
78            message: format!("collation \"{name}\" for encoding \"UTF8\" does not exist"),
79        };
80    }
81    let (sqlstate, object) = match ty {
82        ColumnType::Regclass => ("42P01", "relation"),
83        ColumnType::Regtype => ("42704", "type"),
84        ColumnType::Regrole => ("42704", "role"),
85        ColumnType::Regproc | ColumnType::Regprocedure => ("42883", "function"),
86        _ => ("3F000", "schema"),
87    };
88    SQLError::Routine {
89        sqlstate: sqlstate.into(),
90        message: format!("{object} \"{name}\" does not exist"),
91    }
92}
93
94/// The OID the alias type's input function gives `name`.
95fn read_name<C: OidAliasInput + ?Sized>(
96    catalog: &C,
97    ty: &ColumnType,
98    name: &str,
99) -> Result<i64, SQLError> {
100    catalog
101        .resolve_oid_alias_input(ty, name)?
102        .ok_or_else(|| missing_object(ty, name))
103}
104
105/// The constant parse analysis stores for a cast of the literal `text` to the alias type `ty`, or to an array of it: the object's OID, or the OIDs of the array's elements.
106fn read_constant<C: OidAliasInput + ?Sized>(
107    catalog: &C,
108    ty: &ColumnType,
109    text: &str,
110    array: bool,
111) -> Result<Value, SQLError> {
112    if !array {
113        return read_name(catalog, ty, text).map(Value::Int);
114    }
115    let array = crate::expr::parse_pg_array_literal(text)?;
116    let lower_bounds = array.lower_bounds().to_vec();
117    let mut elements = array.into_elements();
118    read_array_elements(catalog, ty, &mut elements)?;
119    ArrayValue::with_lower_bounds(elements, lower_bounds)
120        .map(Value::Array)
121        .ok_or_else(|| {
122            SQLError::Internal(format!("{} array literal lost its shape", ty.sql_name()))
123        })
124}
125
126fn read_array_elements<C: OidAliasInput + ?Sized>(
127    catalog: &C,
128    ty: &ColumnType,
129    elements: &mut [Value],
130) -> Result<(), SQLError> {
131    for element in elements {
132        match element {
133            Value::Null => {}
134            Value::Str(name) => *element = Value::Int(read_name(catalog, ty, name)?),
135            Value::List(nested) => read_array_elements(catalog, ty, nested)?,
136            other => {
137                return Err(SQLError::TypeMismatch(format!(
138                    "cannot read {other:?} as {}",
139                    ty.sql_name(),
140                )))
141            }
142        }
143    }
144    Ok(())
145}
146
147/// Read an unknown input after ordered analysis selects an OID alias type. Other catalog-dependent input types remain the responsibility of their own binders.
148pub(crate) fn read_unknown_constant(
149    catalog: &dyn OidAliasInput,
150    ty: &ColumnType,
151    text: &str,
152) -> Result<Option<Value>, SQLError> {
153    match ty {
154        ColumnType::Array(element)
155            if is_alias(element) || matches!(element.as_ref(), ColumnType::Regrole) =>
156        {
157            read_constant(catalog, element, text, true).map(Some)
158        }
159        scalar if is_alias(scalar) || matches!(scalar, ColumnType::Regrole) => {
160            read_constant(catalog, scalar, text, false).map(Some)
161        }
162        _ => Ok(None),
163    }
164}
165
166/// The type of the stored constant: the alias type, or an array of it.
167fn constant_type(ty: ColumnType, array: bool) -> ColumnType {
168    if array {
169        ColumnType::Array(Box::new(ty))
170    } else {
171        ty
172    }
173}
174
175/// Read the OID alias constants of a stored schema expression: each `reg*` cast of a string literal becomes the typed constant of the OIDs the names resolve to, so the expression follows the objects through renames, and a name no object has reports the input function's error.
176pub fn read_oid_alias_constants<C: OidAliasInput + ?Sized>(
177    catalog: &C,
178    expression: &mut Expr,
179) -> Result<(), SQLError> {
180    let mut failure = None;
181    let outcome = walk_schema_expr_mut(expression, &mut |node| {
182        let Expr::Cast { expr, ty, .. } = node else {
183            return Ok(());
184        };
185        let Some((alias, array)) = alias_type(ty) else {
186            return Ok(());
187        };
188        let Expr::Literal(Value::Str(text)) = expr.as_ref() else {
189            return Ok(());
190        };
191        match read_constant(catalog, &alias, text, array) {
192            Ok(value) => {
193                **expr = Expr::TypedLiteral {
194                    collation_oid: None,
195                    composite_source: None,
196                    value,
197                    ty: constant_type(alias, array).catalog_name(),
198                };
199                Ok(())
200            }
201            Err(error) => {
202                failure = Some(error);
203                Err(String::new())
204            }
205        }
206    });
207    match (outcome, failure) {
208        (Ok(()), _) => Ok(()),
209        (Err(_), Some(error)) => Err(error),
210        (Err(message), None) => Err(SQLError::Internal(message)),
211    }
212}
213
214/// The first argument of `nextval`, `currval` or `setval` when it is an `unknown` literal: `coerce_type` reads it with `regclassin` for the `regclass` parameter, so the stored constant is the sequence's OID and prints as `'name'::regclass`.
215fn sequence_argument_mut(expression: &mut ScalarExpr) -> Option<&mut ScalarExpr> {
216    let ScalarExpr::Func { name, args, .. } = expression else {
217        return None;
218    };
219    if !is_sequence_function(name) {
220        return None;
221    }
222    args.first_mut()
223        .filter(|argument| matches!(argument, ScalarExpr::Literal(Value::Str(_))))
224}
225
226fn is_sequence_function(name: &str) -> bool {
227    let lower = name.to_ascii_lowercase();
228    let local = lower.strip_prefix("pg_catalog.").unwrap_or(&lower);
229    matches!(local, "nextval" | "currval" | "setval")
230        && (!lower.contains('.') || lower.starts_with("pg_catalog."))
231}
232
233/// [`read_oid_alias_constants`] for one scalar node. The first failure is kept and stops further reads. With `keep_relations`, a `regclass` cast is checked and left as written.
234fn read_scalar_constant<C: OidAliasInput + ?Sized>(
235    catalog: &C,
236    expression: &mut ScalarExpr,
237    keep_relations: bool,
238    failure: &mut Option<SQLError>,
239) {
240    if failure.is_some() {
241        return;
242    }
243    if let Some(argument) = sequence_argument_mut(expression) {
244        let ScalarExpr::Literal(Value::Str(text)) = &*argument else {
245            unreachable!("sequence argument is an unknown literal");
246        };
247        match read_constant(catalog, &ColumnType::Regclass, text, false) {
248            Ok(value) => {
249                if !keep_relations {
250                    *argument = ScalarExpr::TypedLiteral {
251                        collation_oid: None,
252                        composite_source: None,
253                        value,
254                        ty: ColumnType::Regclass.catalog_name(),
255                        bound_type: Some(ColumnType::Regclass),
256                        parameter_index: None,
257                    };
258                }
259            }
260            Err(error) => *failure = Some(error),
261        }
262        return;
263    }
264    let ScalarExpr::Cast { expr, ty, .. } = expression else {
265        return;
266    };
267    let Some((alias, array)) = alias_type(ty) else {
268        return;
269    };
270    let ScalarExpr::Literal(Value::Str(text)) = expr.as_ref() else {
271        return;
272    };
273    match read_constant(catalog, &alias, text, array) {
274        Ok(value) => {
275            if keep_relations && matches!(alias, ColumnType::Regclass) {
276                return;
277            }
278            let bound_type = constant_type(alias, array);
279            **expr = ScalarExpr::TypedLiteral {
280                collation_oid: None,
281                composite_source: None,
282                value,
283                ty: bound_type.catalog_name(),
284                bound_type: Some(bound_type),
285                parameter_index: None,
286            };
287        }
288        Err(error) => *failure = Some(error),
289    }
290}
291
292/// [`read_oid_alias_constants`] over every scalar expression of a stored query, nested ones included: a view stores the OIDs its `reg*` constants name.
293pub fn read_oid_alias_constants_in_plan<C: OidAliasInput + ?Sized>(
294    catalog: &C,
295    plan: &mut QueryPlan,
296) -> Result<(), SQLError> {
297    let mut failure = None;
298    plan.rewrite_scalar_expressions(&mut |root| {
299        root.visit_mut(&mut |expression| {
300            read_scalar_constant(catalog, expression, false, &mut failure);
301        });
302    });
303    failure.map_or(Ok(()), Err)
304}
305
306/// Read a prepared statement's OID alias inputs once. Scalar regclass constants contribute relation dependencies separately; invalidation reads the retained original syntax again. A whole array constant retains its OIDs without becoming scalar relation dependencies.
307pub fn read_prepared_oid_alias_constants<C: OidAliasInput + ?Sized>(
308    catalog: &C,
309    plan: &mut UnifiedPlan,
310) -> Result<(), SQLError> {
311    let mut failure = None;
312    plan.rewrite_scalar_expressions(&mut |root| {
313        root.visit_mut(&mut |expression| {
314            read_scalar_constant(catalog, expression, false, &mut failure);
315        });
316    });
317    failure.map_or(Ok(()), Err)
318}