fix: undouble an executed literal before scanning, so a doubled-quote comment can't hide a rewrite

This commit is contained in:
mateo-berri 2026-08-24 12:39:19 -07:00
parent 4ddf1e5c6d
commit 422b24023c
2 changed files with 24 additions and 2 deletions

View file

@ -631,7 +631,10 @@ def scan_region(
) -> Iterator[Violation]:
"""Violations in one region of `document`, whose text begins at `offset`. Positions are
always counted against the whole document, so a statement nested in a dollar-quoted body
reports its real file line and lines up with the markers read from that file."""
reports its real file line and lines up with the markers read from that file. A single-quoted
literal that `DO` or `EXECUTE` runs as SQL is undoubled before it is scanned, so a `--` or `/*`
in one of its nested strings blanks nothing and the statement after it stays visible, and it is
padded back to its span so the offsets still land."""
masked, bodies, literals = mask(region)
executed = executed_names(masked)
runnable = executed_literals(masked, literals, executed)
@ -644,7 +647,13 @@ def scan_region(
commands_end = base + bind_values_start(clause)
for start, end in literals:
if base <= start and end <= commands_end:
yield from scan_region(document, region[start:end], migration, markers, offset + start)
yield from scan_region(
document,
undouble(region[start:end]).ljust(end - start),
migration,
markers,
offset + start,
)
keyword = offending_keyword(clause)
if keyword is None or exempt:

View file

@ -865,6 +865,19 @@ class TestDynamicSql:
sql = "DO $$\nBEGIN\n EXECUTE 'SELECT ''x''; UPDATE \"Foo\" SET \"a\" = 1';\nEND $$;"
assert _keywords(tmp_path, sql) == ("UPDATE",)
def test_a_comment_dash_inside_a_doubled_quote_does_not_hide_a_later_rewrite(self, tmp_path):
sql = "DO $$\nBEGIN\n EXECUTE 'SELECT ''--''; UPDATE \"Foo\" SET \"a\" = 1';\nEND $$;"
assert _keywords(tmp_path, sql) == ("UPDATE",)
assert _scan(tmp_path, sql)[0].line == 3
def test_a_block_comment_open_inside_a_doubled_quote_does_not_hide_a_later_rewrite(self, tmp_path):
sql = "DO $$\nBEGIN\n EXECUTE 'SELECT ''/*''; DELETE FROM \"Foo\"';\nEND $$;"
assert _keywords(tmp_path, sql) == ("DELETE",)
def test_a_rewrite_genuinely_commented_out_inside_executed_sql_is_not_run(self, tmp_path):
sql = "DO $$\nBEGIN\n EXECUTE 'SELECT 1 -- UPDATE \"Foo\" SET \"a\" = 1';\nEND $$;"
assert _keywords(tmp_path, sql) == ()
def test_a_rewrite_in_a_later_command_before_bind_values_is_flagged(self, tmp_path):
sql = "DO $$\nBEGIN\n EXECUTE 'SELECT 1; DELETE FROM \"Foo\" WHERE \"a\" = $1' USING 1;\nEND $$;"
assert _keywords(tmp_path, sql) == ("DELETE",)