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
30fn iso_week_number(date: &Date) -> Result<i32, RoutineError> {
31	let days = date.to_days_since_epoch();
32
33	let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
34
35	let thursday = days + (4 - dow);
36
37	let thursday_year = {
38		let d = Date::from_days_since_epoch(thursday).ok_or_else(|| RoutineError::FunctionExecutionFailed {
39			function: Fragment::internal("datetime::week"),
40			reason: "failed to compute date from days since epoch".to_string(),
41		})?;
42		d.year()
43	};
44	let jan1 = Date::new(thursday_year, 1, 1).ok_or_else(|| RoutineError::FunctionExecutionFailed {
45		function: Fragment::internal("datetime::week"),
46		reason: "failed to construct Jan 1 date".to_string(),
47	})?;
48	let jan1_days = jan1.to_days_since_epoch();
49
50	Ok((thursday - jan1_days) / 7 + 1)
51}
52
53impl<'a> Routine<FunctionContext<'a>> for DateTimeWeek {
54	fn info(&self) -> &RoutineInfo {
55		&self.info
56	}
57
58	fn return_type(&self, _input_types: &[Type]) -> Type {
59		Type::Int4
60	}
61
62	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
63		if args.len() != 1 {
64			return Err(RoutineError::FunctionArityMismatch {
65				function: ctx.fragment.clone(),
66				expected: 1,
67				actual: args.len(),
68			});
69		}
70
71		let column = &args[0];
72		let (data, bitvec) = column.unwrap_option();
73		let row_count = data.len();
74
75		let result_data = match data {
76			ColumnBuffer::DateTime(container) => {
77				let mut result = Vec::with_capacity(row_count);
78				let mut res_bitvec = Vec::with_capacity(row_count);
79
80				for i in 0..row_count {
81					if let Some(dt) = container.get(i) {
82						let date = dt.date();
83						result.push(iso_week_number(&date)?);
84						res_bitvec.push(true);
85					} else {
86						result.push(0);
87						res_bitvec.push(false);
88					}
89				}
90
91				ColumnBuffer::int4_with_bitvec(result, res_bitvec)
92			}
93			other => {
94				return Err(RoutineError::FunctionInvalidArgumentType {
95					function: ctx.fragment.clone(),
96					argument_index: 0,
97					expected: vec![Type::DateTime],
98					actual: other.get_type(),
99				});
100			}
101		};
102
103		let final_data = if let Some(bv) = bitvec {
104			ColumnBuffer::Option {
105				inner: Box::new(result_data),
106				bitvec: bv.clone(),
107			}
108		} else {
109			result_data
110		};
111
112		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
113	}
114}
115
116impl Function for DateTimeWeek {
117	fn kinds(&self) -> &[FunctionKind] {
118		&[FunctionKind::Scalar]
119	}
120}