Skip to main content

reifydb_function/datetime/
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, datetime::DateTime, r#type::Type};
6
7use crate::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct DateTimeAdd;
14
15impl DateTimeAdd {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21impl ScalarFunction for DateTimeAdd {
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							// Add 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 add day/nanos components
65							if let Some(base_date) = Date::new(year, month as u32, day) {
66								let base_days = base_date.to_days_since_epoch() as i64
67									+ dur.get_days() as i64;
68								let time_nanos = time.to_nanos_since_midnight() as i64
69									+ dur.get_nanos();
70
71								let total_seconds =
72									base_days * 86400 + time_nanos / 1_000_000_000;
73								let nano_part = (time_nanos % 1_000_000_000) as u32;
74
75								match DateTime::from_parts(total_seconds, nano_part) {
76									Ok(result) => container.push(result),
77									Err(_) => container.push_default(),
78								}
79							} else {
80								container.push_default();
81							}
82						}
83						_ => container.push_default(),
84					}
85				}
86
87				Ok(ColumnData::DateTime(container))
88			}
89			(ColumnData::DateTime(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
90				function: ctx.fragment.clone(),
91				argument_index: 1,
92				expected: vec![Type::Duration],
93				actual: other.get_type(),
94			}),
95			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
96				function: ctx.fragment.clone(),
97				argument_index: 0,
98				expected: vec![Type::DateTime],
99				actual: other.get_type(),
100			}),
101		}
102	}
103
104	fn return_type(&self, _input_types: &[Type]) -> Type {
105		Type::DateTime
106	}
107}
108
109fn days_in_month(year: i32, month: u32) -> u32 {
110	match month {
111		1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
112		4 | 6 | 9 | 11 => 30,
113		2 => {
114			if (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) {
115				29
116			} else {
117				28
118			}
119		}
120		_ => 0,
121	}
122}