Skip to main content

reifydb_routine/function/date/
week.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::{
6	fragment::Fragment,
7	value::{date::Date, r#type::Type},
8};
9
10use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
11
12pub struct DateWeek {
13	info: RoutineInfo,
14}
15
16impl Default for DateWeek {
17	fn default() -> Self {
18		Self::new()
19	}
20}
21
22impl DateWeek {
23	pub fn new() -> Self {
24		Self {
25			info: RoutineInfo::new("date::week"),
26		}
27	}
28}
29
30/// Compute the ISO 8601 week number for a date.
31///
32/// ISO 8601 rules:
33/// - Weeks start on Monday
34/// - Week 1 is the week containing January 4th
35/// - A year has 52 or 53 weeks
36/// - Jan 1-3 may belong to week 52/53 of the previous year
37/// - Dec 29-31 may belong to week 1 of the next year
38fn iso_week_number(date: &Date) -> Result<i32, RoutineError> {
39	let days = date.to_days_since_epoch();
40
41	// ISO day of week: Mon=1..Sun=7
42	let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
43
44	// Find the Thursday of this date's week (ISO weeks are identified by their Thursday)
45	let thursday = days + (4 - dow);
46
47	// Find Jan 1 of the year containing that Thursday
48	let thursday_ymd = {
49		let d = Date::from_days_since_epoch(thursday).ok_or_else(|| RoutineError::FunctionExecutionFailed {
50			function: Fragment::internal("date::week"),
51			reason: "failed to compute date from days since epoch".to_string(),
52		})?;
53		d.year()
54	};
55	let jan1 = Date::new(thursday_ymd, 1, 1).ok_or_else(|| RoutineError::FunctionExecutionFailed {
56		function: Fragment::internal("date::week"),
57		reason: "failed to construct Jan 1 date".to_string(),
58	})?;
59	let jan1_days = jan1.to_days_since_epoch();
60
61	// Week number = how many weeks between Jan 1 of that year and the Thursday
62
63	Ok((thursday - jan1_days) / 7 + 1)
64}
65
66impl<'a> Routine<FunctionContext<'a>> for DateWeek {
67	fn info(&self) -> &RoutineInfo {
68		&self.info
69	}
70
71	fn return_type(&self, _input_types: &[Type]) -> Type {
72		Type::Int4
73	}
74
75	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
76		if args.len() != 1 {
77			return Err(RoutineError::FunctionArityMismatch {
78				function: ctx.fragment.clone(),
79				expected: 1,
80				actual: args.len(),
81			});
82		}
83
84		let column = &args[0];
85		let (data, bitvec) = column.unwrap_option();
86		let row_count = data.len();
87
88		let result_data = match data {
89			ColumnBuffer::Date(container) => {
90				let mut result = Vec::with_capacity(row_count);
91				let mut res_bitvec = Vec::with_capacity(row_count);
92
93				for i in 0..row_count {
94					if let Some(date) = container.get(i) {
95						result.push(iso_week_number(date)?);
96						res_bitvec.push(true);
97					} else {
98						result.push(0);
99						res_bitvec.push(false);
100					}
101				}
102
103				ColumnBuffer::int4_with_bitvec(result, res_bitvec)
104			}
105			other => {
106				return Err(RoutineError::FunctionInvalidArgumentType {
107					function: ctx.fragment.clone(),
108					argument_index: 0,
109					expected: vec![Type::Date],
110					actual: other.get_type(),
111				});
112			}
113		};
114
115		let final_data = if let Some(bv) = bitvec {
116			ColumnBuffer::Option {
117				inner: Box::new(result_data),
118				bitvec: bv.clone(),
119			}
120		} else {
121			result_data
122		};
123
124		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
125	}
126}
127
128impl Function for DateWeek {
129	fn kinds(&self) -> &[FunctionKind] {
130		&[FunctionKind::Scalar]
131	}
132}