1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use std::any::Any;
use std::sync::Arc;

use arrow::array::{ArrayRef, GenericStringArray, OffsetSizeTrait};
use arrow::datatypes::DataType;

use datafusion_common::cast::{as_generic_string_array, as_int64_array};
use datafusion_common::{exec_err, Result};
use datafusion_expr::TypeSignature::*;
use datafusion_expr::{ColumnarValue, Volatility};
use datafusion_expr::{ScalarUDFImpl, Signature};

use crate::utils::{make_scalar_function, utf8_to_str_type};

#[derive(Debug)]
pub struct OverlayFunc {
    signature: Signature,
}

impl Default for OverlayFunc {
    fn default() -> Self {
        Self::new()
    }
}

impl OverlayFunc {
    pub fn new() -> Self {
        use DataType::*;
        Self {
            signature: Signature::one_of(
                vec![
                    Exact(vec![Utf8, Utf8, Int64, Int64]),
                    Exact(vec![LargeUtf8, LargeUtf8, Int64, Int64]),
                    Exact(vec![Utf8, Utf8, Int64]),
                    Exact(vec![LargeUtf8, LargeUtf8, Int64]),
                ],
                Volatility::Immutable,
            ),
        }
    }
}

impl ScalarUDFImpl for OverlayFunc {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn name(&self) -> &str {
        "overlay"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
        utf8_to_str_type(&arg_types[0], "overlay")
    }

    fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
        match args[0].data_type() {
            DataType::Utf8 => make_scalar_function(overlay::<i32>, vec![])(args),
            DataType::LargeUtf8 => make_scalar_function(overlay::<i64>, vec![])(args),
            other => exec_err!("Unsupported data type {other:?} for function overlay"),
        }
    }
}

/// OVERLAY(string1 PLACING string2 FROM integer FOR integer2)
/// Replaces a substring of string1 with string2 starting at the integer bit
/// pgsql overlay('Txxxxas' placing 'hom' from 2 for 4) → Thomas
/// overlay('Txxxxas' placing 'hom' from 2) -> Thomxas, without for option, str2's len is instead
pub fn overlay<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
    match args.len() {
        3 => {
            let string_array = as_generic_string_array::<T>(&args[0])?;
            let characters_array = as_generic_string_array::<T>(&args[1])?;
            let pos_num = as_int64_array(&args[2])?;

            let result = string_array
                .iter()
                .zip(characters_array.iter())
                .zip(pos_num.iter())
                .map(|((string, characters), start_pos)| {
                    match (string, characters, start_pos) {
                        (Some(string), Some(characters), Some(start_pos)) => {
                            let string_len = string.chars().count();
                            let characters_len = characters.chars().count();
                            let replace_len = characters_len as i64;
                            let mut res =
                                String::with_capacity(string_len.max(characters_len));

                            //as sql replace index start from 1 while string index start from 0
                            if start_pos > 1 && start_pos - 1 < string_len as i64 {
                                let start = (start_pos - 1) as usize;
                                res.push_str(&string[..start]);
                            }
                            res.push_str(characters);
                            // if start + replace_len - 1 >= string_length, just to string end
                            if start_pos + replace_len - 1 < string_len as i64 {
                                let end = (start_pos + replace_len - 1) as usize;
                                res.push_str(&string[end..]);
                            }
                            Ok(Some(res))
                        }
                        _ => Ok(None),
                    }
                })
                .collect::<Result<GenericStringArray<T>>>()?;
            Ok(Arc::new(result) as ArrayRef)
        }
        4 => {
            let string_array = as_generic_string_array::<T>(&args[0])?;
            let characters_array = as_generic_string_array::<T>(&args[1])?;
            let pos_num = as_int64_array(&args[2])?;
            let len_num = as_int64_array(&args[3])?;

            let result = string_array
                .iter()
                .zip(characters_array.iter())
                .zip(pos_num.iter())
                .zip(len_num.iter())
                .map(|(((string, characters), start_pos), len)| {
                    match (string, characters, start_pos, len) {
                        (Some(string), Some(characters), Some(start_pos), Some(len)) => {
                            let string_len = string.chars().count();
                            let characters_len = characters.chars().count();
                            let replace_len = len.min(string_len as i64);
                            let mut res =
                                String::with_capacity(string_len.max(characters_len));

                            //as sql replace index start from 1 while string index start from 0
                            if start_pos > 1 && start_pos - 1 < string_len as i64 {
                                let start = (start_pos - 1) as usize;
                                res.push_str(&string[..start]);
                            }
                            res.push_str(characters);
                            // if start + replace_len - 1 >= string_length, just to string end
                            if start_pos + replace_len - 1 < string_len as i64 {
                                let end = (start_pos + replace_len - 1) as usize;
                                res.push_str(&string[end..]);
                            }
                            Ok(Some(res))
                        }
                        _ => Ok(None),
                    }
                })
                .collect::<Result<GenericStringArray<T>>>()?;
            Ok(Arc::new(result) as ArrayRef)
        }
        other => {
            exec_err!("overlay was called with {other} arguments. It requires 3 or 4.")
        }
    }
}

#[cfg(test)]
mod tests {
    use arrow::array::{Int64Array, StringArray};

    use super::*;

    #[test]
    fn to_overlay() -> Result<()> {
        let string =
            Arc::new(StringArray::from(vec!["123", "abcdefg", "xyz", "Txxxxas"]));
        let replace_string =
            Arc::new(StringArray::from(vec!["abc", "qwertyasdfg", "ijk", "hom"]));
        let start = Arc::new(Int64Array::from(vec![4, 1, 1, 2])); // start
        let end = Arc::new(Int64Array::from(vec![5, 7, 2, 4])); // replace len

        let res = overlay::<i32>(&[string, replace_string, start, end]).unwrap();
        let result = as_generic_string_array::<i32>(&res).unwrap();
        let expected = StringArray::from(vec!["abc", "qwertyasdfg", "ijkz", "Thomas"]);
        assert_eq!(&expected, result);

        Ok(())
    }
}