reifydb_routine/function/date/
week.rs1use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::{
6 fragment::Fragment,
7 value::{date::Date, r#type::Type},
8};
9
10use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
11
12pub struct DateWeek {
13 info: FunctionInfo,
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: FunctionInfo::new("date::week"),
26 }
27 }
28}
29
30fn iso_week_number(date: &Date) -> Result<i32, FunctionError> {
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(|| FunctionError::ExecutionFailed {
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(|| FunctionError::ExecutionFailed {
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 Function for DateWeek {
67 fn info(&self) -> &FunctionInfo {
68 &self.info
69 }
70
71 fn capabilities(&self) -> &[FunctionCapability] {
72 &[FunctionCapability::Scalar]
73 }
74
75 fn return_type(&self, _input_types: &[Type]) -> Type {
76 Type::Int4
77 }
78
79 fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
80 if args.len() != 1 {
81 return Err(FunctionError::ArityMismatch {
82 function: ctx.fragment.clone(),
83 expected: 1,
84 actual: args.len(),
85 });
86 }
87
88 let column = &args[0];
89 let (data, bitvec) = column.data().unwrap_option();
90 let row_count = data.len();
91
92 let result_data = match data {
93 ColumnData::Date(container) => {
94 let mut result = Vec::with_capacity(row_count);
95 let mut res_bitvec = Vec::with_capacity(row_count);
96
97 for i in 0..row_count {
98 if let Some(date) = container.get(i) {
99 result.push(iso_week_number(date)?);
100 res_bitvec.push(true);
101 } else {
102 result.push(0);
103 res_bitvec.push(false);
104 }
105 }
106
107 ColumnData::int4_with_bitvec(result, res_bitvec)
108 }
109 other => {
110 return Err(FunctionError::InvalidArgumentType {
111 function: ctx.fragment.clone(),
112 argument_index: 0,
113 expected: vec![Type::Date],
114 actual: other.get_type(),
115 });
116 }
117 };
118
119 let final_data = if let Some(bv) = bitvec {
120 ColumnData::Option {
121 inner: Box::new(result_data),
122 bitvec: bv.clone(),
123 }
124 } else {
125 result_data
126 };
127
128 Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
129 }
130}