reifydb_function/text/
index_of.rs1use 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 TextIndexOf;
14
15impl TextIndexOf {
16 pub fn new() -> Self {
17 Self
18 }
19}
20
21impl ScalarFunction for TextIndexOf {
22 fn scalar(&self, ctx: ScalarFunctionContext) -> ScalarFunctionResult<ColumnData> {
23 if let Some(result) = propagate_options(self, &ctx) {
24 return result;
25 }
26
27 let columns = ctx.columns;
28 let row_count = ctx.row_count;
29
30 if columns.len() != 2 {
31 return Err(ScalarFunctionError::ArityMismatch {
32 function: ctx.fragment.clone(),
33 expected: 2,
34 actual: columns.len(),
35 });
36 }
37
38 let str_col = columns.get(0).unwrap();
39 let substr_col = columns.get(1).unwrap();
40
41 match (str_col.data(), substr_col.data()) {
42 (
43 ColumnData::Utf8 {
44 container: str_container,
45 ..
46 },
47 ColumnData::Utf8 {
48 container: substr_container,
49 ..
50 },
51 ) => {
52 let mut result_data = Vec::with_capacity(row_count);
53 let mut result_bitvec = Vec::with_capacity(row_count);
54
55 for i in 0..row_count {
56 if str_container.is_defined(i) && substr_container.is_defined(i) {
57 let s = &str_container[i];
58 let substr = &substr_container[i];
59 let index = s
60 .find(substr.as_str())
61 .map(|pos| {
62 s[..pos].chars().count() as i32
64 })
65 .unwrap_or(-1);
66 result_data.push(index);
67 result_bitvec.push(true);
68 } else {
69 result_data.push(0);
70 result_bitvec.push(false);
71 }
72 }
73
74 Ok(ColumnData::int4_with_bitvec(result_data, result_bitvec))
75 }
76 (
77 ColumnData::Utf8 {
78 ..
79 },
80 other,
81 ) => Err(ScalarFunctionError::InvalidArgumentType {
82 function: ctx.fragment.clone(),
83 argument_index: 1,
84 expected: vec![Type::Utf8],
85 actual: other.get_type(),
86 }),
87 (other, _) => Err(ScalarFunctionError::InvalidArgumentType {
88 function: ctx.fragment.clone(),
89 argument_index: 0,
90 expected: vec![Type::Utf8],
91 actual: other.get_type(),
92 }),
93 }
94 }
95
96 fn return_type(&self, _input_types: &[Type]) -> Type {
97 Type::Int4
98 }
99}