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::Value;
15
16mod production;
17pub use production::read_prepared_oid_alias_constants_owned;
18pub(crate) use production::read_unknown_constant_with_control;
19
20/// 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.
21pub trait OidAliasInput {
22    fn resolve_oid_alias_input(&self, ty: &ColumnType, name: &str)
23        -> Result<Option<i64>, SQLError>;
24
25    /// Native catalogs admit parsed names and lookup workspace before allocation. External catalogs retain their existing callback.
26    fn resolve_oid_alias_input_with_control(
27        &self,
28        ty: &ColumnType,
29        name: &str,
30        control: &uqa_core::memory::ProductionControl<'_>,
31    ) -> Result<Option<i64>, SQLError> {
32        control.check()?;
33        let result = self.resolve_oid_alias_input(ty, name)?;
34        control.check()?;
35        Ok(result)
36    }
37}
38
39impl<T: EngineHook + ?Sized> OidAliasInput for T {
40    fn resolve_oid_alias_input_with_control(
41        &self,
42        ty: &ColumnType,
43        name: &str,
44        control: &uqa_core::memory::ProductionControl<'_>,
45    ) -> Result<Option<i64>, SQLError> {
46        EngineHook::resolve_oid_alias_input_with_control(self, ty, name, control)
47    }
48
49    fn resolve_oid_alias_input(
50        &self,
51        ty: &ColumnType,
52        name: &str,
53    ) -> Result<Option<i64>, SQLError> {
54        match ty {
55            ColumnType::Regclass => EngineHook::resolve_regclass_input(self, name),
56            ColumnType::Regtype => EngineHook::resolve_regtype_input(self, name),
57            ColumnType::Regproc => EngineHook::resolve_regproc(self, name),
58            ColumnType::Regprocedure => EngineHook::resolve_regprocedure_input(self, name),
59            ColumnType::Regnamespace => EngineHook::resolve_regnamespace(self, name),
60            ColumnType::Regcollation => EngineHook::resolve_regcollation(self, name),
61            ColumnType::Regrole => EngineHook::resolve_regrole(self, name),
62            other => Err(SQLError::Internal(format!(
63                "{} is not an OID alias type read at analysis",
64                other.sql_name()
65            ))),
66        }
67    }
68}
69
70/// Whether `ty` is an OID alias type whose input function reads a catalog name at analysis.
71fn is_alias(ty: &ColumnType) -> bool {
72    matches!(
73        ty,
74        ColumnType::Regclass
75            | ColumnType::Regtype
76            | ColumnType::Regproc
77            | ColumnType::Regprocedure
78            | ColumnType::Regcollation
79            | ColumnType::Regnamespace
80    )
81}
82
83/// The OID alias type a cast's type name denotes, and whether the cast is to an array of it.
84fn alias_type(ty: &str) -> Option<(ColumnType, bool)> {
85    if !ty
86        .as_bytes()
87        .windows(3)
88        .any(|window| window.eq_ignore_ascii_case(b"reg"))
89    {
90        return None;
91    }
92    match ColumnType::from_sql_name(ty).ok()? {
93        ColumnType::Array(element) if is_alias(&element) => Some((*element, true)),
94        element if is_alias(&element) => Some((element, false)),
95        _ => None,
96    }
97}
98
99/// The error the alias type's input function reports for a name no object has.
100/// 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.
101fn read_constant<C: OidAliasInput + ?Sized>(
102    catalog: &C,
103    ty: &ColumnType,
104    text: &str,
105    array: bool,
106) -> Result<Value, SQLError> {
107    production::read_constant_with_control(
108        catalog,
109        ty,
110        text,
111        array,
112        &uqa_core::memory::ProductionControl::uncontrolled(),
113    )?
114    .into_uncontrolled()
115    .map_err(|_| SQLError::Internal("ordinary OID input owner".into()))
116}
117
118/// The type of the stored constant: the alias type, or an array of it.
119fn constant_type(ty: ColumnType, array: bool) -> ColumnType {
120    if array {
121        ColumnType::Array(Box::new(ty))
122    } else {
123        ty
124    }
125}
126
127/// 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.
128pub fn read_oid_alias_constants<C: OidAliasInput + ?Sized>(
129    catalog: &C,
130    expression: &mut Expr,
131) -> Result<(), SQLError> {
132    let mut failure = None;
133    let outcome = walk_schema_expr_mut(expression, &mut |node| {
134        let Expr::Cast { expr, ty, .. } = node else {
135            return Ok(());
136        };
137        let Some((alias, array)) = alias_type(ty) else {
138            return Ok(());
139        };
140        let Expr::Literal(Value::Str(text)) = expr.as_ref() else {
141            return Ok(());
142        };
143        match read_constant(catalog, &alias, text, array) {
144            Ok(value) => {
145                **expr = Expr::TypedLiteral {
146                    collation_oid: None,
147                    composite_source: None,
148                    value,
149                    ty: constant_type(alias, array).catalog_name(),
150                };
151                Ok(())
152            }
153            Err(error) => {
154                failure = Some(error);
155                Err(String::new())
156            }
157        }
158    });
159    match (outcome, failure) {
160        (Ok(()), _) => Ok(()),
161        (Err(_), Some(error)) => Err(error),
162        (Err(message), None) => Err(SQLError::Internal(message)),
163    }
164}
165
166/// 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`.
167fn sequence_argument_mut(expression: &mut ScalarExpr) -> Option<&mut ScalarExpr> {
168    let ScalarExpr::Func { name, args, .. } = expression else {
169        return None;
170    };
171    if !is_sequence_function(name) {
172        return None;
173    }
174    args.first_mut()
175        .filter(|argument| matches!(argument, ScalarExpr::Literal(Value::Str(_))))
176}
177
178fn is_sequence_function(name: &str) -> bool {
179    let local = name
180        .get(..11)
181        .filter(|prefix| prefix.eq_ignore_ascii_case("pg_catalog."))
182        .map_or(name, |_| &name[11..]);
183    ["nextval", "currval", "setval"]
184        .iter()
185        .any(|candidate| local.eq_ignore_ascii_case(candidate))
186}
187
188/// [`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.
189fn read_scalar_constant<C: OidAliasInput + ?Sized>(
190    catalog: &C,
191    expression: &mut ScalarExpr,
192    keep_relations: bool,
193    failure: &mut Option<SQLError>,
194) {
195    if failure.is_some() {
196        return;
197    }
198    if let Some(argument) = sequence_argument_mut(expression) {
199        let ScalarExpr::Literal(Value::Str(text)) = &*argument else {
200            unreachable!("sequence argument is an unknown literal");
201        };
202        match read_constant(catalog, &ColumnType::Regclass, text, false) {
203            Ok(value) => {
204                if !keep_relations {
205                    *argument = ScalarExpr::TypedLiteral {
206                        collation_oid: None,
207                        composite_source: None,
208                        value,
209                        ty: ColumnType::Regclass.catalog_name(),
210                        bound_type: Some(ColumnType::Regclass),
211                        parameter_index: None,
212                    };
213                }
214            }
215            Err(error) => *failure = Some(error),
216        }
217        return;
218    }
219    let ScalarExpr::Cast { expr, ty, .. } = expression else {
220        return;
221    };
222    let Some((alias, array)) = alias_type(ty) else {
223        return;
224    };
225    let ScalarExpr::Literal(Value::Str(text)) = expr.as_ref() else {
226        return;
227    };
228    match read_constant(catalog, &alias, text, array) {
229        Ok(value) => {
230            if keep_relations && matches!(alias, ColumnType::Regclass) {
231                return;
232            }
233            let bound_type = constant_type(alias, array);
234            **expr = ScalarExpr::TypedLiteral {
235                collation_oid: None,
236                composite_source: None,
237                value,
238                ty: bound_type.catalog_name(),
239                bound_type: Some(bound_type),
240                parameter_index: None,
241            };
242        }
243        Err(error) => *failure = Some(error),
244    }
245}
246
247/// [`read_oid_alias_constants`] over every scalar expression of a stored query, nested ones included: a view stores the OIDs its `reg*` constants name.
248pub fn read_oid_alias_constants_in_plan<C: OidAliasInput + ?Sized>(
249    catalog: &C,
250    plan: &mut QueryPlan,
251) -> Result<(), SQLError> {
252    let mut failure = None;
253    plan.rewrite_scalar_expressions(&mut |root| {
254        root.visit_mut(&mut |expression| {
255            read_scalar_constant(catalog, expression, false, &mut failure);
256        });
257    });
258    failure.map_or(Ok(()), Err)
259}
260
261/// 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.
262pub fn read_prepared_oid_alias_constants<C: OidAliasInput + ?Sized>(
263    catalog: &C,
264    plan: &mut UnifiedPlan,
265) -> Result<(), SQLError> {
266    let mut failure = None;
267    plan.rewrite_scalar_expressions(&mut |root| {
268        root.visit_mut(&mut |expression| {
269            read_scalar_constant(catalog, expression, false, &mut failure);
270        });
271    });
272    failure.map_or(Ok(()), Err)
273}