1use 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
16pub 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
44fn 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
57fn 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
73fn 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
94fn 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
105fn 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
147pub(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
166fn constant_type(ty: ColumnType, array: bool) -> ColumnType {
168 if array {
169 ColumnType::Array(Box::new(ty))
170 } else {
171 ty
172 }
173}
174
175pub 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
214fn 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
233fn 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
292pub 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
306pub 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}