Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions core/src/main/java/org/apache/calcite/runtime/Like.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,71 @@
return javaPattern.toString();
}

/**
* Translates a SQL LIKE pattern to a MongoDB regular expression, with an
* optional escape string.
*
* <p>Similar to {@link #sqlToRegexLike}, except that the result is anchored
* with {@code ^} and {@code $} so that the entire value must match, as SQL
* LIKE requires.
*/
public static String sqlToRegexMongo(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method is now public static in core, but its name (sqlToRegexMongo) makes it look Mongo-specific even though the logic is generic (anchored regex translation). Worth either noting in the javadoc that it's not actually Mongo-exclusive, or using a more neutral name — not blocking, just a naming nit.

String sqlPattern,
@Nullable CharSequence escapeStr) {
final char escapeChar;
if (escapeStr != null) {
if (escapeStr.length() != 1) {
throw invalidEscapeCharacter(escapeStr.toString());
}
escapeChar = escapeStr.charAt(0);
} else {
escapeChar = 0;
}
return sqlToRegexMongo(sqlPattern, escapeChar);
}

/**
* Translates a SQL LIKE pattern to a MongoDB regular expression.
*/
public static String sqlToRegexMongo(

Check failure on line 139 in core/src/main/java/org/apache/calcite/runtime/Like.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=apache_calcite&issues=AZ_V4qH1-hFVF3iv8RyQ&open=AZ_V4qH1-hFVF3iv8RyQ&pullRequest=5158
String sqlPattern,
char escapeChar) {
final int len = sqlPattern.length();
final StringBuilder javaPattern = new StringBuilder(len + len);
javaPattern.append('^');
for (int i = 0; i < len; i++) {
char c = sqlPattern.charAt(i);
if (c == escapeChar) {
if (i == (sqlPattern.length() - 1)) {
throw invalidEscapeSequence(sqlPattern, i);
}
char nextChar = sqlPattern.charAt(i + 1);
if ((nextChar == '_')
|| (nextChar == '%')
|| (nextChar == escapeChar)) {
if (JAVA_REGEX_SPECIALS.indexOf(nextChar) >= 0) {
javaPattern.append('\\');
}
javaPattern.append(nextChar);
i++;

Check warning on line 159 in core/src/main/java/org/apache/calcite/runtime/Like.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor the code in order to not assign to this loop counter from within the loop body.

See more on https://sonarcloud.io/project/issues?id=apache_calcite&issues=AZ_V4qH1-hFVF3iv8RyP&open=AZ_V4qH1-hFVF3iv8RyP&pullRequest=5158
} else {
throw invalidEscapeSequence(sqlPattern, i);
}
} else if (c == '_') {
javaPattern.append('.');
} else if (c == '%') {
javaPattern.append(".*");
} else {
if (JAVA_REGEX_SPECIALS.indexOf(c) >= 0) {
javaPattern.append('\\');
}
javaPattern.append(c);
}
}
javaPattern.append('$');
return javaPattern.toString();
}

