35 lines
1.1 KiB
Python
35 lines
1.1 KiB
Python
# topology_api/db.py
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from contextlib import contextmanager
|
|
from topology_api.config import READER_DATABASE_URL, WRITER_DATABASE_URL
|
|
|
|
|
|
def get_reader_connection():
|
|
"""Return a new read-only connection with dict_row rows."""
|
|
return psycopg.connect(READER_DATABASE_URL, row_factory=dict_row)
|
|
|
|
|
|
def get_writer_connection():
|
|
"""Return a new write-capable connection with dict_row rows."""
|
|
return psycopg.connect(WRITER_DATABASE_URL, row_factory=dict_row)
|
|
|
|
|
|
@contextmanager
|
|
def read_cursor():
|
|
"""Context manager for read queries. Returns a cursor."""
|
|
with get_reader_connection() as conn:
|
|
conn.execute("SET search_path TO topology, public")
|
|
with conn.cursor() as cur:
|
|
yield cur
|
|
|
|
|
|
@contextmanager
|
|
def write_cursor():
|
|
"""Context manager for write queries. Auto-commits on success, rollback on error."""
|
|
with get_writer_connection() as conn:
|
|
conn.execute("SET search_path TO topology, public")
|
|
with conn.transaction():
|
|
with conn.cursor() as cur:
|
|
yield cur
|