Skip to content

fix(sqlalchemy-bigquery): escape backslashes in LIKE autoescape - #19191

Open
julianxu-goog wants to merge 2 commits into
mainfrom
fix/sqlalchemy-bigquery-like-reescape
Open

julianxu-goog wants to merge 2 commits into
mainfrom
fix/sqlalchemy-bigquery-like-reescape

Conversation

@julianxu-goog

Copy link
Copy Markdown

Escape pre-existing backslashes in BigQueryCompiler._maybe_reescape when converting SQLAlchemy's autoescape=True escape character to BigQuery's \ escape character, preventing LIKE wildcard sanitization bypasses and invalid escape errors.

Also copy binary.modifiers and clone binary.right before rewriting so repeated compilations do not mutate the original expression AST, and guard against non-string right operands.

  • Ensure the tests and linter pass (nox -s lint, unit-3.14, unit-3.11, cover at 100% branch coverage)
  • Code coverage does not decrease

Fixes internal issue b/581920781

…n LIKE autoescape

Escape pre-existing backslashes in BigQueryCompiler._maybe_reescape when converting SQLAlchemy's autoescape character to BigQuery's backslash escape, preventing wildcard sanitization bypasses and invalid escape errors.

Also copy binary.modifiers and clone binary.right before rewriting so repeated compilations do not mutate the original expression AST, and guard against non-string right operands.

Fixes internal issue b/581920781

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the _maybe_reescape method in sqlalchemy_bigquery/base.py to prevent in-place mutation of the original AST by copying modifiers and cloning the right-hand expression. It also adds a type check to ensure binary.right.value is a string before performing replacements, and corrects the backslash escaping logic. Comprehensive unit tests have been added to verify AST immutability, handling of non-string right-hand values, and idempotency of repeated compilations. I have no feedback to provide as there are no review comments and the changes look solid.

@julianxu-goog julianxu-goog assigned tswast and unassigned tswast Nov 24, 2026
@julianxu-goog
julianxu-goog requested a review from tswast November 24, 2026 02:02
@julianxu-goog
julianxu-goog marked this pull request as ready for review November 24, 2026 02:02
@julianxu-goog
julianxu-goog requested review from a team as code owners November 24, 2026 02:02
if (
escape
and escape != "\\"
and isinstance(getattr(binary.right, "value", None), str)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When the right side is not a plain string, this skips the rewrite, but escape is already popped above. So the ESCAPE is dropped without an error, and the caller's escaped wildcards become real wildcards. main raises AttributeError for these, so the PR turns a crash into the bypass it wants to close.

Compiled with f6d50d7 and c6ca4d3 (SQLAlchemy 2.1.9):

expression main this PR
c.contains(bindparam("q"), escape="/"), q = "50/%" AttributeError c LIKE '%' || :q || '%', q = '50/%'
c.startswith(func.replace(d, "%", "/%"), escape="/") AttributeError c LIKE replace(d, '%', '/%') || '%'
c.startswith(literal("50/%") + d, escape="/") AttributeError c LIKE '50/%' || d || '%'

50/% is meant to match the text 50%. Here it matches 50/ followed by anything.

As BigQuery has no ESCAPE, I would raise instead:

if escape and escape != "\\":
    value = getattr(binary.right, "value", None)
    if not isinstance(value, str):
        raise sqlalchemy.exc.CompileError(
            "BigQuery only supports a custom escape character for literal strings"
        )

With that the three cases above raise again and the other two tests in test_like_reescape.py pass. test_like_reescape_non_string_right would need to expect the error, it currently pins the dropped escape.

There is one case left on both branches: bindparam("q", "a/%") has a string default, so only the default is rewritten. A value given at execution ({"q": "50/%"}) goes out as it is.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch, thanks! Updated in 924d0e1 to raise CompileError when a non-\ escape character is used with anything other than a unique string BindParameter (which also closes the named bindparam("q", "a/%") execution-time override case).

…erands

Raise CompileError in BigQueryCompiler._maybe_reescape when a non-backslash escape character is used with a non-literal expression or a named (non-unique) BindParameter, instead of silently dropping the ESCAPE clause.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants