Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix: count migration lines against the whole file, scan EXECUTE'd sql, allow bounded inserts

mateo-berri7e6d303e382b
diff --git a/tests/code_coverage_tests/check_migrations_no_data_rewrites.py b/tests/code_coverage_tests/check_migrations_no_data_rewrites.py
index 61845ac521f..8ebdc43fac2 100644
--- a/tests/code_coverage_tests/check_migrations_no_data_rewrites.py
+++ b/tests/code_coverage_tests/check_migrations_no_data_rewrites.py
@@ -12,7 +12,8 @@ Flagged, per statement, by its leading keyword:
DELETE same scan, and the dead tuples outlive the migration
MERGE both of the above in one statement
INSERT only when it draws rows from a `SELECT`; `INSERT ... VALUES` is bounded
- by the literal row list and passes
+ by the literal row list and passes, scalar subqueries in that list
+ included
WITH a CTE-led statement containing any of the above
Referential actions (`ON DELETE CASCADE`, `ON UPDATE CASCADE`) are schema, never a
@@ -20,7 +21,12 @@ statement's leading keyword, so they pass.
Statements inside dollar-quoted bodies are scanned too. `DO $$ ... $$` is this
repo's idiom for conditional DDL, so a body is where an `UPDATE` would otherwise
-hide.
+hide. The SQL an `EXECUTE` runs is scanned the same way, since a rewrite reads the
+same to Postgres whether it is spelled out or handed over as a string.
+
+Line numbers always count against the whole migration file, however deeply the
+statement is nested, so a reported line points at the statement and the markers
+below line up with the statements they exempt.
Add a column and let the application populate it, or run the rewrite as an opt-in
batched job outside boot. When a rewrite is genuinely bounded and must ship inside
@@ -112,10 +118,12 @@ def blank(text: str) -> str:
return "".join(character if character == "\n" else " " for character in text)
-def mask(sql: str) -> tuple[str, tuple[tuple[int, int], ...]]:
- """Blank comments and quoted text, keeping offsets, and locate dollar-quoted bodies."""
+def mask(sql: str) -> tuple[str, tuple[tuple[int, int], ...], tuple[tuple[int, int], ...]]:
+ """Blank comments and quoted text, keeping offsets, and locate the spans that can still
+ hold SQL: dollar-quoted bodies, and the single-quoted literals `EXECUTE` runs."""
chunks: list[str] = []
bodies: list[tuple[int, int]] = []
+ literals: list[tuple[int, int]] = []
index = 0
length = len(sql)
@@ -139,6 +147,9 @@ def mask(sql: str) -> tuple[str, tuple[tuple[int, int], ...]]:
if character in "'\"":
stop = skip_quoted(sql, index, character)
+ if character == "'":
+ closed = sql[stop - 1 : stop] == character
+ literals.append((index + 1, max(index + 1, stop - 1 if closed else stop)))
chunks.append(blank(sql[index:stop]))
index = stop
continue
@@ -157,7 +168,7 @@ def mask(sql: str) -> tuple[str, tuple[tuple[int, int], ...]]:
chunks.append(character)
index += 1
- return "".join(chunks), tuple(bodies)
+ return "".join(chunks), tuple(bodies), tuple(literals)
def skip_block_comment(sql: str, start: int) -> int:
@@ -224,18 +235,31 @@ def offending_keyword(statement: str) -> str | None:
return keyword
if keyword == "INSERT":
- return "INSERT ... SELECT" if contains(statement, "SELECT") else None
+ return "INSERT ... SELECT" if draws_rows_from_a_select(statement) else None
if keyword == "WITH":
nested = next((name for name in sorted(REWRITES_ROWS) if contains(statement, name)), None)
if nested is not None:
return f"WITH ... {nested}"
- if contains(statement, "INSERT") and contains(statement, "SELECT"):
+ if contains(statement, "INSERT") and draws_rows_from_a_select(statement):
return "WITH ... INSERT ... SELECT"
return None
+def draws_rows_from_a_select(statement: str) -> bool:
+ """Whether an `INSERT` takes its rows from a query rather than a literal list. A
+ top-level `VALUES` bounds the insert to the rows written out there, so the scalar
+ subqueries and helper CTEs that sit in parentheses around it do not make it a
+ rewrite."""
+ return contains(statement, "SELECT") and not contains(strip_parens(statement), "VALUES")
+
+
+def leads_with(statement: str, keyword: str) -> bool:
+ word = leading_keyword(strip_parens(statement))
+ return word is not None and word.group().upper() == keyword
+
+
def contains(statement: str, keyword: str) -> bool:
return re.search(rf"\b{keyword}\b", statement, re.IGNORECASE) is not None
@@ -244,21 +268,35 @@ def exempt_lines(sql: str) -> frozenset[int]:
return frozenset(sql.count("\n", 0, match.start()) + 1 for match in MARKER.finditer(sql))
-def scan(sql: str, migration: str, exempt: frozenset[int], offset: int = 0) -> Iterator[Violation]:
- masked, bodies = mask(sql)
+def scan(sql: str, migration: str, exempt: frozenset[int]) -> Iterator[Violation]:
+ yield from scan_region(sql, sql, migration, exempt, 0)
+
+
+def scan_region(
+ document: str, region: str, migration: str, exempt: frozenset[int], offset: int
+) -> Iterator[Violation]:
+ """Violations in one region of `document`, whose text begins at `offset`. Lines 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."""
+ masked, bodies, literals = mask(region)
for match in STATEMENT.finditer(masked):
+ if leads_with(match.group(), "EXECUTE"):
+ for start, end in literals:
+ if match.start() <= start and end <= match.end():
+ yield from scan_region(document, region[start:end], migration, exempt, offset + start)
+ continue
keyword = offending_keyword(match.group())
if keyword is None:
continue
- first = line_of(sql, offset + keyword_start(match))
- last = line_of(sql, offset + match.end())
+ first = line_of(document, offset + keyword_start(match))
+ last = line_of(document, offset + match.end())
if any(line in exempt for line in range(first - 1, last + 1)):
continue
yield Violation(migration, first, keyword)
for start, end in bodies:
- yield from scan(sql[start:end], migration, exempt, offset + start)
+ yield from scan_region(document, region[start:end], migration, exempt, offset + start)
def keyword_start(statement: re.Match[str]) -> int:
diff --git a/tests/test_litellm/test_check_migrations_no_data_rewrites.py b/tests/test_litellm/test_check_migrations_no_data_rewrites.py
index a4841f7a699..9c6871cf557 100644
--- a/tests/test_litellm/test_check_migrations_no_data_rewrites.py
+++ b/tests/test_litellm/test_check_migrations_no_data_rewrites.py
@@ -97,6 +97,22 @@ class TestInsert:
def test_insert_select_scans_and_is_flagged(self, tmp_path):
assert _keywords(tmp_path, 'INSERT INTO "Foo" ("id") SELECT "id" FROM "Bar";') == ("INSERT ... SELECT",)
+ def test_insert_values_with_a_scalar_subquery_passes(self, tmp_path):
+ sql = 'INSERT INTO "Config" ("k", "v") VALUES (\'rev\', (SELECT max("id")::text FROM "Bar"));'
+ assert _keywords(tmp_path, sql) == ()
+
+ def test_insert_values_with_a_scalar_subquery_per_row_passes(self, tmp_path):
+ sql = (
+ 'INSERT INTO "Config" ("k", "v") VALUES\n'
+ " ('a', (SELECT \"id\" FROM \"Bar\" WHERE \"n\" = 'a')),\n"
+ " ('b', (SELECT \"id\" FROM \"Bar\" WHERE \"n\" = 'b'));"
+ )
+ assert _keywords(tmp_path, sql) == ()
+
+ def test_values_inside_a_subquery_does_not_bound_an_insert_select(self, tmp_path):
+ sql = 'INSERT INTO "Foo" ("id") SELECT "id" FROM (VALUES (1), (2)) AS "v"("id");'
+ assert _keywords(tmp_path, sql) == ("INSERT ... SELECT",)
+
class TestCommonTableExpressions:
def test_cte_led_update_is_flagged(self, tmp_path):
@@ -115,6 +131,10 @@ class TestCommonTableExpressions:
sql = 'WITH batch AS (SELECT "id" FROM "Foo") SELECT count(*) FROM batch;'
assert _keywords(tmp_path, sql) == ()
+ def test_cte_led_insert_values_is_bounded_and_passes(self, tmp_path):
+ sql = 'WITH latest AS (SELECT max("id") AS "id" FROM "Bar")\nINSERT INTO "Config" ("k", "v") VALUES (\'rev\', (SELECT "id"::text FROM latest));'
+ assert _keywords(tmp_path, sql) == ()
+
class TestDollarQuotedBlocks:
def test_update_inside_do_block_is_flagged(self, tmp_path):
@@ -166,6 +186,32 @@ class TestDollarQuotedBlocks:
sql = 'DO $$ BEGIN PERFORM 1; END $$;\nALTER TABLE "Foo" ADD COLUMN "b" TEXT;'
assert _keywords(tmp_path, sql) == ()
+ def test_line_number_inside_a_do_block_counts_from_the_top_of_the_file(self, tmp_path):
+ sql = (
+ "-- AlterTable\n"
+ 'ALTER TABLE "Foo" ADD COLUMN "b" INT;\n'
+ "\n"
+ "DO $$\n"
+ "BEGIN\n"
+ ' UPDATE "Foo" SET "b" = 1;\n'
+ "END $$;"
+ )
+ assert _scan(tmp_path, sql)[0].line == 6
+
+ def test_line_number_inside_a_nested_body_counts_from_the_top_of_the_file(self, tmp_path):
+ sql = (
+ "-- CreateIndex\n"
+ 'CREATE INDEX "i" ON "Foo"("a");\n'
+ "\n"
+ "DO $outer$\n"
+ "BEGIN\n"
+ " EXECUTE $inner$\n"
+ ' UPDATE "Foo" SET "a" = 1\n'
+ " $inner$;\n"
+ "END $outer$;"
+ )
+ assert _scan(tmp_path, sql)[0].line == 7
+
class TestQuotingAndComments:
def test_update_inside_string_literal_passes(self, tmp_path):
@@ -226,6 +272,68 @@ class TestEscapeHatch:
sql = 'UPDATE "Foo" SET "a" = 1;\n-- data-migration-ok: bounded\nALTER TABLE "Bar" ADD COLUMN "b" TEXT;'
assert _keywords(tmp_path, sql) == ("UPDATE",)
+ def test_marker_inside_a_do_block_below_the_first_line_exempts(self, tmp_path):
+ sql = (
+ "-- AlterTable\n"
+ 'ALTER TABLE "Foo" ADD COLUMN "b" INT;\n'
+ "\n"
+ "DO $$\n"
+ "BEGIN\n"
+ " -- data-migration-ok: one config row\n"
+ ' UPDATE "Foo" SET "b" = 1;\n'
+ "END $$;"
+ )
+ assert _keywords(tmp_path, sql) == ()
+
+ def test_marker_above_a_do_block_does_not_exempt_a_rewrite_inside_it(self, tmp_path):
+ sql = (
+ "-- data-migration-ok: bounded, this belongs to the insert below\n"
+ "INSERT INTO \"Config\" (\"k\") VALUES ('x');\n"
+ "\n"
+ 'DO $$ BEGIN UPDATE "Foo" SET "b" = 1; END $$;'
+ )
+ assert _keywords(tmp_path, sql) == ("UPDATE",)
+ assert _scan(tmp_path, sql)[0].line == 4
+
+
+class TestDynamicSql:
+ def test_execute_of_a_quoted_update_is_flagged(self, tmp_path):
+ sql = "DO $$\nBEGIN\n EXECUTE 'UPDATE \"Foo\" SET \"a\" = 1';\nEND $$;"
+ assert _keywords(tmp_path, sql) == ("UPDATE",)
+ assert _scan(tmp_path, sql)[0].line == 3
+
+ def test_execute_of_a_quoted_delete_is_flagged(self, tmp_path):
+ sql = "DO $$\nBEGIN\n EXECUTE 'DELETE FROM \"Foo\"';\nEND $$;"
+ assert _keywords(tmp_path, sql) == ("DELETE",)
+
+ def test_execute_of_a_formatted_update_is_flagged(self, tmp_path):
+ sql = "DO $$\nBEGIN\n EXECUTE format('UPDATE %I SET \"a\" = 1', 'Foo');\nEND $$;"
+ assert _keywords(tmp_path, sql) == ("UPDATE",)
+
+ def test_execute_of_a_dollar_quoted_update_is_flagged(self, tmp_path):
+ sql = 'DO $outer$\nBEGIN\n EXECUTE $q$UPDATE "Foo" SET "a" = 1$q$;\nEND $outer$;'
+ assert _keywords(tmp_path, sql) == ("UPDATE",)
+
+ def test_a_doubled_quote_inside_executed_sql_does_not_hide_the_rewrite(self, tmp_path):
+ sql = "DO $$\nBEGIN\n EXECUTE 'UPDATE \"Foo\" SET \"a\" = date_trunc(''day'', \"t\")';\nEND $$;"
+ assert _keywords(tmp_path, sql) == ("UPDATE",)
+
+ def test_execute_of_ddl_passes(self, tmp_path):
+ sql = "DO $$\nBEGIN\n EXECUTE 'ALTER TABLE \"Foo\" ADD COLUMN \"b\" TEXT';\nEND $$;"
+ assert _keywords(tmp_path, sql) == ()
+
+ def test_execute_of_a_read_only_query_passes(self, tmp_path):
+ sql = "DO $$\nBEGIN\n EXECUTE 'SELECT 1';\nEND $$;"
+ assert _keywords(tmp_path, sql) == ()
+
+ def test_a_marker_exempts_an_executed_rewrite(self, tmp_path):
+ sql = "DO $$\nBEGIN\n -- data-migration-ok: one row\n EXECUTE 'UPDATE \"Foo\" SET \"a\" = 1';\nEND $$;"
+ assert _keywords(tmp_path, sql) == ()
+
+ def test_a_literal_that_is_not_executed_is_still_inert(self, tmp_path):
+ sql = "INSERT INTO \"Foo\" (\"note\") VALUES ('UPDATE \"Bar\" SET \"a\" = 1');"
+ assert _keywords(tmp_path, sql) == ()
+
class TestReporting:
def test_line_number_points_at_the_statement_keyword(self, tmp_path):