Skip to main content

reifydb_function/date/
week.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use 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
17/// Compute the ISO 8601 week number for a date.
18///
19/// ISO 8601 rules:
20/// - Weeks start on Monday
21/// - Week 1 is the week containing January 4th
22/// - A year has 52 or 53 weeks
23/// - Jan 1-3 may belong to week 52/53 of the previous year
24/// - Dec 29-31 may belong to week 1 of the next year
25fn iso_week_number(date: &Date) -> i32 {
26	let days = date.to_days_since_epoch();
27
28	// ISO day of week: Mon=1..Sun=7
29	let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
30
31	// Find the Thursday of this date's week (ISO weeks are identified by their Thursday)
32	let thursday = days + (4 - dow);
33
34	// Find Jan 1 of the year containing that Thursday
35	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	// Week number = how many weeks between Jan 1 of that year and the Thursday
43	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}