This is an automated email from the ASF dual-hosted git repository. villebro pushed a commit to branch 7.0 in repository https://gitbox.apache.org/repos/asf/superset.git
commit afd4c21b7a2c3d32d56df76240b9e712613f31ff Author: Elizabeth Thompson <[email protected]> AuthorDate: Thu Nov 5 18:14:35 2026 -0800 fix(filters): avoid ESCAPE clause for ClickHouse filter-value search (#45926) Co-authored-by: Claude Sonnet 5.5 <[email protected]> (cherry picked from commit 3d76e4868208a60d907ce6a782a7624327f53ec8) --- superset/models/helpers.py | 47 +++++++++++++++- tests/unit_tests/models/helpers_test.py | 95 +++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) diff --git a/superset/models/helpers.py b/superset/models/helpers.py index 6924aa6e1fb..a71198e29bf 100644 --- a/superset/models/helpers.py +++ b/superset/models/helpers.py @@ -61,6 +61,7 @@ from markupsafe import escape, Markup from pandas import DateOffset, Timedelta from sqlalchemy import and_, Column, or_, UniqueConstraint from sqlalchemy.exc import MultipleResultsFound +from sqlalchemy.ext.compiler import compiles from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import ( declared_attr, @@ -231,7 +232,51 @@ def build_like_predicate( .with_variant(sa.Unicode(), "mssql") ) expr = sa.cast(expr, cast_type) - return sa.func.lower(expr).contains(search.lower(), autoescape=True) + return _ContainsSearch(sa.func.lower(expr), search.lower()) + + +class _ContainsSearch(ColumnElement[bool]): + """ + ``expr LIKE '%term%'`` with the term's wildcards escaped. + + Rendering is deferred to compile time so ClickHouse can be special-cased: + its SQLAlchemy compiler rejects the ``ESCAPE`` clause that + ``contains(..., autoescape=True)`` emits. The compiled output is the + grouped ``contains()`` expression, so it is identical to calling + ``contains()`` directly on every other dialect. + """ + + inherit_cache = True + type = sa.Boolean() + _is_implicitly_boolean = True + _traverse_internals = [ + ("expr", visitors.InternalTraversal.dp_clauseelement), + ("term", visitors.InternalTraversal.dp_string), + ] + + def __init__(self, expr: ColumnElement[Any], term: str) -> None: + super().__init__() + self.expr = expr + self.term = term + + @property + def _from_objects(self) -> list[Any]: + return self.expr._from_objects + + +@compiles(_ContainsSearch) +def _compile_contains_search(element: _ContainsSearch, compiler: Any, **kw: Any) -> str: + predicate = element.expr.contains(element.term, autoescape=True) + return compiler.process(predicate.self_group(), **kw) + + +@compiles(_ContainsSearch, "clickhousedb") +def _compile_contains_search_clickhouse( + element: _ContainsSearch, compiler: Any, **kw: Any +) -> str: + # ClickHouse's LIKE has no ESCAPE clause; backslash is its native escape. + term = element.term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + return compiler.process(element.expr.contains(term).self_group(), **kw) 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 72754d3f8f7..afd870258a0 100644 --- a/tests/unit_tests/models/helpers_test.py +++ b/tests/unit_tests/models/helpers_test.py @@ -191,6 +191,101 @@ def test_build_like_predicate_casts_non_text_columns() -> None: assert "ESCAPE" not in bigquery_sql [email protected]( + "dialect_name", + ["postgresql", "mysql", "mssql", "oracle", "sqlite"], +) +def test_build_like_predicate_matches_plain_contains(dialect_name: str) -> None: + """Outside ClickHouse the SQL is identical to ``contains(autoescape=True)``.""" + import sqlalchemy as sa + + from superset.models.helpers import build_like_predicate + + column = sa.column("c", sa.String()) + dialect = sa.dialects.registry.load(dialect_name)() + + def render(predicate: Any) -> str: + return str( + sa.select(column) + .where(predicate) + .compile(dialect=dialect, compile_kwargs={"literal_binds": True}) + ) + + assert render(build_like_predicate(column, "A%_b")) == render( + sa.func.lower(column).contains("a%_b", autoescape=True) + ) + + +def test_build_like_predicate_matches_plain_contains_bigquery() -> None: + import sqlalchemy as sa + + pytest.importorskip("sqlalchemy_bigquery") + from sqlalchemy_bigquery import BigQueryDialect + + from superset.models.helpers import build_like_predicate + + column = sa.column("c", sa.String()) + + def render(predicate: Any) -> str: + return str( + sa.select(column) + .where(predicate) + .compile(dialect=BigQueryDialect(), compile_kwargs={"literal_binds": True}) + ) + + assert render(build_like_predicate(column, "A%_b")) == render( + sa.func.lower(column).contains("a%_b", autoescape=True) + ) + + +def test_build_like_predicate_executes_correctly_on_sqlite() -> None: + import sqlalchemy as sa + + from superset.models.helpers import build_like_predicate + + engine = sa.create_engine("sqlite://") + table = sa.table("t", sa.column("c", sa.String)) + with engine.begin() as conn: + conn.execute(sa.text("CREATE TABLE t (c TEXT)")) + for value in ("50%x", "50ax", "A_b", "ab"): + conn.execute(sa.text("INSERT INTO t VALUES (:v)"), {"v": value}) + + def search(term: str) -> list[str]: + query = sa.select(table.c.c).where(build_like_predicate(table.c.c, term)) + return sorted(row[0] for row in conn.execute(query)) + + assert search("a_") == ["A_b"] + assert search("zz") == [] + assert search("50%") == ["50%x"] + + +def test_build_like_predicate_clickhouse_uses_backslash_escaping() -> None: + """ + clickhouse-connect's compiler raises on ``LIKE ... ESCAPE``; ClickHouse + treats backslash as the LIKE escape character natively, so wildcards are + escaped in the term itself and no ESCAPE clause is emitted. + """ + import sqlalchemy as sa + + pytest.importorskip("clickhouse_connect.cc_sqlalchemy.dialect") + from clickhouse_connect.cc_sqlalchemy.dialect import ClickHouseDialect + + from superset.models.helpers import build_like_predicate + + column = sa.column("c", sa.String()) + predicate = build_like_predicate(column, "50%_a\\B") + clickhouse_sql = str( + sa.select(column) + .where(predicate) + .compile(dialect=ClickHouseDialect(), compile_kwargs={"literal_binds": True}) + ) + assert "ESCAPE" not in clickhouse_sql + assert "= 1" not in clickhouse_sql + # LIKE-level ``\%``, ``\_`` and ``\\`` (each backslash doubled again by the + # dialect's string-literal rendering); the term is lower-cased. + assert "50\\\\%\\\\_a\\\\\\\\b" in clickhouse_sql + + def test_values_for_column_search(database: Database) -> None: """``search`` narrows the distinct-value query in the database.""" import pandas as pd
