Ei kuvausta

db.py 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from __future__ import annotations
  2. from contextlib import contextmanager
  3. import psycopg
  4. from psycopg.rows import dict_row
  5. from app.config import settings
  6. def db_dsn() -> str:
  7. return (
  8. f"host={settings.soc_integrator_db_host} "
  9. f"port={settings.soc_integrator_db_port} "
  10. f"dbname={settings.soc_integrator_db_name} "
  11. f"user={settings.soc_integrator_db_user} "
  12. f"password={settings.soc_integrator_db_password}"
  13. )
  14. @contextmanager
  15. def get_conn():
  16. with psycopg.connect(db_dsn(), row_factory=dict_row, autocommit=True) as conn:
  17. yield conn
  18. def init_schema() -> None:
  19. with get_conn() as conn, conn.cursor() as cur:
  20. cur.execute(
  21. """
  22. CREATE TABLE IF NOT EXISTS incident_index (
  23. incident_key TEXT PRIMARY KEY,
  24. iris_case_id TEXT,
  25. status TEXT NOT NULL,
  26. severity TEXT NOT NULL,
  27. first_seen TIMESTAMPTZ NOT NULL,
  28. last_seen TIMESTAMPTZ NOT NULL
  29. );
  30. """
  31. )
  32. cur.execute(
  33. """
  34. CREATE TABLE IF NOT EXISTS incident_events (
  35. id BIGSERIAL PRIMARY KEY,
  36. incident_key TEXT NOT NULL REFERENCES incident_index(incident_key) ON DELETE CASCADE,
  37. event_id TEXT,
  38. source TEXT NOT NULL,
  39. event_type TEXT NOT NULL,
  40. raw_payload JSONB NOT NULL,
  41. decision_trace JSONB NOT NULL,
  42. created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
  43. );
  44. """
  45. )
  46. cur.execute(
  47. """
  48. CREATE TABLE IF NOT EXISTS escalation_audit (
  49. id BIGSERIAL PRIMARY KEY,
  50. incident_key TEXT NOT NULL REFERENCES incident_index(incident_key) ON DELETE CASCADE,
  51. attempted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  52. status_code INT,
  53. success BOOLEAN NOT NULL,
  54. response_excerpt TEXT
  55. );
  56. """
  57. )
  58. cur.execute(
  59. """
  60. CREATE TABLE IF NOT EXISTS policy_config (
  61. id INT PRIMARY KEY,
  62. data JSONB NOT NULL,
  63. updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
  64. );
  65. """
  66. )
  67. cur.execute(
  68. "CREATE INDEX IF NOT EXISTS idx_incident_events_incident_key_created_at ON incident_events(incident_key, created_at DESC);"
  69. )
  70. cur.execute(
  71. "CREATE INDEX IF NOT EXISTS idx_incident_events_source_event_id ON incident_events(source, event_id);"
  72. )
  73. cur.execute(
  74. "CREATE INDEX IF NOT EXISTS idx_escalation_audit_incident_key_attempted_at ON escalation_audit(incident_key, attempted_at DESC);"
  75. )