You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by el...@apache.org on 2026/09/18 15:11:31 UTC

(superset) 01/01: fix(bigquery): avoid ESCAPE clause in column-value typeahead search (SC-121408)

This is an automated email from the ASF dual-hosted git repository.

eschutho pushed a commit to branch fix-bigquery-like-escape-typeahead
in repository https://gitbox.apache.org/repos/asf/superset.git

commit bf2103ec4ec06017e2317686823a72e8ed9ee63a
Author: Elizabeth Thompson <es...@gmail.com>
AuthorDate: Fri Sep 18 15:11:15 2026 +0000

    fix(bigquery): avoid ESCAPE clause in column-value typeahead search (SC-121408)
    
    BigQuery datasets threw `DatabaseError: Syntax error: Expected end of
    input but got keyword ESCAPE` when a user typed into a filter's
    column-value typeahead search box.
    
    `build_like_predicate` compiled a `LIKE ... ESCAPE '!'` clause via
    `.like(pattern, escape=...)`. SQLAlchemy's base compiler always appends
    a literal `ESCAPE '<char>'` for LIKE, and `sqlalchemy-bigquery`'s
    `BigQueryCompiler` does not override `visit_like_op_binary` /
    `visit_not_like_op_binary`, so the `ESCAPE '!'` clause leaked verbatim
    into GoogleSQL, which has no ESCAPE keyword and rejects it.
    
    Switch to `.contains(search, autoescape=True)`, which IS covered by
    BigQueryCompiler's `visit_contains_op_binary` override (it pops the
    escape modifier and re-encodes wildcards using BigQuery's backslash
    convention). Other engines still emit a dialect-native
    `LIKE ... ESCAPE` predicate, so behavior is unchanged: same
    case-insensitive substring match everywhere. The now-unused
    `LIKE_ESCAPE_CHAR` constant and `escape_like_pattern()` helper are
    removed.
    
    Fixes SUPERSET-PYTHON-176K
    
    Co-Authored-By: Claude Opus 4.8 <no...@anthropic.com>
---
 superset/models/helpers.py              | 30 +++++---------------
 tests/unit_tests/models/helpers_test.py | 49 ++++++++++++++++++---------------
 2 files changed, 34 insertions(+), 45 deletions(-)

