#!/usr/bin/env python3 """Выполнение SQL-запроса к SQLite с безопасным выводом.""" from __future__ import annotations import argparse import csv import json import sqlite3 from pathlib import Path def render_table(columns: list[str], rows: list[tuple]) -> str: widths = [len(column) for column in columns] for row in rows: for index, value in enumerate(row): widths[index] = max(widths[index], len("" if value is None else str(value))) line = " | ".join(column.ljust(widths[index]) for index, column in enumerate(columns)) separator = "-+-".join("-" * width for width in widths) output = [line, separator] for row in rows: output.append(" | ".join(("" if value is None else str(value)).ljust(widths[index]) for index, value in enumerate(row))) return "\n".join(output) def main() -> int: parser = argparse.ArgumentParser(description="SQL-запрос к SQLite") parser.add_argument("--db", type=Path, required=True, help="Файл базы") parser.add_argument("--sql", default="", help="SQL-запрос") parser.add_argument("--file", type=Path, help="Файл с SQL") parser.add_argument("--output", type=Path, help="Файл результата для csv или json") parser.add_argument("--format", choices=["table", "csv", "json"], default="table", help="Формат вывода") parser.add_argument("--allow-write", action="store_true", help="Разрешить изменение базы") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() source = args.db.expanduser().resolve() if not source.is_file(): parser.error(f"База не найдена: {source}") if bool(args.sql) == bool(args.file): parser.error("Укажите ровно одно: --sql или --file") if args.file: sql_path = args.file.expanduser().resolve() if not sql_path.is_file(): parser.error(f"SQL-файл не найден: {sql_path}") sql = sql_path.read_text(encoding="utf-8") else: sql = args.sql if not sql.strip(): parser.error("SQL-запрос пуст") target = args.output.expanduser().resolve() if args.output else None if args.format == "table" and target is None: pass elif target is None: target = Path(f"query.{args.format}").resolve() if target and source == target: parser.error("Выходной файл не должен совпадать с базой") if target and target.exists() and not args.force: parser.error(f"Файл уже существует: {target}. Добавьте --force") if args.format == "table" and args.output is None: target = None if args.allow_write: connection = sqlite3.connect(source) else: connection = sqlite3.connect(source.as_uri() + "?mode=ro", uri=True) try: cursor = connection.execute(sql) if cursor.description is None: if not args.allow_write: parser.error("Запрос не возвращает строки. Для изменения базы нужен --allow-write") connection.commit() print(f"Затронуто строк: {cursor.rowcount}") return 0 columns = [item[0] for item in cursor.description] rows = cursor.fetchall() except sqlite3.Error as error: parser.error(f"Ошибка SQLite: {error}") finally: connection.close() if args.format == "table": text = render_table(columns, rows) if target: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(text + "\n", encoding="utf-8") print(f"Результат: {target}") else: print(text) elif args.format == "csv": target.parent.mkdir(parents=True, exist_ok=True) with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.writer(handle, lineterminator="\n") writer.writerow(columns) writer.writerows(rows) print(f"Результат: {target}") else: payload = [dict(zip(columns, row)) for row in rows] target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(payload, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8") print(f"Результат: {target}") print(f"Строк: {len(rows)}") return 0 if __name__ == "__main__": raise SystemExit(main())