Skip to main content

reifydb_routine/function/datetime/
subtract.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::{container::temporal::TemporalContainer, date::Date, datetime::DateTime, r#type::Type};
6
7use crate::function::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct DateTimeSubtract;
14
15impl DateTimeSubtract {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21impl ScalarFunction for DateTimeSubtract {
22	fn scalar(&self, ctx: ScalarFunctionContext) -> ScalarFunctionResult<ColumnData> {
23		if let Some(result) = propagate_options(self, &ctx) {
24			return result;
25		}
26		let columns = ctx.columns;
27		let row_count = ctx.row_count;
28
29		if columns.len() != 2 {
30			return Err(ScalarFunctionError::ArityMismatch {
31				function: ctx.fragment.clone(),
32				expected: 2,
33				actual: columns.len(),
34			});
35		}
36
37		let dt_col = columns.get(0).unwrap();
38		let dur_col = columns.get(1).unwrap();
39
40		match (dt_col.data(), dur_col.data()) {
41			(ColumnData::DateTime(dt_container), ColumnData::Duration(dur_container)) => {
42				let mut container = TemporalContainer::with_capacity(row_count);
43
44				for i in 0..row_count {
45					match (dt_container.get(i), dur_container.get(i)) {
46						(Some(dt), Some(dur)) => {
47							let date = dt.date();
48							let time = dt.time();
49							let mut year = date.year();
50							let mut month = date.month() as i32;
51							let mut day = date.day();
52
53							// Subtract months component
54							let total_months = month - dur.get_months();
55							year += (total_months - 1).div_euclid(12);
56							month = (total_months - 1).rem_euclid(12) + 1;
57
58							// Clamp day to valid range for the new month
59							let max_day = days_in_month(year, month as u32);
60							if day > max_day {
61								day = max_day;
62							}
63
64							// Convert to seconds since epoch and subtract day/nanos
65							// components
66							if let Some(base_date) = Date::new(year, month as u32, day) {
67								let base_days = base_date.to_days_since_epoch() as i64
68									- dur.get_days() as i64;
69								let time_nanos = time.to_nanos_since_midnight() as i64
70									- dur.get_nanos();
71
72								let total_nanos = base_days as i128
73									* 86_400_000_000_000i128 + time_nanos
74									as i128;
75
76								if total_nanos >= 0 && total_nanos <= u64::MAX as i128 {
77									container.push(DateTime::from_nanos(
78										total_nanos as u64,
79									));
80								} else {
81									return Err(ScalarFunctionError::ExecutionFailed {
82										function: ctx.fragment.clone(),
83										reason: "datetime cannot be before Unix epoch".to_string(),
84									});
85								}
86							} else {
87								return Err(ScalarFunctionError::ExecutionFailed {
88									function: ctx.fragment.clone(),
89									reason: "datetime cannot be before Unix epoch"
90										.to_string(),
91								});
92							}
93						}
94						_ => container.push_default(),
95					}
96				}
97
98				Ok(ColumnData::DateTime(container))
99			}
100			(ColumnData::DateTime(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
101				function: ctx.fragment.clone(),
102				argument_index: 1,
103				expected: vec![Type::Duration],
104				actual: other.get_type(),
105			}),
106			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
107				function: ctx.fragment.clone(),
108				argument_index: 0,
109				expected: vec![Type::DateTime],
110				actual: other.get_type(),
111			}),
112		}
113	}
114
115	fn return_type(&self, _input_types: &[Type]) -> Type {
116		Type::DateTime
117	}
118}
119
120fn days_in_month(year: i32, month: u32) -> u32 {
121	match month {
122		1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
123		4 | 6 | 9 | 11 => 30,
124		2 => {
125			if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
126				29
127			} else {
128				28
129			}
130		}
131		_ => 0,
132	}
133}