Skip to main content

reifydb_routine/function/date/
age.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::{
6	error::TypeError,
7	value::{container::temporal::TemporalContainer, date::Date, duration::Duration, r#type::Type},
8};
9
10use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
11
12pub struct DateAge {
13	info: RoutineInfo,
14}
15
16impl Default for DateAge {
17	fn default() -> Self {
18		Self::new()
19	}
20}
21
22impl DateAge {
23	pub fn new() -> Self {
24		Self {
25			info: RoutineInfo::new("date::age"),
26		}
27	}
28}
29
30/// Compute calendar-aware age between two dates.
31/// Returns Duration with months + days components.
32pub fn date_age(d1: &Date, d2: &Date) -> Result<Duration, Box<TypeError>> {
33	let y1 = d1.year();
34	let m1 = d1.month() as i32;
35	let day1 = d1.day() as i32;
36
37	let y2 = d2.year();
38	let m2 = d2.month() as i32;
39	let day2 = d2.day() as i32;
40
41	let mut years = y1 - y2;
42	let mut months = m1 - m2;
43	let mut days = day1 - day2;
44
45	if days < 0 {
46		months -= 1;
47		// Borrow days from previous month (relative to d2's perspective)
48		let borrow_month = if m1 - 1 < 1 {
49			12
50		} else {
51			m1 - 1
52		};
53		let borrow_year = if m1 - 1 < 1 {
54			y1 - 1
55		} else {
56			y1
57		};
58		days += Date::days_in_month(borrow_year, borrow_month as u32) as i32;
59	}
60
61	if months < 0 {
62		years -= 1;
63		months += 12;
64	}
65
66	let total_months = years * 12 + months;
67	Duration::new(total_months, days, 0)
68}
69
70impl<'a> Routine<FunctionContext<'a>> for DateAge {
71	fn info(&self) -> &RoutineInfo {
72		&self.info
73	}
74
75	fn return_type(&self, _input_types: &[Type]) -> Type {
76		Type::Duration
77	}
78
79	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
80		if args.len() != 2 {
81			return Err(RoutineError::FunctionArityMismatch {
82				function: ctx.fragment.clone(),
83				expected: 2,
84				actual: args.len(),
85			});
86		}
87
88		let col1 = &args[0];
89		let col2 = &args[1];
90		let (data1, bitvec1) = col1.unwrap_option();
91		let (data2, bitvec2) = col2.unwrap_option();
92		let row_count = data1.len();
93
94		let result_data = match (data1, data2) {
95			(ColumnBuffer::Date(container1), ColumnBuffer::Date(container2)) => {
96				let mut container = TemporalContainer::with_capacity(row_count);
97
98				for i in 0..row_count {
99					match (container1.get(i), container2.get(i)) {
100						(Some(d1), Some(d2)) => {
101							container.push(date_age(d1, d2)?);
102						}
103						_ => container.push_default(),
104					}
105				}
106
107				ColumnBuffer::Duration(container)
108			}
109			(ColumnBuffer::Date(_), other) => {
110				return Err(RoutineError::FunctionInvalidArgumentType {
111					function: ctx.fragment.clone(),
112					argument_index: 1,
113					expected: vec![Type::Date],
114					actual: other.get_type(),
115				});
116			}
117			(other, _) => {
118				return Err(RoutineError::FunctionInvalidArgumentType {
119					function: ctx.fragment.clone(),
120					argument_index: 0,
121					expected: vec![Type::Date],
122					actual: other.get_type(),
123				});
124			}
125		};
126
127		let final_data = match (bitvec1, bitvec2) {
128			(Some(bv), _) | (_, Some(bv)) => ColumnBuffer::Option {
129				inner: Box::new(result_data),
130				bitvec: bv.clone(),
131			},
132			_ => result_data,
133		};
134
135		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
136	}
137}
138
139impl Function for DateAge {
140	fn kinds(&self) -> &[FunctionKind] {
141		&[FunctionKind::Scalar]
142	}
143}