Skip to main content

reifydb_routine/function/datetime/
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 DateTimeWeek {
13	info: FunctionInfo,
14}
15
16impl Default for DateTimeWeek {
17	fn default() -> Self {
18		Self::new()
19	}
20}
21
22impl DateTimeWeek {
23	pub fn new() -> Self {
24		Self {
25			info: FunctionInfo::new("datetime::week"),
26		}
27	}
28}
29
30/// Compute the ISO 8601 week number for a date.
31fn iso_week_number(date: &Date) -> Result<i32, FunctionError> {
32	let days = date.to_days_since_epoch();
33
34	// ISO day of week: Mon=1..Sun=7
35	let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
36
37	// Find the Thursday of this date's week (ISO weeks are identified by their Thursday)
38	let thursday = days + (4 - dow);
39
40	// Find Jan 1 of the year containing that Thursday
41	let thursday_year = {
42		let d = Date::from_days_since_epoch(thursday).ok_or_else(|| FunctionError::ExecutionFailed {
43			function: Fragment::internal("datetime::week"),
44			reason: "failed to compute date from days since epoch".to_string(),
45		})?;
46		d.year()
47	};
48	let jan1 = Date::new(thursday_year, 1, 1).ok_or_else(|| FunctionError::ExecutionFailed {
49		function: Fragment::internal("datetime::week"),
50		reason: "failed to construct Jan 1 date".to_string(),
51	})?;
52	let jan1_days = jan1.to_days_since_epoch();
53
54	// Week number = how many weeks between Jan 1 of that year and the Thursday
55	Ok((thursday - jan1_days) / 7 + 1)
56}
57
58impl Function for DateTimeWeek {
59	fn info(&self) -> &FunctionInfo {
60		&self.info
61	}
62
63	fn capabilities(&self) -> &[FunctionCapability] {
64		&[FunctionCapability::Scalar]
65	}
66
67	fn return_type(&self, _input_types: &[Type]) -> Type {
68		Type::Int4
69	}
70
71	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
72		if args.len() != 1 {
73			return Err(FunctionError::ArityMismatch {
74				function: ctx.fragment.clone(),
75				expected: 1,
76				actual: args.len(),
77			});
78		}
79
80		let column = &args[0];
81		let (data, bitvec) = column.data().unwrap_option();
82		let row_count = data.len();
83
84		let result_data = match data {
85			ColumnData::DateTime(container) => {
86				let mut result = Vec::with_capacity(row_count);
87				let mut res_bitvec = Vec::with_capacity(row_count);
88
89				for i in 0..row_count {
90					if let Some(dt) = container.get(i) {
91						let date = dt.date();
92						result.push(iso_week_number(&date)?);
93						res_bitvec.push(true);
94					} else {
95						result.push(0);
96						res_bitvec.push(false);
97					}
98				}
99
100				ColumnData::int4_with_bitvec(result, res_bitvec)
101			}
102			other => {
103				return Err(FunctionError::InvalidArgumentType {
104					function: ctx.fragment.clone(),
105					argument_index: 0,
106					expected: vec![Type::DateTime],
107					actual: other.get_type(),
108				});
109			}
110		};
111
112		let final_data = if let Some(bv) = bitvec {
113			ColumnData::Option {
114				inner: Box::new(result_data),
115				bitvec: bv.clone(),
116			}
117		} else {
118			result_data
119		};
120
121		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
122	}
123}