File size: 2,938 Bytes
f6c0922 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | """
Crea la tabla de auditoría (y sus índices) en la base PostgreSQL/Supabase.
Idempotente: usa CREATE TABLE / CREATE INDEX IF NOT EXISTS, así que puede
correrse varias veces sin efectos secundarios.
Uso:
# Requiere DATABASE_URL en el entorno o en .env
# postgresql://USUARIO:CONTRASEÑA@HOST/NOMBRE_BD?sslmode=require
python scripts/create_auditoria_table.py
No usa el cliente supabase-py porque PostgREST no ejecuta DDL; se conecta vía
psycopg2 directamente al Postgres (psycopg2-binary ya está en requirements.txt).
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
import psycopg2
DDL = """
CREATE TABLE IF NOT EXISTS auditoria (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
entidad TEXT NOT NULL,
entidad_id TEXT NOT NULL,
cama_id BIGINT,
evento TEXT NOT NULL,
estado_anterior TEXT,
estado_nuevo TEXT,
paciente_id BIGINT,
usuario_id TEXT,
rol TEXT,
origen TEXT NOT NULL DEFAULT 'API',
descripcion TEXT,
detalle JSONB,
hospital_id TEXT,
creado_en TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_auditoria_cama_id ON auditoria (cama_id);
CREATE INDEX IF NOT EXISTS idx_auditoria_entidad ON auditoria (entidad, entidad_id);
CREATE INDEX IF NOT EXISTS idx_auditoria_paciente_id ON auditoria (paciente_id);
CREATE INDEX IF NOT EXISTS idx_auditoria_creado_en ON auditoria (creado_en DESC);
CREATE INDEX IF NOT EXISTS idx_auditoria_hospital_id ON auditoria (hospital_id);
"""
def _load_env_file() -> None:
"""Carga DATABASE_URL desde .env si no está ya en el entorno (sin dependencias)."""
if os.getenv("DATABASE_URL"):
return
env_path = Path(__file__).resolve().parent.parent / ".env"
if not env_path.exists():
return
for line in env_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
if key.strip() == "DATABASE_URL":
os.environ.setdefault("DATABASE_URL", value.strip().strip('"').strip("'"))
break
def main() -> int:
_load_env_file()
dsn = os.getenv("DATABASE_URL")
if not dsn:
print(
"ERROR: falta DATABASE_URL. Definila en el entorno o en .env:\n"
" postgresql://USUARIO:CONTRASEÑA@HOST/NOMBRE_BD?sslmode=require",
file=sys.stderr,
)
return 1
print("Conectando a la base…")
with psycopg2.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(DDL)
conn.commit()
print("OK: tabla 'auditoria' e índices creados (o ya existían).")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|