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