Skip to main content

reifydb_routine/function/duration/
trunc.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::{container::temporal::TemporalContainer, duration::Duration, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DurationTrunc {
10	info: FunctionInfo,
11}
12
13impl Default for DurationTrunc {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DurationTrunc {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("duration::trunc"),
23		}
24	}
25}
26
27impl Function for DurationTrunc {
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::Duration
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 dur_col = &args[0];
50		let prec_col = &args[1];
51
52		let (dur_data, dur_bv) = dur_col.data().unwrap_option();
53		let (prec_data, _) = prec_col.data().unwrap_option();
54
55		match (dur_data, prec_data) {
56			(
57				ColumnData::Duration(dur_container),
58				ColumnData::Utf8 {
59					container: prec_container,
60					..
61				},
62			) => {
63				let row_count = dur_data.len();
64				let mut container = TemporalContainer::with_capacity(row_count);
65
66				for i in 0..row_count {
67					match (dur_container.get(i), prec_container.is_defined(i)) {
68						(Some(dur), true) => {
69							let precision = &prec_container[i];
70							let months = dur.get_months();
71							let days = dur.get_days();
72							let nanos = dur.get_nanos();
73
74							let truncated = match precision.as_str() {
75								"year" => Duration::new((months / 12) * 12, 0, 0)?,
76								"month" => Duration::new(months, 0, 0)?,
77								"day" => Duration::new(months, days, 0)?,
78								"hour" => Duration::new(
79									months,
80									days,
81									(nanos / 3_600_000_000_000) * 3_600_000_000_000,
82								)?,
83								"minute" => Duration::new(
84									months,
85									days,
86									(nanos / 60_000_000_000) * 60_000_000_000,
87								)?,
88								"second" => Duration::new(
89									months,
90									days,
91									(nanos / 1_000_000_000) * 1_000_000_000,
92								)?,
93								"millis" => Duration::new(
94									months,
95									days,
96									(nanos / 1_000_000) * 1_000_000,
97								)?,
98								other => {
99									return Err(FunctionError::ExecutionFailed {
100										function: ctx.fragment.clone(),
101										reason: format!(
102											"invalid precision: '{}'",
103											other
104										),
105									});
106								}
107							};
108							container.push(truncated);
109						}
110						_ => container.push_default(),
111					}
112				}
113
114				let mut result_data = ColumnData::Duration(container);
115				if let Some(bv) = dur_bv {
116					result_data = ColumnData::Option {
117						inner: Box::new(result_data),
118						bitvec: bv.clone(),
119					};
120				}
121				Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), result_data)]))
122			}
123			(ColumnData::Duration(_), other) => Err(FunctionError::InvalidArgumentType {
124				function: ctx.fragment.clone(),
125				argument_index: 1,
126				expected: vec![Type::Utf8],
127				actual: other.get_type(),
128			}),
129			(other, _) => Err(FunctionError::InvalidArgumentType {
130				function: ctx.fragment.clone(),
131				argument_index: 0,
132				expected: vec![Type::Duration],
133				actual: other.get_type(),
134			}),
135		}
136	}
137}