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