Skip to content

Commit 67dfa99

Browse files
authored
SQL: fix REPLACE with empty pattern (#148616) (#148650)
This fixes a spin on empty input pattern.
1 parent 978f82a commit 67dfa99

4 files changed

Lines changed: 25 additions & 0 deletions

File tree

docs/changelog/148616.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
area: SQL
2+
issues: []
3+
pr: 148616
4+
summary: Fix REPLACE with empty pattern
5+
type: bug

x-pack/plugin/sql/qa/server/src/main/resources/functions.csv-spec

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,18 @@ Bojan |Bojan
225225

226226
;
227227

228+
selectReplaceWithEmptyPattern
229+
SELECT REPLACE("first_name",'','X') same, "first_name" original FROM "test_emp" ORDER BY "first_name" LIMIT 5;
230+
231+
same:s | original:s
232+
-----------------+---------------
233+
Alejandro |Alejandro
234+
Amabile |Amabile
235+
Anneke |Anneke
236+
Anoosh |Anoosh
237+
Arumugam |Arumugam
238+
;
239+
228240
selectReplaceWithGroupBy
229241
SELECT REPLACE("first_name",'jan','_JAN_') modified, COUNT(*) count FROM "test_emp" GROUP BY REPLACE("first_name",'jan','_JAN_') ORDER BY REPLACE("first_name",'jan','_JAN_') LIMIT 10;
230242

x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionProcessor.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ public static Object doProcess(Object input, Object pattern, Object replacement)
6767

6868
private static void checkResultLength(String input, String pattern, String replacement) {
6969
int patternLen = pattern.length();
70+
if (patternLen == 0) {
71+
return;
72+
}
7073
long matches = 0;
7174
for (int i = input.indexOf(pattern); i >= 0; i = input.indexOf(pattern, i + patternLen)) {
7275
matches++;

x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceProcessorTests.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public void testReplaceFunctionWithEdgeCases() {
5858
assertNull(new Replace(EMPTY, l(null), l(null), l(null)).makePipe().asProcessor().process(null));
5959
}
6060

61+
public void testReplaceFunctionWithEmptyPattern() {
62+
assertEquals("foobar", new Replace(EMPTY, l("foobar"), l(""), l("baz")).makePipe().asProcessor().process(null));
63+
assertEquals("foobar", new Replace(EMPTY, l("foobar"), l(""), l("")).makePipe().asProcessor().process(null));
64+
}
65+
6166
public void testReplaceFunctionInputsValidation() {
6267
SqlIllegalArgumentException siae = expectThrows(
6368
SqlIllegalArgumentException.class,

0 commit comments

Comments
 (0)