Skip to main content

common_function/scalars/string/
insert.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! MySQL-compatible INSERT function implementation.
16//!
17//! INSERT(str, pos, len, newstr) - Inserts newstr into str at position pos,
18//! replacing len characters.
19
20use std::fmt;
21use std::sync::Arc;
22
23use datafusion_common::DataFusionError;
24use datafusion_common::arrow::array::{Array, ArrayRef, AsArray, LargeStringBuilder};
25use datafusion_common::arrow::compute::cast;
26use datafusion_common::arrow::datatypes::DataType;
27use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, Signature, TypeSignature, Volatility};
28
29use crate::function::Function;
30use crate::function_registry::FunctionRegistry;
31
32const NAME: &str = "insert";
33
34/// MySQL-compatible INSERT function.
35///
36/// Syntax: INSERT(str, pos, len, newstr)
37/// Returns str with the substring beginning at position pos and len characters long
38/// replaced by newstr.
39///
40/// - pos is 1-based
41/// - If pos is out of range, returns the original string
42/// - If len is out of range, replaces from pos to end of string
43#[derive(Debug)]
44pub struct InsertFunction {
45    signature: Signature,
46}
47
48impl InsertFunction {
49    pub fn register(registry: &FunctionRegistry) {
50        registry.register_scalar(InsertFunction::default());
51    }
52}
53
54impl Default for InsertFunction {
55    fn default() -> Self {
56        let mut signatures = Vec::new();
57        let string_types = [DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View];
58        let int_types = [
59            DataType::Int64,
60            DataType::Int32,
61            DataType::Int16,
62            DataType::Int8,
63            DataType::UInt64,
64            DataType::UInt32,
65            DataType::UInt16,
66            DataType::UInt8,
67        ];
68
69        for str_type in &string_types {
70            for newstr_type in &string_types {
71                for pos_type in &int_types {
72                    for len_type in &int_types {
73                        signatures.push(TypeSignature::Exact(vec![
74                            str_type.clone(),
75                            pos_type.clone(),
76                            len_type.clone(),
77                            newstr_type.clone(),
78                        ]));
79                    }
80                }
81            }
82        }
83
84        Self {
85            signature: Signature::one_of(signatures, Volatility::Immutable),
86        }
87    }
88}
89
90impl fmt::Display for InsertFunction {
91    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92        write!(f, "{}", NAME.to_ascii_uppercase())
93    }
94}
95
96impl Function for InsertFunction {
97    fn name(&self) -> &str {
98        NAME
99    }
100
101    fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
102        Ok(DataType::LargeUtf8)
103    }
104
105    fn signature(&self) -> &Signature {
106        &self.signature
107    }
108
109    fn invoke_with_args(
110        &self,
111        args: ScalarFunctionArgs,
112    ) -> datafusion_common::Result<ColumnarValue> {
113        if args.args.len() != 4 {
114            return Err(DataFusionError::Execution(
115                "INSERT requires exactly 4 arguments: INSERT(str, pos, len, newstr)".to_string(),
116            ));
117        }
118
119        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
120        let len = arrays[0].len();
121
122        // Cast string arguments to LargeUtf8
123        let str_array = cast_to_large_utf8(&arrays[0], "str")?;
124        let newstr_array = cast_to_large_utf8(&arrays[3], "newstr")?;
125        let pos_array = cast_to_int64(&arrays[1], "pos")?;
126        let replace_len_array = cast_to_int64(&arrays[2], "len")?;
127
128        let str_arr = str_array.as_string::<i64>();
129        let pos_arr = pos_array.as_primitive::<datafusion_common::arrow::datatypes::Int64Type>();
130        let len_arr =
131            replace_len_array.as_primitive::<datafusion_common::arrow::datatypes::Int64Type>();
132        let newstr_arr = newstr_array.as_string::<i64>();
133
134        let mut builder = LargeStringBuilder::with_capacity(len, len * 32);
135
136        for i in 0..len {
137            // Check for NULLs
138            if str_arr.is_null(i)
139                || pos_array.is_null(i)
140                || replace_len_array.is_null(i)
141                || newstr_arr.is_null(i)
142            {
143                builder.append_null();
144                continue;
145            }
146
147            let original = str_arr.value(i);
148            let pos = pos_arr.value(i);
149            let replace_len = len_arr.value(i);
150            let new_str = newstr_arr.value(i);
151
152            let result = insert_string(original, pos, replace_len, new_str);
153            builder.append_value(&result);
154        }
155
156        Ok(ColumnarValue::Array(Arc::new(builder.finish())))
157    }
158}
159
160/// Cast array to LargeUtf8 for uniform string access.
161fn cast_to_large_utf8(array: &ArrayRef, name: &str) -> datafusion_common::Result<ArrayRef> {
162    cast(array.as_ref(), &DataType::LargeUtf8)
163        .map_err(|e| DataFusionError::Execution(format!("INSERT: {} cast failed: {}", name, e)))
164}
165
166fn cast_to_int64(array: &ArrayRef, name: &str) -> datafusion_common::Result<ArrayRef> {
167    cast(array.as_ref(), &DataType::Int64)
168        .map_err(|e| DataFusionError::Execution(format!("INSERT: {} cast failed: {}", name, e)))
169}
170
171/// Perform the INSERT string operation.
172/// pos is 1-based. If pos < 1 or pos > len(str) + 1, returns original string.
173/// if replace_len is negative or past the end of the string, replace to the end.
174fn insert_string(original: &str, pos: i64, replace_len: i64, new_str: &str) -> String {
175    let char_count = original.chars().count();
176
177    // MySQL behavior: if pos < 1 or pos > string length + 1, return original
178    if pos < 1 || pos as usize > char_count + 1 {
179        return original.to_string();
180    }
181
182    let start_idx = (pos - 1) as usize; // Convert to 0-based
183
184    let end_idx = usize::try_from(replace_len).map_or(char_count, |replace_len| {
185        start_idx.saturating_add(replace_len).min(char_count)
186    });
187
188    let start_byte = char_to_byte_idx(original, start_idx);
189    let end_byte = char_to_byte_idx(original, end_idx);
190
191    let mut result = String::with_capacity(original.len() + new_str.len());
192    result.push_str(&original[..start_byte]);
193    result.push_str(new_str);
194    result.push_str(&original[end_byte..]);
195    result
196}
197
198fn char_to_byte_idx(s: &str, char_idx: usize) -> usize {
199    s.char_indices()
200        .nth(char_idx)
201        .map(|(idx, _)| idx)
202        .unwrap_or(s.len())
203}
204
205#[cfg(test)]
206mod tests {
207    use std::sync::Arc;
208
209    use datafusion_common::arrow::array::{Int64Array, StringArray};
210    use datafusion_common::arrow::datatypes::Field;
211    use datafusion_expr::ScalarFunctionArgs;
212
213    use super::*;
214
215    fn create_args(arrays: Vec<ArrayRef>) -> ScalarFunctionArgs {
216        let arg_fields: Vec<_> = arrays
217            .iter()
218            .enumerate()
219            .map(|(i, arr)| {
220                Arc::new(Field::new(
221                    format!("arg_{}", i),
222                    arr.data_type().clone(),
223                    true,
224                ))
225            })
226            .collect();
227
228        ScalarFunctionArgs {
229            args: arrays.iter().cloned().map(ColumnarValue::Array).collect(),
230            arg_fields,
231            return_field: Arc::new(Field::new("result", DataType::LargeUtf8, true)),
232            number_rows: arrays[0].len(),
233            config_options: Arc::new(datafusion_common::config::ConfigOptions::default()),
234        }
235    }
236
237    #[test]
238    fn test_insert_basic() {
239        let function = InsertFunction::default();
240
241        // INSERT('Quadratic', 3, 4, 'What') => 'QuWhattic'
242        let str_arr = Arc::new(StringArray::from(vec!["Quadratic"]));
243        let pos = Arc::new(Int64Array::from(vec![3]));
244        let len = Arc::new(Int64Array::from(vec![4]));
245        let newstr = Arc::new(StringArray::from(vec!["What"]));
246
247        let args = create_args(vec![str_arr, pos, len, newstr]);
248        let result = function.invoke_with_args(args).unwrap();
249
250        if let ColumnarValue::Array(array) = result {
251            let str_array = array.as_string::<i64>();
252            assert_eq!(str_array.value(0), "QuWhattic");
253        } else {
254            panic!("Expected array result");
255        }
256    }
257
258    #[test]
259    fn test_insert_out_of_range_pos() {
260        let function = InsertFunction::default();
261
262        // INSERT('Quadratic', 0, 4, 'What') => 'Quadratic' (pos < 1)
263        let str_arr = Arc::new(StringArray::from(vec!["Quadratic", "Quadratic"]));
264        let pos = Arc::new(Int64Array::from(vec![0, 100]));
265        let len = Arc::new(Int64Array::from(vec![4, 4]));
266        let newstr = Arc::new(StringArray::from(vec!["What", "What"]));
267
268        let args = create_args(vec![str_arr, pos, len, newstr]);
269        let result = function.invoke_with_args(args).unwrap();
270
271        if let ColumnarValue::Array(array) = result {
272            let str_array = array.as_string::<i64>();
273            assert_eq!(str_array.value(0), "Quadratic"); // pos < 1
274            assert_eq!(str_array.value(1), "Quadratic"); // pos > length
275        } else {
276            panic!("Expected array result");
277        }
278    }
279
280    #[test]
281    fn test_insert_replace_to_end() {
282        let function = InsertFunction::default();
283
284        // INSERT('Quadratic', 3, 100, 'What') => 'QuWhat' (len exceeds remaining)
285        let str_arr = Arc::new(StringArray::from(vec!["Quadratic"]));
286        let pos = Arc::new(Int64Array::from(vec![3]));
287        let len = Arc::new(Int64Array::from(vec![100]));
288        let newstr = Arc::new(StringArray::from(vec!["What"]));
289
290        let args = create_args(vec![str_arr, pos, len, newstr]);
291        let result = function.invoke_with_args(args).unwrap();
292
293        if let ColumnarValue::Array(array) = result {
294            let str_array = array.as_string::<i64>();
295            assert_eq!(str_array.value(0), "QuWhat");
296        } else {
297            panic!("Expected array result");
298        }
299    }
300
301    #[test]
302    fn test_insert_negative_replace_len() {
303        let cases = [
304            // INSERT('Quadratic', 3, -1, 'What') => 'QuWhat'
305            (("Quadratic", 3, -1, "What"), "QuWhat"),
306            // INSERT('Quadratic', 1, -1, 'What') => 'What'
307            (("Quadratic", 1, -1, "What"), "What"),
308            (("Quadratic", 9, -1, "What"), "QuadratiWhat"),
309        ];
310        let function = InsertFunction::default();
311
312        for ((curr_str, pos, len, new_str), expected) in cases {
313            let curr_str_arg = Arc::new(StringArray::from(vec![curr_str]));
314            let pos_arg = Arc::new(Int64Array::from(vec![pos]));
315            let len_arg = Arc::new(Int64Array::from(vec![len]));
316            let new_str_arg = Arc::new(StringArray::from(vec![new_str]));
317            let args = create_args(vec![curr_str_arg, pos_arg, len_arg, new_str_arg]);
318
319            let result = function.invoke_with_args(args).unwrap();
320
321            if let ColumnarValue::Array(array) = result {
322                let str_array = array.as_string::<i64>();
323                assert_eq!(
324                    str_array.value(0),
325                    expected,
326                    "INSERT({curr_str:?}, {pos}, {len}, {new_str:?}) = {expected}"
327                );
328            } else {
329                panic!("Expected array result");
330            }
331        }
332    }
333
334    #[test]
335    fn test_insert_unicode() {
336        let function = InsertFunction::default();
337
338        // INSERT('hello世界', 6, 1, 'の') => 'helloの界'
339        let str_arr = Arc::new(StringArray::from(vec!["hello世界"]));
340        let pos = Arc::new(Int64Array::from(vec![6]));
341        let len = Arc::new(Int64Array::from(vec![1]));
342        let newstr = Arc::new(StringArray::from(vec!["の"]));
343
344        let args = create_args(vec![str_arr, pos, len, newstr]);
345        let result = function.invoke_with_args(args).unwrap();
346
347        if let ColumnarValue::Array(array) = result {
348            let str_array = array.as_string::<i64>();
349            assert_eq!(str_array.value(0), "helloの界");
350        } else {
351            panic!("Expected array result");
352        }
353    }
354
355    #[test]
356    fn test_insert_with_nulls() {
357        let function = InsertFunction::default();
358
359        let str_arr = Arc::new(StringArray::from(vec![Some("hello"), None]));
360        let pos = Arc::new(Int64Array::from(vec![1, 1]));
361        let len = Arc::new(Int64Array::from(vec![1, 1]));
362        let newstr = Arc::new(StringArray::from(vec!["X", "X"]));
363
364        let args = create_args(vec![str_arr, pos, len, newstr]);
365        let result = function.invoke_with_args(args).unwrap();
366
367        if let ColumnarValue::Array(array) = result {
368            let str_array = array.as_string::<i64>();
369            assert_eq!(str_array.value(0), "Xello");
370            assert!(str_array.is_null(1));
371        } else {
372            panic!("Expected array result");
373        }
374    }
375}