reifydb_routine/function/date/
week.rs1use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::{
6 fragment::Fragment,
7 value::{date::Date, r#type::Type},
8};
9
10use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
11
12pub struct DateWeek {
13 info: RoutineInfo,
14}
15
16impl Default for DateWeek {
17 fn default() -> Self {
18 Self::new()
19 }
20}
21
22impl DateWeek {
23 pub fn new() -> Self {
24 Self {
25 info: RoutineInfo::new("date::week"),
26 }
27 }
28}
29
30fn iso_week_number(date: &Date) -> Result<i32, RoutineError> {
39 let days = date.to_days_since_epoch();
40
41 let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
43
44 let thursday = days + (4 - dow);
46
47 let thursday_ymd = {
49 let d = Date::from_days_since_epoch(thursday).ok_or_else(|| RoutineError::FunctionExecutionFailed {
50 function: Fragment::internal("date::week"),
51 reason: "failed to compute date from days since epoch".to_string(),
52 })?;
53 d.year()
54 };
55 let jan1 = Date::new(thursday_ymd, 1, 1).ok_or_else(|| RoutineError::FunctionExecutionFailed {
56 function: Fragment::internal("date::week"),
57 reason: "failed to construct Jan 1 date".to_string(),
58 })?;
59 let jan1_days = jan1.to_days_since_epoch();
60
61 Ok((thursday - jan1_days) / 7 + 1)
64}
65
66impl<'a> Routine<FunctionContext<'a>> for DateWeek {
67 fn info(&self) -> &RoutineInfo {
68 &self.info
69 }
70
71 fn return_type(&self, _input_types: &[Type]) -> Type {
72 Type::Int4
73 }
74
75 fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
76 if args.len() != 1 {
77 return Err(RoutineError::FunctionArityMismatch {
78 function: ctx.fragment.clone(),
79 expected: 1,
80 actual: args.len(),
81 });
82 }
83
84 let column = &args[0];
85 let (data, bitvec) = column.unwrap_option();
86 let row_count = data.len();
87
88 let result_data = match data {
89 ColumnBuffer::Date(container) => {
90 let mut result = Vec::with_capacity(row_count);
91 let mut res_bitvec = Vec::with_capacity(row_count);
92
93 for i in 0..row_count {
94 if let Some(date) = container.get(i) {
95 result.push(iso_week_number(date)?);
96 res_bitvec.push(true);
97 } else {
98 result.push(0);
99 res_bitvec.push(false);
100 }
101 }
102
103 ColumnBuffer::int4_with_bitvec(result, res_bitvec)
104 }
105 other => {
106 return Err(RoutineError::FunctionInvalidArgumentType {
107 function: ctx.fragment.clone(),
108 argument_index: 0,
109 expected: vec![Type::Date],
110 actual: other.get_type(),
111 });
112 }
113 };
114
115 let final_data = if let Some(bv) = bitvec {
116 ColumnBuffer::Option {
117 inner: Box::new(result_data),
118 bitvec: bv.clone(),
119 }
120 } else {
121 result_data
122 };
123
124 Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
125 }
126}
127
128impl Function for DateWeek {
129 fn kinds(&self) -> &[FunctionKind] {
130 &[FunctionKind::Scalar]
131 }
132}