Skip to main content

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