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::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, date::Date, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DateFormat {
10	info: FunctionInfo,
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: FunctionInfo::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 Function for DateFormat {
60	fn info(&self) -> &FunctionInfo {
61		&self.info
62	}
63
64	fn capabilities(&self) -> &[FunctionCapability] {
65		&[FunctionCapability::Scalar]
66	}
67
68	fn return_type(&self, _input_types: &[Type]) -> Type {
69		Type::Utf8
70	}
71
72	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
73		if args.len() != 2 {
74			return Err(FunctionError::ArityMismatch {
75				function: ctx.fragment.clone(),
76				expected: 2,
77				actual: args.len(),
78			});
79		}
80
81		let date_col = &args[0];
82		let fmt_col = &args[1];
83		let (date_data, date_bitvec) = date_col.data().unwrap_option();
84		let (fmt_data, fmt_bitvec) = fmt_col.data().unwrap_option();
85		let row_count = date_data.len();
86
87		let result_data = match (date_data, fmt_data) {
88			(
89				ColumnData::Date(date_container),
90				ColumnData::Utf8 {
91					container: fmt_container,
92					..
93				},
94			) => {
95				let mut result = Vec::with_capacity(row_count);
96
97				for i in 0..row_count {
98					match (date_container.get(i), fmt_container.is_defined(i)) {
99						(Some(d), true) => {
100							let fmt_str = &fmt_container[i];
101							let doy = compute_day_of_year(d.year(), d.month(), d.day());
102							match format_date(d.year(), d.month(), d.day(), doy, fmt_str) {
103								Ok(formatted) => {
104									result.push(formatted);
105								}
106								Err(reason) => {
107									return Err(FunctionError::ExecutionFailed {
108										function: ctx.fragment.clone(),
109										reason,
110									});
111								}
112							}
113						}
114						_ => {
115							result.push(String::new());
116						}
117					}
118				}
119
120				ColumnData::Utf8 {
121					container: Utf8Container::new(result),
122					max_bytes: MaxBytes::MAX,
123				}
124			}
125			(ColumnData::Date(_), other) => {
126				return Err(FunctionError::InvalidArgumentType {
127					function: ctx.fragment.clone(),
128					argument_index: 1,
129					expected: vec![Type::Utf8],
130					actual: other.get_type(),
131				});
132			}
133			(other, _) => {
134				return Err(FunctionError::InvalidArgumentType {
135					function: ctx.fragment.clone(),
136					argument_index: 0,
137					expected: vec![Type::Date],
138					actual: other.get_type(),
139				});
140			}
141		};
142
143		let final_data = match (date_bitvec, fmt_bitvec) {
144			(Some(bv), _) | (_, Some(bv)) => ColumnData::Option {
145				inner: Box::new(result_data),
146				bitvec: bv.clone(),
147			},
148			_ => result_data,
149		};
150
151		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
152	}
153}