reifydb_routine/function/date/
end_of_month.rs1use 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 DateEndOfMonth {
10 info: FunctionInfo,
11}
12
13impl Default for DateEndOfMonth {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl DateEndOfMonth {
20 pub fn new() -> Self {
21 Self {
22 info: FunctionInfo::new("date::end_of_month"),
23 }
24 }
25}
26
27impl Function for DateEndOfMonth {
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() != 1 {
42 return Err(FunctionError::ArityMismatch {
43 function: ctx.fragment.clone(),
44 expected: 1,
45 actual: args.len(),
46 });
47 }
48
49 let column = &args[0];
50 let (data, bitvec) = column.data().unwrap_option();
51 let row_count = data.len();
52
53 let result_data = match data {
54 ColumnData::Date(container) => {
55 let mut result = TemporalContainer::with_capacity(row_count);
56
57 for i in 0..row_count {
58 if let Some(date) = container.get(i) {
59 let year = date.year();
60 let month = date.month();
61 let last_day = Date::days_in_month(year, month);
62 match Date::new(year, month, last_day) {
63 Some(d) => result.push(d),
64 None => result.push_default(),
65 }
66 } else {
67 result.push_default();
68 }
69 }
70
71 ColumnData::Date(result)
72 }
73 other => {
74 return Err(FunctionError::InvalidArgumentType {
75 function: ctx.fragment.clone(),
76 argument_index: 0,
77 expected: vec![Type::Date],
78 actual: other.get_type(),
79 });
80 }
81 };
82
83 let final_data = if let Some(bv) = bitvec {
84 ColumnData::Option {
85 inner: Box::new(result_data),
86 bitvec: bv.clone(),
87 }
88 } else {
89 result_data
90 };
91
92 Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
93 }
94}