Skip to main content

reifydb_function/datetime/
new.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, datetime::DateTime, r#type::Type};
6
7use crate::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct DateTimeNew;
14
15impl DateTimeNew {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21impl ScalarFunction for DateTimeNew {
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 date_col = columns.get(0).unwrap();
38		let time_col = columns.get(1).unwrap();
39
40		match (date_col.data(), time_col.data()) {
41			(ColumnData::Date(date_container), ColumnData::Time(time_container)) => {
42				let mut container = TemporalContainer::with_capacity(row_count);
43
44				for i in 0..row_count {
45					match (date_container.get(i), time_container.get(i)) {
46						(Some(date), Some(time)) => {
47							match DateTime::new(
48								date.year(),
49								date.month(),
50								date.day(),
51								time.hour(),
52								time.minute(),
53								time.second(),
54								time.nanosecond(),
55							) {
56								Some(dt) => container.push(dt),
57								None => container.push_default(),
58							}
59						}
60						_ => container.push_default(),
61					}
62				}
63
64				Ok(ColumnData::DateTime(container))
65			}
66			(ColumnData::Date(_), other) => Err(ScalarFunctionError::InvalidArgumentType {
67				function: ctx.fragment.clone(),
68				argument_index: 1,
69				expected: vec![Type::Time],
70				actual: other.get_type(),
71			}),
72			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
73				function: ctx.fragment.clone(),
74				argument_index: 0,
75				expected: vec![Type::Date],
76				actual: other.get_type(),
77			}),
78		}
79	}
80
81	fn return_type(&self, _input_types: &[Type]) -> Type {
82		Type::DateTime
83	}
84}