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