1mod coercion;
10mod collations;
11mod constructs;
12mod fields;
13mod functions;
14mod operators;
15mod routines;
16mod rows;
17mod schema;
18mod subscripts;
19pub use routines::{select_routine, RoutineDeclaration};
20pub use schema::{ColumnReference, ExpressionSchema};
21
22use super::{values, Field, Node};
23use crate::ast::{BinaryOp, Expr, FunctionBinding, RoutineInvocationBinding};
24use crate::catalog::type_metadata::{pg_type_collation_oid, pg_type_modifier, pg_type_oid};
25use crate::type_resolution::{
26 binary_operator_catalog_entry, binary_operator_types, common_context_expression_type,
27 FunctionTypeResolver, RoutineCallDescriptor,
28};
29use crate::{ColumnType, SQLError};
30
31pub struct RoutineIdentity {
32 pub oid: i64,
33 pub invocation: RoutineInvocationBinding,
34 pub result_type: ColumnType,
35}
36
37pub trait ExpressionRoutines {
38 fn resolve(
39 &self,
40 name: &str,
41 binding: Option<&FunctionBinding>,
42 call: RoutineCallDescriptor<'_>,
43 ) -> Result<RoutineIdentity, SQLError>;
44}
45
46pub struct ExpressionContext<'a> {
47 pub schema: &'a dyn ExpressionSchema,
48 pub domain_value: Option<&'a ColumnType>,
49 pub types: Option<&'a dyn FunctionTypeResolver>,
50 pub routines: &'a dyn ExpressionRoutines,
51}
52
53struct TypedNode {
54 node: Node,
55 ty: Option<ColumnType>,
57}
58
59impl TypedNode {
60 fn type_ref(&self) -> Result<&ColumnType, SQLError> {
61 self.ty
62 .as_ref()
63 .ok_or_else(|| super::invalid("expected a selected expression type"))
64 }
65}
66
67impl ExpressionContext<'_> {
68 pub fn check(&self, expression: &Expr) -> Result<Node, SQLError> {
69 self.expression(expression, Some(&ColumnType::Boolean))
70 }
71
72 pub fn expression(
74 &self,
75 expression: &Expr,
76 expected: Option<&ColumnType>,
77 ) -> Result<Node, SQLError> {
78 let mut value = self.encode(expression, expected)?;
79 collations::assign(&mut value.node)?;
80 Ok(value.node)
81 }
82
83 pub fn assignment(&self, expression: &Expr, target: &ColumnType) -> Result<Node, SQLError> {
85 let unknown = self.expression_type(expression)?.is_none();
86 let input_type = target.without_type_modifiers();
87 let value = self.encode(expression, unknown.then_some(&input_type))?;
88 let mut value = Self::coerce_assignment(value, target)?;
89 collations::assign(&mut value.node)?;
90 Ok(value.node)
91 }
92
93 fn expression_type(&self, expression: &Expr) -> Result<Option<ColumnType>, SQLError> {
94 let plan = crate::plan::ExpressionPlan::lower(expression.clone());
95 common_context_expression_type(&plan.scalar, self.schema, &[], self.types)
96 }
97
98 fn encode(
99 &self,
100 expression: &Expr,
101 expected: Option<&ColumnType>,
102 ) -> Result<TypedNode, SQLError> {
103 if let Some(clause) = crate::catalog::collations::expression::ast_clause(expression)? {
104 return self.collated_expression(clause, expected);
105 }
106 let value = match expression {
107 Expr::Column(column) => self.column(column, None)?,
108 Expr::QualifiedColumn { qualifier, column } => self.column(column, Some(qualifier))?,
109 Expr::QualifiedStar(qualifier) => {
110 Self::variable(self.schema.whole_row_reference(qualifier)?)
111 }
112 Expr::Literal(value) => self.literal(expression, value, expected)?,
113 Expr::RetainedLiteral(literal) => self.encode(&literal.materialize()?, expected)?,
114 Expr::TypedLiteral {
115 value,
116 ty,
117 composite_source,
118 collation_oid,
119 } => self.retained_constant(
120 value,
121 self.resolve_type(ty)?,
122 composite_source.as_deref(),
123 *collation_oid,
124 )?,
125 Expr::Binary { op, lhs, rhs } => self.binary(*op, lhs, rhs)?,
126 Expr::UnaryMinus(argument) => self.unary_minus(argument)?,
127 Expr::Array(elements) => self.array(elements, expected)?,
128 Expr::Row(elements) => self.row(elements)?,
129 Expr::CompositeRow { items, binding } => self.stored_row(items, binding)?,
130 Expr::InList {
131 expr,
132 list,
133 negated,
134 } => self.in_list(expr, list, *negated)?,
135 Expr::Case {
136 base,
137 when,
138 else_branch,
139 } => self.case(expression, base.as_deref(), when, else_branch.as_deref())?,
140 Expr::And(items) => self.boolean("and", items)?,
141 Expr::Or(items) => self.boolean("or", items)?,
142 Expr::Not(item) => self.boolean("not", std::slice::from_ref(item.as_ref()))?,
143 Expr::IsNull { expr, negated } => {
144 let (arg, is_row) = self.uncoerced_input(expr)?;
145 TypedNode {
146 node: Node::new(
147 "NULLTEST",
148 [
149 ("arg", arg.into()),
150 ("nulltesttype", i64::from(*negated).into()),
151 ("argisrow", is_row.into()),
152 ("location", (-1).into()),
153 ],
154 ),
155 ty: Some(ColumnType::Boolean),
156 }
157 }
158 Expr::Between { expr, low, high } => self.boolean(
159 "and",
160 &[
161 Expr::Binary {
162 op: BinaryOp::GreaterEqual,
163 lhs: expr.clone(),
164 rhs: low.clone(),
165 },
166 Expr::Binary {
167 op: BinaryOp::LessEqual,
168 lhs: expr.clone(),
169 rhs: high.clone(),
170 },
171 ],
172 )?,
173 Expr::Func {
174 order_syntax,
175 name,
176 binding,
177 args,
178 distinct: false,
179 order_by,
180 filter: None,
181 } if order_by.is_empty() => {
182 if let Some(value) = self.construct(expression, name, binding.as_ref(), args)? {
183 value
184 } else {
185 self.function(name, binding.as_ref(), args, *order_syntax)?
186 }
187 }
188 Expr::Cast { expr, ty, implicit } => self.cast_expression(expr, ty, *implicit)?,
189 _ => {
190 return Err(SQLError::Unsupported(
191 "catalog expression node encoding for this expression".into(),
192 ))
193 }
194 };
195 if let Some(ty) = expected {
196 Self::coerce(value, ty, 2)
197 } else {
198 Ok(value)
199 }
200 }
201
202 fn literal(
203 &self,
204 expression: &Expr,
205 value: &uqa_core::Value,
206 expected: Option<&ColumnType>,
207 ) -> Result<TypedNode, SQLError> {
208 let source = self.expression_type(expression)?;
209 let ty = source
210 .as_ref()
211 .or(expected)
212 .cloned()
213 .unwrap_or(ColumnType::Text);
214 let value = if source.is_none() {
215 if let Some(value) = crate::expr::enums::fold_unknown_literal(
216 self.types.and_then(FunctionTypeResolver::enum_labels),
217 value,
218 &ty,
219 )? {
220 value
221 } else if let uqa_core::Value::Str(text) = value {
222 if crate::expr::requires_catalog_constant_input(&ty) {
223 self.types
224 .and_then(FunctionTypeResolver::catalog_input_functions)
225 .ok_or_else(|| {
226 SQLError::Internal("catalog input functions are unavailable".into())
227 })?
228 .read_unknown_input(text, &ty)?
229 } else {
230 crate::type_resolution::coerce_common_context_value(
231 value.clone(),
232 None,
233 Some(&ty),
234 )?
235 }
236 } else {
237 crate::type_resolution::coerce_common_context_value(value.clone(), None, Some(&ty))?
238 }
239 } else {
240 crate::type_resolution::coerce_common_context_value(
241 value.clone(),
242 source.as_ref(),
243 Some(&ty),
244 )?
245 };
246 self.constant(&value, ty, None)
247 }
248
249 fn constant(
250 &self,
251 value: &uqa_core::Value,
252 ty: ColumnType,
253 source: Option<&crate::expr::composites::CompositeConstantSource>,
254 ) -> Result<TypedNode, SQLError> {
255 Ok(TypedNode {
256 node: values::constant_with_source(
257 value,
258 &ty,
259 source,
260 self.types.and_then(FunctionTypeResolver::composite_types),
261 )?,
262 ty: Some(ty),
263 })
264 }
265
266 fn retained_constant(
267 &self,
268 value: &uqa_core::Value,
269 ty: ColumnType,
270 source: Option<&crate::expr::composites::CompositeConstantSource>,
271 collation: Option<u32>,
272 ) -> Result<TypedNode, SQLError> {
273 let mut value = self.constant(value, ty, source)?;
274 if let Some(oid) = collation {
275 crate::catalog::collations::expression::validate_literal_collation(
276 value.ty.as_ref(),
277 Some(oid),
278 )?;
279 value
280 .node
281 .fields
282 .iter_mut()
283 .find(|(name, _)| name == "constcollid")
284 .expect("constant collation")
285 .1 = i64::from(oid).into();
286 }
287 Ok(value)
288 }
289
290 fn resolve_type(&self, name: &str) -> Result<ColumnType, SQLError> {
291 if let Some(resolver) = self.types {
292 if let Some(ty) = resolver.resolve_type_name(name)? {
293 return Ok(ty);
294 }
295 }
296 ColumnType::from_sql_name(name)
297 }
298
299 fn column(&self, name: &str, qualifier: Option<&str>) -> Result<TypedNode, SQLError> {
300 if let Some(ty) = self.domain_value {
301 if name != "value" || qualifier.is_some() {
302 return Err(SQLError::UnknownColumn(name.into()));
303 }
304 return Ok(TypedNode {
305 node: Node::new(
306 "COERCETODOMAINVALUE",
307 [
308 ("typeId", pg_type_oid(ty).into()),
309 ("typeMod", pg_type_modifier(ty).into()),
310 ("collation", pg_type_collation_oid(ty).into()),
311 ("location", (-1).into()),
312 ],
313 ),
314 ty: Some(ty.clone()),
315 });
316 }
317 let column = self.schema.column_reference(name, qualifier)?;
318 Ok(Self::variable(column))
319 }
320
321 fn variable(column: ColumnReference<'_>) -> TypedNode {
322 let ty = column.ty;
323 let ordinal = column.attribute_number;
324 TypedNode {
325 node: Node::new(
326 "VAR",
327 [
328 ("varno", 1.into()),
329 ("varattno", ordinal.into()),
330 ("vartype", pg_type_oid(ty).into()),
331 ("vartypmod", pg_type_modifier(ty).into()),
332 ("varcollid", column.collation_oid.into()),
333 ("varnullingrels", Field::List(vec![Field::Atom("b".into())])),
334 ("varlevelsup", 0.into()),
335 ("varreturningtype", 0.into()),
336 ("varnosyn", 1.into()),
337 ("varattnosyn", ordinal.into()),
338 ("location", (-1).into()),
339 ],
340 ),
341 ty: Some(ty.clone()),
342 }
343 }
344
345 fn binary(&self, op: BinaryOp, lhs: &Expr, rhs: &Expr) -> Result<TypedNode, SQLError> {
346 if let (Expr::Row(left), Expr::Row(right)) = (lhs, rhs) {
347 return self.row_comparison(op, left, right);
348 }
349 self.scalar_binary(op, lhs, rhs)
350 }
351
352 fn scalar_binary(&self, op: BinaryOp, lhs: &Expr, rhs: &Expr) -> Result<TypedNode, SQLError> {
353 let types = [self.expression_type(lhs)?, self.expression_type(rhs)?];
354 let [left, right, result] =
355 binary_operator_types(op, types[0].as_ref(), types[1].as_ref())?;
356 let identity = binary_operator_catalog_entry(op, [&left, &right])?;
357 let arguments = [
358 self.encode(lhs, Some(&left))?,
359 self.encode(rhs, Some(&right))?,
360 ];
361 Ok(operator_node(
362 identity.oid,
363 identity.function_oid,
364 arguments,
365 result,
366 ))
367 }
368
369 fn boolean(&self, operator: &str, args: &[Expr]) -> Result<TypedNode, SQLError> {
370 let args = args
371 .iter()
372 .map(|arg| {
373 self.encode(arg, Some(&ColumnType::Boolean))
374 .map(|value| value.node.into())
375 })
376 .collect::<Result<_, _>>()?;
377 Ok(TypedNode {
378 node: Node::new(
379 "BOOLEXPR",
380 [
381 ("boolop", Field::Atom(operator.into())),
382 ("args", Field::List(args)),
383 ("location", (-1).into()),
384 ],
385 ),
386 ty: Some(ColumnType::Boolean),
387 })
388 }
389}
390
391fn operator_node(
392 oid: i64,
393 function_oid: i64,
394 arguments: impl IntoIterator<Item = TypedNode>,
395 result: ColumnType,
396) -> TypedNode {
397 let arguments: Vec<_> = arguments.into_iter().collect();
398 TypedNode {
399 node: Node::new(
400 "OPEXPR",
401 [
402 ("opno", oid.into()),
403 ("opfuncid", function_oid.into()),
404 ("opresulttype", pg_type_oid(&result).into()),
405 ("opretset", false.into()),
406 ("opcollid", pg_type_collation_oid(&result).into()),
407 ("inputcollid", 0.into()),
408 (
409 "args",
410 Field::List(arguments.into_iter().map(|arg| arg.node.into()).collect()),
411 ),
412 ("location", (-1).into()),
413 ],
414 ),
415 ty: Some(result),
416 }
417}