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::{
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
21/// Compute the ISO 8601 week number for a date.
22fn iso_week_number(date: &Date) -> i32 {
23	let days = date.to_days_since_epoch();
24
25	// ISO day of week: Mon=1..Sun=7
26	let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
27
28	// Find the Thursday of this date's week (ISO weeks are identified by their Thursday)
29	let thursday = days + (4 - dow);
30
31	// Find Jan 1 of the year containing that Thursday
32	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	// Week number = how many weeks between Jan 1 of that year and the Thursday
40	(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}