Skip to main content

reifydb_function/time/
trunc.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::{container::temporal::TemporalContainer, time::Time, r#type::Type};
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct TimeTrunc;
10
11impl TimeTrunc {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for TimeTrunc {
18	fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
19		if let Some(result) = propagate_options(self, &ctx) {
20			return result;
21		}
22		let columns = ctx.columns;
23		let row_count = ctx.row_count;
24
25		if columns.len() != 2 {
26			return Err(ScalarFunctionError::ArityMismatch {
27				function: ctx.fragment.clone(),
28				expected: 2,
29				actual: columns.len(),
30			});
31		}
32
33		let time_col = columns.get(0).unwrap();
34		let prec_col = columns.get(1).unwrap();
35
36		match (time_col.data(), prec_col.data()) {
37			(
38				ColumnData::Time(time_container),
39				ColumnData::Utf8 {
40					container: prec_container,
41					..
42				},
43			) => {
44				let mut container = TemporalContainer::with_capacity(row_count);
45
46				for i in 0..row_count {
47					match (time_container.get(i), prec_container.is_defined(i)) {
48						(Some(t), true) => {
49							let precision = &prec_container[i];
50							let truncated = match precision.as_str() {
51								"hour" => Time::new(t.hour(), 0, 0, 0),
52								"minute" => Time::new(t.hour(), t.minute(), 0, 0),
53								"second" => {
54									Time::new(t.hour(), t.minute(), t.second(), 0)
55								}
56								other => {
57									return Err(
58										ScalarFunctionError::ExecutionFailed {
59											function: ctx.fragment.clone(),
60											reason: format!(
61												"invalid precision: '{}'",
62												other
63											),
64										},
65									);
66								}
67							};
68							match truncated {
69								Some(val) => container.push(val),
70								None => container.push_default(),
71							}
72						}
73						_ => container.push_default(),
74					}
75				}
76
77				Ok(ColumnData::Time(container))
78			}
79			(ColumnData::Time(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
80				function: ctx.fragment.clone(),
81				argument_index: 1,
82				expected: vec![Type::Utf8],
83				actual: other.get_type(),
84			}),
85			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
86				function: ctx.fragment.clone(),
87				argument_index: 0,
88				expected: vec![Type::Time],
89				actual: other.get_type(),
90			}),
91		}
92	}
93
94	fn return_type(&self, _input_types: &[Type]) -> Type {
95		Type::Time
96	}
97}