Skip to main content

reifydb_function/datetime/
subtract.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
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::{
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_seconds =
73									base_days * 86400 + time_nanos / 1_000_000_000;
74								let nano_rem = time_nanos % 1_000_000_000;
75								let (total_seconds, nano_part) = if nano_rem < 0 {
76									(
77										total_seconds - 1,
78										(1_000_000_000 + nano_rem) as u32,
79									)
80								} else {
81									(total_seconds, nano_rem as u32)
82								};
83
84								match DateTime::from_parts(total_seconds, nano_part) {
85									Ok(result) => container.push(result),
86									Err(_) => container.push_default(),
87								}
88							} else {
89								container.push_default();
90							}
91						}
92						_ => container.push_default(),
93					}
94				}
95
96				Ok(ColumnData::DateTime(container))
97			}
98			(ColumnData::DateTime(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
99				function: ctx.fragment.clone(),
100				argument_index: 1,
101				expected: vec![Type::Duration],
102				actual: other.get_type(),
103			}),
104			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
105				function: ctx.fragment.clone(),
106				argument_index: 0,
107				expected: vec![Type::DateTime],
108				actual: other.get_type(),
109			}),
110		}
111	}
112
113	fn return_type(&self, _input_types: &[Type]) -> Type {
114		Type::DateTime
115	}
116}
117
118fn days_in_month(year: i32, month: u32) -> u32 {
119	match month {
120		1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
121		4 | 6 | 9 | 11 => 30,
122		2 => {
123			if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
124				29
125			} else {
126				28
127			}
128		}
129		_ => 0,
130	}
131}