from __future__ import annotations import sqlite3 from pathlib import Path from database.db_helper import Database, DatabaseSettings, SqliteSettings ADVANCED_MATERIAL_TABLES = { "advanced_material_imports", "advanced_material_validation_attempts", "advanced_materials", } ADVANCED_STYLE_SET_TABLES = { "advanced_style_sources", "advanced_style_consensus_runs", "advanced_style_validation_cases", } def _database(path: Path) -> Database: return Database( DatabaseSettings( backend="sqlite", sqlite=SqliteSettings(path=str(path)), ) ) def _table_names(path: Path) -> set[str]: with sqlite3.connect(path) as connection: rows = connection.execute( "SELECT name FROM sqlite_master WHERE type = 'table'" ).fetchall() return {str(row[0]) for row in rows} def test_0016_fresh_install_and_repeated_initialize_are_idempotent(tmp_path: Path) -> None: path = tmp_path / "advanced-material-fresh.sqlite3" database = _database(path) database.initialize() database.initialize() assert ADVANCED_MATERIAL_TABLES <= _table_names(path) with sqlite3.connect(path) as connection: applied = connection.execute( "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", ("0016_advanced_materials",), ).fetchone() assert applied == (1,) def test_0016_repairs_a_partially_missing_table_without_duplicate_schema_rows( tmp_path: Path, ) -> None: path = tmp_path / "advanced-material-repair.sqlite3" database = _database(path) database.initialize() with sqlite3.connect(path) as connection: connection.execute("PRAGMA foreign_keys = OFF") connection.execute("DROP TABLE advanced_materials") connection.commit() database.initialize() database.initialize() assert ADVANCED_MATERIAL_TABLES <= _table_names(path) with sqlite3.connect(path) as connection: applied = connection.execute( "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", ("0016_advanced_materials",), ).fetchone() assert applied == (1,) def test_0018_installs_advanced_style_set_tables_idempotently(tmp_path: Path) -> None: path = tmp_path / "advanced-style-set.sqlite3" database = _database(path) database.initialize() database.initialize() assert ADVANCED_STYLE_SET_TABLES <= _table_names(path) with sqlite3.connect(path) as connection: applied = connection.execute( "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", ("0018_advanced_style_sets",), ).fetchone() assert applied == (1,)