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
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_ymd = {
38		let d = Date::from_days_since_epoch(thursday).ok_or_else(|| RoutineError::FunctionExecutionFailed {
39			function: Fragment::internal("date::week"),
40			reason: "failed to compute date from days since epoch".to_string(),
41		})?;
42		d.year()
43	};
44	let jan1 = Date::new(thursday_ymd, 1, 1).ok_or_else(|| RoutineError::FunctionExecutionFailed {
45		function: Fragment::internal("date::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 DateWeek {
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::Date(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(date) = container.get(i) {
82						result.push(iso_week_number(date)?);
83						res_bitvec.push(true);
84					} else {
85						result.push(0);
86						res_bitvec.push(false);
87					}
88				}
89
90				ColumnBuffer::int4_with_bitvec(result, res_bitvec)
91			}
92			other => {
93				return Err(RoutineError::FunctionInvalidArgumentType {
94					function: ctx.fragment.clone(),
95					argument_index: 0,
96					expected: vec![Type::Date],
97					actual: other.get_type(),
98				});
99			}
100		};
101
102		let final_data = if let Some(bv) = bitvec {
103			ColumnBuffer::Option {
104				inner: Box::new(result_data),
105				bitvec: bv.clone(),
106			}
107		} else {
108			result_data
109		};
110
111		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
112	}
113}
114
115impl Function for DateWeek {
116	fn kinds(&self) -> &[FunctionKind] {
117		&[FunctionKind::Scalar]
118	}
119}