bito-code-review[bot] commented on code in PR #44546:
URL: https://github.com/apache/superset/pull/44546#discussion_r4079348031
##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -115,25 +115,168 @@ def processor(mock_query_context):
return processor
-def test_query_cache_key_binds_annotation_data_to_requesting_user(processor):
- """The cache key for annotated queries must differ per requesting user."""
+def test_annotation_cache_key_binds_native_annotation_read_scope(processor):
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test type hints</b></div>
<div id="fix">
The new test functions
`test_annotation_cache_key_binds_native_annotation_read_scope` and its siblings
(lines 143, 167, 196, 215, 236, 255, 271) omit return type annotations. BITO.md
rule 12898 mandates complete type annotations on all test functions and
fixtures; add `-> None` and parameter types to match the project typing
standard.
</div>
</div>
<small><i>Code Review Run #b23663</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -115,25 +115,168 @@ def processor(mock_query_context):
return processor
-def test_query_cache_key_binds_annotation_data_to_requesting_user(processor):
- """The cache key for annotated queries must differ per requesting user."""
+def test_annotation_cache_key_binds_native_annotation_read_scope(processor):
+ """The annotation cache key for NATIVE layers must differ when the
+ requester's ``can_read`` (Annotation) access differs -- not who they
are."""
query_obj = MagicMock()
query_obj.annotation_layers = [{"sourceType": "NATIVE", "name": "a",
"value": 1}]
- with (
- patch(
- "superset.common.query_context_processor.get_user_id",
- side_effect=[1, 2],
- ),
- patch("superset.common.query_context_processor.security_manager"),
- ):
- processor.query_cache_key(query_obj)
- processor.query_cache_key(query_obj)
+ # ``security_manager`` autodetects as an async spec under a bare
+ # ``patch()`` (its real object trips ``unittest.mock``'s coroutine
+ # inference), which would silently turn every attribute access into an
+ # ``AsyncMock`` returning a fresh unawaited coroutine per call -- always
+ # unequal to itself and never equal to a configured return value. Forcing
+ # ``new_callable=MagicMock`` keeps these synchronous, as the real object
+ # is.
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access.side_effect = [True, False]
+ processor.annotation_cache_key(query_obj)
+ processor.annotation_cache_key(query_obj)
contexts = [
call.kwargs["annotation_context"] for call in
query_obj.cache_key.call_args_list
]
assert contexts[0] != contexts[1]
+def test_annotation_cache_key_shares_across_same_access_scope():
+ """Two distinct requesters (separate processor/query-object instances,
+ standing in for two different requests) with identical access scope must
+ produce identical annotation-context material. Reusing a single
+ processor/query_obj across both calls (as this test previously did)
+ would pass trivially regardless of whether the key is scope-based or
+ identity-based, since nothing about "who's asking" would ever vary."""
+ layer = {"sourceType": "NATIVE", "name": "a", "value": 1}
+ processor_a = QueryContextProcessor(MagicMock())
+ processor_b = QueryContextProcessor(MagicMock())
+ query_obj_a = MagicMock(annotation_layers=[layer])
+ query_obj_b = MagicMock(annotation_layers=[layer])
+
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access.return_value = True
+ context_a = processor_a._annotation_cache_context(query_obj_a)
+ context_b = processor_b._annotation_cache_context(query_obj_b)
+
+ assert context_a == context_b
+
+
+def test_query_cache_key_does_not_bind_annotation_scope(processor):
+ """The dataframe cache key must stay shared across viewers of the same
+ chart, even when the query has annotation layers — only the separate
+ annotation cache key (see above) carries access-scope material."""
+ query_obj = MagicMock()
+ query_obj.annotation_layers = [{"sourceType": "NATIVE", "name": "a",
"value": 1}]
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ):
+ processor.query_cache_key(query_obj)
+ processor.query_cache_key(query_obj)
+ for call in query_obj.cache_key.call_args_list:
+ assert "annotation_context" not in call.kwargs
+
+
[email protected]
+def mock_annotation_chart():
+ """A found chart, wired as the referenced chart for
+ ``_annotation_source_scope`` tests -- factors out the repeated
+ ``ChartDAO.find_by_id`` patch those tests all need."""
+ chart = MagicMock()
+ with patch(
+ "superset.common.query_context_processor.ChartDAO.find_by_id",
+ return_value=chart,
+ ):
+ yield chart
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Fixture missing return type</b></div>
<div id="fix">
The new `mock_annotation_chart` fixture is a generator (uses `yield`) but
declares no return type. BITO.md rules 12490/12898 explicitly require fixture
return types; annotate it `-> Iterator[MagicMock]` so the fixture contract is
explicit and static checkers can validate it.
</div>
</div>
<small><i>Code Review Run #b23663</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -2186,6 +2329,91 @@ def
test_get_df_payload_no_warning_when_not_memory_limited() -> None:
assert result["warning"] is None
+def
test_get_df_payload_result_decouples_annotation_cache_from_dataframe_cache():
+ """
+ The dataframe cache entry must stay shareable across viewers, and
+ annotation-layer data must be resolved through its own (per-user) cache
+ path -- not stored on the dataframe's cache entry -- so that two viewers
+ of the same annotated chart share one dataframe cache hit while each
+ still gets their own annotation-security-scoped payload.
+ """
+ from superset.common.query_object import QueryObject
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Inline function-body import</b></div>
<div id="fix">
`test_get_df_payload_result_decouples_annotation_cache_from_dataframe_cache`
imports `QueryObject` inline at line 2340.
`superset.common.query_context_processor` already imports it at module level
(query_context_processor.py:71), so no circular dependency exists. BITO.md rule
12745 requires module-level imports; hoist it to the top import block.
</div>
</div>
<small><i>Code Review Run #b23663</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/unit_tests/common/test_query_context_processor.py:
##########
@@ -115,25 +115,168 @@ def processor(mock_query_context):
return processor
-def test_query_cache_key_binds_annotation_data_to_requesting_user(processor):
- """The cache key for annotated queries must differ per requesting user."""
+def test_annotation_cache_key_binds_native_annotation_read_scope(processor):
+ """The annotation cache key for NATIVE layers must differ when the
+ requester's ``can_read`` (Annotation) access differs -- not who they
are."""
query_obj = MagicMock()
query_obj.annotation_layers = [{"sourceType": "NATIVE", "name": "a",
"value": 1}]
- with (
- patch(
- "superset.common.query_context_processor.get_user_id",
- side_effect=[1, 2],
- ),
- patch("superset.common.query_context_processor.security_manager"),
- ):
- processor.query_cache_key(query_obj)
- processor.query_cache_key(query_obj)
+ # ``security_manager`` autodetects as an async spec under a bare
+ # ``patch()`` (its real object trips ``unittest.mock``'s coroutine
+ # inference), which would silently turn every attribute access into an
+ # ``AsyncMock`` returning a fresh unawaited coroutine per call -- always
+ # unequal to itself and never equal to a configured return value. Forcing
+ # ``new_callable=MagicMock`` keeps these synchronous, as the real object
+ # is.
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access.side_effect = [True, False]
+ processor.annotation_cache_key(query_obj)
+ processor.annotation_cache_key(query_obj)
contexts = [
call.kwargs["annotation_context"] for call in
query_obj.cache_key.call_args_list
]
assert contexts[0] != contexts[1]
+def test_annotation_cache_key_shares_across_same_access_scope():
+ """Two distinct requesters (separate processor/query-object instances,
+ standing in for two different requests) with identical access scope must
+ produce identical annotation-context material. Reusing a single
+ processor/query_obj across both calls (as this test previously did)
+ would pass trivially regardless of whether the key is scope-based or
+ identity-based, since nothing about "who's asking" would ever vary."""
+ layer = {"sourceType": "NATIVE", "name": "a", "value": 1}
+ processor_a = QueryContextProcessor(MagicMock())
+ processor_b = QueryContextProcessor(MagicMock())
+ query_obj_a = MagicMock(annotation_layers=[layer])
+ query_obj_b = MagicMock(annotation_layers=[layer])
+
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access.return_value = True
+ context_a = processor_a._annotation_cache_context(query_obj_a)
+ context_b = processor_b._annotation_cache_context(query_obj_b)
+
+ assert context_a == context_b
+
+
+def test_query_cache_key_does_not_bind_annotation_scope(processor):
+ """The dataframe cache key must stay shared across viewers of the same
+ chart, even when the query has annotation layers — only the separate
+ annotation cache key (see above) carries access-scope material."""
+ query_obj = MagicMock()
+ query_obj.annotation_layers = [{"sourceType": "NATIVE", "name": "a",
"value": 1}]
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ):
+ processor.query_cache_key(query_obj)
+ processor.query_cache_key(query_obj)
+ for call in query_obj.cache_key.call_args_list:
+ assert "annotation_context" not in call.kwargs
+
+
[email protected]
+def mock_annotation_chart():
+ """A found chart, wired as the referenced chart for
+ ``_annotation_source_scope`` tests -- factors out the repeated
+ ``ChartDAO.find_by_id`` patch those tests all need."""
+ chart = MagicMock()
+ with patch(
+ "superset.common.query_context_processor.ChartDAO.find_by_id",
+ return_value=chart,
+ ):
+ yield chart
+
+
+def test_annotation_source_scope_binds_datasource_access(
+ processor, mock_annotation_chart
+):
+ """A chart-backed annotation layer's scope must differ when the
+ requester's access to the referenced datasource differs."""
+ mock_annotation_chart.get_query_context.return_value = None
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access_datasource.side_effect = [True, False]
+ security_manager.get_rls_cache_key.return_value = []
+ scope_a = processor._annotation_source_scope(1)
+ scope_b = processor._annotation_source_scope(1)
+ assert scope_a != scope_b
+ assert scope_a["access"] is True
+ assert scope_b["access"] is False
+
+
+def test_annotation_source_scope_reuses_referenced_chart_cache_key(
+ processor, mock_annotation_chart
+):
+ """When the referenced chart has a saved query context, its own cache
+ key(s) -- covering RLS and per-user Jinja/virtual-dataset material -- are
+ reused rather than re-derived."""
+ mock_query_object = MagicMock()
+ mock_query_context = MagicMock()
+ mock_query_context.queries = [mock_query_object]
+ mock_query_context.query_cache_key.return_value = "referenced-chart-key"
+ mock_annotation_chart.get_query_context.return_value = mock_query_context
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access_datasource.return_value = True
+ scope = processor._annotation_source_scope(1)
+ assert scope == {"access": True, "data_key": ["referenced-chart-key"]}
+
mock_query_context.query_cache_key.assert_called_once_with(mock_query_object)
+
+
+def test_annotation_source_scope_fails_closed_on_any_derivation_error(
+ processor, mock_annotation_chart
+):
+ """A lookup failure must fail closed rather than silently deduping onto a
+ successfully-derived scope -- and not just for SupersetException: the RLS
+ lookup is a real DB query and get_extra_cache_keys() renders Jinja for
+ virtual datasets, so a driver or template error is just as likely as a
+ SupersetException here, and must not 500 the whole chart-data request."""
+ mock_annotation_chart.get_query_context.side_effect = RuntimeError("db
boom")
+ with patch(
+ "superset.common.query_context_processor.security_manager",
+ new_callable=MagicMock,
+ ) as security_manager:
+ security_manager.can_access_datasource.return_value = True
+ security_manager.get_rls_cache_key.return_value = []
+ scope = processor._annotation_source_scope(1)
+ assert scope == {"access": False, "data_key": []}
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Fail-closed log unasserted</b></div>
<div id="fix">
`test_annotation_source_scope_fails_closed_on_any_derivation_error` asserts
only the returned scope; it never asserts the `logger.warning` that
`QueryContextProcessor._annotation_source_scope` emits on the fallback path
(query_context_processor.py:553-558). A regression that silently swallows the
error would still pass. Assert the warning to pin the fail-closed observability
contract.
</div>
</div>
<small><i>Code Review Run #b23663</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/testcontainers/db_engine_specs/test_bigquery.py:
##########
@@ -0,0 +1,148 @@
+# 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.
+"""
+Tests Superset's BigQuery string-literal escaping (superset/db_engine_specs/
+bigquery.py's ``_monkeypatch_bigquery_string_literal``) against a real
+GoogleSQL query engine, spun up on demand via testcontainers. Run via
+.github/workflows/testcontainers.yml.
+
+sc-120493-adjacent investigation: an apostrophe in a filter value used to
+break BigQuery queries (apache/superset#35857 / #38835, doubled single
+quotes -- BigQuery rejects ``'Armando''s'`` as two adjacent string literals
+needing whitespace between them). The current fix backslash-escapes instead.
+Reasoning about correctness from the ``sqlalchemy-bigquery`` dialect source
+and the BigQuery DBAPI's ``pyformat`` paramstyle handling is necessary but
+not sufficient; this locks in the actual compiled-and-executed behavior
+against a real engine instead.
+"""
+
+from collections.abc import Iterator
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy.engine import Engine
+
+pytestmark = pytest.mark.testcontainers
+
+from ._driver import require_driver # noqa: E402
+
+require_driver("testcontainers.community.google")
+
+from google.cloud import bigquery # noqa: E402
+from sqlalchemy_bigquery import BigQueryDialect # noqa: E402
+from testcontainers.community.google import BigQueryContainer # noqa: E402
+
+# Importing this triggers _monkeypatch_bigquery_string_literal(), exactly as
+# it runs in a real Superset process.
+import superset.db_engine_specs.bigquery # noqa: E402, F401
+
+DATASET = "ds"
+TABLE = "t"
+
+
[email protected](scope="module")
+def bq_client() -> Iterator[bigquery.Client]:
+ with BigQueryContainer() as container:
+ client = container.get_client()
+ client.create_dataset(f"{client.project}.{DATASET}")
+ client.query(f"CREATE TABLE {DATASET}.{TABLE} (name STRING)").result()
+ yield client
+
+
[email protected](scope="module")
+def engine(bq_client) -> Engine:
+ # user_supplied_client=true is a URL query param, not just a connect_args
+ # key: parse_url() only sets BigQueryDialect.create_connect_args() to
+ # accept the connect_args={"client": ...} override when it's present,
+ # otherwise it tries to build a client from real GCP credentials.
+ return sa.create_engine(
+ "bigquery://?user_supplied_client=true", connect_args={"client":
bq_client}
+ )
+
+
+def _compiled_literal(expr: sa.ColumnElement) -> str:
+ """Render ``expr`` exactly as Superset's actual code path does: compiled
+ with ``literal_binds=True``, then executed as a plain string with no
+ separate bind parameters (superset.db_engine_specs.base.BaseEngineSpec
+ .execute() calls ``cursor.execute(query)``, nothing else)."""
+ return str(
+ expr.compile(dialect=BigQueryDialect(),
compile_kwargs={"literal_binds": True})
+ )
+
+
+def _insert_and_find(engine: Engine, value: str) -> list[str]:
+ t = sa.table(TABLE, sa.column("name"))
+ with engine.connect() as conn:
+ conn.execute(sa.text(f"DELETE FROM {DATASET}.{TABLE} WHERE TRUE")) #
noqa: S608
+ insert_literal = _compiled_literal(sa.literal(value))
+ conn.execute(
+ sa.text(
+ f"INSERT INTO {DATASET}.{TABLE} (name) VALUES
({insert_literal})" # noqa: S608
+ )
+ )
+ where = _compiled_literal(t.c.name == value)
+ rows = conn.execute(
+ sa.text(f"SELECT name FROM {DATASET}.{TABLE} WHERE {where}") #
noqa: S608
+ ).fetchall()
+ return [row[0] for row in rows]
+
+
+def test_apostrophe_value_round_trips(engine: Engine) -> None:
+ """Regression test for apache/superset#35857: an apostrophe in a filter
+ value must not corrupt the compiled query or fail to match."""
+ assert _insert_and_find(engine, "O'Brien") == ["O'Brien"]
+
+
+def test_percent_sign_value_round_trips(engine: Engine) -> None:
+ """
+ A literal percent sign must survive Superset's actual execution path
+ unchanged. Superset's literal_processor does not double it (unlike the
+ upstream sqlalchemy-bigquery function it replaces), which is correct
+ specifically because Superset always executes via cursor.execute(query)
+ with no separate `parameters` -- the BigQuery DBAPI's own pyformat
+ handling only applies `%%` -> `%` de-escaping in that case
+ (google.cloud.bigquery.dbapi.cursor._format_operation), so a lone `%`
+ passes through untouched either way. A doubled `%%` would also survive
+ (de-escaped back to one `%`), so this test would not by itself catch a
+ regression toward doubling -- it exists to pin the actually-shipped
+ behavior, not to distinguish the two.
+ """
+ assert _insert_and_find(engine, "100% sure") == ["100% sure"]
+
+
+def test_combined_percent_and_apostrophe_round_trips(engine: Engine) -> None:
+ assert _insert_and_find(engine, "50% off for O'Brien") == ["50% off for
O'Brien"]
+
+
+def test_doubled_single_quotes_are_rejected_by_bigquery(bq_client) -> None:
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing fixture param type hint</b></div>
<div id="fix">
`bq_client` here is the module's `bq_client` fixture (yields
`bigquery.Client`, line 58), but the parameter is unannotated, while the
sibling tests annotate `engine: Engine`. BITO adaptive rule 11810 requires
fixture-injected parameters to be typed; annotate as `bigquery.Client` for
consistency and mypy/IDE support.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
def test_doubled_single_quotes_are_rejected_by_bigquery(
bq_client: bigquery.Client,
) -> None:
````
</div>
</details>
</div>
<small><i>Code Review Run #b23663</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/testcontainers/db_engine_specs/test_bigquery.py:
##########
@@ -0,0 +1,148 @@
+# 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.
+"""
+Tests Superset's BigQuery string-literal escaping (superset/db_engine_specs/
+bigquery.py's ``_monkeypatch_bigquery_string_literal``) against a real
+GoogleSQL query engine, spun up on demand via testcontainers. Run via
+.github/workflows/testcontainers.yml.
+
+sc-120493-adjacent investigation: an apostrophe in a filter value used to
+break BigQuery queries (apache/superset#35857 / #38835, doubled single
+quotes -- BigQuery rejects ``'Armando''s'`` as two adjacent string literals
+needing whitespace between them). The current fix backslash-escapes instead.
+Reasoning about correctness from the ``sqlalchemy-bigquery`` dialect source
+and the BigQuery DBAPI's ``pyformat`` paramstyle handling is necessary but
+not sufficient; this locks in the actual compiled-and-executed behavior
+against a real engine instead.
+"""
+
+from collections.abc import Iterator
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy.engine import Engine
+
+pytestmark = pytest.mark.testcontainers
+
+from ._driver import require_driver # noqa: E402
+
+require_driver("testcontainers.community.google")
+
+from google.cloud import bigquery # noqa: E402
+from sqlalchemy_bigquery import BigQueryDialect # noqa: E402
+from testcontainers.community.google import BigQueryContainer # noqa: E402
+
+# Importing this triggers _monkeypatch_bigquery_string_literal(), exactly as
+# it runs in a real Superset process.
+import superset.db_engine_specs.bigquery # noqa: E402, F401
+
+DATASET = "ds"
+TABLE = "t"
+
+
[email protected](scope="module")
+def bq_client() -> Iterator[bigquery.Client]:
+ with BigQueryContainer() as container:
+ client = container.get_client()
+ client.create_dataset(f"{client.project}.{DATASET}")
+ client.query(f"CREATE TABLE {DATASET}.{TABLE} (name STRING)").result()
+ yield client
+
+
[email protected](scope="module")
+def engine(bq_client) -> Engine:
+ # user_supplied_client=true is a URL query param, not just a connect_args
+ # key: parse_url() only sets BigQueryDialect.create_connect_args() to
+ # accept the connect_args={"client": ...} override when it's present,
+ # otherwise it tries to build a client from real GCP credentials.
+ return sa.create_engine(
+ "bigquery://?user_supplied_client=true", connect_args={"client":
bq_client}
+ )
+
+
+def _compiled_literal(expr: sa.ColumnElement) -> str:
+ """Render ``expr`` exactly as Superset's actual code path does: compiled
+ with ``literal_binds=True``, then executed as a plain string with no
+ separate bind parameters (superset.db_engine_specs.base.BaseEngineSpec
+ .execute() calls ``cursor.execute(query)``, nothing else)."""
+ return str(
+ expr.compile(dialect=BigQueryDialect(),
compile_kwargs={"literal_binds": True})
+ )
+
+
+def _insert_and_find(engine: Engine, value: str) -> list[str]:
+ t = sa.table(TABLE, sa.column("name"))
+ with engine.connect() as conn:
+ conn.execute(sa.text(f"DELETE FROM {DATASET}.{TABLE} WHERE TRUE")) #
noqa: S608
+ insert_literal = _compiled_literal(sa.literal(value))
+ conn.execute(
+ sa.text(
+ f"INSERT INTO {DATASET}.{TABLE} (name) VALUES
({insert_literal})" # noqa: S608
+ )
+ )
+ where = _compiled_literal(t.c.name == value)
+ rows = conn.execute(
+ sa.text(f"SELECT name FROM {DATASET}.{TABLE} WHERE {where}") #
noqa: S608
+ ).fetchall()
+ return [row[0] for row in rows]
+
+
+def test_apostrophe_value_round_trips(engine: Engine) -> None:
+ """Regression test for apache/superset#35857: an apostrophe in a filter
+ value must not corrupt the compiled query or fail to match."""
+ assert _insert_and_find(engine, "O'Brien") == ["O'Brien"]
+
+
+def test_percent_sign_value_round_trips(engine: Engine) -> None:
+ """
+ A literal percent sign must survive Superset's actual execution path
+ unchanged. Superset's literal_processor does not double it (unlike the
+ upstream sqlalchemy-bigquery function it replaces), which is correct
+ specifically because Superset always executes via cursor.execute(query)
+ with no separate `parameters` -- the BigQuery DBAPI's own pyformat
+ handling only applies `%%` -> `%` de-escaping in that case
+ (google.cloud.bigquery.dbapi.cursor._format_operation), so a lone `%`
+ passes through untouched either way. A doubled `%%` would also survive
+ (de-escaped back to one `%`), so this test would not by itself catch a
+ regression toward doubling -- it exists to pin the actually-shipped
+ behavior, not to distinguish the two.
+ """
+ assert _insert_and_find(engine, "100% sure") == ["100% sure"]
+
+
+def test_combined_percent_and_apostrophe_round_trips(engine: Engine) -> None:
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test docstring</b></div>
<div id="fix">
This new test is the only one of the four without a docstring; BITO adaptive
rule 12147 requires docstrings on all new test functions. A one-liner stating
the scenario (a value combining `%` and `'`) keeps the suite's
self-documentation consistent with its siblings.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
def test_combined_percent_and_apostrophe_round_trips(engine: Engine) -> None:
"""Round-trips a value containing both a percent sign and an
apostrophe."""
````
</div>
</details>
</div>
<small><i>Code Review Run #b23663</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]