1use alloc::boxed::Box;
19use alloc::format;
20use alloc::string::{String, ToString};
21use alloc::vec::Vec;
22
23use spg_sql::ast::{BinOp, CastTarget, ColumnName, Expr, Literal, UnOp};
24use spg_storage::{ColumnSchema, DataType, Row, TsLexeme, TsQueryAst, Value};
25
26#[derive(Debug, Clone)]
30pub struct EvalContext<'a> {
31 pub columns: &'a [ColumnSchema],
32 pub table_alias: Option<&'a str>,
33 pub params: &'a [Value],
38 pub default_text_search_config: Option<&'a str>,
45}
46
47impl<'a> EvalContext<'a> {
48 pub const fn new(columns: &'a [ColumnSchema], table_alias: Option<&'a str>) -> Self {
49 Self {
50 columns,
51 table_alias,
52 params: &[],
53 default_text_search_config: None,
54 }
55 }
56
57 #[must_use]
61 pub const fn with_params(mut self, params: &'a [Value]) -> Self {
62 self.params = params;
63 self
64 }
65
66 #[must_use]
70 pub const fn with_default_text_search_config(mut self, cfg: Option<&'a str>) -> Self {
71 self.default_text_search_config = cfg;
72 self
73 }
74}
75
76#[derive(Debug, Clone, PartialEq)]
77pub enum EvalError {
78 ColumnNotFound {
79 name: String,
80 },
81 UnknownQualifier {
82 qualifier: String,
83 },
84 DivisionByZero,
85 TypeMismatch {
86 detail: String,
87 },
88 PlaceholderOutOfRange {
92 n: u16,
93 bound: u16,
94 },
95}
96
97impl core::fmt::Display for EvalError {
98 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
99 match self {
100 Self::ColumnNotFound { name } => write!(f, "column not found: {name}"),
101 Self::UnknownQualifier { qualifier } => {
102 write!(f, "unknown table qualifier: {qualifier}")
103 }
104 Self::DivisionByZero => f.write_str("division by zero"),
105 Self::TypeMismatch { detail } => write!(f, "type mismatch: {detail}"),
106 Self::PlaceholderOutOfRange { n, bound } => write!(
107 f,
108 "parameter ${n} referenced but only {bound} bound by client"
109 ),
110 }
111 }
112}
113
114pub fn eval_expr(expr: &Expr, row: &Row, ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
115 match expr {
116 Expr::Literal(l) => Ok(literal_to_value(l)),
117 Expr::Column(c) => resolve_column(c, row, ctx),
118 Expr::Placeholder(n) => {
119 let idx = usize::from(*n).saturating_sub(1);
120 ctx.params
121 .get(idx)
122 .cloned()
123 .ok_or_else(|| EvalError::PlaceholderOutOfRange {
124 n: *n,
125 bound: u16::try_from(ctx.params.len()).unwrap_or(u16::MAX),
126 })
127 }
128 Expr::Unary { op, expr } => {
129 let v = eval_expr(expr, row, ctx)?;
130 apply_unary(*op, v)
131 }
132 Expr::Binary { lhs, op, rhs } => {
133 let l = eval_expr(lhs, row, ctx)?;
134 let r = eval_expr(rhs, row, ctx)?;
135 apply_binary(*op, l, r)
136 }
137 Expr::Cast { expr, target } => {
138 let v = eval_expr(expr, row, ctx)?;
139 cast_value(v, *target)
140 }
141 Expr::IsNull { expr, negated } => {
142 let v = eval_expr(expr, row, ctx)?;
143 let is_null = matches!(v, Value::Null);
144 Ok(Value::Bool(if *negated { !is_null } else { is_null }))
145 }
146 Expr::FunctionCall { name, args } => {
147 let evaluated: Result<Vec<Value>, _> =
148 args.iter().map(|a| eval_expr(a, row, ctx)).collect();
149 apply_function(name, &evaluated?, ctx)
150 }
151 Expr::Like {
152 expr,
153 pattern,
154 negated,
155 } => {
156 let v = eval_expr(expr, row, ctx)?;
157 let p = eval_expr(pattern, row, ctx)?;
158 let (text, pat) = match (v, p) {
160 (Value::Null, _) | (_, Value::Null) => return Ok(Value::Null),
161 (Value::Text(a), Value::Text(b)) => (a, b),
162 (Value::Text(_), other) | (other, _) => {
163 return Err(EvalError::TypeMismatch {
164 detail: format!("LIKE requires text operands, got {:?}", other.data_type()),
165 });
166 }
167 };
168 let m = like_match(&text, &pat);
169 Ok(Value::Bool(if *negated { !m } else { m }))
170 }
171 Expr::Extract { field, source } => {
172 let v = eval_expr(source, row, ctx)?;
173 extract_field(*field, &v)
174 }
175 Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
179 Err(EvalError::TypeMismatch {
180 detail: "subquery reached row eval — engine resolver bug".into(),
181 })
182 }
183 Expr::WindowFunction { .. } => Err(EvalError::TypeMismatch {
188 detail: "window function reached row eval — engine rewrite bug".into(),
189 }),
190 Expr::Array(items) => {
196 let mut materialised: Vec<Value> = Vec::with_capacity(items.len());
197 for elem in items {
198 materialised.push(eval_expr(elem, row, ctx)?);
199 }
200 let mut has_text = false;
201 let mut has_bigint = false;
202 let mut has_int = false;
203 for v in &materialised {
204 match v {
205 Value::Null => {}
206 Value::Int(_) | Value::SmallInt(_) => has_int = true,
207 Value::BigInt(_) => has_bigint = true,
208 Value::Text(_) | Value::Json(_) => has_text = true,
209 _ => has_text = true,
210 }
211 }
212 if has_text || (!has_int && !has_bigint) {
213 let out: Vec<Option<String>> = materialised
214 .into_iter()
215 .map(|v| match v {
216 Value::Null => None,
217 Value::Text(s) | Value::Json(s) => Some(s),
218 other => Some(value_to_text_for_array(&other)),
219 })
220 .collect();
221 return Ok(Value::TextArray(out));
222 }
223 if has_bigint {
224 let out: Vec<Option<i64>> = materialised
225 .into_iter()
226 .map(|v| match v {
227 Value::Null => None,
228 Value::Int(n) => Some(i64::from(n)),
229 Value::SmallInt(n) => Some(i64::from(n)),
230 Value::BigInt(n) => Some(n),
231 _ => unreachable!(),
232 })
233 .collect();
234 return Ok(Value::BigIntArray(out));
235 }
236 let out: Vec<Option<i32>> = materialised
237 .into_iter()
238 .map(|v| match v {
239 Value::Null => None,
240 Value::Int(n) => Some(n),
241 Value::SmallInt(n) => Some(i32::from(n)),
242 _ => unreachable!(),
243 })
244 .collect();
245 Ok(Value::IntArray(out))
246 }
247 Expr::ArraySubscript { target, index } => {
250 let target_v = eval_expr(target, row, ctx)?;
251 let idx_v = eval_expr(index, row, ctx)?;
252 if matches!(target_v, Value::Null) || matches!(idx_v, Value::Null) {
253 return Ok(Value::Null);
254 }
255 let i: i64 = match idx_v {
256 Value::Int(n) => i64::from(n),
257 Value::BigInt(n) => n,
258 Value::SmallInt(n) => i64::from(n),
259 other => {
260 return Err(EvalError::TypeMismatch {
261 detail: format!(
262 "array subscript must be integer, got {:?}",
263 other.data_type()
264 ),
265 });
266 }
267 };
268 if i < 1 {
269 return Ok(Value::Null);
270 }
271 let pos = (i - 1) as usize;
272 match target_v {
273 Value::TextArray(items) => match items.get(pos) {
274 Some(Some(s)) => Ok(Value::Text(s.clone())),
275 Some(None) | None => Ok(Value::Null),
276 },
277 Value::IntArray(items) => match items.get(pos) {
278 Some(Some(n)) => Ok(Value::Int(*n)),
279 Some(None) | None => Ok(Value::Null),
280 },
281 Value::BigIntArray(items) => match items.get(pos) {
282 Some(Some(n)) => Ok(Value::BigInt(*n)),
283 Some(None) | None => Ok(Value::Null),
284 },
285 other => Err(EvalError::TypeMismatch {
286 detail: format!(
287 "subscript target must be an array, got {:?}",
288 other.data_type()
289 ),
290 }),
291 }
292 }
293 Expr::AnyAll {
299 expr,
300 op,
301 array,
302 is_any,
303 } => {
304 let lhs = eval_expr(expr, row, ctx)?;
305 let arr = eval_expr(array, row, ctx)?;
306 if matches!(arr, Value::Null) {
307 return Ok(Value::Null);
308 }
309 let elems: Vec<Option<Value>> = match arr {
310 Value::TextArray(items) => items.into_iter().map(|o| o.map(Value::Text)).collect(),
311 Value::IntArray(items) => items.into_iter().map(|o| o.map(Value::Int)).collect(),
312 Value::BigIntArray(items) => {
313 items.into_iter().map(|o| o.map(Value::BigInt)).collect()
314 }
315 other => {
316 return Err(EvalError::TypeMismatch {
317 detail: format!(
318 "ANY/ALL right-hand side must be an array, got {:?}",
319 other.data_type()
320 ),
321 });
322 }
323 };
324 let mut saw_null = matches!(lhs, Value::Null);
325 let mut saw_match = false;
326 let mut saw_mismatch = false;
327 for elem in elems {
328 let elem_v = match elem {
329 Some(v) => v,
330 None => {
331 saw_null = true;
332 continue;
333 }
334 };
335 if matches!(lhs, Value::Null) {
336 saw_null = true;
337 continue;
338 }
339 match apply_binary(*op, lhs.clone(), elem_v) {
340 Ok(Value::Bool(true)) => saw_match = true,
341 Ok(Value::Bool(false)) => saw_mismatch = true,
342 Ok(Value::Null) => saw_null = true,
343 Ok(other) => {
344 return Err(EvalError::TypeMismatch {
345 detail: format!(
346 "ANY/ALL comparison didn't return Bool: {:?}",
347 other.data_type()
348 ),
349 });
350 }
351 Err(e) => return Err(e),
352 }
353 }
354 let result = if *is_any {
355 if saw_match {
356 Value::Bool(true)
357 } else if saw_null {
358 Value::Null
359 } else {
360 Value::Bool(false)
361 }
362 } else if saw_mismatch {
363 Value::Bool(false)
364 } else if saw_null {
365 Value::Null
366 } else {
367 Value::Bool(true)
368 };
369 Ok(result)
370 }
371 Expr::Case {
377 operand,
378 branches,
379 else_branch,
380 } => {
381 let operand_value = match operand {
382 Some(o) => Some(eval_expr(o, row, ctx)?),
383 None => None,
384 };
385 for (when_expr, then_expr) in branches {
386 let when_value = eval_expr(when_expr, row, ctx)?;
387 let matched = match &operand_value {
388 None => matches!(when_value, Value::Bool(true)),
389 Some(op_v) => matches!(
390 apply_binary(spg_sql::ast::BinOp::Eq, op_v.clone(), when_value)?,
391 Value::Bool(true)
392 ),
393 };
394 if matched {
395 return eval_expr(then_expr, row, ctx);
396 }
397 }
398 match else_branch {
399 Some(e) => eval_expr(e, row, ctx),
400 None => Ok(Value::Null),
401 }
402 }
403 }
404}
405
406fn value_to_text_for_array(v: &Value) -> String {
413 match v {
414 Value::Text(s) | Value::Json(s) => s.clone(),
415 Value::Int(n) => n.to_string(),
416 Value::BigInt(n) => n.to_string(),
417 Value::SmallInt(n) => n.to_string(),
418 Value::Bool(b) => {
419 if *b {
420 "true".into()
421 } else {
422 "false".into()
423 }
424 }
425 Value::Float(x) => format!("{x}"),
426 Value::Date(d) => format_date(*d),
427 Value::Timestamp(t) => format_timestamp(*t),
428 Value::Numeric { scaled, scale } => format_numeric(*scaled, *scale),
429 _ => format!("{v:?}"),
430 }
431}
432
433fn extract_field(field: spg_sql::ast::ExtractField, v: &Value) -> Result<Value, EvalError> {
437 use spg_sql::ast::ExtractField as F;
438 if matches!(v, Value::Null) {
439 return Ok(Value::Null);
440 }
441 if let Value::Interval { months, micros } = *v {
445 let years = months / 12;
446 let mons = months % 12;
447 let secs_total = micros / 1_000_000;
448 let frac = micros % 1_000_000;
449 let result = match field {
450 F::Year => i64::from(years),
451 F::Month => i64::from(mons),
452 F::Day => micros / 86_400_000_000,
453 F::Hour => (secs_total / 3600) % 24,
454 F::Minute => (secs_total / 60) % 60,
455 F::Second => secs_total % 60,
456 F::Microsecond => (secs_total % 60) * 1_000_000 + frac,
457 };
458 return Ok(Value::BigInt(result));
459 }
460 let (days, day_micros) = match *v {
461 Value::Date(d) => (d, 0_i64),
462 Value::Timestamp(t) => {
463 let days = t.div_euclid(86_400_000_000);
464 let day_micros = t.rem_euclid(86_400_000_000);
465 (i32::try_from(days).unwrap_or(i32::MAX), day_micros)
466 }
467 _ => {
468 return Err(EvalError::TypeMismatch {
469 detail: format!(
470 "EXTRACT requires DATE / TIMESTAMP / INTERVAL, got {:?}",
471 v.data_type()
472 ),
473 });
474 }
475 };
476 let (y, m, d) = civil_components(days);
477 let secs = day_micros / 1_000_000;
478 let hh = secs / 3600;
479 let mm = (secs / 60) % 60;
480 let ss = secs % 60;
481 let frac = day_micros % 1_000_000;
482 let result = match field {
483 F::Year => i64::from(y),
484 F::Month => i64::from(m),
485 F::Day => i64::from(d),
486 F::Hour => hh,
487 F::Minute => mm,
488 F::Second => ss,
489 F::Microsecond => ss * 1_000_000 + frac,
490 };
491 Ok(Value::BigInt(result))
492}
493
494fn civil_components(days: i32) -> (i32, u32, u32) {
497 civil_from_days(days)
498}
499
500fn like_match(text: &str, pattern: &str) -> bool {
505 let text: Vec<char> = text.chars().collect();
506 let pat: Vec<char> = pattern.chars().collect();
507 like_match_inner(&text, 0, &pat, 0)
508}
509
510fn like_match_inner(text: &[char], mut ti: usize, pat: &[char], mut pi: usize) -> bool {
511 while pi < pat.len() {
512 match pat[pi] {
513 '%' => {
514 while pi < pat.len() && pat[pi] == '%' {
516 pi += 1;
517 }
518 if pi == pat.len() {
519 return true;
520 }
521 for k in ti..=text.len() {
522 if like_match_inner(text, k, pat, pi) {
523 return true;
524 }
525 }
526 return false;
527 }
528 '_' => {
529 if ti >= text.len() {
530 return false;
531 }
532 ti += 1;
533 pi += 1;
534 }
535 '\\' if pi + 1 < pat.len() => {
536 let want = pat[pi + 1];
537 if ti >= text.len() || text[ti] != want {
538 return false;
539 }
540 ti += 1;
541 pi += 2;
542 }
543 c => {
544 if ti >= text.len() || text[ti] != c {
545 return false;
546 }
547 ti += 1;
548 pi += 1;
549 }
550 }
551 }
552 ti == text.len()
553}
554
555fn apply_function(name: &str, args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
558 match name.to_ascii_lowercase().as_str() {
559 "length" => {
560 if args.len() != 1 {
561 return Err(EvalError::TypeMismatch {
562 detail: format!("length() takes 1 arg, got {}", args.len()),
563 });
564 }
565 match &args[0] {
566 Value::Null => Ok(Value::Null),
567 Value::Text(s) => {
568 let n = i32::try_from(s.chars().count()).unwrap_or(i32::MAX);
569 Ok(Value::Int(n))
570 }
571 Value::Bytes(b) => {
576 let n = i32::try_from(b.len()).unwrap_or(i32::MAX);
577 Ok(Value::Int(n))
578 }
579 other => Err(EvalError::TypeMismatch {
580 detail: format!("length() needs text or bytea, got {:?}", other.data_type()),
581 }),
582 }
583 }
584 "octet_length" => {
588 if args.len() != 1 {
589 return Err(EvalError::TypeMismatch {
590 detail: format!("octet_length() takes 1 arg, got {}", args.len()),
591 });
592 }
593 match &args[0] {
594 Value::Null => Ok(Value::Null),
595 Value::Text(s) => {
596 let n = i32::try_from(s.len()).unwrap_or(i32::MAX);
597 Ok(Value::Int(n))
598 }
599 Value::Bytes(b) => {
600 let n = i32::try_from(b.len()).unwrap_or(i32::MAX);
601 Ok(Value::Int(n))
602 }
603 other => Err(EvalError::TypeMismatch {
604 detail: format!(
605 "octet_length() needs text or bytea, got {:?}",
606 other.data_type()
607 ),
608 }),
609 }
610 }
611 "array_length" => {
618 if args.len() != 2 {
619 return Err(EvalError::TypeMismatch {
620 detail: format!("array_length() takes 2 args, got {}", args.len()),
621 });
622 }
623 if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
624 return Ok(Value::Null);
625 }
626 let len = match &args[0] {
627 Value::TextArray(items) => items.len(),
628 Value::IntArray(items) => items.len(),
629 Value::BigIntArray(items) => items.len(),
630 _ => {
631 return Err(EvalError::TypeMismatch {
632 detail: format!(
633 "array_length() first arg must be an array, got {:?}",
634 args[0].data_type()
635 ),
636 });
637 }
638 };
639 let dim: i64 = match args[1] {
640 Value::Int(n) => i64::from(n),
641 Value::BigInt(n) => n,
642 Value::SmallInt(n) => i64::from(n),
643 _ => {
644 return Err(EvalError::TypeMismatch {
645 detail: format!(
646 "array_length() second arg must be integer, got {:?}",
647 args[1].data_type()
648 ),
649 });
650 }
651 };
652 if dim != 1 {
653 return Ok(Value::Null);
654 }
655 let n = i32::try_from(len).unwrap_or(i32::MAX);
656 Ok(Value::Int(n))
657 }
658 "array_position" => {
663 if args.len() != 2 {
664 return Err(EvalError::TypeMismatch {
665 detail: format!("array_position() takes 2 args, got {}", args.len()),
666 });
667 }
668 if matches!(args[0], Value::Null) {
669 return Ok(Value::Null);
670 }
671 if matches!(args[1], Value::Null) {
672 return Ok(Value::Null);
673 }
674 match (&args[0], &args[1]) {
675 (Value::TextArray(items), Value::Text(needle)) => {
676 for (idx, item) in items.iter().enumerate() {
677 if let Some(s) = item
678 && s == needle
679 {
680 return Ok(Value::Int(i32::try_from(idx + 1).unwrap_or(i32::MAX)));
681 }
682 }
683 Ok(Value::Null)
684 }
685 (Value::IntArray(items), needle_v)
686 if matches!(
687 needle_v,
688 Value::Int(_) | Value::SmallInt(_) | Value::BigInt(_)
689 ) =>
690 {
691 let needle: i64 = match *needle_v {
692 Value::Int(n) => i64::from(n),
693 Value::SmallInt(n) => i64::from(n),
694 Value::BigInt(n) => n,
695 _ => unreachable!(),
696 };
697 for (idx, item) in items.iter().enumerate() {
698 if let Some(n) = item
699 && i64::from(*n) == needle
700 {
701 return Ok(Value::Int(i32::try_from(idx + 1).unwrap_or(i32::MAX)));
702 }
703 }
704 Ok(Value::Null)
705 }
706 (Value::BigIntArray(items), needle_v)
707 if matches!(
708 needle_v,
709 Value::Int(_) | Value::SmallInt(_) | Value::BigInt(_)
710 ) =>
711 {
712 let needle: i64 = match *needle_v {
713 Value::Int(n) => i64::from(n),
714 Value::SmallInt(n) => i64::from(n),
715 Value::BigInt(n) => n,
716 _ => unreachable!(),
717 };
718 for (idx, item) in items.iter().enumerate() {
719 if let Some(n) = item
720 && *n == needle
721 {
722 return Ok(Value::Int(i32::try_from(idx + 1).unwrap_or(i32::MAX)));
723 }
724 }
725 Ok(Value::Null)
726 }
727 (
728 arr @ (Value::TextArray(_) | Value::IntArray(_) | Value::BigIntArray(_)),
729 other,
730 ) => Err(EvalError::TypeMismatch {
731 detail: format!(
732 "array_position() needle type {:?} doesn't match array {:?}",
733 other.data_type(),
734 arr.data_type()
735 ),
736 }),
737 (other, _) => Err(EvalError::TypeMismatch {
738 detail: format!(
739 "array_position() first arg must be an array, got {:?}",
740 other.data_type()
741 ),
742 }),
743 }
744 }
745 "substring" => {
753 if !matches!(args.len(), 2 | 3) {
754 return Err(EvalError::TypeMismatch {
755 detail: format!("substring() takes 2 or 3 args, got {}", args.len()),
756 });
757 }
758 if args.iter().any(|a| matches!(a, Value::Null)) {
759 return Ok(Value::Null);
760 }
761 let start: i64 = match args[1] {
762 Value::Int(n) => i64::from(n),
763 Value::BigInt(n) => n,
764 Value::SmallInt(n) => i64::from(n),
765 _ => {
766 return Err(EvalError::TypeMismatch {
767 detail: format!(
768 "substring() start must be integer, got {:?}",
769 args[1].data_type()
770 ),
771 });
772 }
773 };
774 let length: Option<i64> = if args.len() == 3 {
775 match args[2] {
776 Value::Int(n) => Some(i64::from(n)),
777 Value::BigInt(n) => Some(n),
778 Value::SmallInt(n) => Some(i64::from(n)),
779 _ => {
780 return Err(EvalError::TypeMismatch {
781 detail: format!(
782 "substring() length must be integer, got {:?}",
783 args[2].data_type()
784 ),
785 });
786 }
787 }
788 } else {
789 None
790 };
791 let (effective_start, effective_length): (i64, Option<i64>) = match length {
794 Some(len) => {
795 let end = start.saturating_add(len);
796 if end <= 1 || len < 0 {
797 return Ok(match &args[0] {
798 Value::Text(_) => Value::Text(String::new()),
799 Value::Bytes(_) => Value::Bytes(Vec::new()),
800 other => {
801 return Err(EvalError::TypeMismatch {
802 detail: format!(
803 "substring() needs text or bytea, got {:?}",
804 other.data_type()
805 ),
806 });
807 }
808 });
809 }
810 let eff_start = start.max(1);
811 let eff_len = end - eff_start;
812 (eff_start, Some(eff_len.max(0)))
813 }
814 None => (start.max(1), None),
815 };
816 match &args[0] {
817 Value::Text(s) => {
818 let chars: Vec<char> = s.chars().collect();
820 let skip = (effective_start - 1) as usize;
821 if skip >= chars.len() {
822 return Ok(Value::Text(String::new()));
823 }
824 let take = match effective_length {
825 Some(n) => (n as usize).min(chars.len() - skip),
826 None => chars.len() - skip,
827 };
828 Ok(Value::Text(chars[skip..skip + take].iter().collect()))
829 }
830 Value::Bytes(b) => {
831 let skip = (effective_start - 1) as usize;
832 if skip >= b.len() {
833 return Ok(Value::Bytes(Vec::new()));
834 }
835 let take = match effective_length {
836 Some(n) => (n as usize).min(b.len() - skip),
837 None => b.len() - skip,
838 };
839 Ok(Value::Bytes(b[skip..skip + take].to_vec()))
840 }
841 other => Err(EvalError::TypeMismatch {
842 detail: format!(
843 "substring() needs text or bytea, got {:?}",
844 other.data_type()
845 ),
846 }),
847 }
848 }
849 "position" => {
857 if args.len() != 2 {
858 return Err(EvalError::TypeMismatch {
859 detail: format!("position() takes 2 args, got {}", args.len()),
860 });
861 }
862 if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
863 return Ok(Value::Null);
864 }
865 match (&args[0], &args[1]) {
866 (Value::Text(needle), Value::Text(haystack)) => {
867 if needle.is_empty() {
868 return Ok(Value::Int(1));
869 }
870 let h_chars: Vec<char> = haystack.chars().collect();
872 let n_chars: Vec<char> = needle.chars().collect();
873 if n_chars.len() > h_chars.len() {
874 return Ok(Value::Int(0));
875 }
876 for i in 0..=h_chars.len() - n_chars.len() {
877 if h_chars[i..i + n_chars.len()] == n_chars[..] {
878 return Ok(Value::Int(i32::try_from(i + 1).unwrap_or(i32::MAX)));
879 }
880 }
881 Ok(Value::Int(0))
882 }
883 (Value::Bytes(needle), Value::Bytes(haystack)) => {
884 if needle.is_empty() {
885 return Ok(Value::Int(1));
886 }
887 if needle.len() > haystack.len() {
888 return Ok(Value::Int(0));
889 }
890 for i in 0..=haystack.len() - needle.len() {
891 if &haystack[i..i + needle.len()] == needle.as_slice() {
892 return Ok(Value::Int(i32::try_from(i + 1).unwrap_or(i32::MAX)));
893 }
894 }
895 Ok(Value::Int(0))
896 }
897 (a, b) => Err(EvalError::TypeMismatch {
898 detail: format!(
899 "position() operands must both be text or both bytea, got {:?} and {:?}",
900 a.data_type(),
901 b.data_type()
902 ),
903 }),
904 }
905 }
906 "upper" => {
907 if args.len() != 1 {
908 return Err(EvalError::TypeMismatch {
909 detail: format!("upper() takes 1 arg, got {}", args.len()),
910 });
911 }
912 match &args[0] {
913 Value::Null => Ok(Value::Null),
914 Value::Text(s) => Ok(Value::Text(s.to_uppercase())),
915 other => Err(EvalError::TypeMismatch {
916 detail: format!("upper() needs text, got {:?}", other.data_type()),
917 }),
918 }
919 }
920 "lower" => {
921 if args.len() != 1 {
922 return Err(EvalError::TypeMismatch {
923 detail: format!("lower() takes 1 arg, got {}", args.len()),
924 });
925 }
926 match &args[0] {
927 Value::Null => Ok(Value::Null),
928 Value::Text(s) => Ok(Value::Text(s.to_lowercase())),
929 other => Err(EvalError::TypeMismatch {
930 detail: format!("lower() needs text, got {:?}", other.data_type()),
931 }),
932 }
933 }
934 "abs" => {
935 if args.len() != 1 {
936 return Err(EvalError::TypeMismatch {
937 detail: format!("abs() takes 1 arg, got {}", args.len()),
938 });
939 }
940 match &args[0] {
941 Value::Null => Ok(Value::Null),
942 Value::Int(n) => Ok(Value::Int(n.wrapping_abs())),
943 Value::BigInt(n) => Ok(Value::BigInt(n.wrapping_abs())),
944 Value::Float(x) => Ok(Value::Float(x.abs())),
945 other => Err(EvalError::TypeMismatch {
946 detail: format!("abs() needs numeric, got {:?}", other.data_type()),
947 }),
948 }
949 }
950 "coalesce" => {
951 for a in args {
952 if !matches!(a, Value::Null) {
953 return Ok(a.clone());
954 }
955 }
956 Ok(Value::Null)
957 }
958 "date_trunc" => date_trunc(args),
959 "date_part" => date_part(args),
960 "age" => age(args),
961 "to_char" => to_char(args),
962 "encode" => encode_text(args),
964 "decode" => decode_text(args),
965 "error_on_null" => error_on_null(args),
966 "to_tsvector" => fts_to_tsvector(args, ctx),
971 "plainto_tsquery" => fts_plainto_tsquery(args, ctx),
972 "phraseto_tsquery" => fts_phraseto_tsquery(args, ctx),
973 "websearch_to_tsquery" => fts_websearch_to_tsquery(args, ctx),
974 "to_tsquery" => fts_to_tsquery(args, ctx),
975 "ts_rank" => fts_ts_rank(args),
978 "ts_rank_cd" => fts_ts_rank_cd(args),
979 "set_config" => Ok(args.get(1).cloned().unwrap_or(Value::Null)),
984 "current_setting" => Ok(Value::Text(String::new())),
985 "pg_get_serial_sequence" | "pg_get_constraintdef" | "pg_get_indexdef" => Ok(Value::Null),
991 "version" => Ok(Value::Text("PostgreSQL 16 (SPG-compat)".into())),
992 "nextval" | "currval" | "lastval" => Ok(Value::Null),
999 "setval" => Ok(args.first().cloned().unwrap_or(Value::Null)),
1000 "similarity" => {
1005 if args.len() != 2 {
1006 return Err(EvalError::TypeMismatch {
1007 detail: format!("similarity() takes 2 args, got {}", args.len()),
1008 });
1009 }
1010 if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
1011 return Ok(Value::Null);
1012 }
1013 let a = match &args[0] {
1014 Value::Text(s) => s.as_str(),
1015 other => {
1016 return Err(EvalError::TypeMismatch {
1017 detail: format!("similarity() needs text, got {:?}", other.data_type()),
1018 });
1019 }
1020 };
1021 let b = match &args[1] {
1022 Value::Text(s) => s.as_str(),
1023 other => {
1024 return Err(EvalError::TypeMismatch {
1025 detail: format!("similarity() needs text, got {:?}", other.data_type()),
1026 });
1027 }
1028 };
1029 Ok(Value::Float(spg_storage::trgm::similarity(a, b)))
1032 }
1033 "show_trgm" => {
1034 if args.len() != 1 {
1035 return Err(EvalError::TypeMismatch {
1036 detail: format!("show_trgm() takes 1 arg, got {}", args.len()),
1037 });
1038 }
1039 if matches!(args[0], Value::Null) {
1040 return Ok(Value::Null);
1041 }
1042 let s = match &args[0] {
1043 Value::Text(s) => s.as_str(),
1044 other => {
1045 return Err(EvalError::TypeMismatch {
1046 detail: format!("show_trgm() needs text, got {:?}", other.data_type()),
1047 });
1048 }
1049 };
1050 let trigrams: Vec<Option<String>> = spg_storage::trgm::extract_trigrams(s)
1054 .into_iter()
1055 .map(Some)
1056 .collect();
1057 Ok(Value::TextArray(trigrams))
1058 }
1059 other => Err(EvalError::TypeMismatch {
1060 detail: format!("unknown function `{other}`"),
1061 }),
1062 }
1063}
1064
1065fn fts_ts_rank(args: &[Value]) -> Result<Value, EvalError> {
1070 let (vec, query) = parse_rank_args("ts_rank", args)?;
1071 match (vec, query) {
1072 (None, _) | (_, None) => Ok(Value::Null),
1073 (Some(v), Some(q)) => Ok(Value::Float(f64::from(crate::fts::ts_rank(&v, &q)))),
1074 }
1075}
1076
1077fn fts_ts_rank_cd(args: &[Value]) -> Result<Value, EvalError> {
1078 let (vec, query) = parse_rank_args("ts_rank_cd", args)?;
1079 match (vec, query) {
1080 (None, _) | (_, None) => Ok(Value::Null),
1081 (Some(v), Some(q)) => Ok(Value::Float(f64::from(crate::fts::ts_rank_cd(&v, &q)))),
1082 }
1083}
1084
1085fn parse_rank_args(
1086 name: &str,
1087 args: &[Value],
1088) -> Result<
1089 (
1090 Option<Vec<spg_storage::TsLexeme>>,
1091 Option<spg_storage::TsQueryAst>,
1092 ),
1093 EvalError,
1094> {
1095 if args.len() != 2 {
1096 return Err(EvalError::TypeMismatch {
1097 detail: format!(
1098 "{name}() takes 2 args in v7.12.2 (weights array + normalisation flag are v7.12.x carve-out), got {}",
1099 args.len()
1100 ),
1101 });
1102 }
1103 let vec = match &args[0] {
1104 Value::Null => None,
1105 Value::TsVector(v) => Some(v.clone()),
1106 other => {
1107 return Err(EvalError::TypeMismatch {
1108 detail: format!(
1109 "{name}() first arg must be tsvector, got {:?}",
1110 other.data_type()
1111 ),
1112 });
1113 }
1114 };
1115 let query = match &args[1] {
1116 Value::Null => None,
1117 Value::TsQuery(q) => Some(q.clone()),
1118 other => {
1119 return Err(EvalError::TypeMismatch {
1120 detail: format!(
1121 "{name}() second arg must be tsquery, got {:?}",
1122 other.data_type()
1123 ),
1124 });
1125 }
1126 };
1127 Ok((vec, query))
1128}
1129
1130fn ts_match(l: Value, r: Value) -> Result<Value, EvalError> {
1135 let (vec, query) = match (l, r) {
1136 (Value::Null, _) | (_, Value::Null) => return Ok(Value::Null),
1137 (Value::TsVector(v), Value::TsQuery(q)) => (v, q),
1138 (Value::TsQuery(q), Value::TsVector(v)) => (v, q),
1139 (l, r) => {
1140 return Err(EvalError::TypeMismatch {
1141 detail: format!(
1142 "@@ requires (tsvector, tsquery), got ({:?}, {:?})",
1143 l.data_type(),
1144 r.data_type()
1145 ),
1146 });
1147 }
1148 };
1149 Ok(Value::Bool(crate::fts::ts_query_matches(&vec, &query)))
1150}
1151
1152fn fts_to_tsvector(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1157 let (config, text) = parse_fts_args("to_tsvector", args, ctx)?;
1158 match text {
1159 None => Ok(Value::Null),
1160 Some(t) => Ok(Value::TsVector(crate::fts::to_tsvector(config, &t))),
1161 }
1162}
1163
1164fn fts_plainto_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1165 let (config, text) = parse_fts_args("plainto_tsquery", args, ctx)?;
1166 match text {
1167 None => Ok(Value::Null),
1168 Some(t) => Ok(Value::TsQuery(crate::fts::plainto_tsquery(config, &t))),
1169 }
1170}
1171
1172fn fts_phraseto_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1173 let (config, text) = parse_fts_args("phraseto_tsquery", args, ctx)?;
1174 match text {
1175 None => Ok(Value::Null),
1176 Some(t) => Ok(Value::TsQuery(crate::fts::phraseto_tsquery(config, &t))),
1177 }
1178}
1179
1180fn fts_websearch_to_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1181 let (config, text) = parse_fts_args("websearch_to_tsquery", args, ctx)?;
1182 match text {
1183 None => Ok(Value::Null),
1184 Some(t) => Ok(Value::TsQuery(crate::fts::websearch_to_tsquery(config, &t))),
1185 }
1186}
1187
1188fn fts_to_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1189 let (config, text) = parse_fts_args("to_tsquery", args, ctx)?;
1190 match text {
1191 None => Ok(Value::Null),
1192 Some(t) => Ok(Value::TsQuery(crate::fts::to_tsquery(config, &t)?)),
1193 }
1194}
1195
1196fn parse_fts_args(
1201 name: &str,
1202 args: &[Value],
1203 ctx: &EvalContext<'_>,
1204) -> Result<(crate::fts::TsConfig, Option<String>), EvalError> {
1205 let (config_arg, text_arg) = match args {
1206 [t] => (None, t),
1207 [c, t] => (Some(c), t),
1208 _ => {
1209 return Err(EvalError::TypeMismatch {
1210 detail: format!("{name}() takes 1 or 2 args, got {}", args.len()),
1211 });
1212 }
1213 };
1214 let config = match config_arg {
1215 None => match ctx.default_text_search_config {
1216 Some(name_str) => crate::fts::TsConfig::from_name(name_str).ok_or_else(|| {
1217 EvalError::TypeMismatch {
1218 detail: format!(
1219 "text search config not implemented: {name_str:?} (supported: simple, english)"
1220 ),
1221 }
1222 })?,
1223 None => crate::fts::TsConfig::Simple,
1224 },
1225 Some(Value::Null) => return Ok((crate::fts::TsConfig::Simple, None)),
1226 Some(Value::Text(name_str)) => crate::fts::TsConfig::from_name(name_str).ok_or_else(|| {
1227 EvalError::TypeMismatch {
1228 detail: format!(
1229 "text search config not implemented: {name_str:?} (supported: simple, english)"
1230 ),
1231 }
1232 })?,
1233 Some(other) => {
1234 return Err(EvalError::TypeMismatch {
1235 detail: format!(
1236 "{name}() config arg must be text, got {:?}",
1237 other.data_type()
1238 ),
1239 });
1240 }
1241 };
1242 let text = match text_arg {
1243 Value::Null => None,
1244 Value::Text(s) => Some(s.clone()),
1245 other => {
1246 return Err(EvalError::TypeMismatch {
1247 detail: format!(
1248 "{name}() text arg must be text, got {:?}",
1249 other.data_type()
1250 ),
1251 });
1252 }
1253 };
1254 Ok((config, text))
1255}
1256
1257fn encode_text(args: &[Value]) -> Result<Value, EvalError> {
1263 if args.len() != 2 {
1264 return Err(EvalError::TypeMismatch {
1265 detail: format!("encode() takes 2 args, got {}", args.len()),
1266 });
1267 }
1268 if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
1269 return Ok(Value::Null);
1270 }
1271 let bytes: &[u8] = match &args[0] {
1272 Value::Text(s) => s.as_bytes(),
1273 other => {
1274 return Err(EvalError::TypeMismatch {
1275 detail: format!("encode() expects text bytes, got {:?}", other.data_type()),
1276 });
1277 }
1278 };
1279 let fmt = match &args[1] {
1280 Value::Text(s) => s.to_ascii_lowercase(),
1281 other => {
1282 return Err(EvalError::TypeMismatch {
1283 detail: format!("encode() format must be text, got {:?}", other.data_type()),
1284 });
1285 }
1286 };
1287 let out = match fmt.as_str() {
1288 "base64" => b64_encode(bytes, B64_STD),
1289 "base64url" => b64_encode(bytes, B64_URL),
1290 "base32hex" => b32hex_encode(bytes),
1291 "hex" => hex_encode(bytes),
1292 other => {
1293 return Err(EvalError::TypeMismatch {
1294 detail: format!("encode(): unknown format `{other}`"),
1295 });
1296 }
1297 };
1298 Ok(Value::Text(out))
1299}
1300
1301fn decode_text(args: &[Value]) -> Result<Value, EvalError> {
1305 if args.len() != 2 {
1306 return Err(EvalError::TypeMismatch {
1307 detail: format!("decode() takes 2 args, got {}", args.len()),
1308 });
1309 }
1310 if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
1311 return Ok(Value::Null);
1312 }
1313 let text = match &args[0] {
1314 Value::Text(s) => s.as_str(),
1315 other => {
1316 return Err(EvalError::TypeMismatch {
1317 detail: format!("decode() expects text, got {:?}", other.data_type()),
1318 });
1319 }
1320 };
1321 let fmt = match &args[1] {
1322 Value::Text(s) => s.to_ascii_lowercase(),
1323 other => {
1324 return Err(EvalError::TypeMismatch {
1325 detail: format!("decode() format must be text, got {:?}", other.data_type()),
1326 });
1327 }
1328 };
1329 let bytes = match fmt.as_str() {
1330 "base64" => b64_decode(text, B64_STD)?,
1331 "base64url" => b64_decode(text, B64_URL)?,
1332 "base32hex" => b32hex_decode(text)?,
1333 "hex" => hex_decode(text)?,
1334 other => {
1335 return Err(EvalError::TypeMismatch {
1336 detail: format!("decode(): unknown format `{other}`"),
1337 });
1338 }
1339 };
1340 let s = String::from_utf8(bytes).map_err(|_| EvalError::TypeMismatch {
1341 detail: "decode(): result bytes are not valid UTF-8 (SPG stores raw bytes as Text)".into(),
1342 })?;
1343 Ok(Value::Text(s))
1344}
1345
1346fn error_on_null(args: &[Value]) -> Result<Value, EvalError> {
1350 if args.len() != 1 {
1351 return Err(EvalError::TypeMismatch {
1352 detail: format!("error_on_null() takes 1 arg, got {}", args.len()),
1353 });
1354 }
1355 if matches!(args[0], Value::Null) {
1356 return Err(EvalError::TypeMismatch {
1357 detail: "error_on_null(): argument is NULL".into(),
1358 });
1359 }
1360 Ok(args[0].clone())
1361}
1362
1363const B64_STD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1366const B64_URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1367const B32HEX_ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHIJKLMNOPQRSTUV";
1368
1369fn b64_encode(bytes: &[u8], alpha: &[u8; 64]) -> String {
1370 let mut out = String::with_capacity((bytes.len() + 2) / 3 * 4);
1371 let mut i = 0;
1372 while i + 3 <= bytes.len() {
1373 let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
1374 out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
1375 out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
1376 out.push(alpha[((n >> 6) & 0x3f) as usize] as char);
1377 out.push(alpha[(n & 0x3f) as usize] as char);
1378 i += 3;
1379 }
1380 let rem = bytes.len() - i;
1381 if rem == 1 {
1382 let n = (bytes[i] as u32) << 16;
1383 out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
1384 out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
1385 out.push('=');
1386 out.push('=');
1387 } else if rem == 2 {
1388 let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
1389 out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
1390 out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
1391 out.push(alpha[((n >> 6) & 0x3f) as usize] as char);
1392 out.push('=');
1393 }
1394 out
1395}
1396
1397fn b64_decode(text: &str, alpha: &[u8; 64]) -> Result<Vec<u8>, EvalError> {
1398 let mut lookup = [255u8; 256];
1399 for (i, &c) in alpha.iter().enumerate() {
1400 lookup[c as usize] = i as u8;
1401 }
1402 let mut out = Vec::with_capacity(text.len() * 3 / 4);
1403 let mut buf: u32 = 0;
1404 let mut bits: u32 = 0;
1405 for c in text.bytes() {
1406 if c == b'=' {
1407 break;
1408 }
1409 if c == b'\n' || c == b'\r' || c == b' ' {
1410 continue;
1411 }
1412 let v = lookup[c as usize];
1413 if v == 255 {
1414 return Err(EvalError::TypeMismatch {
1415 detail: format!("decode(base64): invalid char {:?}", c as char),
1416 });
1417 }
1418 buf = (buf << 6) | v as u32;
1419 bits += 6;
1420 if bits >= 8 {
1421 bits -= 8;
1422 out.push(((buf >> bits) & 0xff) as u8);
1423 }
1424 }
1425 Ok(out)
1426}
1427
1428fn b32hex_encode(bytes: &[u8]) -> String {
1429 let mut out = String::with_capacity((bytes.len() * 8 + 4) / 5);
1430 let mut buf: u64 = 0;
1431 let mut bits: u32 = 0;
1432 for &b in bytes {
1433 buf = (buf << 8) | b as u64;
1434 bits += 8;
1435 while bits >= 5 {
1436 bits -= 5;
1437 out.push(B32HEX_ALPHABET[((buf >> bits) & 0x1f) as usize] as char);
1438 }
1439 }
1440 if bits > 0 {
1441 out.push(B32HEX_ALPHABET[((buf << (5 - bits)) & 0x1f) as usize] as char);
1442 }
1443 while out.len() % 8 != 0 {
1445 out.push('=');
1446 }
1447 out
1448}
1449
1450fn b32hex_decode(text: &str) -> Result<Vec<u8>, EvalError> {
1451 let mut lookup = [255u8; 256];
1452 for (i, &c) in B32HEX_ALPHABET.iter().enumerate() {
1453 lookup[c as usize] = i as u8;
1454 let lower = (c as char).to_ascii_lowercase() as u8;
1456 lookup[lower as usize] = i as u8;
1457 }
1458 let mut out = Vec::with_capacity(text.len() * 5 / 8);
1459 let mut buf: u64 = 0;
1460 let mut bits: u32 = 0;
1461 for c in text.bytes() {
1462 if c == b'=' {
1463 break;
1464 }
1465 if c == b'\n' || c == b'\r' || c == b' ' {
1466 continue;
1467 }
1468 let v = lookup[c as usize];
1469 if v == 255 {
1470 return Err(EvalError::TypeMismatch {
1471 detail: format!("decode(base32hex): invalid char {:?}", c as char),
1472 });
1473 }
1474 buf = (buf << 5) | v as u64;
1475 bits += 5;
1476 if bits >= 8 {
1477 bits -= 8;
1478 out.push(((buf >> bits) & 0xff) as u8);
1479 }
1480 }
1481 Ok(out)
1482}
1483
1484fn hex_encode(bytes: &[u8]) -> String {
1485 const HEX: &[u8; 16] = b"0123456789abcdef";
1486 let mut out = String::with_capacity(bytes.len() * 2);
1487 for &b in bytes {
1488 out.push(HEX[(b >> 4) as usize] as char);
1489 out.push(HEX[(b & 0xf) as usize] as char);
1490 }
1491 out
1492}
1493
1494fn hex_decode(text: &str) -> Result<Vec<u8>, EvalError> {
1495 let trimmed = text.trim();
1496 if trimmed.len() % 2 != 0 {
1497 return Err(EvalError::TypeMismatch {
1498 detail: "decode(hex): input length must be even".into(),
1499 });
1500 }
1501 let mut out = Vec::with_capacity(trimmed.len() / 2);
1502 let mut hi: u8 = 0;
1503 for (i, c) in trimmed.bytes().enumerate() {
1504 let v = match c {
1505 b'0'..=b'9' => c - b'0',
1506 b'a'..=b'f' => c - b'a' + 10,
1507 b'A'..=b'F' => c - b'A' + 10,
1508 _ => {
1509 return Err(EvalError::TypeMismatch {
1510 detail: format!("decode(hex): invalid char {:?}", c as char),
1511 });
1512 }
1513 };
1514 if i % 2 == 0 {
1515 hi = v;
1516 } else {
1517 out.push((hi << 4) | v);
1518 }
1519 }
1520 Ok(out)
1521}
1522
1523fn date_part(args: &[Value]) -> Result<Value, EvalError> {
1528 use spg_sql::ast::ExtractField as F;
1529 if args.len() != 2 {
1530 return Err(EvalError::TypeMismatch {
1531 detail: format!("date_part() takes 2 args, got {}", args.len()),
1532 });
1533 }
1534 if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
1535 return Ok(Value::Null);
1536 }
1537 let Value::Text(field_name) = &args[0] else {
1538 return Err(EvalError::TypeMismatch {
1539 detail: format!(
1540 "date_part() needs a text field, got {:?}",
1541 args[0].data_type()
1542 ),
1543 });
1544 };
1545 let field = match field_name.to_ascii_lowercase().as_str() {
1546 "year" => F::Year,
1547 "month" => F::Month,
1548 "day" => F::Day,
1549 "hour" => F::Hour,
1550 "minute" => F::Minute,
1551 "second" => F::Second,
1552 "microsecond" | "microseconds" => F::Microsecond,
1553 other => {
1554 return Err(EvalError::TypeMismatch {
1555 detail: format!(
1556 "unknown date_part field {other:?}; \
1557 supported: year, month, day, hour, minute, second, microsecond"
1558 ),
1559 });
1560 }
1561 };
1562 extract_field(field, &args[1])
1563}
1564
1565fn age(args: &[Value]) -> Result<Value, EvalError> {
1575 if args.is_empty() || args.len() > 2 {
1576 return Err(EvalError::TypeMismatch {
1577 detail: format!("age() takes 1 or 2 args, got {}", args.len()),
1578 });
1579 }
1580 if args.iter().any(|v| matches!(v, Value::Null)) {
1581 return Ok(Value::Null);
1582 }
1583 let to_micros = |v: &Value| -> Result<i64, EvalError> {
1586 match v {
1587 Value::Timestamp(t) => Ok(*t),
1588 Value::Date(d) => Ok(i64::from(*d) * 86_400_000_000),
1589 other => Err(EvalError::TypeMismatch {
1590 detail: format!("age() needs DATE or TIMESTAMP, got {:?}", other.data_type()),
1591 }),
1592 }
1593 };
1594 if args.len() == 1 {
1595 return Err(EvalError::TypeMismatch {
1596 detail: "single-arg age() is unsupported in v2.12 \
1597 (use age(CURRENT_DATE, t) explicitly)"
1598 .into(),
1599 });
1600 }
1601 let a = to_micros(&args[0])?;
1602 let b = to_micros(&args[1])?;
1603 let delta = a.checked_sub(b).ok_or(EvalError::TypeMismatch {
1604 detail: "age() subtraction overflows i64 microseconds".into(),
1605 })?;
1606 Ok(Value::Interval {
1607 months: 0,
1608 micros: delta,
1609 })
1610}
1611
1612fn to_char(args: &[Value]) -> Result<Value, EvalError> {
1618 use core::fmt::Write as _;
1619 if args.len() != 2 {
1620 return Err(EvalError::TypeMismatch {
1621 detail: format!("to_char() takes 2 args, got {}", args.len()),
1622 });
1623 }
1624 if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
1625 return Ok(Value::Null);
1626 }
1627 let Value::Text(fmt) = &args[1] else {
1628 return Err(EvalError::TypeMismatch {
1629 detail: format!(
1630 "to_char() needs a text format, got {:?}",
1631 args[1].data_type()
1632 ),
1633 });
1634 };
1635 let (days, day_micros) = match &args[0] {
1636 Value::Date(d) => (*d, 0_i64),
1637 Value::Timestamp(t) => {
1638 let days = t.div_euclid(86_400_000_000);
1639 (
1640 i32::try_from(days).unwrap_or(i32::MAX),
1641 t.rem_euclid(86_400_000_000),
1642 )
1643 }
1644 other => {
1645 return Err(EvalError::TypeMismatch {
1646 detail: format!(
1647 "to_char() needs DATE or TIMESTAMP, got {:?}",
1648 other.data_type()
1649 ),
1650 });
1651 }
1652 };
1653 let (y, mo, d) = civil_from_days(days);
1654 let secs = day_micros / 1_000_000;
1655 let frac = day_micros % 1_000_000;
1656 let hh24 = u32::try_from(secs / 3600).unwrap_or(0);
1660 let mi = u32::try_from((secs / 60) % 60).unwrap_or(0);
1661 let ss = u32::try_from(secs % 60).unwrap_or(0);
1662 let hh12 = match hh24 % 12 {
1663 0 => 12,
1664 x => x,
1665 };
1666 let ampm = if hh24 < 12 { "AM" } else { "PM" };
1667 let ms = u32::try_from(frac / 1_000).unwrap_or(0); let us = u32::try_from(frac).unwrap_or(0); let mut out = String::with_capacity(fmt.len() + 8);
1671 let bytes = fmt.as_bytes();
1672 let mut i = 0;
1673 while i < bytes.len() {
1675 let rest = &bytes[i..];
1677 if rest.starts_with(b"YYYY") {
1678 let _ = write!(out, "{y:04}");
1679 i += 4;
1680 } else if rest.starts_with(b"YY") {
1681 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
1682 let yy = (y.rem_euclid(100)) as u32;
1683 let _ = write!(out, "{yy:02}");
1684 i += 2;
1685 } else if rest.starts_with(b"Month") {
1686 out.push_str(MONTH_FULL[(mo - 1) as usize]);
1687 i += 5;
1688 } else if rest.starts_with(b"Mon") {
1689 out.push_str(MONTH_ABBR[(mo - 1) as usize]);
1690 i += 3;
1691 } else if rest.starts_with(b"MM") {
1692 let _ = write!(out, "{mo:02}");
1693 i += 2;
1694 } else if rest.starts_with(b"DD") {
1695 let _ = write!(out, "{d:02}");
1696 i += 2;
1697 } else if rest.starts_with(b"HH24") {
1698 let _ = write!(out, "{hh24:02}");
1699 i += 4;
1700 } else if rest.starts_with(b"HH12") {
1701 let _ = write!(out, "{hh12:02}");
1702 i += 4;
1703 } else if rest.starts_with(b"MI") {
1704 let _ = write!(out, "{mi:02}");
1705 i += 2;
1706 } else if rest.starts_with(b"SS") {
1707 let _ = write!(out, "{ss:02}");
1708 i += 2;
1709 } else if rest.starts_with(b"MS") {
1710 let _ = write!(out, "{ms:03}");
1711 i += 2;
1712 } else if rest.starts_with(b"US") {
1713 let _ = write!(out, "{us:06}");
1714 i += 2;
1715 } else if rest.starts_with(b"AM") || rest.starts_with(b"PM") {
1716 out.push_str(ampm);
1717 i += 2;
1718 } else {
1719 out.push(bytes[i] as char);
1721 i += 1;
1722 }
1723 }
1724 Ok(Value::Text(out))
1725}
1726
1727const MONTH_FULL: [&str; 12] = [
1728 "January",
1729 "February",
1730 "March",
1731 "April",
1732 "May",
1733 "June",
1734 "July",
1735 "August",
1736 "September",
1737 "October",
1738 "November",
1739 "December",
1740];
1741const MONTH_ABBR: [&str; 12] = [
1742 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1743];
1744
1745fn date_trunc(args: &[Value]) -> Result<Value, EvalError> {
1750 if args.len() != 2 {
1751 return Err(EvalError::TypeMismatch {
1752 detail: format!("date_trunc() takes 2 args, got {}", args.len()),
1753 });
1754 }
1755 if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
1756 return Ok(Value::Null);
1757 }
1758 let Value::Text(unit) = &args[0] else {
1759 return Err(EvalError::TypeMismatch {
1760 detail: format!(
1761 "date_trunc() needs a text unit, got {:?}",
1762 args[0].data_type()
1763 ),
1764 });
1765 };
1766 let micros = match &args[1] {
1769 Value::Timestamp(t) => *t,
1770 Value::Date(d) => i64::from(*d) * 86_400_000_000,
1771 other => {
1772 return Err(EvalError::TypeMismatch {
1773 detail: format!(
1774 "date_trunc() needs DATE or TIMESTAMP, got {:?}",
1775 other.data_type()
1776 ),
1777 });
1778 }
1779 };
1780 let unit_lc = unit.to_ascii_lowercase();
1781 let days = micros.div_euclid(86_400_000_000);
1782 let day_micros = micros.rem_euclid(86_400_000_000);
1783 let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
1784 let (y, m, _) = civil_from_days(day_i32);
1785 let truncated = match unit_lc.as_str() {
1786 "year" => i64::from(days_from_civil(y, 1, 1)) * 86_400_000_000,
1787 "month" => i64::from(days_from_civil(y, m, 1)) * 86_400_000_000,
1788 "day" => days * 86_400_000_000,
1789 "hour" => days * 86_400_000_000 + (day_micros / 3_600_000_000) * 3_600_000_000,
1790 "minute" => days * 86_400_000_000 + (day_micros / 60_000_000) * 60_000_000,
1791 "second" => days * 86_400_000_000 + (day_micros / 1_000_000) * 1_000_000,
1792 other => {
1793 return Err(EvalError::TypeMismatch {
1794 detail: format!(
1795 "unknown date_trunc unit {other:?}; \
1796 supported: year, month, day, hour, minute, second"
1797 ),
1798 });
1799 }
1800 };
1801 Ok(Value::Timestamp(truncated))
1802}
1803
1804pub fn cast_value(v: Value, target: CastTarget) -> Result<Value, EvalError> {
1806 if matches!(v, Value::Null) {
1807 return Ok(Value::Null);
1808 }
1809 match target {
1810 CastTarget::Vector => cast_to_vector(v),
1811 CastTarget::Text => Ok(Value::Text(value_to_text(&v))),
1812 CastTarget::Int => cast_numeric_to_int(v),
1813 CastTarget::BigInt => cast_numeric_to_bigint(v),
1814 CastTarget::Float => cast_numeric_to_float(v),
1815 CastTarget::Bool => cast_to_bool(v),
1816 CastTarget::Date => cast_to_date(v),
1817 CastTarget::Timestamp | CastTarget::Timestamptz => cast_to_timestamp(v),
1820 CastTarget::Interval => cast_to_interval(v),
1824 CastTarget::Json | CastTarget::Jsonb => match v {
1828 Value::Json(s) => Ok(Value::Json(s)),
1829 Value::Text(s) => Ok(Value::Json(s)),
1830 other => Err(EvalError::TypeMismatch {
1831 detail: alloc::format!(
1832 "::json / ::jsonb only accepts TEXT-shape inputs, got {:?}",
1833 other.data_type()
1834 ),
1835 }),
1836 },
1837 CastTarget::RegType | CastTarget::RegClass => Err(EvalError::TypeMismatch {
1840 detail: "::regtype / ::regclass not supported on SPG \
1841 (no pg_catalog); use SHOW TABLES / spg_table_ddl instead"
1842 .into(),
1843 }),
1844 CastTarget::TextArray => match v {
1848 Value::TextArray(items) => Ok(Value::TextArray(items)),
1849 Value::Text(s) => decode_text_array_external(&s).map(Value::TextArray),
1850 other => Err(EvalError::TypeMismatch {
1851 detail: alloc::format!(
1852 "::TEXT[] only accepts TEXT / TEXT[] inputs, got {:?}",
1853 other.data_type()
1854 ),
1855 }),
1856 },
1857 CastTarget::IntArray => cast_to_int_array(v),
1861 CastTarget::BigIntArray => cast_to_bigint_array(v),
1862 CastTarget::TsVector => match v {
1869 Value::TsVector(items) => Ok(Value::TsVector(items)),
1870 Value::Text(s) => decode_tsvector_external(&s).map(Value::TsVector),
1871 other => Err(EvalError::TypeMismatch {
1872 detail: alloc::format!(
1873 "::tsvector only accepts TEXT / tsvector inputs, got {:?}",
1874 other.data_type()
1875 ),
1876 }),
1877 },
1878 CastTarget::TsQuery => match v {
1879 Value::TsQuery(ast) => Ok(Value::TsQuery(ast)),
1880 Value::Text(s) => decode_tsquery_external(&s).map(Value::TsQuery),
1881 other => Err(EvalError::TypeMismatch {
1882 detail: alloc::format!(
1883 "::tsquery only accepts TEXT / tsquery inputs, got {:?}",
1884 other.data_type()
1885 ),
1886 }),
1887 },
1888 }
1889}
1890
1891fn cast_to_int_array(v: Value) -> Result<Value, EvalError> {
1892 match v {
1893 Value::IntArray(items) => Ok(Value::IntArray(items)),
1894 Value::BigIntArray(items) => {
1895 let mut out: Vec<Option<i32>> = Vec::with_capacity(items.len());
1896 for item in items {
1897 match item {
1898 None => out.push(None),
1899 Some(n) => match i32::try_from(n) {
1900 Ok(x) => out.push(Some(x)),
1901 Err(_) => {
1902 return Err(EvalError::TypeMismatch {
1903 detail: alloc::format!("::INT[] element {n} overflows i32"),
1904 });
1905 }
1906 },
1907 }
1908 }
1909 Ok(Value::IntArray(out))
1910 }
1911 Value::Text(s) => decode_int_array_external(&s).map(Value::IntArray),
1912 Value::TextArray(items) => {
1913 let mut out: Vec<Option<i32>> = Vec::with_capacity(items.len());
1914 for item in items {
1915 match item {
1916 None => out.push(None),
1917 Some(s) => match s.parse::<i32>() {
1918 Ok(n) => out.push(Some(n)),
1919 Err(_) => {
1920 return Err(EvalError::TypeMismatch {
1921 detail: alloc::format!("::INT[] cannot parse {s:?}"),
1922 });
1923 }
1924 },
1925 }
1926 }
1927 Ok(Value::IntArray(out))
1928 }
1929 other => Err(EvalError::TypeMismatch {
1930 detail: alloc::format!("::INT[] does not accept {:?}", other.data_type()),
1931 }),
1932 }
1933}
1934
1935fn cast_to_bigint_array(v: Value) -> Result<Value, EvalError> {
1936 match v {
1937 Value::BigIntArray(items) => Ok(Value::BigIntArray(items)),
1938 Value::IntArray(items) => Ok(Value::BigIntArray(
1939 items.into_iter().map(|x| x.map(i64::from)).collect(),
1940 )),
1941 Value::Text(s) => decode_bigint_array_external(&s).map(Value::BigIntArray),
1942 Value::TextArray(items) => {
1943 let mut out: Vec<Option<i64>> = Vec::with_capacity(items.len());
1944 for item in items {
1945 match item {
1946 None => out.push(None),
1947 Some(s) => match s.parse::<i64>() {
1948 Ok(n) => out.push(Some(n)),
1949 Err(_) => {
1950 return Err(EvalError::TypeMismatch {
1951 detail: alloc::format!("::BIGINT[] cannot parse {s:?}"),
1952 });
1953 }
1954 },
1955 }
1956 }
1957 Ok(Value::BigIntArray(out))
1958 }
1959 other => Err(EvalError::TypeMismatch {
1960 detail: alloc::format!("::BIGINT[] does not accept {:?}", other.data_type()),
1961 }),
1962 }
1963}
1964
1965fn decode_int_array_external(s: &str) -> Result<Vec<Option<i32>>, EvalError> {
1966 let trimmed = s.trim();
1967 let inner = trimmed
1968 .strip_prefix('{')
1969 .and_then(|x| x.strip_suffix('}'))
1970 .ok_or_else(|| EvalError::TypeMismatch {
1971 detail: alloc::format!("INT[] literal {s:?} must be enclosed in '{{...}}'"),
1972 })?;
1973 if inner.trim().is_empty() {
1974 return Ok(Vec::new());
1975 }
1976 inner
1977 .split(',')
1978 .map(|part| {
1979 let p = part.trim();
1980 if p.eq_ignore_ascii_case("NULL") {
1981 Ok(None)
1982 } else {
1983 p.parse::<i32>()
1984 .map(Some)
1985 .map_err(|_| EvalError::TypeMismatch {
1986 detail: alloc::format!("INT[] element {p:?} is not an i32"),
1987 })
1988 }
1989 })
1990 .collect()
1991}
1992
1993fn decode_bigint_array_external(s: &str) -> Result<Vec<Option<i64>>, EvalError> {
1994 let trimmed = s.trim();
1995 let inner = trimmed
1996 .strip_prefix('{')
1997 .and_then(|x| x.strip_suffix('}'))
1998 .ok_or_else(|| EvalError::TypeMismatch {
1999 detail: alloc::format!("BIGINT[] literal {s:?} must be enclosed in '{{...}}'"),
2000 })?;
2001 if inner.trim().is_empty() {
2002 return Ok(Vec::new());
2003 }
2004 inner
2005 .split(',')
2006 .map(|part| {
2007 let p = part.trim();
2008 if p.eq_ignore_ascii_case("NULL") {
2009 Ok(None)
2010 } else {
2011 p.parse::<i64>()
2012 .map(Some)
2013 .map_err(|_| EvalError::TypeMismatch {
2014 detail: alloc::format!("BIGINT[] element {p:?} is not an i64"),
2015 })
2016 }
2017 })
2018 .collect()
2019}
2020
2021fn decode_text_array_external(s: &str) -> Result<Vec<Option<String>>, EvalError> {
2026 let trimmed = s.trim();
2027 let inner = trimmed
2028 .strip_prefix('{')
2029 .and_then(|x| x.strip_suffix('}'))
2030 .ok_or_else(|| EvalError::TypeMismatch {
2031 detail: alloc::format!("TEXT[] literal {s:?} must be enclosed in '{{...}}'"),
2032 })?;
2033 let mut out: Vec<Option<String>> = Vec::new();
2034 if inner.trim().is_empty() {
2035 return Ok(out);
2036 }
2037 let bytes = inner.as_bytes();
2038 let mut i = 0;
2039 while i <= bytes.len() {
2040 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
2041 i += 1;
2042 }
2043 if i < bytes.len() && bytes[i] == b'"' {
2044 i += 1;
2045 let mut buf = String::new();
2046 while i < bytes.len() && bytes[i] != b'"' {
2047 if bytes[i] == b'\\' && i + 1 < bytes.len() {
2048 buf.push(bytes[i + 1] as char);
2049 i += 2;
2050 } else {
2051 buf.push(bytes[i] as char);
2052 i += 1;
2053 }
2054 }
2055 if i >= bytes.len() {
2056 return Err(EvalError::TypeMismatch {
2057 detail: "unterminated quoted element in TEXT[] literal".into(),
2058 });
2059 }
2060 i += 1;
2061 out.push(Some(buf));
2062 } else {
2063 let start = i;
2064 while i < bytes.len() && bytes[i] != b',' {
2065 i += 1;
2066 }
2067 let raw = inner[start..i].trim();
2068 if raw.eq_ignore_ascii_case("NULL") {
2069 out.push(None);
2070 } else {
2071 out.push(Some(raw.to_string()));
2072 }
2073 }
2074 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
2075 i += 1;
2076 }
2077 if i >= bytes.len() {
2078 break;
2079 }
2080 if bytes[i] != b',' {
2081 return Err(EvalError::TypeMismatch {
2082 detail: "expected ',' between TEXT[] elements".into(),
2083 });
2084 }
2085 i += 1;
2086 }
2087 Ok(out)
2088}
2089
2090fn cast_to_interval(v: Value) -> Result<Value, EvalError> {
2091 match v {
2092 Value::Interval { months, micros } => Ok(Value::Interval { months, micros }),
2093 Value::Text(s) => {
2094 let (months, micros) = spg_sql::parser::parse_interval_text(&s).ok_or_else(|| {
2095 EvalError::TypeMismatch {
2096 detail: alloc::format!("cannot parse {s:?} as INTERVAL"),
2097 }
2098 })?;
2099 Ok(Value::Interval { months, micros })
2100 }
2101 other => Err(EvalError::TypeMismatch {
2102 detail: alloc::format!(
2103 "::INTERVAL only accepts TEXT-shape inputs, got {:?}",
2104 other.data_type()
2105 ),
2106 }),
2107 }
2108}
2109
2110fn cast_to_date(v: Value) -> Result<Value, EvalError> {
2111 match v {
2112 Value::Date(d) => Ok(Value::Date(d)),
2113 Value::Int(n) => Ok(Value::Date(n)),
2116 Value::BigInt(n) => {
2117 i32::try_from(n)
2118 .map(Value::Date)
2119 .map_err(|_| EvalError::TypeMismatch {
2120 detail: "bigint days-since-epoch out of DATE range".into(),
2121 })
2122 }
2123 Value::Timestamp(t) => {
2125 let days = t.div_euclid(86_400_000_000);
2126 i32::try_from(days)
2127 .map(Value::Date)
2128 .map_err(|_| EvalError::TypeMismatch {
2129 detail: "timestamp out of DATE range".into(),
2130 })
2131 }
2132 Value::Text(s) => parse_date_literal(&s)
2133 .map(Value::Date)
2134 .ok_or(EvalError::TypeMismatch {
2135 detail: format!("cannot parse {s:?} as DATE (expected YYYY-MM-DD)"),
2136 }),
2137 other => Err(EvalError::TypeMismatch {
2138 detail: format!("cannot cast {:?} to DATE", other.data_type()),
2139 }),
2140 }
2141}
2142
2143fn cast_to_timestamp(v: Value) -> Result<Value, EvalError> {
2144 match v {
2145 Value::Timestamp(t) => Ok(Value::Timestamp(t)),
2146 Value::Int(n) => Ok(Value::Timestamp(i64::from(n))),
2150 Value::BigInt(n) => Ok(Value::Timestamp(n)),
2151 Value::Date(d) => Ok(Value::Timestamp(i64::from(d) * 86_400_000_000)),
2153 Value::Text(s) => {
2154 parse_timestamp_literal(&s)
2155 .map(Value::Timestamp)
2156 .ok_or(EvalError::TypeMismatch {
2157 detail: format!(
2158 "cannot parse {s:?} as TIMESTAMP \
2159 (expected YYYY-MM-DD[ HH:MM:SS[.ffffff]])"
2160 ),
2161 })
2162 }
2163 other => Err(EvalError::TypeMismatch {
2164 detail: format!("cannot cast {:?} to TIMESTAMP", other.data_type()),
2165 }),
2166 }
2167}
2168
2169fn value_to_text(v: &Value) -> String {
2170 match v {
2171 Value::SmallInt(n) => format!("{n}"),
2175 Value::Int(n) => format!("{n}"),
2176 Value::BigInt(n) => format!("{n}"),
2177 Value::Float(x) => format!("{x}"),
2178 Value::Text(s) | Value::Json(s) => s.clone(),
2180 Value::Bool(b) => (if *b { "true" } else { "false" }).into(),
2181 Value::Vector(v) => {
2182 let cells: Vec<String> = v.iter().map(|x| format!("{x}")).collect();
2183 format!("[{}]", cells.join(", "))
2184 }
2185 Value::Sq8Vector(q) => {
2190 let cells: Vec<String> = spg_storage::quantize::dequantize(q)
2191 .iter()
2192 .map(|x| format!("{x}"))
2193 .collect();
2194 format!("[{}]", cells.join(", "))
2195 }
2196 Value::HalfVector(h) => {
2199 let cells: Vec<String> = h.to_f32_vec().iter().map(|x| format!("{x}")).collect();
2200 format!("[{}]", cells.join(", "))
2201 }
2202 Value::Numeric { scaled, scale } => format_numeric(*scaled, *scale),
2203 Value::Date(d) => format_date(*d),
2204 Value::Timestamp(t) => format_timestamp(*t),
2205 Value::Interval { months, micros } => format_interval(*months, *micros),
2206 Value::Null => "NULL".into(),
2207 Value::Bytes(b) => format_bytea_hex(b),
2209 Value::TextArray(items) => format_text_array(items),
2211 Value::IntArray(items) => format_int_array(items),
2212 Value::BigIntArray(items) => format_bigint_array(items),
2213 Value::TsVector(lexs) => format_tsvector(lexs),
2215 Value::TsQuery(ast) => format_tsquery(ast),
2216 _ => format!("{v:?}"),
2218 }
2219}
2220
2221pub fn format_date(days: i32) -> String {
2224 let (y, m, d) = civil_from_days(days);
2225 format!("{y:04}-{m:02}-{d:02}")
2226}
2227
2228pub fn format_timestamptz(micros: i64) -> String {
2239 let base = format_timestamp(micros);
2240 let mut s = String::with_capacity(base.len() + 3);
2241 s.push_str(&base);
2242 s.push_str("+00");
2243 s
2244}
2245
2246pub fn format_timestamp(micros: i64) -> String {
2247 const MICROS_PER_DAY: i64 = 86_400_000_000;
2248 let days = micros.div_euclid(MICROS_PER_DAY);
2251 let day_micros = micros.rem_euclid(MICROS_PER_DAY);
2252 let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
2253 let (y, m, d) = civil_from_days(day_i32);
2254 let secs = day_micros / 1_000_000;
2255 let frac = day_micros % 1_000_000;
2256 let hh = secs / 3600;
2257 let mm = (secs / 60) % 60;
2258 let ss = secs % 60;
2259 if frac == 0 {
2260 format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}")
2261 } else {
2262 let raw = format!("{frac:06}");
2264 let trimmed = raw.trim_end_matches('0');
2265 format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}.{trimmed}")
2266 }
2267}
2268
2269#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2274fn civil_from_days(days: i32) -> (i32, u32, u32) {
2275 let z = i64::from(days) + 719_468;
2276 let era = z.div_euclid(146_097);
2277 let doe = (z - era * 146_097) as u32;
2281 let yoe = (doe.saturating_sub(doe / 1460) + doe / 36524 - doe / 146_096) / 365;
2282 let y_base = i64::from(yoe) + era * 400;
2283 let doy = doe.saturating_sub(365 * yoe + yoe / 4 - yoe / 100);
2284 let mp = (5 * doy + 2) / 153;
2285 let d = doy.saturating_sub((153 * mp + 2) / 5) + 1;
2286 let m = if mp < 10 { mp + 3 } else { mp - 9 };
2287 let y = if m <= 2 { y_base + 1 } else { y_base };
2288 (y as i32, m, d)
2289}
2290
2291#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2294pub fn days_from_civil(y: i32, m: u32, d: u32) -> i32 {
2295 let y_adj = if m <= 2 {
2296 i64::from(y) - 1
2297 } else {
2298 i64::from(y)
2299 };
2300 let era = y_adj.div_euclid(400);
2301 let yoe = (y_adj - era * 400) as u32;
2302 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d.saturating_sub(1);
2303 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2304 let total = era * 146_097 + i64::from(doe) - 719_468;
2305 i32::try_from(total).unwrap_or(i32::MAX)
2306}
2307
2308pub fn parse_date_literal(s: &str) -> Option<i32> {
2312 let bytes = s.as_bytes();
2313 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
2314 return None;
2315 }
2316 let y: i32 = s[0..4].parse().ok()?;
2317 let m: u32 = s[5..7].parse().ok()?;
2318 let d: u32 = s[8..10].parse().ok()?;
2319 if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
2320 return None;
2321 }
2322 Some(days_from_civil(y, m, d))
2323}
2324
2325pub fn parse_timestamp_literal(s: &str) -> Option<i64> {
2330 let trimmed = s.trim();
2331 let (date_part, time_part) = match trimmed.find([' ', 'T']) {
2332 Some(i) => (&trimmed[..i], Some(&trimmed[i + 1..])),
2333 None => (trimmed, None),
2334 };
2335 let days = parse_date_literal(date_part)?;
2336 let (day_micros, tz_offset_micros) = match time_part {
2337 None => (0, 0),
2338 Some(t) => parse_time_of_day_micros(t)?,
2339 };
2340 Some(i64::from(days) * 86_400_000_000 + day_micros - tz_offset_micros)
2350}
2351
2352fn parse_time_of_day_micros(t: &str) -> Option<(i64, i64)> {
2365 let t = t.trim();
2366 let (core, tz_micros) = if let Some(rest) = t.strip_suffix('Z') {
2372 (rest, 0i64)
2373 } else if let Some(rest) = t.strip_suffix(" UTC").or_else(|| t.strip_suffix("UTC")) {
2374 (rest, 0i64)
2375 } else if let Some((idx, sign_byte)) = find_offset_sign(t) {
2376 let suffix = &t[idx..];
2377 let micros = parse_tz_offset_suffix(suffix, sign_byte == b'+')?;
2378 (&t[..idx], micros)
2379 } else {
2380 (t, 0i64)
2381 };
2382 let (time, frac_str) = match core.split_once('.') {
2383 Some((a, b)) => (a, Some(b)),
2384 None => (core, None),
2385 };
2386 let bytes = time.as_bytes();
2387 if bytes.len() != 8 || bytes[2] != b':' || bytes[5] != b':' {
2388 return None;
2389 }
2390 let hh: i64 = time[0..2].parse().ok()?;
2391 let mm: i64 = time[3..5].parse().ok()?;
2392 let ss: i64 = time[6..8].parse().ok()?;
2393 if !(0..24).contains(&hh) || !(0..60).contains(&mm) || !(0..60).contains(&ss) {
2394 return None;
2395 }
2396 let frac_micros: i64 = match frac_str {
2397 None => 0,
2398 Some(f) => {
2399 if f.is_empty() || f.len() > 9 {
2401 return None;
2402 }
2403 let mut padded = String::with_capacity(6);
2404 padded.push_str(&f[..f.len().min(6)]);
2405 while padded.len() < 6 {
2406 padded.push('0');
2407 }
2408 padded.parse().ok()?
2409 }
2410 };
2411 Some((
2412 ((hh * 3600 + mm * 60 + ss) * 1_000_000) + frac_micros,
2413 tz_micros,
2414 ))
2415}
2416
2417fn find_offset_sign(t: &str) -> Option<(usize, u8)> {
2423 let bytes = t.as_bytes();
2424 if bytes.len() < 9 {
2426 return None;
2427 }
2428 for i in 8..bytes.len() {
2429 match bytes[i] {
2430 b'+' | b'-' => return Some((i, bytes[i])),
2431 _ => {}
2432 }
2433 }
2434 None
2435}
2436
2437fn parse_tz_offset_suffix(suffix: &str, is_positive: bool) -> Option<i64> {
2441 let body = &suffix[1..];
2443 let (hh, mm): (i64, i64) = if let Some((h, m)) = body.split_once(':') {
2444 (h.parse().ok()?, m.parse().ok()?)
2445 } else {
2446 match body.len() {
2447 2 => (body.parse().ok()?, 0),
2448 3 => {
2449 return None;
2453 }
2454 4 => {
2455 let h: i64 = body[0..2].parse().ok()?;
2456 let m: i64 = body[2..4].parse().ok()?;
2457 (h, m)
2458 }
2459 _ => return None,
2460 }
2461 };
2462 if !(0..=18).contains(&hh) || !(0..60).contains(&mm) {
2463 return None;
2464 }
2465 let abs = (hh * 3600 + mm * 60) * 1_000_000;
2466 Some(if is_positive { abs } else { -abs })
2467}
2468
2469pub fn format_interval(months: i32, micros: i64) -> String {
2474 const MICROS_PER_DAY: i64 = 86_400_000_000;
2475 let mut parts: Vec<String> = Vec::new();
2476 let years = months / 12;
2477 let mons = months % 12;
2478 let unit = |n: i64, singular: &'static str, plural: &'static str| -> &'static str {
2481 if n == 1 { singular } else { plural }
2482 };
2483 if years != 0 {
2484 parts.push(format!(
2485 "{years} {}",
2486 unit(i64::from(years), "year", "years")
2487 ));
2488 }
2489 if mons != 0 {
2490 parts.push(format!("{mons} {}", unit(i64::from(mons), "mon", "mons")));
2491 }
2492 let days = micros / MICROS_PER_DAY;
2493 let mut rem = micros % MICROS_PER_DAY;
2494 if days != 0 {
2495 parts.push(format!("{days} {}", unit(days, "day", "days")));
2496 }
2497 if rem != 0 {
2498 let neg = rem < 0;
2499 if neg {
2500 rem = -rem;
2501 }
2502 let secs = rem / 1_000_000;
2503 let frac = rem % 1_000_000;
2504 let hh = secs / 3600;
2505 let mm = (secs / 60) % 60;
2506 let ss = secs % 60;
2507 let sign = if neg { "-" } else { "" };
2508 if frac == 0 {
2509 parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}"));
2510 } else {
2511 let raw = format!("{frac:06}");
2512 let trimmed = raw.trim_end_matches('0');
2513 parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}.{trimmed}"));
2514 }
2515 }
2516 if parts.is_empty() {
2517 "0".into()
2518 } else {
2519 parts.join(" ")
2520 }
2521}
2522
2523fn add_months_to_civil(y: i32, m: u32, d: u32, months: i32) -> (i32, u32, u32) {
2526 let total_months = i64::from(y) * 12 + i64::from(m) - 1 + i64::from(months);
2527 let new_year = i32::try_from(total_months.div_euclid(12)).unwrap_or(i32::MAX);
2528 let new_month_zero = total_months.rem_euclid(12);
2529 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2530 let new_month = (new_month_zero as u32) + 1;
2531 let max_day = days_in_month(new_year, new_month);
2532 (new_year, new_month, d.min(max_day))
2533}
2534
2535const fn days_in_month(y: i32, m: u32) -> u32 {
2536 match m {
2537 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
2538 2 => {
2539 if y.rem_euclid(4) == 0 && (y.rem_euclid(100) != 0 || y.rem_euclid(400) == 0) {
2541 29
2542 } else {
2543 28
2544 }
2545 }
2546 _ => 30,
2549 }
2550}
2551
2552pub fn format_text_array(items: &[Option<String>]) -> String {
2558 let mut out = String::with_capacity(2 + items.len() * 8);
2559 out.push('{');
2560 for (i, item) in items.iter().enumerate() {
2561 if i > 0 {
2562 out.push(',');
2563 }
2564 match item {
2565 None => out.push_str("NULL"),
2566 Some(s) => {
2567 let needs_quote = s.is_empty()
2568 || s.eq_ignore_ascii_case("NULL")
2569 || s.chars()
2570 .any(|c| matches!(c, ',' | '{' | '}' | '"' | '\\' | ' ' | '\t'));
2571 if needs_quote {
2572 out.push('"');
2573 for c in s.chars() {
2574 if c == '"' || c == '\\' {
2575 out.push('\\');
2576 }
2577 out.push(c);
2578 }
2579 out.push('"');
2580 } else {
2581 out.push_str(s);
2582 }
2583 }
2584 }
2585 }
2586 out.push('}');
2587 out
2588}
2589
2590pub fn format_int_array(items: &[Option<i32>]) -> String {
2594 let mut out = String::with_capacity(2 + items.len() * 4);
2595 out.push('{');
2596 for (i, item) in items.iter().enumerate() {
2597 if i > 0 {
2598 out.push(',');
2599 }
2600 match item {
2601 None => out.push_str("NULL"),
2602 Some(n) => out.push_str(&n.to_string()),
2603 }
2604 }
2605 out.push('}');
2606 out
2607}
2608
2609pub fn format_bigint_array(items: &[Option<i64>]) -> String {
2612 let mut out = String::with_capacity(2 + items.len() * 6);
2613 out.push('{');
2614 for (i, item) in items.iter().enumerate() {
2615 if i > 0 {
2616 out.push(',');
2617 }
2618 match item {
2619 None => out.push_str("NULL"),
2620 Some(n) => out.push_str(&n.to_string()),
2621 }
2622 }
2623 out.push('}');
2624 out
2625}
2626
2627pub fn format_tsvector(lexs: &[TsLexeme]) -> String {
2633 let mut out = String::with_capacity(lexs.len() * 12);
2634 for (i, l) in lexs.iter().enumerate() {
2635 if i > 0 {
2636 out.push(' ');
2637 }
2638 out.push('\'');
2639 for c in l.word.chars() {
2640 if c == '\'' {
2641 out.push('\'');
2642 }
2643 out.push(c);
2644 }
2645 out.push('\'');
2646 if !l.positions.is_empty() {
2647 for (pi, p) in l.positions.iter().enumerate() {
2648 out.push(if pi == 0 { ':' } else { ',' });
2649 out.push_str(&p.to_string());
2650 }
2651 match l.weight {
2656 3 => out.push('A'),
2657 2 => out.push('B'),
2658 1 => out.push('C'),
2659 _ => {}
2660 }
2661 }
2662 }
2663 out
2664}
2665
2666pub fn format_tsquery(ast: &TsQueryAst) -> String {
2669 fn go(ast: &TsQueryAst, parent_prec: u8, out: &mut String) {
2670 let (own_prec, write_self): (u8, &dyn Fn(&mut String)) = match ast {
2672 TsQueryAst::Or(_, _) => (1, &|_| {}),
2673 TsQueryAst::And(_, _) | TsQueryAst::Phrase { .. } => (2, &|_| {}),
2674 TsQueryAst::Not(_) => (3, &|_| {}),
2675 TsQueryAst::Term { .. } => (4, &|_| {}),
2676 };
2677 let need_parens = own_prec < parent_prec;
2678 if need_parens {
2679 out.push('(');
2680 }
2681 match ast {
2682 TsQueryAst::Term { word, .. } => {
2683 out.push('\'');
2684 for c in word.chars() {
2685 if c == '\'' {
2686 out.push('\'');
2687 }
2688 out.push(c);
2689 }
2690 out.push('\'');
2691 }
2692 TsQueryAst::And(a, b) => {
2693 go(a, own_prec, out);
2694 out.push_str(" & ");
2695 go(b, own_prec, out);
2696 }
2697 TsQueryAst::Or(a, b) => {
2698 go(a, own_prec, out);
2699 out.push_str(" | ");
2700 go(b, own_prec, out);
2701 }
2702 TsQueryAst::Not(x) => {
2703 out.push('!');
2704 go(x, own_prec, out);
2705 }
2706 TsQueryAst::Phrase {
2707 left,
2708 right,
2709 distance,
2710 } => {
2711 go(left, own_prec, out);
2712 out.push_str(&alloc::format!(" <{distance}> "));
2713 go(right, own_prec, out);
2714 }
2715 }
2716 write_self(out);
2717 if need_parens {
2718 out.push(')');
2719 }
2720 }
2721 let mut out = String::new();
2722 go(ast, 0, &mut out);
2723 out
2724}
2725
2726pub fn decode_tsvector_external(s: &str) -> Result<Vec<TsLexeme>, EvalError> {
2735 let mut out: Vec<TsLexeme> = Vec::new();
2736 let mut i = 0;
2737 let bytes = s.as_bytes();
2738 while i < bytes.len() {
2739 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
2740 i += 1;
2741 }
2742 if i >= bytes.len() {
2743 break;
2744 }
2745 let word = if bytes[i] == b'\'' {
2748 i += 1;
2749 let mut w = String::new();
2750 loop {
2751 if i >= bytes.len() {
2752 return Err(EvalError::TypeMismatch {
2753 detail: "tsvector literal: unterminated quoted lexeme".into(),
2754 });
2755 }
2756 let b = bytes[i];
2757 if b == b'\'' {
2758 if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
2759 w.push('\'');
2760 i += 2;
2761 } else {
2762 i += 1;
2763 break;
2764 }
2765 } else {
2766 w.push(b as char);
2767 i += 1;
2768 }
2769 }
2770 w
2771 } else {
2772 let start = i;
2774 while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b':' {
2775 i += 1;
2776 }
2777 core::str::from_utf8(&bytes[start..i])
2778 .map_err(|_| EvalError::TypeMismatch {
2779 detail: "tsvector literal: non-UTF-8 lexeme".into(),
2780 })?
2781 .to_string()
2782 };
2783 if word.is_empty() {
2784 return Err(EvalError::TypeMismatch {
2785 detail: "tsvector literal: empty lexeme".into(),
2786 });
2787 }
2788 let mut positions: Vec<u16> = Vec::new();
2791 let mut weight: u8 = 0;
2792 if i < bytes.len() && bytes[i] == b':' {
2793 i += 1;
2794 loop {
2795 let start = i;
2796 while i < bytes.len() && bytes[i].is_ascii_digit() {
2797 i += 1;
2798 }
2799 if start == i {
2800 return Err(EvalError::TypeMismatch {
2801 detail: "tsvector literal: expected digit after ':'".into(),
2802 });
2803 }
2804 let num: u16 = core::str::from_utf8(&bytes[start..i])
2805 .expect("ascii digits")
2806 .parse()
2807 .map_err(|_| EvalError::TypeMismatch {
2808 detail: alloc::format!(
2809 "tsvector literal: position {} overflows u16",
2810 core::str::from_utf8(&bytes[start..i]).unwrap_or("?")
2811 ),
2812 })?;
2813 positions.push(num);
2814 if i < bytes.len() {
2815 let w = bytes[i];
2816 if matches!(w, b'A' | b'B' | b'C' | b'D') {
2817 weight = match w {
2818 b'A' => 3,
2819 b'B' => 2,
2820 b'C' => 1,
2821 _ => 0,
2822 };
2823 i += 1;
2824 }
2825 }
2826 if i < bytes.len() && bytes[i] == b',' {
2827 i += 1;
2828 continue;
2829 }
2830 break;
2831 }
2832 }
2833 positions.sort_unstable();
2834 positions.dedup();
2835 match out.binary_search_by(|l| l.word.as_str().cmp(word.as_str())) {
2838 Ok(idx) => {
2839 for p in positions {
2840 if !out[idx].positions.contains(&p) {
2841 out[idx].positions.push(p);
2842 }
2843 }
2844 out[idx].positions.sort_unstable();
2845 if weight != 0 {
2846 out[idx].weight = weight;
2847 }
2848 }
2849 Err(idx) => {
2850 out.insert(
2851 idx,
2852 TsLexeme {
2853 word,
2854 positions,
2855 weight,
2856 },
2857 );
2858 }
2859 }
2860 }
2861 Ok(out)
2862}
2863
2864pub fn decode_tsquery_external(s: &str) -> Result<TsQueryAst, EvalError> {
2870 let mut p = TsQueryParser {
2871 bytes: s.as_bytes(),
2872 pos: 0,
2873 };
2874 p.skip_ws();
2875 if p.pos >= p.bytes.len() {
2876 return Err(EvalError::TypeMismatch {
2877 detail: "tsquery literal: empty".into(),
2878 });
2879 }
2880 let ast = p.parse_or()?;
2881 p.skip_ws();
2882 if p.pos < p.bytes.len() {
2883 return Err(EvalError::TypeMismatch {
2884 detail: alloc::format!("tsquery literal: trailing garbage at offset {}", p.pos),
2885 });
2886 }
2887 Ok(ast)
2888}
2889
2890struct TsQueryParser<'a> {
2891 bytes: &'a [u8],
2892 pos: usize,
2893}
2894
2895impl<'a> TsQueryParser<'a> {
2896 fn skip_ws(&mut self) {
2897 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_whitespace() {
2898 self.pos += 1;
2899 }
2900 }
2901 fn peek(&self) -> Option<u8> {
2902 self.bytes.get(self.pos).copied()
2903 }
2904 fn parse_or(&mut self) -> Result<TsQueryAst, EvalError> {
2905 let mut lhs = self.parse_and()?;
2906 loop {
2907 self.skip_ws();
2908 if self.peek() != Some(b'|') {
2909 return Ok(lhs);
2910 }
2911 self.pos += 1;
2912 let rhs = self.parse_and()?;
2913 lhs = TsQueryAst::Or(Box::new(lhs), Box::new(rhs));
2914 }
2915 }
2916 fn parse_and(&mut self) -> Result<TsQueryAst, EvalError> {
2917 let mut lhs = self.parse_unary()?;
2918 loop {
2919 self.skip_ws();
2920 match self.peek() {
2921 Some(b'&') => {
2922 self.pos += 1;
2923 let rhs = self.parse_unary()?;
2924 lhs = TsQueryAst::And(Box::new(lhs), Box::new(rhs));
2925 }
2926 Some(b'<') => {
2927 self.pos += 1;
2929 let start = self.pos;
2930 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
2931 self.pos += 1;
2932 }
2933 if start == self.pos || self.peek() != Some(b'>') {
2934 return Err(EvalError::TypeMismatch {
2935 detail: "tsquery literal: malformed <N> phrase operator".into(),
2936 });
2937 }
2938 let n: u16 = core::str::from_utf8(&self.bytes[start..self.pos])
2939 .expect("ascii digits")
2940 .parse()
2941 .map_err(|_| EvalError::TypeMismatch {
2942 detail: "tsquery literal: phrase distance overflows u16".into(),
2943 })?;
2944 self.pos += 1; let rhs = self.parse_unary()?;
2946 lhs = TsQueryAst::Phrase {
2947 left: Box::new(lhs),
2948 right: Box::new(rhs),
2949 distance: n,
2950 };
2951 }
2952 _ => return Ok(lhs),
2953 }
2954 }
2955 }
2956 fn parse_unary(&mut self) -> Result<TsQueryAst, EvalError> {
2957 self.skip_ws();
2958 if self.peek() == Some(b'!') {
2959 self.pos += 1;
2960 let inner = self.parse_unary()?;
2961 return Ok(TsQueryAst::Not(Box::new(inner)));
2962 }
2963 self.parse_atom()
2964 }
2965 fn parse_atom(&mut self) -> Result<TsQueryAst, EvalError> {
2966 self.skip_ws();
2967 match self.peek() {
2968 Some(b'(') => {
2969 self.pos += 1;
2970 let inner = self.parse_or()?;
2971 self.skip_ws();
2972 if self.peek() != Some(b')') {
2973 return Err(EvalError::TypeMismatch {
2974 detail: "tsquery literal: missing ')'".into(),
2975 });
2976 }
2977 self.pos += 1;
2978 Ok(inner)
2979 }
2980 Some(b'\'') => {
2981 self.pos += 1;
2982 let mut w = String::new();
2983 loop {
2984 match self.peek() {
2985 None => {
2986 return Err(EvalError::TypeMismatch {
2987 detail: "tsquery literal: unterminated quoted lexeme".into(),
2988 });
2989 }
2990 Some(b'\'') => {
2991 if self.bytes.get(self.pos + 1) == Some(&b'\'') {
2992 w.push('\'');
2993 self.pos += 2;
2994 } else {
2995 self.pos += 1;
2996 break;
2997 }
2998 }
2999 Some(b) => {
3000 w.push(b as char);
3001 self.pos += 1;
3002 }
3003 }
3004 }
3005 self.skip_weight_suffix();
3008 Ok(TsQueryAst::Term {
3009 word: w,
3010 weight_mask: 0,
3011 })
3012 }
3013 Some(b) if b.is_ascii_alphanumeric() || b == b'_' => {
3014 let start = self.pos;
3015 while self.pos < self.bytes.len() {
3016 let c = self.bytes[self.pos];
3017 if c.is_ascii_alphanumeric() || c == b'_' {
3018 self.pos += 1;
3019 } else {
3020 break;
3021 }
3022 }
3023 let w = core::str::from_utf8(&self.bytes[start..self.pos])
3024 .map_err(|_| EvalError::TypeMismatch {
3025 detail: "tsquery literal: non-UTF-8 lexeme".into(),
3026 })?
3027 .to_string();
3028 self.skip_weight_suffix();
3029 Ok(TsQueryAst::Term {
3030 word: w,
3031 weight_mask: 0,
3032 })
3033 }
3034 Some(b) => Err(EvalError::TypeMismatch {
3035 detail: alloc::format!(
3036 "tsquery literal: unexpected byte {:?} at offset {}",
3037 b as char,
3038 self.pos
3039 ),
3040 }),
3041 None => Err(EvalError::TypeMismatch {
3042 detail: "tsquery literal: expected term".into(),
3043 }),
3044 }
3045 }
3046 fn skip_weight_suffix(&mut self) {
3047 if self.peek() != Some(b':') {
3048 return;
3049 }
3050 self.pos += 1;
3051 while let Some(b) = self.peek() {
3052 if matches!(
3053 b,
3054 b'A' | b'B' | b'C' | b'D' | b'a' | b'b' | b'c' | b'd' | b'*'
3055 ) || b.is_ascii_digit()
3056 {
3057 self.pos += 1;
3058 } else {
3059 break;
3060 }
3061 }
3062 }
3063}
3064
3065pub fn format_bytea_hex(b: &[u8]) -> String {
3069 let mut out = String::with_capacity(2 + 2 * b.len());
3070 out.push_str("\\x");
3071 const HEX: &[u8; 16] = b"0123456789abcdef";
3072 for byte in b {
3073 out.push(HEX[(byte >> 4) as usize] as char);
3074 out.push(HEX[(byte & 0x0F) as usize] as char);
3075 }
3076 out
3077}
3078
3079pub fn format_numeric(scaled: i128, scale: u8) -> String {
3084 if scale == 0 {
3085 return format!("{scaled}");
3086 }
3087 let negative = scaled < 0;
3088 let mag_str = scaled.unsigned_abs().to_string();
3089 let mag_bytes = mag_str.as_bytes();
3090 let scale_u = scale as usize;
3091 let mut out = String::with_capacity(mag_str.len() + 3);
3092 if negative {
3093 out.push('-');
3094 }
3095 if mag_bytes.len() <= scale_u {
3096 out.push('0');
3097 out.push('.');
3098 for _ in mag_bytes.len()..scale_u {
3099 out.push('0');
3100 }
3101 out.push_str(&mag_str);
3102 } else {
3103 let split = mag_bytes.len() - scale_u;
3104 out.push_str(&mag_str[..split]);
3105 out.push('.');
3106 out.push_str(&mag_str[split..]);
3107 }
3108 out
3109}
3110
3111fn cast_numeric_to_int(v: Value) -> Result<Value, EvalError> {
3112 match v {
3113 Value::Int(n) => Ok(Value::Int(n)),
3114 Value::BigInt(n) => i32::try_from(n)
3115 .map(Value::Int)
3116 .map_err(|_| EvalError::TypeMismatch {
3117 detail: format!("bigint {n} does not fit in int"),
3118 }),
3119 #[allow(clippy::cast_possible_truncation)]
3120 Value::Float(x) => Ok(Value::Int(x as i32)),
3121 Value::Text(s) => {
3122 s.trim()
3123 .parse::<i32>()
3124 .map(Value::Int)
3125 .map_err(|_| EvalError::TypeMismatch {
3126 detail: format!("cannot parse {s:?} as int"),
3127 })
3128 }
3129 Value::Bool(b) => Ok(Value::Int(i32::from(b))),
3130 other => Err(EvalError::TypeMismatch {
3131 detail: format!("cannot cast {:?} to int", other.data_type()),
3132 }),
3133 }
3134}
3135
3136fn cast_numeric_to_bigint(v: Value) -> Result<Value, EvalError> {
3137 match v {
3138 Value::Int(n) => Ok(Value::BigInt(i64::from(n))),
3139 Value::BigInt(n) => Ok(Value::BigInt(n)),
3140 #[allow(clippy::cast_possible_truncation)]
3141 Value::Float(x) => Ok(Value::BigInt(x as i64)),
3142 Value::Text(s) => {
3143 s.trim()
3144 .parse::<i64>()
3145 .map(Value::BigInt)
3146 .map_err(|_| EvalError::TypeMismatch {
3147 detail: format!("cannot parse {s:?} as bigint"),
3148 })
3149 }
3150 Value::Bool(b) => Ok(Value::BigInt(i64::from(b))),
3151 other => Err(EvalError::TypeMismatch {
3152 detail: format!("cannot cast {:?} to bigint", other.data_type()),
3153 }),
3154 }
3155}
3156
3157fn cast_numeric_to_float(v: Value) -> Result<Value, EvalError> {
3158 match v {
3159 Value::Int(n) => Ok(Value::Float(f64::from(n))),
3160 #[allow(clippy::cast_precision_loss)]
3161 Value::BigInt(n) => Ok(Value::Float(n as f64)),
3162 Value::Float(x) => Ok(Value::Float(x)),
3163 Value::Text(s) => {
3164 s.trim()
3165 .parse::<f64>()
3166 .map(Value::Float)
3167 .map_err(|_| EvalError::TypeMismatch {
3168 detail: format!("cannot parse {s:?} as float"),
3169 })
3170 }
3171 other => Err(EvalError::TypeMismatch {
3172 detail: format!("cannot cast {:?} to float", other.data_type()),
3173 }),
3174 }
3175}
3176
3177fn cast_to_bool(v: Value) -> Result<Value, EvalError> {
3178 match v {
3179 Value::Bool(b) => Ok(Value::Bool(b)),
3180 Value::Int(n) => Ok(Value::Bool(n != 0)),
3181 Value::BigInt(n) => Ok(Value::Bool(n != 0)),
3182 Value::Text(s) => {
3183 let lo = s.trim().to_ascii_lowercase();
3184 match lo.as_str() {
3185 "true" | "t" | "yes" | "y" | "1" | "on" => Ok(Value::Bool(true)),
3186 "false" | "f" | "no" | "n" | "0" | "off" => Ok(Value::Bool(false)),
3187 _ => Err(EvalError::TypeMismatch {
3188 detail: format!("cannot parse {s:?} as bool"),
3189 }),
3190 }
3191 }
3192 other => Err(EvalError::TypeMismatch {
3193 detail: format!("cannot cast {:?} to bool", other.data_type()),
3194 }),
3195 }
3196}
3197
3198pub fn cast_to_vector(v: Value) -> Result<Value, EvalError> {
3201 match v {
3202 Value::Null => Ok(Value::Null),
3203 Value::Vector(v) => Ok(Value::Vector(v)),
3204 Value::Text(s) => parse_vector_text(&s)
3205 .map(Value::Vector)
3206 .ok_or(EvalError::TypeMismatch {
3207 detail: format!("cannot parse {s:?} as a vector literal"),
3208 }),
3209 other => Err(EvalError::TypeMismatch {
3210 detail: format!("::vector requires text input, got {:?}", other.data_type()),
3211 }),
3212 }
3213}
3214
3215fn parse_vector_text(s: &str) -> Option<Vec<f32>> {
3217 let trimmed = s.trim();
3218 let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?;
3219 let trimmed_inner = inner.trim();
3220 if trimmed_inner.is_empty() {
3221 return Some(Vec::new());
3222 }
3223 let mut out = Vec::new();
3224 for part in trimmed_inner.split(',') {
3225 let f: f32 = part.trim().parse().ok()?;
3226 out.push(f);
3227 }
3228 Some(out)
3229}
3230
3231fn literal_to_value(l: &Literal) -> Value {
3232 match l {
3233 Literal::Integer(n) => {
3234 if let Ok(small) = i32::try_from(*n) {
3235 Value::Int(small)
3236 } else {
3237 Value::BigInt(*n)
3238 }
3239 }
3240 Literal::Float(x) => Value::Float(*x),
3241 Literal::String(s) => Value::Text(s.clone()),
3242 Literal::Vector(v) => Value::Vector(v.clone()),
3243 Literal::Bool(b) => Value::Bool(*b),
3244 Literal::Null => Value::Null,
3245 Literal::Interval { months, micros, .. } => Value::Interval {
3246 months: *months,
3247 micros: *micros,
3248 },
3249 }
3250}
3251
3252fn resolve_column(c: &ColumnName, row: &Row, ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
3253 if let Some(q) = &c.qualifier {
3254 let composite = alloc::format!("{q}.{name}", name = c.name);
3259 if let Some(pos) = ctx.columns.iter().position(|s| s.name == composite) {
3260 return Ok(row.values[pos].clone());
3261 }
3262 let expected = ctx.table_alias.ok_or_else(|| EvalError::UnknownQualifier {
3263 qualifier: q.clone(),
3264 })?;
3265 if q != expected {
3266 return Err(EvalError::UnknownQualifier {
3267 qualifier: q.clone(),
3268 });
3269 }
3270 }
3271 if let Some(pos) = ctx.columns.iter().position(|s| s.name == c.name) {
3272 return Ok(row.values[pos].clone());
3273 }
3274 let suffix = alloc::format!(".{name}", name = c.name);
3277 let mut matches = ctx
3278 .columns
3279 .iter()
3280 .enumerate()
3281 .filter(|(_, s)| s.name.ends_with(&suffix));
3282 let first = matches.next();
3283 let extra = matches.next();
3284 match (first, extra) {
3285 (Some((pos, _)), None) => Ok(row.values[pos].clone()),
3286 (Some(_), Some(_)) => Err(EvalError::TypeMismatch {
3287 detail: alloc::format!("ambiguous column reference: {}", c.name),
3288 }),
3289 _ => Err(EvalError::ColumnNotFound {
3290 name: c.name.clone(),
3291 }),
3292 }
3293}
3294
3295fn apply_unary(op: UnOp, v: Value) -> Result<Value, EvalError> {
3296 match (op, v) {
3297 (_, Value::Null) => Ok(Value::Null),
3298 (UnOp::Neg, Value::Int(n)) => {
3299 n.checked_neg()
3300 .map(Value::Int)
3301 .ok_or(EvalError::TypeMismatch {
3302 detail: "integer overflow on unary -".into(),
3303 })
3304 }
3305 (UnOp::Neg, Value::BigInt(n)) => {
3306 n.checked_neg()
3307 .map(Value::BigInt)
3308 .ok_or(EvalError::TypeMismatch {
3309 detail: "bigint overflow on unary -".into(),
3310 })
3311 }
3312 (UnOp::Neg, Value::Float(x)) => Ok(Value::Float(-x)),
3313 (UnOp::Neg, other) => Err(EvalError::TypeMismatch {
3314 detail: format!("unary - applied to {:?}", other.data_type()),
3315 }),
3316 (UnOp::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
3317 (UnOp::Not, other) => Err(EvalError::TypeMismatch {
3318 detail: format!("NOT applied to {:?}", other.data_type()),
3319 }),
3320 }
3321}
3322
3323fn values_not_distinct(l: &Value, r: &Value) -> bool {
3326 match (l, r) {
3327 (Value::Null, Value::Null) => true,
3328 (Value::Null, _) | (_, Value::Null) => false,
3329 _ => l == r,
3330 }
3331}
3332
3333fn apply_binary(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
3334 if let BinOp::And = op {
3337 return and_3vl(l, r);
3338 }
3339 if let BinOp::Or = op {
3340 return or_3vl(l, r);
3341 }
3342 if let BinOp::IsNotDistinctFrom = op {
3345 return Ok(Value::Bool(values_not_distinct(&l, &r)));
3346 }
3347 if let BinOp::IsDistinctFrom = op {
3348 return Ok(Value::Bool(!values_not_distinct(&l, &r)));
3349 }
3350 if l.is_null() || r.is_null() {
3352 return Ok(Value::Null);
3353 }
3354 if matches!(l, Value::Numeric { .. }) || matches!(r, Value::Numeric { .. }) {
3357 return apply_binary_numeric(op, l, r);
3358 }
3359 if let Some(result) = apply_binary_calendar(op, &l, &r)? {
3367 return Ok(result);
3368 }
3369 match op {
3370 BinOp::Add => arith(l, r, i64::checked_add, |a, b| a + b, "+"),
3371 BinOp::Sub => arith(l, r, i64::checked_sub, |a, b| a - b, "-"),
3372 BinOp::Mul => arith(l, r, i64::checked_mul, |a, b| a * b, "*"),
3373 BinOp::Div => div_op(l, r),
3374 BinOp::L2Distance => l2_distance(l, r),
3375 BinOp::InnerProduct => inner_product(l, r),
3376 BinOp::CosineDistance => cosine_distance(l, r),
3377 BinOp::Concat => Ok(text_concat(&l, &r)),
3378 BinOp::JsonGet => crate::json::path_get(&l, &r, false),
3379 BinOp::JsonGetText => crate::json::path_get(&l, &r, true),
3380 BinOp::JsonGetPath => crate::json::path_walk(&l, &r, false),
3381 BinOp::JsonGetPathText => crate::json::path_walk(&l, &r, true),
3382 BinOp::JsonContains => crate::json::contains(&l, &r),
3383 BinOp::TsMatch => ts_match(l, r),
3386 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
3387 compare(op, &l, &r)
3388 }
3389 BinOp::And | BinOp::Or | BinOp::IsDistinctFrom | BinOp::IsNotDistinctFrom => {
3390 unreachable!("handled above")
3391 }
3392 }
3393}
3394
3395fn apply_binary_calendar(op: BinOp, l: &Value, r: &Value) -> Result<Option<Value>, EvalError> {
3399 let int_value = |v: &Value| -> Option<i64> {
3400 match v {
3401 Value::SmallInt(n) => Some(i64::from(*n)),
3402 Value::Int(n) => Some(i64::from(*n)),
3403 Value::BigInt(n) => Some(*n),
3404 _ => None,
3405 }
3406 };
3407 match (l, r) {
3411 (Value::Date(a), Value::Date(b)) if op == BinOp::Sub => {
3412 return Ok(Some(Value::BigInt(i64::from(*a) - i64::from(*b))));
3413 }
3414 (Value::Timestamp(a), Value::Timestamp(b)) if op == BinOp::Sub => {
3415 let delta = a.checked_sub(*b).ok_or(EvalError::TypeMismatch {
3416 detail: "TIMESTAMP - TIMESTAMP overflows i64 microseconds".into(),
3417 })?;
3418 return Ok(Some(Value::BigInt(delta)));
3419 }
3420 _ => {}
3421 }
3422 if let Some(out) = apply_binary_interval(op, l, r)? {
3426 return Ok(Some(out));
3427 }
3428 match (l, r) {
3429 (Value::Date(d), other) if op == BinOp::Add => {
3430 if let Some(n) = int_value(other) {
3431 let days = i64::from(*d).saturating_add(n);
3432 let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3433 detail: "DATE + integer overflows DATE range".into(),
3434 })?;
3435 return Ok(Some(Value::Date(days32)));
3436 }
3437 }
3438 (other, Value::Date(d)) if op == BinOp::Add => {
3439 if let Some(n) = int_value(other) {
3440 let days = i64::from(*d).saturating_add(n);
3441 let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3442 detail: "integer + DATE overflows DATE range".into(),
3443 })?;
3444 return Ok(Some(Value::Date(days32)));
3445 }
3446 }
3447 (Value::Date(d), other) if op == BinOp::Sub => {
3448 if let Some(n) = int_value(other) {
3449 let days = i64::from(*d).saturating_sub(n);
3450 let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3451 detail: "DATE - integer overflows DATE range".into(),
3452 })?;
3453 return Ok(Some(Value::Date(days32)));
3454 }
3455 }
3456 _ => {}
3457 }
3458 Ok(None)
3459}
3460
3461fn apply_binary_interval(op: BinOp, l: &Value, r: &Value) -> Result<Option<Value>, EvalError> {
3469 let (lhs, rhs, sign): (&Value, &Value, i64) = match (l, r, op) {
3472 (Value::Interval { .. }, _, BinOp::Add) => (r, l, 1),
3473 (_, Value::Interval { .. }, BinOp::Add) => (l, r, 1),
3474 (_, Value::Interval { .. }, BinOp::Sub) => (l, r, -1),
3475 _ => return Ok(None),
3476 };
3477 let Value::Interval {
3478 months: rhs_months,
3479 micros: rhs_us,
3480 } = rhs
3481 else {
3482 unreachable!("rhs guaranteed to be Interval by the match above");
3483 };
3484 let signed_months = i64::from(*rhs_months) * sign;
3485 let signed_micros = rhs_us.checked_mul(sign).ok_or(EvalError::TypeMismatch {
3486 detail: "INTERVAL micros overflows on negation".into(),
3487 })?;
3488 match lhs {
3489 Value::Timestamp(t) => Ok(Some(Value::Timestamp(add_interval_to_micros(
3490 *t,
3491 signed_months,
3492 signed_micros,
3493 )?))),
3494 Value::Date(d) => {
3495 let day_aligned = signed_micros.rem_euclid(86_400_000_000) == 0;
3499 if day_aligned {
3500 let micros_per_day = 86_400_000_000_i64;
3501 let days_delta = signed_micros / micros_per_day;
3502 let shifted = shift_date_by_months(*d, signed_months)?;
3503 let new_days =
3504 i64::from(shifted)
3505 .checked_add(days_delta)
3506 .ok_or(EvalError::TypeMismatch {
3507 detail: "DATE ± INTERVAL overflows DATE range".into(),
3508 })?;
3509 let days32 = i32::try_from(new_days).map_err(|_| EvalError::TypeMismatch {
3510 detail: "DATE ± INTERVAL overflows DATE range".into(),
3511 })?;
3512 Ok(Some(Value::Date(days32)))
3513 } else {
3514 let base =
3515 i64::from(*d)
3516 .checked_mul(86_400_000_000)
3517 .ok_or(EvalError::TypeMismatch {
3518 detail: "DATE → TIMESTAMP lift overflows for INTERVAL math".into(),
3519 })?;
3520 Ok(Some(Value::Timestamp(add_interval_to_micros(
3521 base,
3522 signed_months,
3523 signed_micros,
3524 )?)))
3525 }
3526 }
3527 Value::Interval {
3528 months: lhs_months,
3529 micros: lhs_us,
3530 } => {
3531 let new_months = i64::from(*lhs_months)
3532 .checked_add(signed_months)
3533 .and_then(|n| i32::try_from(n).ok())
3534 .ok_or(EvalError::TypeMismatch {
3535 detail: "INTERVAL ± INTERVAL months overflows i32".into(),
3536 })?;
3537 let new_micros = lhs_us
3538 .checked_add(signed_micros)
3539 .ok_or(EvalError::TypeMismatch {
3540 detail: "INTERVAL ± INTERVAL micros overflows i64".into(),
3541 })?;
3542 Ok(Some(Value::Interval {
3543 months: new_months,
3544 micros: new_micros,
3545 }))
3546 }
3547 _ => Err(EvalError::TypeMismatch {
3548 detail: format!(
3549 "operator {op:?} not defined for {:?} and INTERVAL",
3550 lhs.data_type()
3551 ),
3552 }),
3553 }
3554}
3555
3556fn shift_date_by_months(d: i32, months: i64) -> Result<i32, EvalError> {
3558 let (y, m, day) = civil_from_days(d);
3559 let months_i32 = i32::try_from(months).map_err(|_| EvalError::TypeMismatch {
3560 detail: "INTERVAL months delta out of i32 range".into(),
3561 })?;
3562 let (ny, nm, nd) = add_months_to_civil(y, m, day, months_i32);
3563 Ok(days_from_civil(ny, nm, nd))
3564}
3565
3566fn add_interval_to_micros(t: i64, months: i64, micros: i64) -> Result<i64, EvalError> {
3570 let mut out = t;
3571 if months != 0 {
3572 const MICROS_PER_DAY: i64 = 86_400_000_000;
3573 let days = out.div_euclid(MICROS_PER_DAY);
3574 let day_micros = out.rem_euclid(MICROS_PER_DAY);
3575 let day_i32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3576 detail: "TIMESTAMP day component out of i32 range for INTERVAL months math".into(),
3577 })?;
3578 let shifted_days = shift_date_by_months(day_i32, months)?;
3579 out = i64::from(shifted_days)
3580 .checked_mul(MICROS_PER_DAY)
3581 .and_then(|n| n.checked_add(day_micros))
3582 .ok_or(EvalError::TypeMismatch {
3583 detail: "TIMESTAMP ± INTERVAL months overflows i64 microseconds".into(),
3584 })?;
3585 }
3586 out.checked_add(micros).ok_or(EvalError::TypeMismatch {
3587 detail: "TIMESTAMP ± INTERVAL micros overflows i64".into(),
3588 })
3589}
3590
3591#[allow(clippy::needless_pass_by_value)] fn apply_binary_numeric(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
3596 let float_path = matches!(l, Value::Float(_)) || matches!(r, Value::Float(_));
3600 if float_path {
3601 let af = as_f64(&l)?;
3602 let bf = as_f64(&r)?;
3603 return match op {
3604 BinOp::Add => Ok(Value::Float(af + bf)),
3605 BinOp::Sub => Ok(Value::Float(af - bf)),
3606 BinOp::Mul => Ok(Value::Float(af * bf)),
3607 BinOp::Div => {
3608 if bf == 0.0 {
3609 Err(EvalError::DivisionByZero)
3610 } else {
3611 Ok(Value::Float(af / bf))
3612 }
3613 }
3614 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
3615 let ord = af.partial_cmp(&bf).ok_or(EvalError::TypeMismatch {
3616 detail: "NaN in NUMERIC/Float comparison".into(),
3617 })?;
3618 Ok(Value::Bool(cmp_to_bool(op, ord)))
3619 }
3620 BinOp::Concat => Ok(text_concat(&l, &r)),
3621 other => Err(EvalError::TypeMismatch {
3622 detail: format!("operator {other:?} not defined for NUMERIC and Float"),
3623 }),
3624 };
3625 }
3626 let (a, sa) = numeric_or_widen(&l).ok_or_else(|| EvalError::TypeMismatch {
3628 detail: format!("NUMERIC op against non-numeric {:?}", l.data_type()),
3629 })?;
3630 let (b, sb) = numeric_or_widen(&r).ok_or_else(|| EvalError::TypeMismatch {
3631 detail: format!("NUMERIC op against non-numeric {:?}", r.data_type()),
3632 })?;
3633 match op {
3634 BinOp::Add | BinOp::Sub => {
3635 let target_scale = sa.max(sb);
3636 let lhs = rescale(a, sa, target_scale).ok_or(EvalError::TypeMismatch {
3637 detail: "NUMERIC overflow on rescale".into(),
3638 })?;
3639 let rhs = rescale(b, sb, target_scale).ok_or(EvalError::TypeMismatch {
3640 detail: "NUMERIC overflow on rescale".into(),
3641 })?;
3642 let r = match op {
3643 BinOp::Add => lhs.checked_add(rhs),
3644 BinOp::Sub => lhs.checked_sub(rhs),
3645 _ => unreachable!(),
3646 }
3647 .ok_or(EvalError::TypeMismatch {
3648 detail: "NUMERIC overflow on +/-".into(),
3649 })?;
3650 Ok(Value::Numeric {
3651 scaled: r,
3652 scale: target_scale,
3653 })
3654 }
3655 BinOp::Mul => {
3656 let scaled = a.checked_mul(b).ok_or(EvalError::TypeMismatch {
3657 detail: "NUMERIC overflow on *".into(),
3658 })?;
3659 Ok(Value::Numeric {
3660 scaled,
3661 scale: sa.saturating_add(sb),
3662 })
3663 }
3664 BinOp::Div => {
3665 if b == 0 {
3666 return Err(EvalError::DivisionByZero);
3667 }
3668 let target_scale = sa.max(sb);
3672 let bump = pow10_i128(target_scale.saturating_add(sb).saturating_sub(sa));
3676 let num = a.checked_mul(bump).ok_or(EvalError::TypeMismatch {
3677 detail: "NUMERIC overflow on / scaling".into(),
3678 })?;
3679 let half = if b >= 0 { b / 2 } else { -(b / 2) };
3680 let adj = if (num >= 0) == (b >= 0) {
3681 num + half
3682 } else {
3683 num - half
3684 };
3685 Ok(Value::Numeric {
3686 scaled: adj / b,
3687 scale: target_scale,
3688 })
3689 }
3690 BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
3691 let target_scale = sa.max(sb);
3692 let lhs = rescale(a, sa, target_scale).ok_or(EvalError::TypeMismatch {
3693 detail: "NUMERIC overflow on rescale".into(),
3694 })?;
3695 let rhs = rescale(b, sb, target_scale).ok_or(EvalError::TypeMismatch {
3696 detail: "NUMERIC overflow on rescale".into(),
3697 })?;
3698 Ok(Value::Bool(cmp_to_bool(op, lhs.cmp(&rhs))))
3699 }
3700 BinOp::Concat => Ok(text_concat(&l, &r)),
3701 other => Err(EvalError::TypeMismatch {
3702 detail: format!("operator {other:?} not defined for NUMERIC"),
3703 }),
3704 }
3705}
3706
3707fn numeric_or_widen(v: &Value) -> Option<(i128, u8)> {
3711 match v {
3712 Value::Numeric { scaled, scale } => Some((*scaled, *scale)),
3713 Value::Int(n) => Some((i128::from(*n), 0)),
3714 Value::SmallInt(n) => Some((i128::from(*n), 0)),
3715 Value::BigInt(n) => Some((i128::from(*n), 0)),
3716 _ => None,
3717 }
3718}
3719
3720fn rescale(scaled: i128, src: u8, dst: u8) -> Option<i128> {
3721 if src == dst {
3722 return Some(scaled);
3723 }
3724 if dst > src {
3725 scaled.checked_mul(pow10_i128(dst - src))
3726 } else {
3727 let drop = pow10_i128(src - dst);
3728 let half = drop / 2;
3729 let r = if scaled >= 0 {
3730 scaled + half
3731 } else {
3732 scaled - half
3733 };
3734 Some(r / drop)
3735 }
3736}
3737
3738const fn pow10_i128(p: u8) -> i128 {
3739 let mut acc: i128 = 1;
3740 let mut i = 0;
3741 while i < p {
3742 acc *= 10;
3743 i += 1;
3744 }
3745 acc
3746}
3747
3748const fn cmp_to_bool(op: BinOp, ord: core::cmp::Ordering) -> bool {
3749 use core::cmp::Ordering::{Equal, Greater, Less};
3750 match op {
3751 BinOp::Eq => matches!(ord, Equal),
3752 BinOp::NotEq => !matches!(ord, Equal),
3753 BinOp::Lt => matches!(ord, Less),
3754 BinOp::LtEq => matches!(ord, Less | Equal),
3755 BinOp::Gt => matches!(ord, Greater),
3756 BinOp::GtEq => matches!(ord, Greater | Equal),
3757 _ => false,
3758 }
3759}
3760
3761fn text_concat(l: &Value, r: &Value) -> Value {
3765 match (l, r) {
3770 (Value::Null, _) | (_, Value::Null) => {
3771 if matches!(
3775 l,
3776 Value::TextArray(_) | Value::IntArray(_) | Value::BigIntArray(_) | Value::Bytes(_)
3777 ) || matches!(
3778 r,
3779 Value::TextArray(_) | Value::IntArray(_) | Value::BigIntArray(_) | Value::Bytes(_)
3780 ) {
3781 return Value::Null;
3782 }
3783 }
3784 (Value::TextArray(a), Value::TextArray(b)) => {
3785 let mut out = a.clone();
3786 out.extend(b.iter().cloned());
3787 return Value::TextArray(out);
3788 }
3789 (Value::TextArray(a), Value::Text(s)) => {
3790 let mut out = a.clone();
3791 out.push(Some(s.clone()));
3792 return Value::TextArray(out);
3793 }
3794 (Value::Text(s), Value::TextArray(b)) => {
3795 let mut out: alloc::vec::Vec<Option<alloc::string::String>> =
3796 alloc::vec::Vec::with_capacity(1 + b.len());
3797 out.push(Some(s.clone()));
3798 out.extend(b.iter().cloned());
3799 return Value::TextArray(out);
3800 }
3801 (Value::IntArray(a), Value::IntArray(b)) => {
3806 let mut out = a.clone();
3807 out.extend(b.iter().copied());
3808 return Value::IntArray(out);
3809 }
3810 (Value::IntArray(a), Value::Int(n)) => {
3811 let mut out = a.clone();
3812 out.push(Some(*n));
3813 return Value::IntArray(out);
3814 }
3815 (Value::IntArray(a), Value::SmallInt(n)) => {
3816 let mut out = a.clone();
3817 out.push(Some(i32::from(*n)));
3818 return Value::IntArray(out);
3819 }
3820 (Value::Int(n), Value::IntArray(b)) => {
3821 let mut out: alloc::vec::Vec<Option<i32>> = alloc::vec::Vec::with_capacity(1 + b.len());
3822 out.push(Some(*n));
3823 out.extend(b.iter().copied());
3824 return Value::IntArray(out);
3825 }
3826 (Value::SmallInt(n), Value::IntArray(b)) => {
3827 let mut out: alloc::vec::Vec<Option<i32>> = alloc::vec::Vec::with_capacity(1 + b.len());
3828 out.push(Some(i32::from(*n)));
3829 out.extend(b.iter().copied());
3830 return Value::IntArray(out);
3831 }
3832 (Value::BigIntArray(a), Value::BigIntArray(b)) => {
3833 let mut out = a.clone();
3834 out.extend(b.iter().copied());
3835 return Value::BigIntArray(out);
3836 }
3837 (Value::BigIntArray(a), Value::IntArray(b)) => {
3838 let mut out = a.clone();
3839 out.extend(b.iter().map(|o| o.map(i64::from)));
3840 return Value::BigIntArray(out);
3841 }
3842 (Value::IntArray(a), Value::BigIntArray(b)) => {
3843 let mut out: alloc::vec::Vec<Option<i64>> =
3844 a.iter().map(|o| o.map(i64::from)).collect();
3845 out.extend(b.iter().copied());
3846 return Value::BigIntArray(out);
3847 }
3848 (Value::BigIntArray(a), Value::BigInt(n)) => {
3849 let mut out = a.clone();
3850 out.push(Some(*n));
3851 return Value::BigIntArray(out);
3852 }
3853 (Value::BigIntArray(a), Value::Int(n)) => {
3854 let mut out = a.clone();
3855 out.push(Some(i64::from(*n)));
3856 return Value::BigIntArray(out);
3857 }
3858 (Value::BigIntArray(a), Value::SmallInt(n)) => {
3859 let mut out = a.clone();
3860 out.push(Some(i64::from(*n)));
3861 return Value::BigIntArray(out);
3862 }
3863 (Value::BigInt(n), Value::BigIntArray(b)) => {
3864 let mut out: alloc::vec::Vec<Option<i64>> = alloc::vec::Vec::with_capacity(1 + b.len());
3865 out.push(Some(*n));
3866 out.extend(b.iter().copied());
3867 return Value::BigIntArray(out);
3868 }
3869 (Value::Int(n), Value::BigIntArray(b)) => {
3870 let mut out: alloc::vec::Vec<Option<i64>> = alloc::vec::Vec::with_capacity(1 + b.len());
3871 out.push(Some(i64::from(*n)));
3872 out.extend(b.iter().copied());
3873 return Value::BigIntArray(out);
3874 }
3875 (Value::SmallInt(n), Value::BigIntArray(b)) => {
3876 let mut out: alloc::vec::Vec<Option<i64>> = alloc::vec::Vec::with_capacity(1 + b.len());
3877 out.push(Some(i64::from(*n)));
3878 out.extend(b.iter().copied());
3879 return Value::BigIntArray(out);
3880 }
3881 (Value::Bytes(a), Value::Bytes(b)) => {
3883 let mut out = a.clone();
3884 out.extend_from_slice(b);
3885 return Value::Bytes(out);
3886 }
3887 _ => {}
3888 }
3889 let a = value_to_text(l);
3890 let b = value_to_text(r);
3891 Value::Text(a + &b)
3892}
3893
3894fn inner_product(l: Value, r: Value) -> Result<Value, EvalError> {
3897 let (a, b) = unwrap_vec_pair(l, r, "<#>")?;
3898 let mut dot: f64 = 0.0;
3899 for (x, y) in a.iter().zip(b.iter()) {
3900 dot += f64::from(*x) * f64::from(*y);
3901 }
3902 Ok(Value::Float(-dot))
3903}
3904
3905fn cosine_distance(l: Value, r: Value) -> Result<Value, EvalError> {
3908 let (a, b) = unwrap_vec_pair(l, r, "<=>")?;
3909 let mut dot: f64 = 0.0;
3910 let mut na: f64 = 0.0;
3911 let mut nb: f64 = 0.0;
3912 for (x, y) in a.iter().zip(b.iter()) {
3913 let xf = f64::from(*x);
3914 let yf = f64::from(*y);
3915 dot += xf * yf;
3916 na += xf * xf;
3917 nb += yf * yf;
3918 }
3919 let denom = sqrt_newton(na) * sqrt_newton(nb);
3920 if denom == 0.0 {
3921 return Ok(Value::Float(f64::NAN));
3922 }
3923 Ok(Value::Float(1.0 - dot / denom))
3924}
3925
3926fn unwrap_vec_pair(l: Value, r: Value, op: &str) -> Result<(Vec<f32>, Vec<f32>), EvalError> {
3927 let to_f32 = |v: Value| -> Option<Vec<f32>> {
3935 match v {
3936 Value::Vector(a) => Some(a),
3937 Value::Sq8Vector(q) => Some(spg_storage::quantize::dequantize(&q)),
3938 Value::HalfVector(h) => Some(h.to_f32_vec()),
3940 _ => None,
3941 }
3942 };
3943 let l_ty = l.data_type();
3944 let r_ty = r.data_type();
3945 match (to_f32(l), to_f32(r)) {
3946 (Some(a), Some(b)) => {
3947 if a.len() != b.len() {
3948 return Err(EvalError::TypeMismatch {
3949 detail: format!("vector dim mismatch in {op}: {} vs {}", a.len(), b.len()),
3950 });
3951 }
3952 Ok((a, b))
3953 }
3954 _ => Err(EvalError::TypeMismatch {
3955 detail: format!("{op} requires two vectors, got {l_ty:?} and {r_ty:?}"),
3956 }),
3957 }
3958}
3959
3960fn arith(
3965 l: Value,
3966 r: Value,
3967 int_op: impl Fn(i64, i64) -> Option<i64>,
3968 float_op: impl Fn(f64, f64) -> f64,
3969 op_name: &str,
3970) -> Result<Value, EvalError> {
3971 let widen = |v: Value| -> Value {
3974 match v {
3975 Value::SmallInt(n) => Value::Int(i32::from(n)),
3976 other => other,
3977 }
3978 };
3979 let l = widen(l);
3980 let r = widen(r);
3981 match (l, r) {
3982 (Value::Int(a), Value::Int(b)) => {
3983 let result = int_op(i64::from(a), i64::from(b)).ok_or(EvalError::TypeMismatch {
3984 detail: format!("integer overflow on {op_name}"),
3985 })?;
3986 if let Ok(small) = i32::try_from(result) {
3987 Ok(Value::Int(small))
3988 } else {
3989 Ok(Value::BigInt(result))
3990 }
3991 }
3992 (Value::Int(a), Value::BigInt(b)) | (Value::BigInt(b), Value::Int(a)) => {
3993 let result = int_op(i64::from(a), b).ok_or(EvalError::TypeMismatch {
3994 detail: format!("bigint overflow on {op_name}"),
3995 })?;
3996 Ok(Value::BigInt(result))
3997 }
3998 (Value::BigInt(a), Value::BigInt(b)) => {
3999 let result = int_op(a, b).ok_or(EvalError::TypeMismatch {
4000 detail: format!("bigint overflow on {op_name}"),
4001 })?;
4002 Ok(Value::BigInt(result))
4003 }
4004 (a, b)
4005 if a.data_type() == Some(DataType::Float) || b.data_type() == Some(DataType::Float) =>
4006 {
4007 let af = as_f64(&a)?;
4008 let bf = as_f64(&b)?;
4009 Ok(Value::Float(float_op(af, bf)))
4010 }
4011 (a, b) => Err(EvalError::TypeMismatch {
4012 detail: format!(
4013 "{op_name} applied to non-numeric: {:?} vs {:?}",
4014 a.data_type(),
4015 b.data_type()
4016 ),
4017 }),
4018 }
4019}
4020
4021#[allow(clippy::many_single_char_names)] fn l2_distance(l: Value, r: Value) -> Result<Value, EvalError> {
4027 let (a, b) = unwrap_vec_pair(l, r, "<->")?;
4032 let mut sum: f64 = 0.0;
4033 for (x, y) in a.iter().zip(b.iter()) {
4034 let d = f64::from(*x) - f64::from(*y);
4035 sum += d * d;
4036 }
4037 Ok(Value::Float(sqrt_newton(sum)))
4038}
4039
4040fn sqrt_newton(x: f64) -> f64 {
4045 if x <= 0.0 {
4046 return 0.0;
4047 }
4048 let mut g = x;
4049 for _ in 0..10 {
4052 g = 0.5 * (g + x / g);
4053 }
4054 g
4055}
4056
4057fn div_op(l: Value, r: Value) -> Result<Value, EvalError> {
4058 let any_float = matches!(l.data_type(), Some(DataType::Float))
4059 || matches!(r.data_type(), Some(DataType::Float));
4060 if any_float {
4061 let a = as_f64(&l)?;
4062 let b = as_f64(&r)?;
4063 if b == 0.0 {
4064 return Err(EvalError::DivisionByZero);
4065 }
4066 return Ok(Value::Float(a / b));
4067 }
4068 arith(
4069 l,
4070 r,
4071 |a, b| {
4072 if b == 0 { None } else { Some(a / b) }
4073 },
4074 |a, b| a / b,
4075 "/",
4076 )
4077 .map_err(|e| match e {
4078 EvalError::TypeMismatch { detail } if detail.contains('/') => EvalError::DivisionByZero,
4081 other => other,
4082 })
4083}
4084
4085fn as_f64(v: &Value) -> Result<f64, EvalError> {
4086 match v {
4087 Value::SmallInt(n) => Ok(f64::from(*n)),
4088 Value::Int(n) => Ok(f64::from(*n)),
4089 #[allow(clippy::cast_precision_loss)]
4090 Value::BigInt(n) => Ok(*n as f64),
4091 Value::Float(x) => Ok(*x),
4092 #[allow(clippy::cast_precision_loss)]
4093 Value::Numeric { scaled, scale } => {
4094 let mut div = 1.0_f64;
4095 for _ in 0..*scale {
4096 div *= 10.0;
4097 }
4098 Ok((*scaled as f64) / div)
4099 }
4100 other => Err(EvalError::TypeMismatch {
4101 detail: format!("cannot convert {:?} to FLOAT", other.data_type()),
4102 }),
4103 }
4104}
4105
4106fn compare(op: BinOp, l: &Value, r: &Value) -> Result<Value, EvalError> {
4107 let ord = match (l, r) {
4108 (Value::Int(a), Value::Int(b)) => i64::from(*a).cmp(&i64::from(*b)),
4109 (Value::Int(a), Value::BigInt(b)) => i64::from(*a).cmp(b),
4110 (Value::BigInt(a), Value::Int(b)) => a.cmp(&i64::from(*b)),
4111 (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b),
4112 (a, b)
4113 if matches!(a.data_type(), Some(DataType::Float))
4114 || matches!(b.data_type(), Some(DataType::Float)) =>
4115 {
4116 let af = as_f64(a)?;
4117 let bf = as_f64(b)?;
4118 af.partial_cmp(&bf).ok_or(EvalError::TypeMismatch {
4119 detail: "NaN in comparison".into(),
4120 })?
4121 }
4122 (Value::Text(a), Value::Text(b)) => a.cmp(b),
4123 (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
4124 (Value::Date(a), Value::Date(b)) => a.cmp(b),
4128 (Value::Timestamp(a), Value::Timestamp(b)) => a.cmp(b),
4129 (Value::Date(a), Value::Timestamp(b)) => (i64::from(*a) * 86_400_000_000).cmp(b),
4130 (Value::Timestamp(a), Value::Date(b)) => a.cmp(&(i64::from(*b) * 86_400_000_000)),
4131 (Value::Date(a), Value::Text(b)) => {
4135 let bd = parse_date_literal(b).ok_or_else(|| EvalError::TypeMismatch {
4136 detail: format!("cannot parse {b:?} as DATE for comparison"),
4137 })?;
4138 a.cmp(&bd)
4139 }
4140 (Value::Text(a), Value::Date(b)) => {
4141 let ad = parse_date_literal(a).ok_or_else(|| EvalError::TypeMismatch {
4142 detail: format!("cannot parse {a:?} as DATE for comparison"),
4143 })?;
4144 ad.cmp(b)
4145 }
4146 (Value::Timestamp(a), Value::Text(b)) => {
4147 let bt = parse_timestamp_literal(b).ok_or_else(|| EvalError::TypeMismatch {
4148 detail: format!("cannot parse {b:?} as TIMESTAMP for comparison"),
4149 })?;
4150 a.cmp(&bt)
4151 }
4152 (Value::Text(a), Value::Timestamp(b)) => {
4153 let at = parse_timestamp_literal(a).ok_or_else(|| EvalError::TypeMismatch {
4154 detail: format!("cannot parse {a:?} as TIMESTAMP for comparison"),
4155 })?;
4156 at.cmp(b)
4157 }
4158 (a, b) => {
4159 return Err(EvalError::TypeMismatch {
4160 detail: format!(
4161 "comparison between {:?} and {:?}",
4162 a.data_type(),
4163 b.data_type()
4164 ),
4165 });
4166 }
4167 };
4168 let result = match op {
4169 BinOp::Eq => ord.is_eq(),
4170 BinOp::NotEq => !ord.is_eq(),
4171 BinOp::Lt => ord.is_lt(),
4172 BinOp::LtEq => ord.is_le(),
4173 BinOp::Gt => ord.is_gt(),
4174 BinOp::GtEq => ord.is_ge(),
4175 BinOp::And
4176 | BinOp::Or
4177 | BinOp::Add
4178 | BinOp::Sub
4179 | BinOp::Mul
4180 | BinOp::Div
4181 | BinOp::L2Distance
4182 | BinOp::InnerProduct
4183 | BinOp::CosineDistance
4184 | BinOp::Concat
4185 | BinOp::JsonGet
4186 | BinOp::JsonGetText
4187 | BinOp::JsonGetPath
4188 | BinOp::JsonGetPathText
4189 | BinOp::JsonContains
4190 | BinOp::TsMatch
4191 | BinOp::IsDistinctFrom
4192 | BinOp::IsNotDistinctFrom => {
4193 unreachable!("compare() only called with comparison ops")
4194 }
4195 };
4196 Ok(Value::Bool(result))
4197}
4198
4199fn and_3vl(l: Value, r: Value) -> Result<Value, EvalError> {
4201 match (l, r) {
4202 (Value::Bool(false), _) | (_, Value::Bool(false)) => Ok(Value::Bool(false)),
4203 (Value::Bool(true), Value::Bool(true)) => Ok(Value::Bool(true)),
4204 (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
4205 (a, b) => Err(EvalError::TypeMismatch {
4206 detail: format!(
4207 "AND on non-boolean: {:?} and {:?}",
4208 a.data_type(),
4209 b.data_type()
4210 ),
4211 }),
4212 }
4213}
4214
4215fn or_3vl(l: Value, r: Value) -> Result<Value, EvalError> {
4216 match (l, r) {
4217 (Value::Bool(true), _) | (_, Value::Bool(true)) => Ok(Value::Bool(true)),
4218 (Value::Bool(false), Value::Bool(false)) => Ok(Value::Bool(false)),
4219 (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
4220 (a, b) => Err(EvalError::TypeMismatch {
4221 detail: format!(
4222 "OR on non-boolean: {:?} and {:?}",
4223 a.data_type(),
4224 b.data_type()
4225 ),
4226 }),
4227 }
4228}
4229
4230#[cfg(test)]
4231mod tests {
4232 use super::*;
4233 use alloc::vec;
4234 use spg_storage::{ColumnSchema, Row};
4235
4236 fn col(name: &str, ty: DataType) -> ColumnSchema {
4237 ColumnSchema::new(name, ty, true)
4238 }
4239
4240 fn ctx<'a>(cols: &'a [ColumnSchema], alias: Option<&'a str>) -> EvalContext<'a> {
4241 EvalContext::new(cols, alias)
4242 }
4243
4244 fn lit(n: i64) -> Expr {
4245 Expr::Literal(Literal::Integer(n))
4246 }
4247
4248 fn null() -> Expr {
4249 Expr::Literal(Literal::Null)
4250 }
4251
4252 fn col_ref(name: &str) -> Expr {
4253 Expr::Column(ColumnName {
4254 qualifier: None,
4255 name: name.into(),
4256 })
4257 }
4258
4259 #[test]
4260 fn literal_evaluates_to_value() {
4261 let r = Row::new(vec![]);
4262 let cs: [ColumnSchema; 0] = [];
4263 let c = ctx(&cs, None);
4264 assert_eq!(eval_expr(&lit(42), &r, &c).unwrap(), Value::Int(42));
4265 assert_eq!(
4266 eval_expr(&Expr::Literal(Literal::Float(1.5)), &r, &c).unwrap(),
4267 Value::Float(1.5)
4268 );
4269 assert_eq!(eval_expr(&null(), &r, &c).unwrap(), Value::Null);
4270 }
4271
4272 #[test]
4273 fn column_lookup_unqualified() {
4274 let cs = vec![col("a", DataType::Int), col("b", DataType::Text)];
4275 let r = Row::new(vec![Value::Int(7), Value::Text("hi".into())]);
4276 let c = ctx(&cs, None);
4277 assert_eq!(eval_expr(&col_ref("a"), &r, &c).unwrap(), Value::Int(7));
4278 assert_eq!(
4279 eval_expr(&col_ref("b"), &r, &c).unwrap(),
4280 Value::Text("hi".into())
4281 );
4282 }
4283
4284 #[test]
4285 fn column_not_found_errors() {
4286 let cs = vec![col("a", DataType::Int)];
4287 let r = Row::new(vec![Value::Int(0)]);
4288 let c = ctx(&cs, None);
4289 let err = eval_expr(&col_ref("ghost"), &r, &c).unwrap_err();
4290 assert!(matches!(err, EvalError::ColumnNotFound { ref name } if name == "ghost"));
4291 }
4292
4293 #[test]
4294 fn qualified_column_matches_alias() {
4295 let cs = vec![col("a", DataType::Int)];
4296 let r = Row::new(vec![Value::Int(5)]);
4297 let c = ctx(&cs, Some("u"));
4298 let qualified = Expr::Column(ColumnName {
4299 qualifier: Some("u".into()),
4300 name: "a".into(),
4301 });
4302 assert_eq!(eval_expr(&qualified, &r, &c).unwrap(), Value::Int(5));
4303 }
4304
4305 #[test]
4306 fn qualified_column_unknown_alias_errors() {
4307 let cs = vec![col("a", DataType::Int)];
4308 let r = Row::new(vec![Value::Int(5)]);
4309 let c = ctx(&cs, Some("u"));
4310 let wrong = Expr::Column(ColumnName {
4311 qualifier: Some("x".into()),
4312 name: "a".into(),
4313 });
4314 assert!(matches!(
4315 eval_expr(&wrong, &r, &c).unwrap_err(),
4316 EvalError::UnknownQualifier { .. }
4317 ));
4318 }
4319
4320 #[test]
4321 fn arithmetic_with_widening() {
4322 let r = Row::new(vec![]);
4323 let cs: [ColumnSchema; 0] = [];
4324 let c = ctx(&cs, None);
4325 let e = Expr::Binary {
4326 lhs: alloc::boxed::Box::new(lit(2)),
4327 op: BinOp::Add,
4328 rhs: alloc::boxed::Box::new(Expr::Literal(Literal::Float(0.5))),
4329 };
4330 assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Float(2.5));
4331 }
4332
4333 #[test]
4334 fn division_by_zero_errors() {
4335 let r = Row::new(vec![]);
4336 let cs: [ColumnSchema; 0] = [];
4337 let c = ctx(&cs, None);
4338 let e = Expr::Binary {
4339 lhs: alloc::boxed::Box::new(lit(1)),
4340 op: BinOp::Div,
4341 rhs: alloc::boxed::Box::new(lit(0)),
4342 };
4343 assert_eq!(
4344 eval_expr(&e, &r, &c).unwrap_err(),
4345 EvalError::DivisionByZero
4346 );
4347 }
4348
4349 #[test]
4350 fn comparison_returns_bool() {
4351 let r = Row::new(vec![]);
4352 let cs: [ColumnSchema; 0] = [];
4353 let c = ctx(&cs, None);
4354 let e = Expr::Binary {
4355 lhs: alloc::boxed::Box::new(lit(1)),
4356 op: BinOp::Lt,
4357 rhs: alloc::boxed::Box::new(lit(2)),
4358 };
4359 assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
4360 }
4361
4362 #[test]
4363 fn null_propagates_through_arithmetic() {
4364 let r = Row::new(vec![]);
4365 let cs: [ColumnSchema; 0] = [];
4366 let c = ctx(&cs, None);
4367 let e = Expr::Binary {
4368 lhs: alloc::boxed::Box::new(lit(1)),
4369 op: BinOp::Add,
4370 rhs: alloc::boxed::Box::new(null()),
4371 };
4372 assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
4373 }
4374
4375 #[test]
4376 fn and_three_valued_logic() {
4377 let r = Row::new(vec![]);
4378 let cs: [ColumnSchema; 0] = [];
4379 let c = ctx(&cs, None);
4380 let tt = |a: bool, b_null: bool| Expr::Binary {
4381 lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
4382 op: BinOp::And,
4383 rhs: alloc::boxed::Box::new(if b_null {
4384 null()
4385 } else {
4386 Expr::Literal(Literal::Bool(true))
4387 }),
4388 };
4389 assert_eq!(
4391 eval_expr(&tt(false, true), &r, &c).unwrap(),
4392 Value::Bool(false)
4393 );
4394 assert_eq!(eval_expr(&tt(true, true), &r, &c).unwrap(), Value::Null);
4396 assert_eq!(
4398 eval_expr(&tt(true, false), &r, &c).unwrap(),
4399 Value::Bool(true)
4400 );
4401 }
4402
4403 #[test]
4404 fn or_three_valued_logic() {
4405 let r = Row::new(vec![]);
4406 let cs: [ColumnSchema; 0] = [];
4407 let c = ctx(&cs, None);
4408 let or_with_null = |a: bool| Expr::Binary {
4409 lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
4410 op: BinOp::Or,
4411 rhs: alloc::boxed::Box::new(null()),
4412 };
4413 assert_eq!(
4415 eval_expr(&or_with_null(true), &r, &c).unwrap(),
4416 Value::Bool(true)
4417 );
4418 assert_eq!(
4420 eval_expr(&or_with_null(false), &r, &c).unwrap(),
4421 Value::Null
4422 );
4423 }
4424
4425 #[test]
4426 fn not_on_null_is_null() {
4427 let r = Row::new(vec![]);
4428 let cs: [ColumnSchema; 0] = [];
4429 let c = ctx(&cs, None);
4430 let e = Expr::Unary {
4431 op: UnOp::Not,
4432 expr: alloc::boxed::Box::new(null()),
4433 };
4434 assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
4435 }
4436
4437 #[test]
4438 fn text_comparison_lexicographic() {
4439 let r = Row::new(vec![]);
4440 let cs: [ColumnSchema; 0] = [];
4441 let c = ctx(&cs, None);
4442 let e = Expr::Binary {
4443 lhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("apple".into()))),
4444 op: BinOp::Lt,
4445 rhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("banana".into()))),
4446 };
4447 assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
4448 }
4449
4450 #[test]
4451 fn interval_format_basics() {
4452 assert_eq!(format_interval(0, 0), "0");
4453 assert_eq!(format_interval(0, 86_400_000_000), "1 day");
4454 assert_eq!(format_interval(0, -86_400_000_000), "-1 days");
4455 assert_eq!(format_interval(0, 3_600_000_000), "01:00:00");
4456 assert_eq!(
4457 format_interval(0, 86_400_000_000 + 9_000_000),
4458 "1 day 00:00:09"
4459 );
4460 assert_eq!(format_interval(14, 0), "1 year 2 mons");
4461 assert_eq!(format_interval(-1, 0), "-1 mons");
4462 }
4463
4464 #[test]
4465 fn interval_add_to_timestamp_micros_part() {
4466 let ts = i64::from(days_from_civil(2024, 1, 1)) * 86_400_000_000;
4468 let r = add_interval_to_micros(ts, 0, 3_600_000_000).unwrap();
4469 let expected = ts + 3_600_000_000;
4470 assert_eq!(r, expected);
4471 }
4472
4473 #[test]
4474 fn interval_clamp_month_end() {
4475 let d = days_from_civil(2024, 1, 31);
4477 let shifted = shift_date_by_months(d, 1).unwrap();
4478 let (y, m, day) = civil_from_days(shifted);
4479 assert_eq!((y, m, day), (2024, 2, 29));
4480 let d = days_from_civil(2023, 1, 31);
4482 let shifted = shift_date_by_months(d, 1).unwrap();
4483 let (y, m, day) = civil_from_days(shifted);
4484 assert_eq!((y, m, day), (2023, 2, 28));
4485 let d = days_from_civil(2024, 3, 31);
4487 let shifted = shift_date_by_months(d, -1).unwrap();
4488 let (y, m, day) = civil_from_days(shifted);
4489 assert_eq!((y, m, day), (2024, 2, 29));
4490 }
4491
4492 #[test]
4493 fn interval_date_plus_pure_days_stays_date() {
4494 let d = days_from_civil(2024, 6, 1);
4496 let lhs = Value::Date(d);
4497 let rhs = Value::Interval {
4498 months: 0,
4499 micros: 7 * 86_400_000_000,
4500 };
4501 let v = apply_binary_interval(BinOp::Add, &lhs, &rhs)
4502 .unwrap()
4503 .unwrap();
4504 let expected = days_from_civil(2024, 6, 8);
4505 assert_eq!(v, Value::Date(expected));
4506 }
4507
4508 #[test]
4509 fn interval_date_plus_sub_day_lifts_to_timestamp() {
4510 let d = days_from_civil(2024, 6, 1);
4512 let lhs = Value::Date(d);
4513 let rhs = Value::Interval {
4514 months: 0,
4515 micros: 3_600_000_000,
4516 };
4517 let v = apply_binary_interval(BinOp::Add, &lhs, &rhs)
4518 .unwrap()
4519 .unwrap();
4520 let expected = i64::from(d) * 86_400_000_000 + 3_600_000_000;
4521 assert_eq!(v, Value::Timestamp(expected));
4522 }
4523}