pki_ca/ca_api/db.py

25 lines
639 B
Python

# ca_api/db.py
from __future__ import annotations
import os
from contextlib import contextmanager
import psycopg
from psycopg.rows import dict_row
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@localhost:5432/ca")
@contextmanager
def db_cursor():
"""
Transaction-per-request.
Uses dict_row because ca_core expects dict-like rows (row["status"], etc.).
"""
conn = psycopg.connect(DATABASE_URL, row_factory=dict_row)
try:
with conn: # commits on success, rolls back on exception
with conn.cursor() as cur:
yield cur
finally:
conn.close()