File size: 2,637 Bytes
201b13c | 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 | from contextlib import contextmanager
from typing import Any, Iterator
try:
import psycopg2
from psycopg2.extras import RealDictCursor
except Exception: # pragma: no cover - optional dependency safety
psycopg2 = None
RealDictCursor = None
from core.config import settings
from core.logger import logger
class Database:
def is_configured(self) -> bool:
return bool(settings.DATABASE_URL)
def connect(self):
if psycopg2 is None or RealDictCursor is None:
raise RuntimeError("psycopg2 is not installed in the active Python environment")
if not self.is_configured():
raise RuntimeError("DATABASE_URL is not configured")
return psycopg2.connect(
settings.DATABASE_URL,
cursor_factory=RealDictCursor,
)
@contextmanager
def cursor(self) -> Iterator[Any]:
connection = None
cursor = None
try:
connection = self.connect()
cursor = connection.cursor()
yield cursor
connection.commit()
except Exception:
if connection is not None:
connection.rollback()
raise
finally:
if cursor is not None:
cursor.close()
if connection is not None:
connection.close()
def fetch_all(self, query: str, params: tuple[Any, ...] | None = None) -> list[dict[str, Any]]:
if not self.is_configured():
return []
try:
with self.cursor() as cursor:
cursor.execute(query, params or ())
return list(cursor.fetchall())
except Exception as exc:
logger.warning(f"Database fetch_all failed: {exc}")
return []
def fetch_one(self, query: str, params: tuple[Any, ...] | None = None) -> dict[str, Any] | None:
if not self.is_configured():
return None
try:
with self.cursor() as cursor:
cursor.execute(query, params or ())
return cursor.fetchone()
except Exception as exc:
logger.warning(f"Database fetch_one failed: {exc}")
return None
def execute(self, query: str, params: tuple[Any, ...] | None = None) -> bool:
if not self.is_configured():
return False
try:
with self.cursor() as cursor:
cursor.execute(query, params or ())
return True
except Exception as exc:
logger.warning(f"Database execute failed: {exc}")
return False
db = Database()
|