Skip to main content

reifydb_routine/function/datetime/
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 DateTimeDiff {
10	info: FunctionInfo,
11}
12
13impl Default for DateTimeDiff {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DateTimeDiff {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("datetime::diff"),
23		}
24	}
25}
26
27impl Function for DateTimeDiff {
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::DateTime(container1), ColumnData::DateTime(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(dt1), Some(dt2)) => {
62							let diff_nanos = dt1.to_nanos() as i64 - dt2.to_nanos() as i64;
63							container.push(Duration::from_nanoseconds(diff_nanos)?);
64						}
65						_ => container.push_default(),
66					}
67				}
68
69				ColumnData::Duration(container)
70			}
71			(ColumnData::DateTime(_), other) => {
72				return Err(FunctionError::InvalidArgumentType {
73					function: ctx.fragment.clone(),
74					argument_index: 1,
75					expected: vec![Type::DateTime],
76					actual: other.get_type(),
77				});
78			}
79			(other, _) => {
80				return Err(FunctionError::InvalidArgumentType {
81					function: ctx.fragment.clone(),
82					argument_index: 0,
83					expected: vec![Type::DateTime],
84					actual: other.get_type(),
85				});
86			}
87		};
88
89		let final_data = match (bitvec1, bitvec2) {
90			(Some(bv), _) | (_, Some(bv)) => ColumnData::Option {
91				inner: Box::new(result_data),
92				bitvec: bv.clone(),
93			},
94			_ => result_data,
95		};
96
97		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
98	}
99}