Skip to main content

reifydb_function/date/
format.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::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, date::Date, r#type::Type};
6
7use crate::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct DateFormat;
14
15impl DateFormat {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21fn format_date(year: i32, month: u32, day: u32, day_of_year: u32, fmt: &str) -> Result<String, String> {
22	let mut result = String::new();
23	let mut chars = fmt.chars().peekable();
24
25	while let Some(ch) = chars.next() {
26		if ch == '%' {
27			match chars.next() {
28				Some('Y') => result.push_str(&format!("{:04}", year)),
29				Some('m') => result.push_str(&format!("{:02}", month)),
30				Some('d') => result.push_str(&format!("{:02}", day)),
31				Some('j') => result.push_str(&format!("{:03}", day_of_year)),
32				Some('%') => result.push('%'),
33				Some(c) => return Err(format!("invalid format specifier: '%{}'", c)),
34				None => return Err("unexpected end of format string after '%'".to_string()),
35			}
36		} else {
37			result.push(ch);
38		}
39	}
40
41	Ok(result)
42}
43
44/// Compute day of year from year/month/day
45fn compute_day_of_year(year: i32, month: u32, day: u32) -> u32 {
46	let mut doy = 0u32;
47	for m in 1..month {
48		doy += Date::days_in_month(year, m);
49	}
50	doy + day
51}
52
53impl ScalarFunction for DateFormat {
54	fn scalar(&self, ctx: ScalarFunctionContext) -> ScalarFunctionResult<ColumnData> {
55		if let Some(result) = propagate_options(self, &ctx) {
56			return result;
57		}
58
59		let columns = ctx.columns;
60		let row_count = ctx.row_count;
61
62		if columns.len() != 2 {
63			return Err(ScalarFunctionError::ArityMismatch {
64				function: ctx.fragment.clone(),
65				expected: 2,
66				actual: columns.len(),
67			});
68		}
69
70		let date_col = columns.get(0).unwrap();
71		let fmt_col = columns.get(1).unwrap();
72
73		match (date_col.data(), fmt_col.data()) {
74			(
75				ColumnData::Date(date_container),
76				ColumnData::Utf8 {
77					container: fmt_container,
78					..
79				},
80			) => {
81				let mut result_data = Vec::with_capacity(row_count);
82
83				for i in 0..row_count {
84					match (date_container.get(i), fmt_container.is_defined(i)) {
85						(Some(d), true) => {
86							let fmt_str = &fmt_container[i];
87							let doy = compute_day_of_year(d.year(), d.month(), d.day());
88							match format_date(d.year(), d.month(), d.day(), doy, fmt_str) {
89								Ok(formatted) => {
90									result_data.push(formatted);
91								}
92								Err(reason) => {
93									return Err(
94										ScalarFunctionError::ExecutionFailed {
95											function: ctx.fragment.clone(),
96											reason,
97										},
98									);
99								}
100							}
101						}
102						_ => {
103							result_data.push(String::new());
104						}
105					}
106				}
107
108				Ok(ColumnData::Utf8 {
109					container: Utf8Container::new(result_data),
110					max_bytes: MaxBytes::MAX,
111				})
112			}
113			(ColumnData::Date(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
114				function: ctx.fragment.clone(),
115				argument_index: 1,
116				expected: vec![Type::Utf8],
117				actual: other.get_type(),
118			}),
119			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
120				function: ctx.fragment.clone(),
121				argument_index: 0,
122				expected: vec![Type::Date],
123				actual: other.get_type(),
124			}),
125		}
126	}
127
128	fn return_type(&self, _input_types: &[Type]) -> Type {
129		Type::Utf8
130	}
131}