Spaces:
Running
Running
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import sqlite3 | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| from base_datos import iniciar_historial_usuario | |
| from config import HISTORY_DB_PATH | |
| def _obtener_tablas(conn: sqlite3.Connection) -> list[str]: | |
| rows = conn.execute( | |
| "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name" | |
| ).fetchall() | |
| return [str(r[0]) for r in rows] | |
| def limpiar_datos(db_path: Path) -> dict[str, int]: | |
| if not db_path.exists(): | |
| iniciar_historial_usuario() | |
| deleted_by_table: dict[str, int] = {} | |
| with sqlite3.connect(db_path) as conn: | |
| conn.execute("PRAGMA foreign_keys = OFF") | |
| tables = _obtener_tablas(conn) | |
| for table_name in tables: | |
| cur = conn.execute(f"DELETE FROM {table_name}") | |
| deleted_by_table[table_name] = int(cur.rowcount or 0) | |
| all_tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()} | |
| if "sqlite_sequence" in all_tables: | |
| conn.execute("DELETE FROM sqlite_sequence") | |
| conn.commit() | |
| return deleted_by_table | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description="Elimina todos los datos de la BDM (SQLite) del proyecto.") | |
| parser.add_argument( | |
| "--db-path", | |
| type=Path, | |
| default=HISTORY_DB_PATH, | |
| help=f"Ruta de la base de datos (por defecto: {HISTORY_DB_PATH})", | |
| ) | |
| args = parser.parse_args() | |
| db_path = args.db_path.resolve() | |
| deleted_by_table = limpiar_datos(db_path) | |
| total = sum(deleted_by_table.values()) | |
| print(f"BD limpiada: {db_path}") | |
| for table_name, count in deleted_by_table.items(): | |
| print(f" {table_name}: {count} filas eliminadas") | |
| print(f"Total eliminado: {total} filas") | |
| iniciar_historial_usuario() | |
| print("Esquema verificado (tablas e índices recreados si faltaban).") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |