Skip to main content

reifydb_function/text/
index_of.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 TextIndexOf;
10
11impl TextIndexOf {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for TextIndexOf {
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 substr_col = columns.get(1).unwrap();
36
37		match (str_col.data(), substr_col.data()) {
38			(
39				ColumnData::Utf8 {
40					container: str_container,
41					..
42				},
43				ColumnData::Utf8 {
44					container: substr_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) && substr_container.is_defined(i) {
53						let s = &str_container[i];
54						let substr = &substr_container[i];
55						let index = s
56							.find(substr.as_str())
57							.map(|pos| {
58								// Convert byte position to character position
59								s[..pos].chars().count() as i32
60							})
61							.unwrap_or(-1);
62						result_data.push(index);
63						result_bitvec.push(true);
64					} else {
65						result_data.push(0);
66						result_bitvec.push(false);
67					}
68				}
69
70				Ok(ColumnData::int4_with_bitvec(result_data, result_bitvec))
71			}
72			(
73				ColumnData::Utf8 {
74					..
75				},
76				other,
77			) => Err(ScalarFunctionError::InvalidArgumentType {
78				function: ctx.fragment.clone(),
79				argument_index: 1,
80				expected: vec![Type::Utf8],
81				actual: other.get_type(),
82			}),
83			(other, _) => Err(ScalarFunctionError::InvalidArgumentType {
84				function: ctx.fragment.clone(),
85				argument_index: 0,
86				expected: vec![Type::Utf8],
87				actual: other.get_type(),
88			}),
89		}
90	}
91
92	fn return_type(&self, _input_types: &[Type]) -> Type {
93		Type::Int4
94	}
95}