Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 71 additions & 10 deletions pkgs/cold-store-reaper/scripts/repair_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,31 @@
statements whose SQL carries no quotes, pass through untouched.

The filter is line-oriented and constant-memory: it buffers only the
lines of one candidate statement (which ends at a line ending in
``');``). An unterminated statement at EOF is flushed unchanged —
lines of one candidate statement. A candidate ends at a line ending
in ``');`` only when that line really closes the statement (#6531):
either the buffered text already parses as a valid statement ending
exactly at that line, or (a mis-escaped literal, which cannot be
parsed) the next line begins a new top-level statement or the input
ends. A line ending in ``');`` inside the embedded SQL — a trigger
body's ``SELECT RAISE(ABORT, 'bad');`` — therefore does not split the
statement. An unterminated statement at EOF is flushed unchanged —
the caller's truncation guard judges the filtered stream.
"""

import re
import sys

SCHEMA_INSERT = b"INSERT INTO sqlite_schema("
STATEMENT_END = b"');"
QUOTE = 0x27 # '
COMMA = 0x2C # ,
SPACE = b" \t\r\n"
# A line that begins a new top-level dump statement (column 0).
TOP_LEVEL_START = re.compile(
rb"(?:INSERT|PRAGMA|COMMIT|BEGIN|CREATE|DELETE|UPDATE|DROP|ALTER|"
rb"REPLACE|ANALYZE|VACUUM|--)",
re.IGNORECASE,
)


def parse_literal(text, pos):
Expand Down Expand Up @@ -139,23 +152,71 @@ def repair_chunk(chunk):
return repair_statement(core) + newline


def ends_statement(chunk, next_line):
"""Whether the buffered chunk (last line ends in ``');``) is complete.

A valid literal closing exactly at the chunk end is definitive.
Otherwise the chunk may be a mis-escaped statement (unparseable by
design), so it ends only where a new top-level statement follows,
or at EOF (next_line is None).
"""
text = chunk.rstrip(b"\r\n").lstrip()
if text.startswith(SCHEMA_INSERT):
pos = _final_literal_start(text)
if pos is not None:
end = parse_literal(text, pos)
if end is not None and text[end:] == b");":
return True
if next_line is None:
return True
return bool(
next_line.lstrip().startswith(SCHEMA_INSERT)
or TOP_LEVEL_START.match(next_line)
)


def _final_literal_start(text):
"""Index of the opening quote of the final VALUES() literal, or None."""
vpos = text.find(b"VALUES(")
if vpos < 0:
return None
pos = vpos + len(b"VALUES(")
for _ in range(4):
pos = skip_value(text, pos)
if pos is None or pos >= len(text) or text[pos] != COMMA:
return None
pos += 1
while pos < len(text) and text[pos] in SPACE:
pos += 1
if pos >= len(text) or text[pos] != QUOTE:
return None
return pos


def main():
out = sys.stdout.buffer
buffered = None
for line in sys.stdin.buffer:
lines = iter(sys.stdin.buffer)
line = next(lines, None)
while line is not None:
next_line = next(lines, None)
if buffered is not None:
buffered.append(line)
if line.rstrip(b"\r\n").endswith(STATEMENT_END):
out.write(repair_chunk(b"".join(buffered)))
buffered = None
continue
if line.lstrip().startswith(SCHEMA_INSERT):
if line.rstrip(b"\r\n").endswith(STATEMENT_END):
chunk = b"".join(buffered)
if ends_statement(chunk, next_line):
out.write(repair_chunk(chunk))
buffered = None
elif line.lstrip().startswith(SCHEMA_INSERT):
if line.rstrip(b"\r\n").endswith(STATEMENT_END) and ends_statement(
line, next_line
):
out.write(repair_chunk(line))
else:
buffered = [line]
continue
out.write(line)
else:
out.write(line)
line = next_line
if buffered is not None:
out.write(b"".join(buffered))
out.flush()
Expand Down
49 changes: 49 additions & 0 deletions pkgs/cold-store-reaper/tests/test_export_turso.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,55 @@ def test_unterminated_statement_at_eof_flushes_unchanged(self):
data = b"BEGIN TRANSACTION;\n" + BROKEN_SCHEMA_INSERT[:-20]
self.assertEqual(self.run_filter(data), data)

def test_interior_line_ending_in_quote_paren_semicolon_is_not_a_boundary(self):
# #6531: a multi-line schema statement whose embedded SQL has an
# interior line ending in "');" (a trigger body's RAISE) is one
# statement, not a repaired fragment plus a raw tail. Oracle:
# the filtered stream loads in stock sqlite3 with the full SQL.
import sqlite3

sql = (
"CREATE TRIGGER tr AFTER INSERT ON ft BEGIN SELECT RAISE(ABORT, 'bad');\n"
" INSERT INTO log VALUES('x'); END"
)
raw = (
"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql) "
"VALUES('trigger','tr','ft',0,'" + sql + "');\n"
).encode()
escaped = raw.replace(b"'bad'", b"''bad''").replace(b"VALUES('x')", b"VALUES(''x'')")
for variant in (raw, escaped):
data = (
b"PRAGMA writable_schema=ON;\n"
+ variant
+ b"PRAGMA writable_schema=OFF;\n"
)
out = self.run_filter(data)
# Mis-escaped input is repaired (quotes doubled); escaped
# input passes through byte-identical.
self.assertEqual(out, data.replace(raw, escaped) if variant is raw else data)
db = sqlite3.connect(":memory:")
db.executescript(
"CREATE TABLE ft(x); CREATE TABLE log(v);"
"PRAGMA writable_schema=ON;"
"DELETE FROM sqlite_schema WHERE name='tr';"
)
db.executescript(out.decode())
self.assertEqual(
db.execute("SELECT sql FROM sqlite_schema WHERE name='tr'").fetchone()[0],
sql,
)
db.close()

def test_multiline_statement_followed_by_more_statements(self):
data = (
b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
b" VALUES('table','a','a',0,'CREATE TABLE a (x); -- ''c'');\n"
b"');\n"
b"INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
b" VALUES('table','t','t',0,'CREATE TABLE t (x INTEGER)');\n"
)
self.assertEqual(self.run_filter(data), data)


if __name__ == "__main__":
unittest.main()
Loading