Skip to main content

reifydb_routine/function/date/
format.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::value::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, date::Date, r#type::Type};
6
7use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
8
9pub struct DateFormat {
10	info: RoutineInfo,
11}
12
13impl Default for DateFormat {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DateFormat {
20	pub fn new() -> Self {
21		Self {
22			info: RoutineInfo::new("date::format"),
23		}
24	}
25}
26
27fn format_date(year: i32, month: u32, day: u32, day_of_year: u32, fmt: &str) -> Result<String, String> {
28	let mut result = String::new();
29	let mut chars = fmt.chars().peekable();
30
31	while let Some(ch) = chars.next() {
32		if ch == '%' {
33			match chars.next() {
34				Some('Y') => result.push_str(&format!("{:04}", year)),
35				Some('m') => result.push_str(&format!("{:02}", month)),
36				Some('d') => result.push_str(&format!("{:02}", day)),
37				Some('j') => result.push_str(&format!("{:03}", day_of_year)),
38				Some('%') => result.push('%'),
39				Some(c) => return Err(format!("invalid format specifier: '%{}'", c)),
40				None => return Err("unexpected end of format string after '%'".to_string()),
41			}
42		} else {
43			result.push(ch);
44		}
45	}
46
47	Ok(result)
48}
49
50fn compute_day_of_year(year: i32, month: u32, day: u32) -> u32 {
51	let mut doy = 0u32;
52	for m in 1..month {
53		doy += Date::days_in_month(year, m);
54	}
55	doy + day
56}
57
58impl<'a> Routine<FunctionContext<'a>> for DateFormat {
59	fn info(&self) -> &RoutineInfo {
60		&self.info
61	}
62
63	fn return_type(&self, _input_types: &[Type]) -> Type {
64		Type::Utf8
65	}
66
67	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
68		if args.len() != 2 {
69			return Err(RoutineError::FunctionArityMismatch {
70				function: ctx.fragment.clone(),
71				expected: 2,
72				actual: args.len(),
73			});
74		}
75
76		let date_col = &args[0];
77		let fmt_col = &args[1];
78		let (date_data, date_bitvec) = date_col.unwrap_option();
79		let (fmt_data, fmt_bitvec) = fmt_col.unwrap_option();
80		let row_count = date_data.len();
81
82		let result_data = match (date_data, fmt_data) {
83			(
84				ColumnBuffer::Date(date_container),
85				ColumnBuffer::Utf8 {
86					container: fmt_container,
87					..
88				},
89			) => {
90				let mut result = Vec::with_capacity(row_count);
91
92				for i in 0..row_count {
93					match (date_container.get(i), fmt_container.is_defined(i)) {
94						(Some(d), true) => {
95							let fmt_str = fmt_container.get(i).unwrap();
96							let doy = compute_day_of_year(d.year(), d.month(), d.day());
97							match format_date(d.year(), d.month(), d.day(), doy, fmt_str) {
98								Ok(formatted) => {
99									result.push(formatted);
100								}
101								Err(reason) => {
102									return Err(
103										RoutineError::FunctionExecutionFailed {
104											function: ctx.fragment.clone(),
105											reason,
106										},
107									);
108								}
109							}
110						}
111						_ => {
112							result.push(String::new());
113						}
114					}
115				}
116
117				ColumnBuffer::Utf8 {
118					container: Utf8Container::new(result),
119					max_bytes: MaxBytes::MAX,
120				}
121			}
122			(ColumnBuffer::Date(_), other) => {
123				return Err(RoutineError::FunctionInvalidArgumentType {
124					function: ctx.fragment.clone(),
125					argument_index: 1,
126					expected: vec![Type::Utf8],
127					actual: other.get_type(),
128				});
129			}
130			(other, _) => {
131				return Err(RoutineError::FunctionInvalidArgumentType {
132					function: ctx.fragment.clone(),
133					argument_index: 0,
134					expected: vec![Type::Date],
135					actual: other.get_type(),
136				});
137			}
138		};
139
140		let final_data = match (date_bitvec, fmt_bitvec) {
141			(Some(bv), _) | (_, Some(bv)) => ColumnBuffer::Option {
142				inner: Box::new(result_data),
143				bitvec: bv.clone(),
144			},
145			_ => result_data,
146		};
147
148		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
149	}
150}
151
152impl Function for DateFormat {
153	fn kinds(&self) -> &[FunctionKind] {
154		&[FunctionKind::Scalar]
155	}
156}