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
50/// Compute day of year from year/month/day
51fn compute_day_of_year(year: i32, month: u32, day: u32) -> u32 {
52	let mut doy = 0u32;
53	for m in 1..month {
54		doy += Date::days_in_month(year, m);
55	}
56	doy + day
57}
58
59impl<'a> Routine<FunctionContext<'a>> for DateFormat {
60	fn info(&self) -> &RoutineInfo {
61		&self.info
62	}
63
64	fn return_type(&self, _input_types: &[Type]) -> Type {
65		Type::Utf8
66	}
67
68	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
69		if args.len() != 2 {
70			return Err(RoutineError::FunctionArityMismatch {
71				function: ctx.fragment.clone(),
72				expected: 2,
73				actual: args.len(),
74			});
75		}
76
77		let date_col = &args[0];
78		let fmt_col = &args[1];
79		let (date_data, date_bitvec) = date_col.unwrap_option();
80		let (fmt_data, fmt_bitvec) = fmt_col.unwrap_option();
81		let row_count = date_data.len();
82
83		let result_data = match (date_data, fmt_data) {
84			(
85				ColumnBuffer::Date(date_container),
86				ColumnBuffer::Utf8 {
87					container: fmt_container,
88					..
89				},
90			) => {
91				let mut result = Vec::with_capacity(row_count);
92
93				for i in 0..row_count {
94					match (date_container.get(i), fmt_container.is_defined(i)) {
95						(Some(d), true) => {
96							let fmt_str = fmt_container.get(i).unwrap();
97							let doy = compute_day_of_year(d.year(), d.month(), d.day());
98							match format_date(d.year(), d.month(), d.day(), doy, fmt_str) {
99								Ok(formatted) => {
100									result.push(formatted);
101								}
102								Err(reason) => {
103									return Err(
104										RoutineError::FunctionExecutionFailed {
105											function: ctx.fragment.clone(),
106											reason,
107										},
108									);
109								}
110							}
111						}
112						_ => {
113							result.push(String::new());
114						}
115					}
116				}
117
118				ColumnBuffer::Utf8 {
119					container: Utf8Container::new(result),
120					max_bytes: MaxBytes::MAX,
121				}
122			}
123			(ColumnBuffer::Date(_), other) => {
124				return Err(RoutineError::FunctionInvalidArgumentType {
125					function: ctx.fragment.clone(),
126					argument_index: 1,
127					expected: vec![Type::Utf8],
128					actual: other.get_type(),
129				});
130			}
131			(other, _) => {
132				return Err(RoutineError::FunctionInvalidArgumentType {
133					function: ctx.fragment.clone(),
134					argument_index: 0,
135					expected: vec![Type::Date],
136					actual: other.get_type(),
137				});
138			}
139		};
140
141		let final_data = match (date_bitvec, fmt_bitvec) {
142			(Some(bv), _) | (_, Some(bv)) => ColumnBuffer::Option {
143				inner: Box::new(result_data),
144				bitvec: bv.clone(),
145			},
146			_ => result_data,
147		};
148
149		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
150	}
151}
152
153impl Function for DateFormat {
154	fn kinds(&self) -> &[FunctionKind] {
155		&[FunctionKind::Scalar]
156	}
157}