Skip to main content

reifydb_routine/function/date/
add.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, date::Date, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DateAdd {
10	info: FunctionInfo,
11}
12
13impl Default for DateAdd {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DateAdd {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("date::add"),
23		}
24	}
25}
26
27impl Function for DateAdd {
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::Date
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 date_col = &args[0];
50		let dur_col = &args[1];
51		let (date_data, date_bitvec) = date_col.data().unwrap_option();
52		let (dur_data, dur_bitvec) = dur_col.data().unwrap_option();
53		let row_count = date_data.len();
54
55		let result_data = match (date_data, dur_data) {
56			(ColumnData::Date(date_container), ColumnData::Duration(dur_container)) => {
57				let mut container = TemporalContainer::with_capacity(row_count);
58
59				for i in 0..row_count {
60					match (date_container.get(i), dur_container.get(i)) {
61						(Some(date), Some(dur)) => {
62							let mut year = date.year();
63							let mut month = date.month() as i32;
64							let mut day = date.day();
65
66							// Add months component
67							let total_months = month + dur.get_months();
68							year += (total_months - 1).div_euclid(12);
69							month = (total_months - 1).rem_euclid(12) + 1;
70
71							// Clamp day to valid range for the new month
72							let max_day = days_in_month(year, month as u32);
73							if day > max_day {
74								day = max_day;
75							}
76
77							// Convert to days_since_epoch and add days component
78							if let Some(base) = Date::new(year, month as u32, day) {
79								let total_days = base.to_days_since_epoch()
80									+ dur.get_days() + (dur.get_nanos()
81									/ 86_400_000_000_000)
82									as i32;
83								match Date::from_days_since_epoch(total_days) {
84									Some(result) => container.push(result),
85									None => container.push_default(),
86								}
87							} else {
88								container.push_default();
89							}
90						}
91						_ => container.push_default(),
92					}
93				}
94
95				ColumnData::Date(container)
96			}
97			(ColumnData::Date(_), other) => {
98				return Err(FunctionError::InvalidArgumentType {
99					function: ctx.fragment.clone(),
100					argument_index: 1,
101					expected: vec![Type::Duration],
102					actual: other.get_type(),
103				});
104			}
105			(other, _) => {
106				return Err(FunctionError::InvalidArgumentType {
107					function: ctx.fragment.clone(),
108					argument_index: 0,
109					expected: vec![Type::Date],
110					actual: other.get_type(),
111				});
112			}
113		};
114
115		let final_data = match (date_bitvec, dur_bitvec) {
116			(Some(bv), _) | (_, Some(bv)) => ColumnData::Option {
117				inner: Box::new(result_data),
118				bitvec: bv.clone(),
119			},
120			_ => result_data,
121		};
122
123		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
124	}
125}
126
127fn days_in_month(year: i32, month: u32) -> u32 {
128	match month {
129		1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
130		4 | 6 | 9 | 11 => 30,
131		2 => {
132			if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
133				29
134			} else {
135				28
136			}
137		}
138		_ => 0,
139	}
140}