Skip to main content

reifydb_function/datetime/
second.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::r#type::Type;
6
7use crate::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct DateTimeSecond;
14
15impl DateTimeSecond {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21impl ScalarFunction for DateTimeSecond {
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() != 1 {
30			return Err(ScalarFunctionError::ArityMismatch {
31				function: ctx.fragment.clone(),
32				expected: 1,
33				actual: columns.len(),
34			});
35		}
36
37		let col = columns.get(0).unwrap();
38
39		match col.data() {
40			ColumnData::DateTime(container) => {
41				let mut data = Vec::with_capacity(row_count);
42				let mut bitvec = Vec::with_capacity(row_count);
43
44				for i in 0..row_count {
45					if let Some(dt) = container.get(i) {
46						data.push(dt.second() as i32);
47						bitvec.push(true);
48					} else {
49						data.push(0);
50						bitvec.push(false);
51					}
52				}
53
54				Ok(ColumnData::int4_with_bitvec(data, bitvec))
55			}
56			other => Err(ScalarFunctionError::InvalidArgumentType {
57				function: ctx.fragment.clone(),
58				argument_index: 0,
59				expected: vec![Type::DateTime],
60				actual: other.get_type(),
61			}),
62		}
63	}
64
65	fn return_type(&self, _input_types: &[Type]) -> Type {
66		Type::Int4
67	}
68}