diff --git a/superset/models/helpers.py b/superset/models/helpers.py
index 29a05cc6ce6..fe1746440ac 100644
--- a/superset/models/helpers.py
+++ b/superset/models/helpers.py
@@ -199,27 +199,6 @@ def get_effective_hours_offset(
 R_SUFFIX = "__right_suffix"
 
 
-# Escape character for LIKE patterns built from user-supplied search text.
-# Deliberately not a backslash: dialects that escape backslashes when rendering
-# string literals would emit a two-character ESCAPE clause, which is a syntax
-# error on engines that honour standard-conforming strings.
-LIKE_ESCAPE_CHAR = "!"
-
-
-def escape_like_pattern(value: str) -> str:
-    """
-    Neutralize LIKE wildcards in user-supplied search text.
-
-    Without this a user typing ``%`` or ``_`` would match every row, which is
-    both wrong and, on a large table, a scan the search was meant to avoid.
-    """
-    return (
-        value.replace(LIKE_ESCAPE_CHAR, LIKE_ESCAPE_CHAR * 2)
-        .replace("%", f"{LIKE_ESCAPE_CHAR}%")
-        .replace("_", f"{LIKE_ESCAPE_CHAR}_")
-    )
-
-
 def build_like_predicate(
     expr: ColumnElement[Any],
     search: str,
@@ -227,11 +206,16 @@ def build_like_predicate(
     """
     Build a case-insensitive containment predicate for ``expr``.
 
+    Uses ``contains(..., autoescape=True)`` rather than a raw ``LIKE ...
+    ESCAPE`` clause because BigQuery's GoogleSQL dialect has no ESCAPE
+    keyword and rejects it outright; ``contains()`` lets each dialect's
+    compiler render wildcard-escaping in its own supported syntax (BigQuery's
+    compiler swaps in backslash-escaping instead of an ESCAPE clause).
+
     ``lower(expr) LIKE lower('%term%')`` is used rather than ``ILIKE`` because
     the latter is not portable across engines.
     """
-    pattern = f"%{escape_like_pattern(search)}%".lower()
-    return sa.func.lower(expr).like(pattern, escape=LIKE_ESCAPE_CHAR)
+    return sa.func.lower(expr).contains(search.lower(), autoescape=True)
 
 
 def _is_parenthesized(sqla_col: ColumnElement) -> bool:
diff --git a/tests/unit_tests/models/helpers_test.py b/tests/unit_tests/models/helpers_test.py
index 0ecfb7af7e7..d373726f5bb 100644
--- a/tests/unit_tests/models/helpers_test.py
+++ b/tests/unit_tests/models/helpers_test.py
@@ -105,36 +105,39 @@ def test_values_for_column(database: Database) -> None:
         assert table.values_for_column("a") == [1, None]
 
 
-@pytest.mark.parametrize(
-    "raw,expected",
-    [
-        ("plain", "plain"),
-        ("50%", "50!%"),
-        ("a_b", "a!_b"),
-        ("wow!", "wow!!"),
-        ("!%_", "!!!%!_"),
-    ],
-)
-def test_escape_like_pattern(raw: str, expected: str) -> None:
-    """Wildcards typed by a user are data, not pattern syntax."""
-    from superset.models.helpers import escape_like_pattern
-
-    assert escape_like_pattern(raw) == expected
-
-
 def test_build_like_predicate_is_case_insensitive_and_escaped() -> None:
     import sqlalchemy as sa
 
     from superset.models.helpers import build_like_predicate
 
-    compiled = str(
-        build_like_predicate(sa.column("c"), "50%").compile(
+    predicate = build_like_predicate(sa.column("c"), "50%")
+
+    # The search term is lower-cased for a case-insensitive match, and the
+    # user's ``%`` wildcard is neutralized (autoescape) rather than matching
+    # every row.
+    postgres_sql = str(
+        predicate.compile(
             dialect=sa.dialects.registry.load("postgresql")(),
             compile_kwargs={"literal_binds": True},
         )
-    ).replace("%%", "%")
+    )
+    assert "lower(c)" in postgres_sql
+    assert "50" in postgres_sql
+    # Other engines still get a dialect-native ESCAPE clause, proving they are
+    # unaffected by the BigQuery-specific fix.
+    assert "ESCAPE" in postgres_sql
+
+    # Regression test for SUPERSET-PYTHON-176K: BigQuery's GoogleSQL has no
+    # ESCAPE keyword, so the compiled predicate must not emit one.
+    from sqlalchemy_bigquery import BigQueryDialect
 
-    assert compiled == "lower(c) LIKE '%50!%%' ESCAPE '!'"
+    bigquery_sql = str(
+        predicate.compile(
+            dialect=BigQueryDialect(),
+            compile_kwargs={"literal_binds": True},
+        )
+    )
+    assert "ESCAPE" not in bigquery_sql
 
 
 def test_values_for_column_search(database: Database) -> None:
@@ -157,8 +160,10 @@ def test_values_for_column_search(database: Database) -> None:
         assert table.values_for_column("a", search="ali") == ["Alice"]
 
     sql = str(read_sql_query.call_args.kwargs["sql"])
+    # ``.contains()`` compiles to a concatenated pattern rather than a single
+    # ``'%ali%'`` literal, e.g. ``... LIKE '%' || 'ali' || '%'`` on sqlite.
     assert "LIKE" in sql
-    assert "'%ali%'" in sql
+    assert "'ali'" in sql
 
 
 def test_values_for_column_without_search_has_no_predicate(