Skip to main content

reifydb_routine/function/date/
day_of_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::value::r#type::Type;
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct DateDayOfWeek {
10	info: FunctionInfo,
11}
12
13impl Default for DateDayOfWeek {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl DateDayOfWeek {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("date::day_of_week"),
23		}
24	}
25}
26
27impl Function for DateDayOfWeek {
28	fn info(&self) -> &FunctionInfo {
29		&self.info
30	}
31
32	fn capabilities(&self) -> &[FunctionCapability] {
33		&[FunctionCapability::Scalar]
34	}
35
36	fn return_type(&self, _input_types: &[Type]) -> Type {
37		Type::Int4
38	}
39
40	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
41		if args.len() != 1 {
42			return Err(FunctionError::ArityMismatch {
43				function: ctx.fragment.clone(),
44				expected: 1,
45				actual: args.len(),
46			});
47		}
48
49		let column = &args[0];
50		let (data, bitvec) = column.data().unwrap_option();
51		let row_count = data.len();
52
53		let result_data = match data {
54			ColumnData::Date(container) => {
55				let mut result = Vec::with_capacity(row_count);
56				let mut res_bitvec = Vec::with_capacity(row_count);
57
58				for i in 0..row_count {
59					if let Some(date) = container.get(i) {
60						// ISO 8601: Mon=1, Sun=7
61						// 1970-01-01 was Thursday (ISO day 4), so days_since_epoch 0 = Thursday
62						// (days + 3) % 7 shifts Thursday=0 to Monday=0 base
63						// +7) % 7 handles negative days, +1 converts to 1-based
64						let days = date.to_days_since_epoch();
65						let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
66						result.push(dow);
67						res_bitvec.push(true);
68					} else {
69						result.push(0);
70						res_bitvec.push(false);
71					}
72				}
73
74				ColumnData::int4_with_bitvec(result, res_bitvec)
75			}
76			other => {
77				return Err(FunctionError::InvalidArgumentType {
78					function: ctx.fragment.clone(),
79					argument_index: 0,
80					expected: vec![Type::Date],
81					actual: other.get_type(),
82				});
83			}
84		};
85
86		let final_data = if let Some(bv) = bitvec {
87			ColumnData::Option {
88				inner: Box::new(result_data),
89				bitvec: bv.clone(),
90			}
91		} else {
92			result_data
93		};
94
95		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
96	}
97}