reifydb_routine/function/datetime/
day_of_year.rs1use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::value::{date::Date, r#type::Type};
6
7use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
8
9pub struct DateTimeDayOfYear {
10 info: RoutineInfo,
11}
12
13impl Default for DateTimeDayOfYear {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl DateTimeDayOfYear {
20 pub fn new() -> Self {
21 Self {
22 info: RoutineInfo::new("datetime::day_of_year"),
23 }
24 }
25}
26
27impl<'a> Routine<FunctionContext<'a>> for DateTimeDayOfYear {
28 fn info(&self) -> &RoutineInfo {
29 &self.info
30 }
31
32 fn return_type(&self, _input_types: &[Type]) -> Type {
33 Type::Int4
34 }
35
36 fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
37 if args.len() != 1 {
38 return Err(RoutineError::FunctionArityMismatch {
39 function: ctx.fragment.clone(),
40 expected: 1,
41 actual: args.len(),
42 });
43 }
44
45 let column = &args[0];
46 let (data, bitvec) = column.unwrap_option();
47 let row_count = data.len();
48
49 let result_data = match data {
50 ColumnBuffer::DateTime(container) => {
51 let mut result = Vec::with_capacity(row_count);
52 let mut res_bitvec = Vec::with_capacity(row_count);
53
54 for i in 0..row_count {
55 if let Some(dt) = container.get(i) {
56 let date = dt.date();
57 let jan1 = Date::new(date.year(), 1, 1).ok_or_else(|| {
58 RoutineError::FunctionExecutionFailed {
59 function: ctx.fragment.clone(),
60 reason: "failed to construct Jan 1 date".to_string(),
61 }
62 })?;
63 let doy = date.to_days_since_epoch() - jan1.to_days_since_epoch() + 1;
64 result.push(doy);
65 res_bitvec.push(true);
66 } else {
67 result.push(0);
68 res_bitvec.push(false);
69 }
70 }
71
72 ColumnBuffer::int4_with_bitvec(result, res_bitvec)
73 }
74 other => {
75 return Err(RoutineError::FunctionInvalidArgumentType {
76 function: ctx.fragment.clone(),
77 argument_index: 0,
78 expected: vec![Type::DateTime],
79 actual: other.get_type(),
80 });
81 }
82 };
83
84 let final_data = if let Some(bv) = bitvec {
85 ColumnBuffer::Option {
86 inner: Box::new(result_data),
87 bitvec: bv.clone(),
88 }
89 } else {
90 result_data
91 };
92
93 Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
94 }
95}
96
97impl Function for DateTimeDayOfYear {
98 fn kinds(&self) -> &[FunctionKind] {
99 &[FunctionKind::Scalar]
100 }
101}