Skip to main content

reifydb_function/date/
end_of_month.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, date::Date, r#type::Type};
6
7use crate::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct DateEndOfMonth;
14
15impl DateEndOfMonth {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21impl ScalarFunction for DateEndOfMonth {
22	fn scalar(&self, ctx: ScalarFunctionContext) -> ScalarFunctionResult<ColumnData> {
23		if let Some(result) = propagate_options(self, &ctx) {
24			return result;
25		}
26
27		let columns = ctx.columns;
28		let row_count = ctx.row_count;
29
30		if columns.len() != 1 {
31			return Err(ScalarFunctionError::ArityMismatch {
32				function: ctx.fragment.clone(),
33				expected: 1,
34				actual: columns.len(),
35			});
36		}
37
38		let col = columns.get(0).unwrap();
39
40		match col.data() {
41			ColumnData::Date(container) => {
42				let mut result = TemporalContainer::with_capacity(row_count);
43
44				for i in 0..row_count {
45					if let Some(date) = container.get(i) {
46						let year = date.year();
47						let month = date.month();
48						let last_day = Date::days_in_month(year, month);
49						match Date::new(year, month, last_day) {
50							Some(d) => result.push(d),
51							None => result.push_default(),
52						}
53					} else {
54						result.push_default();
55					}
56				}
57
58				Ok(ColumnData::Date(result))
59			}
60			other => Err(ScalarFunctionError::InvalidArgumentType {
61				function: ctx.fragment.clone(),
62				argument_index: 0,
63				expected: vec![Type::Date],
64				actual: other.get_type(),
65			}),
66		}
67	}
68
69	fn return_type(&self, _input_types: &[Type]) -> Type {
70		Type::Date
71	}
72}