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