reifydb_function/date/
week.rs1use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::{date::Date, r#type::Type};
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct DateWeek;
10
11impl DateWeek {
12 pub fn new() -> Self {
13 Self
14 }
15}
16
17fn iso_week_number(date: &Date) -> i32 {
26 let days = date.to_days_since_epoch();
27
28 let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
30
31 let thursday = days + (4 - dow);
33
34 let thursday_ymd = {
36 let d = Date::from_days_since_epoch(thursday).unwrap();
37 d.year()
38 };
39 let jan1 = Date::new(thursday_ymd, 1, 1).unwrap();
40 let jan1_days = jan1.to_days_since_epoch();
41
42 let week = (thursday - jan1_days) / 7 + 1;
44
45 week
46}
47
48impl ScalarFunction for DateWeek {
49 fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
50 if let Some(result) = propagate_options(self, &ctx) {
51 return result;
52 }
53
54 let columns = ctx.columns;
55 let row_count = ctx.row_count;
56
57 if columns.len() != 1 {
58 return Err(ScalarFunctionError::ArityMismatch {
59 function: ctx.fragment.clone(),
60 expected: 1,
61 actual: columns.len(),
62 });
63 }
64
65 let col = columns.get(0).unwrap();
66
67 match col.data() {
68 ColumnData::Date(container) => {
69 let mut data = Vec::with_capacity(row_count);
70 let mut bitvec = Vec::with_capacity(row_count);
71
72 for i in 0..row_count {
73 if let Some(date) = container.get(i) {
74 data.push(iso_week_number(&date));
75 bitvec.push(true);
76 } else {
77 data.push(0);
78 bitvec.push(false);
79 }
80 }
81
82 Ok(ColumnData::int4_with_bitvec(data, bitvec))
83 }
84 other => Err(ScalarFunctionError::InvalidArgumentType {
85 function: ctx.fragment.clone(),
86 argument_index: 0,
87 expected: vec![Type::Date],
88 actual: other.get_type(),
89 }),
90 }
91 }
92
93 fn return_type(&self, _input_types: &[Type]) -> Type {
94 Type::Int4
95 }
96}