Skip to main content

reifydb_routine/function/date/
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, date::Date, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DateTrunc {
10	info: FunctionInfo,
11}
12
13impl Default for DateTrunc {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DateTrunc {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("date::trunc"),
23		}
24	}
25}
26
27impl Function for DateTrunc {
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::Date
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 date_col = &args[0];
50		let prec_col = &args[1];
51		let (date_data, date_bitvec) = date_col.data().unwrap_option();
52		let (prec_data, prec_bitvec) = prec_col.data().unwrap_option();
53		let row_count = date_data.len();
54
55		let result_data = match (date_data, prec_data) {
56			(
57				ColumnData::Date(date_container),
58				ColumnData::Utf8 {
59					container: prec_container,
60					..
61				},
62			) => {
63				let mut container = TemporalContainer::with_capacity(row_count);
64
65				for i in 0..row_count {
66					match (date_container.get(i), prec_container.is_defined(i)) {
67						(Some(d), true) => {
68							let precision = &prec_container[i];
69							let truncated =
70								match precision.as_str() {
71									"year" => Date::new(d.year(), 1, 1),
72									"month" => Date::new(d.year(), d.month(), 1),
73									other => {
74										return Err(FunctionError::ExecutionFailed {
75										function: ctx.fragment.clone(),
76										reason: format!("invalid precision: '{}'", other),
77									});
78									}
79								};
80							match truncated {
81								Some(val) => container.push(val),
82								None => container.push_default(),
83							}
84						}
85						_ => container.push_default(),
86					}
87				}
88
89				ColumnData::Date(container)
90			}
91			(ColumnData::Date(_), other) => {
92				return Err(FunctionError::InvalidArgumentType {
93					function: ctx.fragment.clone(),
94					argument_index: 1,
95					expected: vec![Type::Utf8],
96					actual: other.get_type(),
97				});
98			}
99			(other, _) => {
100				return Err(FunctionError::InvalidArgumentType {
101					function: ctx.fragment.clone(),
102					argument_index: 0,
103					expected: vec![Type::Date],
104					actual: other.get_type(),
105				});
106			}
107		};
108
109		let final_data = match (date_bitvec, prec_bitvec) {
110			(Some(bv), _) | (_, Some(bv)) => ColumnData::Option {
111				inner: Box::new(result_data),
112				bitvec: bv.clone(),
113			},
114			_ => result_data,
115		};
116
117		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
118	}
119}