#!/usr/bin/env python3 """Простой раннер миграций SQLite.""" from __future__ import annotations import argparse import sqlite3 from datetime import datetime, timezone from pathlib import Path def open_database(path: Path, writable: bool) -> sqlite3.Connection: if writable: return sqlite3.connect(path) if not path.exists(): return sqlite3.connect(":memory:") return sqlite3.connect(path.as_uri() + "?mode=ro", uri=True) def applied_versions(connection: sqlite3.Connection) -> set[str]: try: rows = connection.execute("SELECT version FROM schema_migrations").fetchall() except sqlite3.OperationalError: return set() return {str(row[0]) for row in rows} def main() -> int: parser = argparse.ArgumentParser(description="Миграции SQLite") parser.add_argument("--db", type=Path, required=True, help="Файл базы") parser.add_argument("--dir", type=Path, required=True, help="Папка с файлами .sql") parser.add_argument("--apply", action="store_true", help="Выполнить миграции") args = parser.parse_args() database = args.db.expanduser().resolve() migrations_dir = args.dir.expanduser().resolve() if not migrations_dir.is_dir(): parser.error(f"Папка не найдена: {migrations_dir}") if not database.parent.is_dir(): parser.error(f"Папка базы не существует: {database.parent}") files = sorted(path for path in migrations_dir.glob("*.sql") if path.is_file()) if not files: parser.error("В папке нет файлов .sql") connection = open_database(database, args.apply) try: applied = applied_versions(connection) pending = [path for path in files if path.stem not in applied] print(f"Файлов: {len(files)}, применено: {len(applied & {path.stem for path in files})}, ожидает: {len(pending)}") for path in pending: print(f" ожидает: {path.name}") if not pending: print("Все миграции уже применены") return 0 if not args.apply: print("Это предпросмотр. Для выполнения добавьте --apply.") return 0 connection.execute( "CREATE TABLE IF NOT EXISTS schema_migrations (" "version TEXT PRIMARY KEY, applied_at TEXT NOT NULL)" ) connection.commit() for path in pending: sql = path.read_text(encoding="utf-8") if not sql.strip(): parser.error(f"Пустая миграция: {path.name}") print(f"Применяется: {path.name}") try: connection.executescript(sql) connection.execute( "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)", (path.stem, datetime.now(timezone.utc).isoformat(timespec="seconds")), ) connection.commit() except sqlite3.Error as error: connection.rollback() print(f"Ошибка в {path.name}: {error}") return 1 print(f"Применено миграций: {len(pending)}") return 0 finally: connection.close() if __name__ == "__main__": raise SystemExit(main())