From d8780735c022cc304007c7734e4eeba2f101e2a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:42:07 +0000 Subject: [PATCH] fix(cold-store-reaper): rebuild turso dumps with repeated tables and vector indexes libsql's /dump of the atlas database emits the vector table vec_snowflake_m_v2_768_f32 twice, byte for byte, so the sqlite3 rebuild stopped on the second copy's first primary key. Its last statement also creates a libsql_vector_idx index, which stock sqlite3 cannot run. dedupe_dump.py drops a repeated table block only when its CREATE and every row match the first copy (sha256 and count), and fails the export when they differ. vector_index_dump.py records each libsql vector index statement in cold_store_libsql_vector_indexes instead of running it; the index data stays in its shadow tables. Refs #12000 Co-Authored-By: Claude Opus 5.5 --- pkgs/cold-store-reaper/scripts/dedupe_dump.py | 155 ++++++++++++++++++ .../cold-store-reaper/scripts/export-turso.sh | 23 ++- .../scripts/vector_index_dump.py | 80 +++++++++ .../tests/test_dedupe_dump.py | 135 +++++++++++++++ .../tests/test_export_turso.py | 56 +++++++ .../tests/test_vector_index_dump.py | 108 ++++++++++++ 6 files changed, 556 insertions(+), 1 deletion(-) create mode 100644 pkgs/cold-store-reaper/scripts/dedupe_dump.py create mode 100755 pkgs/cold-store-reaper/scripts/vector_index_dump.py create mode 100644 pkgs/cold-store-reaper/tests/test_dedupe_dump.py create mode 100644 pkgs/cold-store-reaper/tests/test_vector_index_dump.py diff --git a/pkgs/cold-store-reaper/scripts/dedupe_dump.py b/pkgs/cold-store-reaper/scripts/dedupe_dump.py new file mode 100644 index 0000000000..5df1cb5ba5 --- /dev/null +++ b/pkgs/cold-store-reaper/scripts/dedupe_dump.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Drop a table block that a libsql /dump repeats byte for byte (#12000). + +Reads a SQL dump on stdin and writes it to stdout. libsql's /dump can +emit a table twice: the atlas database's vector table +(``vec_snowflake_m_v2_768_f32``, which carries a ``libsql_vector_idx`` +index) came out as ``CREATE TABLE IF NOT EXISTS ...`` plus all of its +rows, then the same ``CREATE TABLE IF NOT EXISTS ...`` and every row +again, in the same order. The live table has no duplicate keys, so a +plain sqlite3 rebuild stops on the second copy's first primary key. + +The filter recognises a block as a ``CREATE TABLE [IF NOT EXISTS] `` +statement on one line followed by the ``INSERT INTO VALUES`` +lines right after it. For every table it keeps a running SHA-256 of +that first block's INSERT lines and their count. When a second +``CREATE TABLE`` for a table already seen arrives: + +* the CREATE statement must be byte-identical to the first one, and +* the INSERT lines that follow are consumed without being written, + and their hash and count must equal the first block's. + +When both hold, the repeat is dropped and one line on stderr says so +(table name and row count only, never row values). When either does +not hold, the filter exits 1 with a message: rows that differ are a +real conflict, and dropping them silently would lose data. Every other +line passes through byte-identical. + +Constant memory: one digest, one count and one CREATE line per table, +never the rows themselves. +""" + +import hashlib +import re +import sys + +CREATE = re.compile( + rb'^CREATE TABLE (?:IF NOT EXISTS )?("(?:[^"]|"")+"|\'(?:[^\']|\'\')+\'|[A-Za-z_][A-Za-z0-9_]*)' +) + + +def table_name(token): + """The bare table name of a CREATE TABLE name token.""" + if token[:1] in (b'"', b"'"): + quote = token[:1] + return token[1:-1].replace(quote + quote, quote) + return token + + +def insert_prefixes(name): + """The INSERT line prefixes a dump uses for this table.""" + quoted = b'"' + name.replace(b'"', b'""') + b'"' + prefixes = [b"INSERT INTO " + quoted + b" VALUES"] + if re.fullmatch(rb"[A-Za-z_][A-Za-z0-9_]*", name): + prefixes.append(b"INSERT INTO " + name + b" VALUES") + return tuple(prefixes) + + +class Block: + """One table's CREATE statement and the INSERT lines right after it.""" + + def __init__(self, name): + self.name = name + self.prefixes = insert_prefixes(name) + self.create = [] # the CREATE statement's lines (it may span several) + self.digest = hashlib.sha256() + self.count = 0 + + @property + def label(self): + return self.name.decode(errors="replace") + + def owns(self, line): + return line.startswith(self.prefixes) + + def add(self, line): + self.digest.update(line) + self.count += 1 + + def same_rows(self, other): + return (self.count, self.digest.digest()) == (other.count, other.digest.digest()) + + +def ends_statement(line): + return line.rstrip(b"\r\n \t").endswith(b";") + + +def fail(message): + sys.stderr.write(f"dedupe_dump: {message}\n") + sys.exit(1) + + +def finish_repeat(original, again): + if not original.same_rows(again): + fail( + f"table {original.label} is dumped twice with different rows " + f"({original.count} rows, then {again.count}); not dropping either copy" + ) + sys.stderr.write( + f"dedupe_dump: dropped a repeated copy of table {original.label} " + f"({again.count} rows identical to the first copy)\n" + ) + + +def main(): + out = sys.stdout.buffer + first = {} # table name -> its first Block + block = None # the Block whose CREATE or INSERT lines are being read + original = None # set while block is a repeat of this first Block + in_create = False + for line in sys.stdin.buffer: + if block is not None: + if in_create: + block.create.append(line) + in_create = not ends_statement(line) + if not in_create and original is not None and block.create != original.create: + fail( + f"table {block.label} is created twice with different " + "definitions; not dropping either copy" + ) + if original is None: + out.write(line) + continue + if block.owns(line): + block.add(line) + if original is None: + out.write(line) + continue + if original is not None: + finish_repeat(original, block) + block = original = None + match = CREATE.match(line) + if match: + name = table_name(match.group(1)) + block = Block(name) + block.create.append(line) + in_create = not ends_statement(line) + if name in first: + original = first[name] + if not in_create and block.create != original.create: + fail( + f"table {block.label} is created twice with different " + "definitions; not dropping either copy" + ) + continue # the repeated CREATE is dropped with its rows + first[name] = block + out.write(line) + if block is not None and original is not None: + if in_create: + fail(f"table {block.label}: the dump ends inside a repeated CREATE statement") + finish_repeat(original, block) + out.flush() + + +if __name__ == "__main__": + main() diff --git a/pkgs/cold-store-reaper/scripts/export-turso.sh b/pkgs/cold-store-reaper/scripts/export-turso.sh index a0c366a34b..6132d8ac68 100755 --- a/pkgs/cold-store-reaper/scripts/export-turso.sh +++ b/pkgs/cold-store-reaper/scripts/export-turso.sh @@ -13,6 +13,11 @@ # dump through scripts/repair_dump.py (libsql does not escape single # quotes inside the sqlite_schema INSERTs that register virtual # tables, so FTS5 databases are otherwise unparseable — #1391), +# scripts/dedupe_dump.py (libsql can dump a table twice; an exact +# repeat is dropped, a differing one fails the export — #12000) and +# scripts/vector_index_dump.py (stock sqlite3 cannot build a libsql +# vector index, so its CREATE INDEX is kept as a recorded statement; +# the index data stays in its shadow tables — #12000), # require the filtered dump to end in COMMIT; (a truncated dump # otherwise rebuilds into an integrity-clean but partial database), # stream it through @@ -251,7 +256,23 @@ PY # streams the dump (constant memory, one statement buffered) and # rewrites only verifiably mis-escaped schema literals with proper # '' doubling; everything else passes through byte-identical. - if ! python3 "${SCRIPT_DIR}/repair_dump.py" <"${dump_sql}" >"${filtered_sql}"; then + # + # Repeat pass (#12000): libsql's /dump can emit a table twice (the + # atlas vector table came out whole, then whole again, byte for + # byte), and the rebuild then stops on the second copy's first + # primary key. dedupe_dump.py drops a repeated copy only when its + # CREATE statement and every row match the first copy exactly, and + # fails (exit 1) when they differ, so no row is dropped silently. + # + # Vector index pass (#12000): a libsql vector index is dumped as + # CREATE INDEX ... (libsql_vector_idx(...)), which stock sqlite3 + # cannot run, so the rebuild died on the dump's last statement. + # vector_index_dump.py records that statement in the table + # cold_store_libsql_vector_indexes instead; the index's data is in + # its shadow tables, which are dumped and rebuilt as plain tables. + if ! python3 "${SCRIPT_DIR}/repair_dump.py" <"${dump_sql}" | + python3 "${SCRIPT_DIR}/dedupe_dump.py" | + python3 "${SCRIPT_DIR}/vector_index_dump.py" >"${filtered_sql}"; then echo "turso export: ERROR: ${name}: dump repair filter failed" >&2 return 1 fi diff --git a/pkgs/cold-store-reaper/scripts/vector_index_dump.py b/pkgs/cold-store-reaper/scripts/vector_index_dump.py new file mode 100755 index 0000000000..337913e151 --- /dev/null +++ b/pkgs/cold-store-reaper/scripts/vector_index_dump.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Keep a libsql vector index as a recorded statement (#12000). + +Reads a SQL dump on stdin and writes it to stdout. libsql's /dump ends +a database with a vector index on a statement such as:: + + CREATE INDEX vec_idx ON vec (libsql_vector_idx(v)); + +``libsql_vector_idx`` exists only in libsql, so the stock sqlite3 CLI +that rebuilds the export stops there ("no such function"), after every +row has loaded, and the whole export fails. The index's data is not +lost by skipping the statement: libsql keeps it in ordinary tables +(``_shadow`` and ``libsql_vector_meta_shadow``), and those are +dumped and rebuilt like any other table. + +So each such ``CREATE INDEX`` line is replaced by a row in a small +table, ``cold_store_libsql_vector_indexes(name, sql)``, holding the +statement exactly as libsql dumped it. Restoring into libsql: drop the +index's shadow table and its ``libsql_vector_meta_shadow`` row, then run +the recorded statement, and libsql rebuilds the index from the vectors. + +Only a single-line ``CREATE INDEX`` whose text calls +``libsql_vector_idx(`` is rewritten. One that does not end on its line +fails the filter (exit 1) rather than being guessed at. Every other +line passes through byte-identical, so a dump without a vector index +comes out unchanged. +""" + +import re +import sys + +TABLE = b"cold_store_libsql_vector_indexes" +VECTOR_INDEX = re.compile( + rb'^CREATE INDEX (?:IF NOT EXISTS )?("(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*) ON .*' + rb"\blibsql_vector_idx\s*\(", + re.IGNORECASE, +) + + +def literal(raw): + return b"'" + raw.replace(b"'", b"''") + b"'" + + +def index_name(token): + if token[:1] == b'"': + return token[1:-1].replace(b'""', b'"') + return token + + +def main(): + out = sys.stdout.buffer + created = False + for line in sys.stdin.buffer: + match = VECTOR_INDEX.match(line) + if not match: + out.write(line) + continue + statement = line.rstrip(b"\r\n") + if not statement.rstrip(b" \t").endswith(b");"): + sys.stderr.write( + "vector_index_dump: a libsql vector index statement does not end " + "on its line; not rewriting it\n" + ) + sys.exit(1) + name = index_name(match.group(1)) + if not created: + out.write( + b"CREATE TABLE IF NOT EXISTS " + TABLE + b"(name TEXT PRIMARY KEY, sql TEXT NOT NULL);\n" + ) + created = True + out.write(b"INSERT INTO " + TABLE + b" VALUES(" + literal(name) + b"," + literal(statement) + b");\n") + sys.stderr.write( + f"vector_index_dump: kept libsql vector index {name.decode(errors='replace')} " + f"as a recorded statement in {TABLE.decode()}\n" + ) + out.flush() + + +if __name__ == "__main__": + main() diff --git a/pkgs/cold-store-reaper/tests/test_dedupe_dump.py b/pkgs/cold-store-reaper/tests/test_dedupe_dump.py new file mode 100644 index 0000000000..66b5ed66bf --- /dev/null +++ b/pkgs/cold-store-reaper/tests/test_dedupe_dump.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Tests for scripts/dedupe_dump.py (#12000).""" + +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +FILTER = Path(__file__).resolve().parent.parent / "scripts" / "dedupe_dump.py" + +VEC_CREATE = ( + "CREATE TABLE IF NOT EXISTS vec (chunk_id INTEGER PRIMARY KEY, v BLOB NOT NULL);\n" +) +VEC_ROWS = "INSERT INTO vec VALUES(1,X'00');\nINSERT INTO vec VALUES(4,X'01');\n" + + +def run(text): + return subprocess.run( + [sys.executable, str(FILTER)], + input=text.encode(), + capture_output=True, + check=False, + ) + + +def rebuild(sql): + with tempfile.TemporaryDirectory() as tmp: + conn = sqlite3.connect(Path(tmp) / "out.db") + try: + conn.executescript(sql) + return conn.execute("SELECT chunk_id FROM vec ORDER BY chunk_id").fetchall() + finally: + conn.close() + + +class TestDedupeDump(unittest.TestCase): + def test_identical_repeated_table_is_dropped_and_rebuilds(self): + # The atlas shape: the whole vec table, then all of it again. + dump = ( + "BEGIN TRANSACTION;\n" + + VEC_CREATE + + VEC_ROWS + + VEC_CREATE + + VEC_ROWS + + "CREATE TABLE IF NOT EXISTS after (x);\n" + "INSERT INTO after VALUES(1);\n" + "COMMIT;\n" + ) + result = run(dump) + self.assertEqual(result.returncode, 0, result.stderr) + out = result.stdout.decode() + self.assertEqual(out.count("INSERT INTO vec"), 2) + self.assertEqual(out.count("CREATE TABLE IF NOT EXISTS vec"), 1) + self.assertIn("INSERT INTO after VALUES(1);", out) + self.assertTrue(out.endswith("COMMIT;\n")) + self.assertIn( + "dropped a repeated copy of table vec (2 rows identical to the first copy)", + result.stderr.decode(), + ) + self.assertNotIn("X'00'", result.stderr.decode()) + self.assertEqual(rebuild(out), [(1,), (4,)]) + + def test_repeat_with_a_different_row_fails_and_drops_nothing_silently(self): + dump = ( + VEC_CREATE + + VEC_ROWS + + VEC_CREATE + + "INSERT INTO vec VALUES(1,X'00');\nINSERT INTO vec VALUES(4,X'02');\n" + ) + result = run(dump) + self.assertEqual(result.returncode, 1) + self.assertIn("dumped twice with different rows", result.stderr.decode()) + + def test_repeat_with_fewer_rows_fails(self): + dump = VEC_CREATE + VEC_ROWS + VEC_CREATE + "INSERT INTO vec VALUES(1,X'00');\n" + result = run(dump) + self.assertEqual(result.returncode, 1) + self.assertIn("(2 rows, then 1)", result.stderr.decode()) + + def test_repeat_with_a_different_definition_fails(self): + dump = ( + VEC_CREATE + + VEC_ROWS + + "CREATE TABLE IF NOT EXISTS vec (chunk_id INTEGER PRIMARY KEY, v BLOB);\n" + + VEC_ROWS + ) + result = run(dump) + self.assertEqual(result.returncode, 1) + self.assertIn("created twice with different definitions", result.stderr.decode()) + + def test_multiline_create_is_matched_whole(self): + create = "CREATE TABLE IF NOT EXISTS s(\n id TEXT PRIMARY KEY);\n" + row = "INSERT INTO s VALUES('a');\n" + result = run(create + row + create + row + "COMMIT;\n") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.decode(), create + row + "COMMIT;\n") + + def test_quoted_table_names(self): + create = "CREATE TABLE IF NOT EXISTS 'chunks_fts_data'(id INTEGER PRIMARY KEY, block BLOB);\n" + row = "INSERT INTO \"chunks_fts_data\" VALUES(1,X'00');\n" + result = run(create + row + create + row) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.decode(), create + row) + + def test_dump_without_repeats_passes_byte_identical(self): + dump = ( + "PRAGMA foreign_keys=OFF;\n" + "BEGIN TRANSACTION;\n" + + VEC_CREATE + + VEC_ROWS + + "CREATE INDEX vec_idx ON vec (v);\n" + "PRAGMA writable_schema=ON;\n" + "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" + "VALUES('table','f','f',0,'CREATE VIRTUAL TABLE f USING fts5(x)');\n" + "PRAGMA writable_schema=OFF;\n" + "COMMIT;\n" + ) + result = run(dump) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.decode(), dump) + self.assertEqual(result.stderr, b"") + + def test_repeat_at_end_of_input_is_checked(self): + bad = VEC_CREATE + VEC_ROWS + VEC_CREATE + "INSERT INTO vec VALUES(9,X'00');\n" + self.assertEqual(run(bad).returncode, 1) + good = VEC_CREATE + VEC_ROWS + VEC_CREATE + VEC_ROWS + result = run(good) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.decode(), VEC_CREATE + VEC_ROWS) + + +if __name__ == "__main__": + unittest.main() diff --git a/pkgs/cold-store-reaper/tests/test_export_turso.py b/pkgs/cold-store-reaper/tests/test_export_turso.py index 4eb7012f26..1e281ac8a2 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -215,6 +215,62 @@ def test_rebuild_failure_names_the_repeated_statement(self): ) self.assertNotIn("X'00'", result.stderr.split("UNIQUE")[1]) + def test_table_dumped_twice_identically_is_filed_once(self): + # #12000: libsql's /dump emitted the atlas vec table whole, then + # whole again; the exact repeat is dropped and the export files. + block = ( + "CREATE TABLE IF NOT EXISTS vec (chunk_id INTEGER PRIMARY KEY, v BLOB);\n" + "INSERT INTO vec VALUES(1,X'00');\n" + "INSERT INTO vec VALUES(2,X'01');\n" + ) + body = self.capture.parent / "repeat.sql" + body.write_text("BEGIN TRANSACTION;\n" + block + block + "COMMIT;\n") + env = {**self.env, "STUB_DUMP_BODY_FILE": str(body)} + result = self.run_script(env=env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn( + "dropped a repeated copy of table vec (2 rows identical to the first copy)", + result.stderr, + ) + self.assertIn("put-backup", (self.capture / "cold-store.log").read_text()) + + def test_table_dumped_twice_with_different_rows_fails(self): + create = "CREATE TABLE IF NOT EXISTS vec (chunk_id INTEGER PRIMARY KEY, v BLOB);\n" + body = self.capture.parent / "conflict.sql" + body.write_text( + "BEGIN TRANSACTION;\n" + + create + + "INSERT INTO vec VALUES(1,X'00');\n" + + create + + "INSERT INTO vec VALUES(1,X'01');\n" + + "COMMIT;\n" + ) + env = {**self.env, "STUB_DUMP_BODY_FILE": str(body)} + result = self.run_script(env=env) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("dumped twice with different rows", result.stderr) + self.assertIn("db1: dump repair filter failed", result.stderr) + self.assertFalse((self.capture / "cold-store.log").exists()) + + def test_libsql_vector_index_is_recorded_and_the_export_files(self): + # #12000: stock sqlite3 has no libsql_vector_idx, so the dump's + # CREATE INDEX for a vector index killed the rebuild at the end. + body = self.capture.parent / "vector.sql" + body.write_text( + "BEGIN TRANSACTION;\n" + "CREATE TABLE IF NOT EXISTS vec (chunk_id INTEGER PRIMARY KEY, v F32_BLOB(1));\n" + "INSERT INTO vec VALUES(1,X'0000803f');\n" + "CREATE TABLE IF NOT EXISTS vec_idx_shadow (index_key INTEGER, data BLOB, PRIMARY KEY (index_key));\n" + "INSERT INTO vec_idx_shadow VALUES(1,X'00');\n" + "CREATE INDEX vec_idx ON vec (libsql_vector_idx(v));\n" + "COMMIT;\n" + ) + env = {**self.env, "STUB_DUMP_BODY_FILE": str(body)} + result = self.run_script(env=env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("kept libsql vector index vec_idx", result.stderr) + self.assertIn("put-backup", (self.capture / "cold-store.log").read_text()) + def test_retry_pass_delay_must_be_an_integer(self): env = {**self.env, "TURSO_DUMP_RETRY_PASS_DELAY_SECONDS": "soon"} result = self.run_script(env=env) diff --git a/pkgs/cold-store-reaper/tests/test_vector_index_dump.py b/pkgs/cold-store-reaper/tests/test_vector_index_dump.py new file mode 100644 index 0000000000..0bb84dc86e --- /dev/null +++ b/pkgs/cold-store-reaper/tests/test_vector_index_dump.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Tests for scripts/vector_index_dump.py (#12000).""" + +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +FILTER = Path(__file__).resolve().parent.parent / "scripts" / "vector_index_dump.py" + +INDEX = "CREATE INDEX vec_idx ON vec (libsql_vector_idx(v));" +# The atlas tail's shape: shadow tables are ordinary tables, the index +# statement comes last, inside the writable_schema block. +DUMP = ( + "PRAGMA foreign_keys=OFF;\n" + "BEGIN TRANSACTION;\n" + "CREATE TABLE IF NOT EXISTS vec (chunk_id INTEGER PRIMARY KEY, v F32_BLOB(2) NOT NULL);\n" + "INSERT INTO vec VALUES(1,X'0000803f00000040');\n" + "CREATE TABLE IF NOT EXISTS libsql_vector_meta_shadow ( name TEXT PRIMARY KEY, metadata BLOB ) WITHOUT ROWID;\n" + "INSERT INTO libsql_vector_meta_shadow VALUES('vec_idx',X'01');\n" + "CREATE TABLE IF NOT EXISTS vec_idx_shadow (index_key INTEGER , data BLOB, PRIMARY KEY (index_key));\n" + "INSERT INTO vec_idx_shadow VALUES(1,X'02');\n" + "PRAGMA writable_schema=ON;\n" + "CREATE INDEX vec_idx_shadow_idx ON vec_idx_shadow (index_key);\n" + + INDEX + + "\n" + "PRAGMA writable_schema=OFF;\n" + "COMMIT;\n" +) + + +def run(text): + return subprocess.run( + [sys.executable, str(FILTER)], input=text.encode(), capture_output=True, check=False + ) + + +class TestVectorIndexDump(unittest.TestCase): + def test_vector_index_is_recorded_and_the_dump_rebuilds(self): + result = run(DUMP) + self.assertEqual(result.returncode, 0, result.stderr) + out = result.stdout.decode() + self.assertNotIn("\n" + INDEX + "\n", out) + self.assertIn("kept libsql vector index vec_idx", result.stderr.decode()) + with tempfile.TemporaryDirectory() as tmp: + conn = sqlite3.connect(Path(tmp) / "out.db") + try: + conn.executescript(out) + self.assertEqual(conn.execute("PRAGMA integrity_check").fetchone(), ("ok",)) + self.assertEqual( + conn.execute("SELECT name, sql FROM cold_store_libsql_vector_indexes").fetchall(), + [("vec_idx", INDEX)], + ) + # The index data itself is kept in the shadow tables. + self.assertEqual(conn.execute("SELECT count(*) FROM vec_idx_shadow").fetchone(), (1,)) + self.assertEqual( + conn.execute("SELECT name FROM libsql_vector_meta_shadow").fetchall(), [("vec_idx",)] + ) + finally: + conn.close() + + def test_stock_sqlite_cannot_build_the_original(self): + # Guards the premise: without the filter the rebuild fails. + with tempfile.TemporaryDirectory() as tmp: + conn = sqlite3.connect(Path(tmp) / "out.db") + try: + with self.assertRaises(sqlite3.OperationalError): + conn.executescript(DUMP) + finally: + conn.close() + + def test_quotes_in_the_statement_are_escaped(self): + index = "CREATE INDEX \"it's\" ON vec (libsql_vector_idx(v, 'metric=cosine'));" + result = run(index + "\n") + self.assertEqual(result.returncode, 0, result.stderr) + conn = sqlite3.connect(":memory:") + try: + conn.executescript(result.stdout.decode()) + self.assertEqual( + conn.execute("SELECT name, sql FROM cold_store_libsql_vector_indexes").fetchall(), + [("it's", index)], + ) + finally: + conn.close() + + def test_two_vector_indexes_share_one_table(self): + a = "CREATE INDEX a ON vec (libsql_vector_idx(v));" + b = "CREATE INDEX b ON vec (libsql_vector_idx(v));" + result = run(a + "\n" + b + "\n") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.decode().count("CREATE TABLE"), 1) + + def test_dump_without_a_vector_index_passes_byte_identical(self): + dump = DUMP.replace(INDEX + "\n", "") + result = run(dump) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.decode(), dump) + self.assertEqual(result.stderr, b"") + + def test_unterminated_statement_fails(self): + result = run("CREATE INDEX vec_idx ON vec (libsql_vector_idx(v)\n);\n") + self.assertEqual(result.returncode, 1) + + +if __name__ == "__main__": + unittest.main()