uqa_sql/schema/dependencies/
oid_alias.rs1use 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
20pub trait OidAliasInput {
22 fn resolve_oid_alias_input(&self, ty: &ColumnType, name: &str)
23 -> Result<Option<i64>, SQLError>;
24
25 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
70fn 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
83fn 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
99fn 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
118fn constant_type(ty: ColumnType, array: bool) -> ColumnType {
120 if array {
121 ColumnType::Array(Box::new(ty))
122 } else {
123 ty
124 }
125}
126
127pub 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
166fn 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
188fn 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
247pub 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
261pub 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}