Skip to main content

reifydb_routine/function/date/
diff.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{container::temporal::TemporalContainer, duration::Duration, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DateDiff {
10	info: FunctionInfo,
11}
12
13impl Default for DateDiff {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DateDiff {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("date::diff"),
23		}
24	}
25}
26
27impl Function for DateDiff {
28	fn info(&self) -> &FunctionInfo {
29		&self.info
30	}
31
32	fn capabilities(&self) -> &[FunctionCapability] {
33		&[FunctionCapability::Scalar]
34	}
35
36	fn return_type(&self, _input_types: &[Type]) -> Type {
37		Type::Duration
38	}
39
40	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
41		if args.len() != 2 {
42			return Err(FunctionError::ArityMismatch {
43				function: ctx.fragment.clone(),
44				expected: 2,
45				actual: args.len(),
46			});
47		}
48
49		let col1 = &args[0];
50		let col2 = &args[1];
51		let (data1, bitvec1) = col1.data().unwrap_option();
52		let (data2, bitvec2) = col2.data().unwrap_option();
53		let row_count = data1.len();
54
55		let result_data = match (data1, data2) {
56			(ColumnData::Date(container1), ColumnData::Date(container2)) => {
57				let mut container = TemporalContainer::with_capacity(row_count);
58
59				for i in 0..row_count {
60					match (container1.get(i), container2.get(i)) {
61						(Some(d1), Some(d2)) => {
62							let diff_days = (d1.to_days_since_epoch()
63								- d2.to_days_since_epoch()) as i64;
64							container.push(Duration::from_days(diff_days)?);
65						}
66						_ => container.push_default(),
67					}
68				}
69
70				ColumnData::Duration(container)
71			}
72			(ColumnData::Date(_), other) => {
73				return Err(FunctionError::InvalidArgumentType {
74					function: ctx.fragment.clone(),
75					argument_index: 1,
76					expected: vec![Type::Date],
77					actual: other.get_type(),
78				});
79			}
80			(other, _) => {
81				return Err(FunctionError::InvalidArgumentType {
82					function: ctx.fragment.clone(),
83					argument_index: 0,
84					expected: vec![Type::Date],
85					actual: other.get_type(),
86				});
87			}
88		};
89
90		let final_data = match (bitvec1, bitvec2) {
91			(Some(bv), _) | (_, Some(bv)) => ColumnData::Option {
92				inner: Box::new(result_data),
93				bitvec: bv.clone(),
94			},
95			_ => result_data,
96		};
97
98		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
99	}
100}