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::{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 DateTimeWeek {
13	info: RoutineInfo,
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: RoutineInfo::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, RoutineError> {
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(|| RoutineError::FunctionExecutionFailed {
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(|| RoutineError::FunctionExecutionFailed {
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<'a> Routine<FunctionContext<'a>> for DateTimeWeek {
59	fn info(&self) -> &RoutineInfo {
60		&self.info
61	}
62
63	fn return_type(&self, _input_types: &[Type]) -> Type {
64		Type::Int4
65	}
66
67	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
68		if args.len() != 1 {
69			return Err(RoutineError::FunctionArityMismatch {
70				function: ctx.fragment.clone(),
71				expected: 1,
72				actual: args.len(),
73			});
74		}
75
76		let column = &args[0];
77		let (data, bitvec) = column.unwrap_option();
78		let row_count = data.len();
79
80		let result_data = match data {
81			ColumnBuffer::DateTime(container) => {
82				let mut result = Vec::with_capacity(row_count);
83				let mut res_bitvec = Vec::with_capacity(row_count);
84
85				for i in 0..row_count {
86					if let Some(dt) = container.get(i) {
87						let date = dt.date();
88						result.push(iso_week_number(&date)?);
89						res_bitvec.push(true);
90					} else {
91						result.push(0);
92						res_bitvec.push(false);
93					}
94				}
95
96				ColumnBuffer::int4_with_bitvec(result, res_bitvec)
97			}
98			other => {
99				return Err(RoutineError::FunctionInvalidArgumentType {
100					function: ctx.fragment.clone(),
101					argument_index: 0,
102					expected: vec![Type::DateTime],
103					actual: other.get_type(),
104				});
105			}
106		};
107
108		let final_data = if let Some(bv) = bitvec {
109			ColumnBuffer::Option {
110				inner: Box::new(result_data),
111				bitvec: bv.clone(),
112			}
113		} else {
114			result_data
115		};
116
117		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
118	}
119}
120
121impl Function for DateTimeWeek {
122	fn kinds(&self) -> &[FunctionKind] {
123		&[FunctionKind::Scalar]
124	}
125}