reifydb_routine/function/time/
format.rs1use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct TimeFormat {
10 info: FunctionInfo,
11}
12
13impl Default for TimeFormat {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl TimeFormat {
20 pub fn new() -> Self {
21 Self {
22 info: FunctionInfo::new("time::format"),
23 }
24 }
25}
26
27fn format_time(hour: u32, minute: u32, second: u32, nanosecond: 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.peek() {
34 Some('H') => {
35 chars.next();
36 result.push_str(&format!("{:02}", hour));
37 }
38 Some('M') => {
39 chars.next();
40 result.push_str(&format!("{:02}", minute));
41 }
42 Some('S') => {
43 chars.next();
44 result.push_str(&format!("{:02}", second));
45 }
46 Some('f') => {
47 chars.next();
48 result.push_str(&format!("{:09}", nanosecond));
49 }
50 Some('3') => {
51 chars.next();
52 if chars.peek() == Some(&'f') {
53 chars.next();
54 result.push_str(&format!("{:03}", nanosecond / 1_000_000));
55 } else {
56 return Err(
57 "invalid format specifier: '%3' (expected '%3f')".to_string()
58 );
59 }
60 }
61 Some('6') => {
62 chars.next();
63 if chars.peek() == Some(&'f') {
64 chars.next();
65 result.push_str(&format!("{:06}", nanosecond / 1_000));
66 } else {
67 return Err(
68 "invalid format specifier: '%6' (expected '%6f')".to_string()
69 );
70 }
71 }
72 Some('%') => {
73 chars.next();
74 result.push('%');
75 }
76 Some(c) => {
77 let c = *c;
78 return Err(format!("invalid format specifier: '%{}'", c));
79 }
80 None => return Err("unexpected end of format string after '%'".to_string()),
81 }
82 } else {
83 result.push(ch);
84 }
85 }
86
87 Ok(result)
88}
89
90impl Function for TimeFormat {
91 fn info(&self) -> &FunctionInfo {
92 &self.info
93 }
94
95 fn capabilities(&self) -> &[FunctionCapability] {
96 &[FunctionCapability::Scalar]
97 }
98
99 fn return_type(&self, _input_types: &[Type]) -> Type {
100 Type::Utf8
101 }
102
103 fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
104 if args.len() != 2 {
105 return Err(FunctionError::ArityMismatch {
106 function: ctx.fragment.clone(),
107 expected: 2,
108 actual: args.len(),
109 });
110 }
111
112 let time_col = &args[0];
113 let fmt_col = &args[1];
114
115 let (time_data, time_bv) = time_col.data().unwrap_option();
116 let (fmt_data, _) = fmt_col.data().unwrap_option();
117
118 match (time_data, fmt_data) {
119 (
120 ColumnData::Time(time_container),
121 ColumnData::Utf8 {
122 container: fmt_container,
123 ..
124 },
125 ) => {
126 let row_count = time_data.len();
127 let mut result_data = Vec::with_capacity(row_count);
128
129 for i in 0..row_count {
130 match (time_container.get(i), fmt_container.is_defined(i)) {
131 (Some(t), true) => {
132 let fmt_str = &fmt_container[i];
133 match format_time(
134 t.hour(),
135 t.minute(),
136 t.second(),
137 t.nanosecond(),
138 fmt_str,
139 ) {
140 Ok(formatted) => {
141 result_data.push(formatted);
142 }
143 Err(reason) => {
144 return Err(FunctionError::ExecutionFailed {
145 function: ctx.fragment.clone(),
146 reason,
147 });
148 }
149 }
150 }
151 _ => {
152 result_data.push(String::new());
153 }
154 }
155 }
156
157 let mut final_data = ColumnData::Utf8 {
158 container: Utf8Container::new(result_data),
159 max_bytes: MaxBytes::MAX,
160 };
161 if let Some(bv) = time_bv {
162 final_data = ColumnData::Option {
163 inner: Box::new(final_data),
164 bitvec: bv.clone(),
165 };
166 }
167 Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
168 }
169 (ColumnData::Time(_), other) => Err(FunctionError::InvalidArgumentType {
170 function: ctx.fragment.clone(),
171 argument_index: 1,
172 expected: vec![Type::Utf8],
173 actual: other.get_type(),
174 }),
175 (other, _) => Err(FunctionError::InvalidArgumentType {
176 function: ctx.fragment.clone(),
177 argument_index: 0,
178 expected: vec![Type::Time],
179 actual: other.get_type(),
180 }),
181 }
182 }
183}