reifydb_routine/function/time/
trunc.rs1use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{container::temporal::TemporalContainer, time::Time, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct TimeTrunc {
10 info: FunctionInfo,
11}
12
13impl Default for TimeTrunc {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl TimeTrunc {
20 pub fn new() -> Self {
21 Self {
22 info: FunctionInfo::new("time::trunc"),
23 }
24 }
25}
26
27impl Function for TimeTrunc {
28 fn info(&self) -> &FunctionInfo {
29 &self.info
30 }
31
32 fn capabilities(&self) -> &[FunctionCapability] {
33 &[FunctionCapability::Scalar]
34 }
35
36 fn return_type(&self, _input_types: &[Type]) -> Type {
37 Type::Time
38 }
39
40 fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
41 if args.len() != 2 {
42 return Err(FunctionError::ArityMismatch {
43 function: ctx.fragment.clone(),
44 expected: 2,
45 actual: args.len(),
46 });
47 }
48
49 let time_col = &args[0];
50 let prec_col = &args[1];
51
52 let (time_data, time_bv) = time_col.data().unwrap_option();
53 let (prec_data, _) = prec_col.data().unwrap_option();
54
55 match (time_data, prec_data) {
56 (
57 ColumnData::Time(time_container),
58 ColumnData::Utf8 {
59 container: prec_container,
60 ..
61 },
62 ) => {
63 let row_count = time_data.len();
64 let mut container = TemporalContainer::with_capacity(row_count);
65
66 for i in 0..row_count {
67 match (time_container.get(i), prec_container.is_defined(i)) {
68 (Some(t), true) => {
69 let precision = &prec_container[i];
70 let truncated = match precision.as_str() {
71 "hour" => Time::new(t.hour(), 0, 0, 0),
72 "minute" => Time::new(t.hour(), t.minute(), 0, 0),
73 "second" => {
74 Time::new(t.hour(), t.minute(), t.second(), 0)
75 }
76 other => {
77 return Err(FunctionError::ExecutionFailed {
78 function: ctx.fragment.clone(),
79 reason: format!(
80 "invalid precision: '{}'",
81 other
82 ),
83 });
84 }
85 };
86 match truncated {
87 Some(val) => container.push(val),
88 None => container.push_default(),
89 }
90 }
91 _ => container.push_default(),
92 }
93 }
94
95 let mut result_data = ColumnData::Time(container);
96 if let Some(bv) = time_bv {
97 result_data = ColumnData::Option {
98 inner: Box::new(result_data),
99 bitvec: bv.clone(),
100 };
101 }
102 Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), result_data)]))
103 }
104 (ColumnData::Time(_), other) => Err(FunctionError::InvalidArgumentType {
105 function: ctx.fragment.clone(),
106 argument_index: 1,
107 expected: vec![Type::Utf8],
108 actual: other.get_type(),
109 }),
110 (other, _) => Err(FunctionError::InvalidArgumentType {
111 function: ctx.fragment.clone(),
112 argument_index: 0,
113 expected: vec![Type::Time],
114 actual: other.get_type(),
115 }),
116 }
117 }
118}