reifydb_routine/function/text/
length.rs1use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::value::r#type::Type;
6
7use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
8
9pub struct TextLength {
10 info: RoutineInfo,
11}
12
13impl Default for TextLength {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl TextLength {
20 pub fn new() -> Self {
21 Self {
22 info: RoutineInfo::new("text::length"),
23 }
24 }
25}
26
27impl<'a> Routine<FunctionContext<'a>> for TextLength {
28 fn info(&self) -> &RoutineInfo {
29 &self.info
30 }
31
32 fn return_type(&self, _input_types: &[Type]) -> Type {
33 Type::Int4
34 }
35
36 fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
37 if args.len() != 1 {
38 return Err(RoutineError::FunctionArityMismatch {
39 function: ctx.fragment.clone(),
40 expected: 1,
41 actual: args.len(),
42 });
43 }
44
45 let column = &args[0];
46 let (data, bitvec) = column.unwrap_option();
47 let row_count = data.len();
48
49 match data {
50 ColumnBuffer::Utf8 {
51 container,
52 ..
53 } => {
54 let mut result = Vec::with_capacity(row_count);
55 let mut res_bitvec = Vec::with_capacity(row_count);
56
57 for i in 0..row_count {
58 if container.is_defined(i) {
59 let text = container.get(i).unwrap();
60 result.push(text.len() as i32);
61 res_bitvec.push(true);
62 } else {
63 result.push(0);
64 res_bitvec.push(false);
65 }
66 }
67
68 let result_data = ColumnBuffer::int4_with_bitvec(result, res_bitvec);
69 let final_data = match bitvec {
70 Some(bv) => ColumnBuffer::Option {
71 inner: Box::new(result_data),
72 bitvec: bv.clone(),
73 },
74 None => result_data,
75 };
76 Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
77 }
78 other => Err(RoutineError::FunctionInvalidArgumentType {
79 function: ctx.fragment.clone(),
80 argument_index: 0,
81 expected: vec![Type::Utf8],
82 actual: other.get_type(),
83 }),
84 }
85 }
86}
87
88impl Function for TextLength {
89 fn kinds(&self) -> &[FunctionKind] {
90 &[FunctionKind::Scalar]
91 }
92}