Skip to main content

reifydb_function/datetime/
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 DateTimeWeek;
10
11impl DateTimeWeek {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17/// Compute the ISO 8601 week number for a date.
18fn iso_week_number(date: &Date) -> i32 {
19	let days = date.to_days_since_epoch();
20
21	// ISO day of week: Mon=1..Sun=7
22	let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
23
24	// Find the Thursday of this date's week (ISO weeks are identified by their Thursday)
25	let thursday = days + (4 - dow);
26
27	// Find Jan 1 of the year containing that Thursday
28	let thursday_year = {
29		let d = Date::from_days_since_epoch(thursday).unwrap();
30		d.year()
31	};
32	let jan1 = Date::new(thursday_year, 1, 1).unwrap();
33	let jan1_days = jan1.to_days_since_epoch();
34
35	// Week number = how many weeks between Jan 1 of that year and the Thursday
36	(thursday - jan1_days) / 7 + 1
37}
38
39impl ScalarFunction for DateTimeWeek {
40	fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
41		if let Some(result) = propagate_options(self, &ctx) {
42			return result;
43		}
44		let columns = ctx.columns;
45		let row_count = ctx.row_count;
46
47		if columns.len() != 1 {
48			return Err(ScalarFunctionError::ArityMismatch {
49				function: ctx.fragment.clone(),
50				expected: 1,
51				actual: columns.len(),
52			});
53		}
54
55		let col = columns.get(0).unwrap();
56
57		match col.data() {
58			ColumnData::DateTime(container) => {
59				let mut data = Vec::with_capacity(row_count);
60				let mut bitvec = Vec::with_capacity(row_count);
61
62				for i in 0..row_count {
63					if let Some(dt) = container.get(i) {
64						let date = dt.date();
65						data.push(iso_week_number(&date));
66						bitvec.push(true);
67					} else {
68						data.push(0);
69						bitvec.push(false);
70					}
71				}
72
73				Ok(ColumnData::int4_with_bitvec(data, bitvec))
74			}
75			other => Err(ScalarFunctionError::InvalidArgumentType {
76				function: ctx.fragment.clone(),
77				argument_index: 0,
78				expected: vec![Type::DateTime],
79				actual: other.get_type(),
80			}),
81		}
82	}
83
84	fn return_type(&self, _input_types: &[Type]) -> Type {
85		Type::Int4
86	}
87}