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::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::{
6	fragment::Fragment,
7	value::{date::Date, r#type::Type},
8};
9
10use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
11
12pub struct DateWeek {
13	info: FunctionInfo,
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: FunctionInfo::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, FunctionError> {
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(|| FunctionError::ExecutionFailed {
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(|| FunctionError::ExecutionFailed {
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 Function for DateWeek {
67	fn info(&self) -> &FunctionInfo {
68		&self.info
69	}
70
71	fn capabilities(&self) -> &[FunctionCapability] {
72		&[FunctionCapability::Scalar]
73	}
74
75	fn return_type(&self, _input_types: &[Type]) -> Type {
76		Type::Int4
77	}
78
79	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
80		if args.len() != 1 {
81			return Err(FunctionError::ArityMismatch {
82				function: ctx.fragment.clone(),
83				expected: 1,
84				actual: args.len(),
85			});
86		}
87
88		let column = &args[0];
89		let (data, bitvec) = column.data().unwrap_option();
90		let row_count = data.len();
91
92		let result_data = match data {
93			ColumnData::Date(container) => {
94				let mut result = Vec::with_capacity(row_count);
95				let mut res_bitvec = Vec::with_capacity(row_count);
96
97				for i in 0..row_count {
98					if let Some(date) = container.get(i) {
99						result.push(iso_week_number(date)?);
100						res_bitvec.push(true);
101					} else {
102						result.push(0);
103						res_bitvec.push(false);
104					}
105				}
106
107				ColumnData::int4_with_bitvec(result, res_bitvec)
108			}
109			other => {
110				return Err(FunctionError::InvalidArgumentType {
111					function: ctx.fragment.clone(),
112					argument_index: 0,
113					expected: vec![Type::Date],
114					actual: other.get_type(),
115				});
116			}
117		};
118
119		let final_data = if let Some(bv) = bitvec {
120			ColumnData::Option {
121				inner: Box::new(result_data),
122				bitvec: bv.clone(),
123			}
124		} else {
125			result_data
126		};
127
128		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
129	}
130}