Skip to main content

reifydb_function/date/
day_of_week.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::r#type::Type;
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct DateDayOfWeek;
10
11impl DateDayOfWeek {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for DateDayOfWeek {
18	fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
19		if let Some(result) = propagate_options(self, &ctx) {
20			return result;
21		}
22
23		let columns = ctx.columns;
24		let row_count = ctx.row_count;
25
26		if columns.len() != 1 {
27			return Err(ScalarFunctionError::ArityMismatch {
28				function: ctx.fragment.clone(),
29				expected: 1,
30				actual: columns.len(),
31			});
32		}
33
34		let col = columns.get(0).unwrap();
35
36		match col.data() {
37			ColumnData::Date(container) => {
38				let mut data = Vec::with_capacity(row_count);
39				let mut bitvec = Vec::with_capacity(row_count);
40
41				for i in 0..row_count {
42					if let Some(date) = container.get(i) {
43						// ISO 8601: Mon=1, Sun=7
44						// 1970-01-01 was Thursday (ISO day 4), so days_since_epoch 0 = Thursday
45						// (days + 3) % 7 shifts Thursday=0 to Monday=0 base
46						// +7) % 7 handles negative days, +1 converts to 1-based
47						let days = date.to_days_since_epoch();
48						let dow = ((days % 7 + 3) % 7 + 7) % 7 + 1;
49						data.push(dow);
50						bitvec.push(true);
51					} else {
52						data.push(0);
53						bitvec.push(false);
54					}
55				}
56
57				Ok(ColumnData::int4_with_bitvec(data, bitvec))
58			}
59			other => Err(ScalarFunctionError::InvalidArgumentType {
60				function: ctx.fragment.clone(),
61				argument_index: 0,
62				expected: vec![Type::Date],
63				actual: other.get_type(),
64			}),
65		}
66	}
67
68	fn return_type(&self, _input_types: &[Type]) -> Type {
69		Type::Int4
70	}
71}