Skip to main content

reifydb_function/date/
add.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, r#type::Type};
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct DateAdd;
10
11impl DateAdd {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for DateAdd {
18	fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
19		if let Some(result) = propagate_options(self, &ctx) {
20			return result;
21		}
22
23		let columns = ctx.columns;
24		let row_count = ctx.row_count;
25
26		if columns.len() != 2 {
27			return Err(ScalarFunctionError::ArityMismatch {
28				function: ctx.fragment.clone(),
29				expected: 2,
30				actual: columns.len(),
31			});
32		}
33
34		let date_col = columns.get(0).unwrap();
35		let dur_col = columns.get(1).unwrap();
36
37		match (date_col.data(), dur_col.data()) {
38			(ColumnData::Date(date_container), ColumnData::Duration(dur_container)) => {
39				let mut container = TemporalContainer::with_capacity(row_count);
40
41				for i in 0..row_count {
42					match (date_container.get(i), dur_container.get(i)) {
43						(Some(date), Some(dur)) => {
44							let mut year = date.year();
45							let mut month = date.month() as i32;
46							let mut day = date.day();
47
48							// Add months component
49							let total_months = month + dur.get_months();
50							year += (total_months - 1).div_euclid(12);
51							month = (total_months - 1).rem_euclid(12) + 1;
52
53							// Clamp day to valid range for the new month
54							let max_day = days_in_month(year, month as u32);
55							if day > max_day {
56								day = max_day;
57							}
58
59							// Convert to days_since_epoch and add days component
60							if let Some(base) = Date::new(year, month as u32, day) {
61								let total_days = base.to_days_since_epoch()
62									+ dur.get_days() + (dur.get_nanos()
63									/ 86_400_000_000_000)
64									as i32;
65								match Date::from_days_since_epoch(total_days) {
66									Some(result) => container.push(result),
67									None => container.push_default(),
68								}
69							} else {
70								container.push_default();
71							}
72						}
73						_ => container.push_default(),
74					}
75				}
76
77				Ok(ColumnData::Date(container))
78			}
79			(ColumnData::Date(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
80				function: ctx.fragment.clone(),
81				argument_index: 1,
82				expected: vec![Type::Duration],
83				actual: other.get_type(),
84			}),
85			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
86				function: ctx.fragment.clone(),
87				argument_index: 0,
88				expected: vec![Type::Date],
89				actual: other.get_type(),
90			}),
91		}
92	}
93
94	fn return_type(&self, _input_types: &[Type]) -> Type {
95		Type::Date
96	}
97}
98
99fn days_in_month(year: i32, month: u32) -> u32 {
100	match month {
101		1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
102		4 | 6 | 9 | 11 => 30,
103		2 => {
104			if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
105				29
106			} else {
107				28
108			}
109		}
110		_ => 0,
111	}
112}