private static RuntimeException invalidEscapeCharacter(String s) {
return new RuntimeException(
"Invalid escape character '" + s + "'");
Expand Down
50 changes: 50 additions & 0 deletions core/src/test/java/org/apache/calcite/runtime/LikeTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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.
*/
package org.apache.calcite.runtime;

import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/** Unit tests for {@link Like}. */
class LikeTest {

/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-7693">[CALCITE-7693]
* Move MongoDB LIKE-to-regex conversion into runtime.Like for consistency</a>. */
@Test void testSqlToRegexMongo() {
assertThat(Like.sqlToRegexMongo("", null), is("^$"));
assertThat(Like.sqlToRegexMongo("abc", null), is("^abc$"));
assertThat(Like.sqlToRegexMongo("A%", null), is("^A.*$"));
assertThat(Like.sqlToRegexMongo("A_", null), is("^A.$"));
assertThat(Like.sqlToRegexMongo("%abc%", null), is("^.*abc.*$"));
// '.' is an ordinary SQL LIKE character; it must be escaped so that it is
// literal in the generated regex.
assertThat(Like.sqlToRegexMongo("A.B%", null), is("^A\\.B.*$"));
}

@Test void testSqlToRegexMongoWithEscape() {
// '\' escapes the wildcards, making them literal.
assertThat(Like.sqlToRegexMongo("A\\_B\\%C%", "\\"), is("^A_B%C.*$"));
assertThat(Like.sqlToRegexMongo("BROOKLYN\\%", "\\"), is("^BROOKLYN%$"));
// A custom escape character.
assertThat(Like.sqlToRegexMongo("BROOKLYN!%", "!"), is("^BROOKLYN%$"));
// The escape character followed by itself is a literal escape character.
assertThat(Like.sqlToRegexMongo("A\\\\B", "\\"), is("^A\\\\B$"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.runtime.Like;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.util.JsonBuilder;
Expand Down Expand Up @@ -321,8 +322,8 @@ private Void translateLike(RexCall call,
final RexLiteral patternLiteral = (RexLiteral) right;
final String sqlPattern = patternLiteral.getValue2().toString();

final @Nullable Character escapeChar = escapeChar(call);
final String finalRegex = sqlLikeToMongoRegex(sqlPattern, escapeChar);
final @Nullable String escapeChar = escapeChar(call);
final String finalRegex = Like.sqlToRegexMongo(sqlPattern, escapeChar);

switch (left.getKind()) {
case INPUT_REF:
Expand Down Expand Up @@ -364,8 +365,8 @@ private Void translateNotLike(RexCall call, List<Map<String, Object>> orMapList)
final RexLiteral patternLiteral = (RexLiteral) right;
final String sqlPattern = patternLiteral.getValue2().toString();

final @Nullable Character escapeChar = escapeChar(call);
final String finalRegex = sqlLikeToMongoRegex(sqlPattern, escapeChar);
final @Nullable String escapeChar = escapeChar(call);
final String finalRegex = Like.sqlToRegexMongo(sqlPattern, escapeChar);

final String name;
switch (left.getKind()) {
Expand Down Expand Up @@ -404,8 +405,8 @@ private static RexNode stripCast(RexNode node) {
return node;
}

/** Returns the escape character declared in a LIKE expression, or null. */
private static @Nullable Character escapeChar(RexCall call) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we rename this to escapeStr to match the parameter name in Like.sqlToRegexMongo? (escapeString also works but reads a bit ambiguous — could be misread as "a string that's been escaped" rather than "the escape string from the LIKE clause".)

/** Returns the escape string declared in a LIKE expression, or null. */
private static @Nullable String escapeChar(RexCall call) {
if (call.operands.size() != 3) {
return null;
}
Expand All @@ -417,72 +418,7 @@ private static RexNode stripCast(RexNode node) {
if (escape.length() != 1) {
throw new AssertionError("cannot translate LIKE with multi-character escape: " + call);
}
return escape.charAt(0);
}

/**
* Converts SQL LIKE pattern to MongoDB regex pattern.
*
* <p>SQL: {@code %} matches zero or more characters, {@code _} matches a single
* character. MongoDB: {@code .*} matches zero or more characters, {@code .}
* matches a single character.
*
* <p>We add {@code ^} and {@code $} anchors so that the entire string matches
* the pattern, just as SQL LIKE does.
*/
private static String sqlLikeToMongoRegex(String sqlPattern, @Nullable Character escapeChar) {
final StringBuilder regex = new StringBuilder(sqlPattern.length() * 2);
regex.append("^");
for (int i = 0; i < sqlPattern.length(); i++) {
char c = sqlPattern.charAt(i);
if (escapeChar != null && c == escapeChar) {
if (i == sqlPattern.length() - 1) {
throw new AssertionError("Invalid escape sequence at end of LIKE pattern: "
+ sqlPattern);
}
final char nextChar = sqlPattern.charAt(i + 1);
if (nextChar == '%' || nextChar == '_' || nextChar == escapeChar) {
regex.append(escapeRegexChar(nextChar));
i++;
} else {
throw new AssertionError("Invalid escape sequence in LIKE pattern: " + sqlPattern);
}
} else if (c == '%') {
regex.append(".*");
} else if (c == '_') {
regex.append('.');
} else {
regex.append(escapeRegexChar(c));
}
}
regex.append("$");
return regex.toString();
}

/**
* Escapes a character for use in a MongoDB regex if it's a special regex character.
*/
private static String escapeRegexChar(char c) {
// MongoDB regex special characters that need escaping
switch (c) {
case '\\':
case '^':
case '$':
case '.':
case '|':
case '?':
case '*':
case '+':
case '(':
case ')':
case '[':
case ']':
case '{':
case '}':
return "\\" + c;
default:
return String.valueOf(c);
}
return escape;
}
}
}
Loading