1use super::{eval, time, BinaryOp, EvalContext, Expr, Result, SQLError, SQLParam, Value};
10
11use uqa_core::memory::{Produced, ProductionControl};
12
13mod comparison;
14#[cfg(test)]
15mod production_tests;
16
17pub use comparison::{
18 compare_nullable_with_control, compare_typed_values_with_control, compare_with_control,
19 eval_comparison_truth, eval_comparison_truth_with_control, type_comparison_can_fail,
20 validate_legacy_vector_comparison, value_comparison_can_fail,
21 values_equal_nullable_with_control, values_equal_with_control,
22};
23pub(super) use comparison::{eval_comparison_op, values_equal, values_equal_nullable};
24
25pub(super) fn eval_binary(
26 op: BinaryOp,
27 lhs: &Expr,
28 rhs: &Expr,
29 ctx: &EvalContext<'_>,
30) -> Result<Value> {
31 if let Some(value) = eval_binary_borrowed(op, lhs, rhs, ctx)? {
32 return Ok(value);
33 }
34 let l = eval(lhs, ctx)?;
35 let r = eval(rhs, ctx)?;
36 if is_arithmetic(op) && real_expr(lhs, ctx.params) && real_expr(rhs, ctx.params) {
37 return super::eval_float_arithmetic(op, &l, &r, super::FloatWidth::Real);
38 }
39 eval_binary_values_with_integer_width(op, &l, &r, integer_binary_width(lhs, rhs))
40}
41
42pub(super) fn is_arithmetic(op: BinaryOp) -> bool {
43 matches!(
44 op,
45 BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide
46 )
47}
48
49fn real_expr(expression: &Expr, params: &[SQLParam]) -> bool {
50 match expression {
51 Expr::Cast { ty, .. } | Expr::TypedLiteral { ty, .. } => {
52 matches!(
53 crate::ast::ColumnType::from_sql_name(ty),
54 Ok(crate::ast::ColumnType::Real)
55 )
56 }
57 Expr::Param(index) => index
58 .checked_sub(1)
59 .and_then(|index| params.get(index))
60 .and_then(SQLParam::declared_scalar_type)
61 .is_some_and(|ty| matches!(ty, crate::ast::ColumnType::Real)),
62 Expr::UnaryMinus(inner) => real_expr(inner, params),
63 Expr::Binary { op, lhs, rhs } if is_arithmetic(*op) => {
64 real_expr(lhs, params) && real_expr(rhs, params)
65 }
66 _ => false,
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
71pub enum IntegerWidth {
72 SmallInt,
73 Integer,
74 BigInt,
75}
76
77#[must_use]
78pub fn integer_width_for_literal(value: i64) -> IntegerWidth {
79 if i32::try_from(value).is_ok() {
80 IntegerWidth::Integer
81 } else {
82 IntegerWidth::BigInt
83 }
84}
85
86#[must_use]
87pub fn integer_width_for_type(ty: &str) -> Option<IntegerWidth> {
88 let ty = ty.trim();
89 [
90 (
91 IntegerWidth::SmallInt,
92 &["smallint", "int2", "pg_catalog.int2"][..],
93 ),
94 (
95 IntegerWidth::Integer,
96 &[
97 "integer",
98 "int",
99 "int4",
100 "serial",
101 "serial4",
102 "pg_catalog.int4",
103 ][..],
104 ),
105 (
106 IntegerWidth::BigInt,
107 &["bigint", "int8", "bigserial", "serial8", "pg_catalog.int8"][..],
108 ),
109 ]
110 .into_iter()
111 .find_map(|(width, names)| {
112 names
113 .iter()
114 .any(|name| ty.eq_ignore_ascii_case(name))
115 .then_some(width)
116 })
117}
118
119fn integer_expr_width(expr: &Expr) -> Option<IntegerWidth> {
120 match expr {
121 Expr::Literal(Value::Int(value)) => Some(integer_width_for_literal(*value)),
122 Expr::Cast { ty, .. } | Expr::TypedLiteral { ty, .. } => integer_width_for_type(ty),
123 Expr::Binary {
124 op: BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide,
125 lhs,
126 rhs,
127 } => Some(integer_expr_width(lhs)?.max(integer_expr_width(rhs)?)),
128 _ => None,
129 }
130}
131
132fn integer_binary_width(lhs: &Expr, rhs: &Expr) -> Option<IntegerWidth> {
133 Some(integer_expr_width(lhs)?.max(integer_expr_width(rhs)?))
134}
135
136pub fn eval_binary_values(op: BinaryOp, l: &Value, r: &Value) -> Result<Value> {
141 eval_binary_values_with_control(op, l, r, &ProductionControl::uncontrolled()).map(|value| {
142 value
143 .into_uncontrolled()
144 .expect("ordinary binary result has no reservation")
145 })
146}
147
148pub fn eval_binary_values_with_control(
150 op: BinaryOp,
151 l: &Value,
152 r: &Value,
153 control: &ProductionControl<'_>,
154) -> Result<Produced<Value>> {
155 control.check()?;
156 match op {
157 BinaryOp::Equal
158 | BinaryOp::NotEqual
159 | BinaryOp::Less
160 | BinaryOp::LessEqual
161 | BinaryOp::Greater
162 | BinaryOp::GreaterEqual => {
163 let value = eval_comparison_truth_with_control(op, l, r, control)?
164 .map(Value::Bool)
165 .unwrap_or(Value::Null);
166 control
167 .finish(value, control.empty_reservation())
168 .map_err(Into::into)
169 }
170 BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide => {
171 arith(l, r, op, control)
172 }
173 }
174}
175
176pub fn eval_binary_values_with_integer_width(
180 op: BinaryOp,
181 l: &Value,
182 r: &Value,
183 integer_width: Option<IntegerWidth>,
184) -> Result<Value> {
185 eval_binary_values_with_integer_width_with_control(
186 op,
187 l,
188 r,
189 integer_width,
190 &ProductionControl::uncontrolled(),
191 )
192 .map(|value| {
193 value
194 .into_uncontrolled()
195 .expect("ordinary width-checked result has no reservation")
196 })
197}
198
199pub fn eval_binary_values_with_integer_width_with_control(
201 op: BinaryOp,
202 l: &Value,
203 r: &Value,
204 integer_width: Option<IntegerWidth>,
205 control: &ProductionControl<'_>,
206) -> Result<Produced<Value>> {
207 let result = eval_binary_values_with_control(op, l, r, control)?;
208 let Some(integer_width) = integer_width else {
209 return Ok(result);
210 };
211 let Value::Int(value) = *result else {
212 return Ok(result);
213 };
214 let in_range = match integer_width {
215 IntegerWidth::SmallInt => i16::try_from(value).is_ok(),
216 IntegerWidth::Integer => i32::try_from(value).is_ok(),
217 IntegerWidth::BigInt => true,
218 };
219 if in_range {
220 Ok(result)
221 } else {
222 Err(out_of_range(match integer_width {
223 IntegerWidth::SmallInt => "smallint",
224 IntegerWidth::Integer => "integer",
225 IntegerWidth::BigInt => "bigint",
226 }))
227 }
228}
229
230pub(super) enum EvalOperand<'a> {
231 Borrowed(&'a Value),
232 Owned(Value),
233}
234
235impl EvalOperand<'_> {
236 fn as_value(&self) -> &Value {
237 match self {
238 Self::Borrowed(value) => value,
239 Self::Owned(value) => value,
240 }
241 }
242}
243
244pub(super) fn eval_binary_borrowed(
245 op: BinaryOp,
246 lhs: &Expr,
247 rhs: &Expr,
248 ctx: &EvalContext<'_>,
249) -> Result<Option<Value>> {
250 if !matches!(
251 op,
252 BinaryOp::Equal
253 | BinaryOp::NotEqual
254 | BinaryOp::Less
255 | BinaryOp::LessEqual
256 | BinaryOp::Greater
257 | BinaryOp::GreaterEqual
258 ) {
259 return Ok(None);
260 }
261 let Some(l) = eval_operand_borrowed(lhs, ctx)? else {
262 return Ok(None);
263 };
264 let Some(r) = eval_operand_borrowed(rhs, ctx)? else {
265 return Ok(None);
266 };
267 let l = l.as_value();
268 let r = r.as_value();
269 Ok(Some(eval_comparison_op(op, l, r)?))
270}
271
272pub(super) fn eval_operand_borrowed<'a>(
273 expr: &Expr,
274 ctx: &EvalContext<'a>,
275) -> Result<Option<EvalOperand<'a>>> {
276 match expr {
277 Expr::Literal(value) => Ok(Some(EvalOperand::Owned(value.clone()))),
278 Expr::Param(i) => match i.checked_sub(1).and_then(|index| ctx.params.get(index)) {
279 Some(SQLParam::Scalar(value) | SQLParam::TypedScalar { value, .. }) => {
280 Ok(Some(EvalOperand::Borrowed(value)))
281 }
282 Some(SQLParam::Vector(_)) | Some(SQLParam::Tensor(_)) => Ok(None),
283 None => Err(SQLError::MissingParam(*i)),
284 },
285 Expr::Column(name) => {
286 if ctx.row_lookup()?.column_is_ambiguous(name) {
287 return Err(SQLError::AmbiguousColumn(name.clone()));
288 }
289 Ok(Some(match ctx.row_lookup()?.column(name) {
290 Some(value) => EvalOperand::Borrowed(value),
291 None => EvalOperand::Owned(Value::Null),
292 }))
293 }
294 Expr::QualifiedColumn { qualifier, column } => {
295 if ctx
296 .row_lookup()?
297 .qualified_column_is_ambiguous(qualifier, column)
298 {
299 return Err(SQLError::AmbiguousColumn(format!("{qualifier}.{column}")));
300 }
301 Ok(Some(
302 match ctx.row_lookup()?.qualified_column(qualifier, column) {
303 Some(value) => EvalOperand::Borrowed(value),
304 None => EvalOperand::Owned(Value::Null),
305 },
306 ))
307 }
308 _ => Ok(None),
309 }
310}
311
312pub fn truthy(v: &Value) -> bool {
314 match v {
315 Value::Null => false,
316 Value::Bool(b) => *b,
317 Value::Int(n) => *n != 0,
318 Value::Float(f) => *f != 0.0,
319 Value::Decimal(d) => !d.is_zero(),
320 Value::Str(s) | Value::FixedChar(s) => super::parse_boolean_input(s) == Some(true),
321 _ => true,
322 }
323}
324
325pub(crate) fn division_by_zero() -> SQLError {
327 SQLError::Routine {
328 sqlstate: "22012".into(),
329 message: "division by zero".into(),
330 }
331}
332
333pub(crate) fn datetime_out_of_range(type_name: &str) -> SQLError {
335 SQLError::Routine {
336 sqlstate: "22008".into(),
337 message: format!("{type_name} out of range"),
338 }
339}
340
341pub(crate) fn out_of_range(type_name: &str) -> SQLError {
343 SQLError::Routine {
344 sqlstate: "22003".into(),
345 message: format!("{type_name} out of range"),
346 }
347}
348
349fn arith(
350 a: &Value,
351 b: &Value,
352 op: BinaryOp,
353 control: &ProductionControl<'_>,
354) -> Result<Produced<Value>> {
355 control.check()?;
356 if matches!(a, Value::Null) || matches!(b, Value::Null) {
358 return control
359 .finish(Value::Null, control.empty_reservation())
360 .map_err(Into::into);
361 }
362 if let (Value::Int(li), Value::Int(ri)) = (a, b) {
368 let out = match op {
369 BinaryOp::Add => li.checked_add(*ri),
370 BinaryOp::Subtract => li.checked_sub(*ri),
371 BinaryOp::Multiply => li.checked_mul(*ri),
372 BinaryOp::Divide => {
373 if *ri == 0 {
374 return Err(division_by_zero());
375 }
376 li.checked_div(*ri)
378 }
379 _ => {
380 return Err(SQLError::Internal(format!(
381 "non-arithmetic operator {op:?} reached integer arithmetic"
382 )))
383 }
384 };
385 let value = out.map(Value::Int).ok_or_else(|| out_of_range("bigint"))?;
386 return control
387 .finish(value, control.empty_reservation())
388 .map_err(Into::into);
389 }
390 if matches!(op, BinaryOp::Subtract)
391 && matches!(a, Value::JsonB(_) | Value::Map(_) | Value::List(_))
392 {
393 if let Some(value) = super::json::json_delete_values_with_control(a, b, control)? {
394 return Ok(value);
395 }
396 }
397 if matches!(a, Value::Temporal(_)) || matches!(b, Value::Temporal(_)) {
398 let value = time::temporal_arith_with_control(a, b, op, control)?;
399 return control
400 .finish(value, control.empty_reservation())
401 .map_err(Into::into);
402 }
403 let has_decimal = matches!(a, Value::Decimal(_)) || matches!(b, Value::Decimal(_));
404 let has_float = matches!(a, Value::Float(_)) || matches!(b, Value::Float(_));
405 if has_decimal && !has_float {
409 return decimal_arith(a, b, op, control);
410 }
411 let value = super::eval_float_arithmetic_with_control(
412 op,
413 a,
414 b,
415 super::FloatWidth::DoublePrecision,
416 control,
417 )?;
418 control
419 .finish(value, control.empty_reservation())
420 .map_err(Into::into)
421}
422
423fn decimal_arith(
424 a: &Value,
425 b: &Value,
426 op: BinaryOp,
427 control: &ProductionControl<'_>,
428) -> Result<Produced<Value>> {
429 let left = super::conversion::to_decimal_with_control(a, control)?;
430 let right = super::conversion::to_decimal_with_control(b, control)?;
431 let value = match op {
432 BinaryOp::Add => left.checked_add_with_control(&right, control)?,
433 BinaryOp::Subtract => left.checked_sub_with_control(&right, control)?,
434 BinaryOp::Multiply => left.checked_mul_with_control(&right, control)?,
435 BinaryOp::Divide => {
436 if right.is_zero() {
437 return Err(division_by_zero());
438 }
439 left.checked_div_postgres_with_control(&right, control)?
440 }
441 _ => {
442 return Err(SQLError::Internal(format!(
443 "non-arithmetic operator {op:?} reached decimal arithmetic"
444 )))
445 }
446 }
447 .ok_or_else(|| out_of_range("numeric"))?;
448 let (value, memory) = value.into_parts();
449 control
450 .finish(Value::Decimal(value), memory)
451 .map_err(Into::into)
452}