#!/usr/bin/env python3 """Анализ и создание индексов SQLite.""" from __future__ import annotations import argparse import re import sqlite3 from pathlib import Path def quote(name: str) -> str: return '"' + name.replace('"', '""') + '"' def main() -> int: parser = argparse.ArgumentParser(description="Индексы SQLite") parser.add_argument("--db", type=Path, required=True, help="Файл базы") parser.add_argument("--table", required=True, help="Имя таблицы") parser.add_argument("--columns", default="", help="Колонки индекса через запятую") parser.add_argument("--name", default="", help="Имя нового индекса") parser.add_argument("--list", action="store_true", help="Показать существующие индексы") parser.add_argument("--apply", action="store_true", help="Создать индекс") parser.add_argument("--analyze", action="store_true", help="Выполнить ANALYZE после создания") args = parser.parse_args() source = args.db.expanduser().resolve() if not source.is_file(): parser.error(f"База не найдена: {source}") if args.apply: connection = sqlite3.connect(source) else: connection = sqlite3.connect(source.as_uri() + "?mode=ro", uri=True) try: exists = connection.execute( "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", (args.table,) ).fetchone()[0] if not exists: parser.error(f"Таблица не найдена: {args.table}") info = list(connection.execute(f"PRAGMA table_info({quote(args.table)})")) table_columns = [row[1] for row in info] indexes = list(connection.execute(f"PRAGMA index_list({quote(args.table)})")) if args.list: if not indexes: print("Индексов нет") return 0 for index in indexes: index_name = index[1] unique = "да" if index[2] else "нет" columns = [row[2] for row in connection.execute(f"PRAGMA index_info({quote(index_name)})")] print(f"{index_name}: уникальный={unique}, колонки={', '.join(columns)}") return 0 columns = [item.strip() for item in args.columns.split(",") if item.strip()] if not columns: parser.error("Укажите колонки через --columns или используйте --list") missing = [name for name in columns if name not in table_columns] if missing: parser.error("Нет колонок: " + ", ".join(missing)) for index in indexes: index_name = index[1] existing = tuple(row[2] for row in connection.execute(f"PRAGMA index_info({quote(index_name)})")) if existing == tuple(columns): print(f"Индекс уже существует: {index_name}") return 0 if args.name: index_name = args.name else: suffix = re.sub(r"[^A-Za-z0-9_]+", "_", "_".join(columns)).strip("_") index_name = f"idx_{args.table}_{suffix}" if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", index_name): parser.error("Имя индекса должно состоять из латиницы, цифр и подчёркиваний") sql = f"CREATE INDEX IF NOT EXISTS {quote(index_name)} ON {quote(args.table)} ({', '.join(quote(name) for name in columns)});" print(sql) if not args.apply: print("Это предпросмотр. Для создания индекса добавьте --apply.") return 0 connection.execute(sql) connection.commit() if args.analyze: connection.execute(f"ANALYZE {quote(args.table)};") connection.commit() print("ANALYZE выполнен") print(f"Индекс создан: {index_name}") return 0 except sqlite3.Error as error: parser.error(f"Ошибка SQLite: {error}") finally: connection.close() return 0 if __name__ == "__main__": raise SystemExit(main())