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::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::{
6	error::TypeError,
7	value::{container::temporal::TemporalContainer, date::Date, duration::Duration, r#type::Type},
8};
9
10use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
11
12pub struct DateAge {
13	info: FunctionInfo,
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: FunctionInfo::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 Function for DateAge {
71	fn info(&self) -> &FunctionInfo {
72		&self.info
73	}
74
75	fn capabilities(&self) -> &[FunctionCapability] {
76		&[FunctionCapability::Scalar]
77	}
78
79	fn return_type(&self, _input_types: &[Type]) -> Type {
80		Type::Duration
81	}
82
83	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
84		if args.len() != 2 {
85			return Err(FunctionError::ArityMismatch {
86				function: ctx.fragment.clone(),
87				expected: 2,
88				actual: args.len(),
89			});
90		}
91
92		let col1 = &args[0];
93		let col2 = &args[1];
94		let (data1, bitvec1) = col1.data().unwrap_option();
95		let (data2, bitvec2) = col2.data().unwrap_option();
96		let row_count = data1.len();
97
98		let result_data = match (data1, data2) {
99			(ColumnData::Date(container1), ColumnData::Date(container2)) => {
100				let mut container = TemporalContainer::with_capacity(row_count);
101
102				for i in 0..row_count {
103					match (container1.get(i), container2.get(i)) {
104						(Some(d1), Some(d2)) => {
105							container.push(date_age(d1, d2)?);
106						}
107						_ => container.push_default(),
108					}
109				}
110
111				ColumnData::Duration(container)
112			}
113			(ColumnData::Date(_), other) => {
114				return Err(FunctionError::InvalidArgumentType {
115					function: ctx.fragment.clone(),
116					argument_index: 1,
117					expected: vec![Type::Date],
118					actual: other.get_type(),
119				});
120			}
121			(other, _) => {
122				return Err(FunctionError::InvalidArgumentType {
123					function: ctx.fragment.clone(),
124					argument_index: 0,
125					expected: vec![Type::Date],
126					actual: other.get_type(),
127				});
128			}
129		};
130
131		let final_data = match (bitvec1, bitvec2) {
132			(Some(bv), _) | (_, Some(bv)) => ColumnData::Option {
133				inner: Box::new(result_data),
134				bitvec: bv.clone(),
135			},
136			_ => result_data,
137		};
138
139		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
140	}
141}