Skip to main content

reifydb_function/text/
repeat.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::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, r#type::Type};
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct TextRepeat;
10
11impl TextRepeat {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for TextRepeat {
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 count_col = columns.get(1).unwrap();
36
37		match str_col.data() {
38			ColumnData::Utf8 {
39				container: str_container,
40				..
41			} => {
42				let mut result_data = Vec::with_capacity(row_count);
43
44				for i in 0..row_count {
45					if !str_container.is_defined(i) {
46						result_data.push(String::new());
47						continue;
48					}
49
50					let count = match count_col.data() {
51						ColumnData::Int1(c) => c.get(i).map(|&v| v as i64),
52						ColumnData::Int2(c) => c.get(i).map(|&v| v as i64),
53						ColumnData::Int4(c) => c.get(i).map(|&v| v as i64),
54						ColumnData::Int8(c) => c.get(i).copied(),
55						ColumnData::Uint1(c) => c.get(i).map(|&v| v as i64),
56						ColumnData::Uint2(c) => c.get(i).map(|&v| v as i64),
57						ColumnData::Uint4(c) => c.get(i).map(|&v| v as i64),
58						_ => {
59							return Err(ScalarFunctionError::InvalidArgumentType {
60								function: ctx.fragment.clone(),
61								argument_index: 1,
62								expected: vec![
63									Type::Int1,
64									Type::Int2,
65									Type::Int4,
66									Type::Int8,
67								],
68								actual: count_col.data().get_type(),
69							});
70						}
71					};
72
73					match count {
74						Some(n) if n >= 0 => {
75							let s = &str_container[i];
76							result_data.push(s.repeat(n as usize));
77						}
78						Some(_) => {
79							result_data.push(String::new());
80						}
81						None => {
82							result_data.push(String::new());
83						}
84					}
85				}
86
87				Ok(ColumnData::Utf8 {
88					container: Utf8Container::new(result_data),
89					max_bytes: MaxBytes::MAX,
90				})
91			}
92			other => Err(ScalarFunctionError::InvalidArgumentType {
93				function: ctx.fragment.clone(),
94				argument_index: 0,
95				expected: vec![Type::Utf8],
96				actual: other.get_type(),
97			}),
98		}
99	}
100
101	fn return_type(&self, _input_types: &[Type]) -> Type {
102		Type::Utf8
103	}
104}