Skip to main content

reifydb_function/text/
starts_with.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 TextStartsWith;
10
11impl TextStartsWith {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for TextStartsWith {
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() != 2 {
27			return Err(ScalarFunctionError::ArityMismatch {
28				function: ctx.fragment.clone(),
29				expected: 2,
30				actual: columns.len(),
31			});
32		}
33
34		let str_col = columns.get(0).unwrap();
35		let prefix_col = columns.get(1).unwrap();
36
37		match (str_col.data(), prefix_col.data()) {
38			(
39				ColumnData::Utf8 {
40					container: str_container,
41					..
42				},
43				ColumnData::Utf8 {
44					container: prefix_container,
45					..
46				},
47			) => {
48				let mut result_data = Vec::with_capacity(row_count);
49				let mut result_bitvec = Vec::with_capacity(row_count);
50
51				for i in 0..row_count {
52					if str_container.is_defined(i) && prefix_container.is_defined(i) {
53						let s = &str_container[i];
54						let prefix = &prefix_container[i];
55						result_data.push(s.starts_with(prefix.as_str()));
56						result_bitvec.push(true);
57					} else {
58						result_data.push(false);
59						result_bitvec.push(false);
60					}
61				}
62
63				Ok(ColumnData::bool_with_bitvec(result_data, result_bitvec))
64			}
65			(
66				ColumnData::Utf8 {
67					..
68				},
69				other,
70			) => Err(ScalarFunctionError::InvalidArgumentType {
71				function: ctx.fragment.clone(),
72				argument_index: 1,
73				expected: vec![Type::Utf8],
74				actual: other.get_type(),
75			}),
76			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
77				function: ctx.fragment.clone(),
78				argument_index: 0,
79				expected: vec![Type::Utf8],
80				actual: other.get_type(),
81			}),
82		}
83	}
84
85	fn return_type(&self, _input_types: &[Type]) -> Type {
86		Type::Boolean
87	}
88}