-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.py
More file actions
39 lines (34 loc) · 961 Bytes
/
db.py
File metadata and controls
39 lines (34 loc) · 961 Bytes
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
"""
Database connection management.
Provides connection pooling and error handling for PostgreSQL/Neon database.
"""
import psycopg
from contextlib import contextmanager
from config import DATABASE_URL
@contextmanager
def get_conn():
"""
Get a database connection with automatic cleanup.
Yields:
Database connection object
Raises:
RuntimeError: If connection fails
"""
conn = None
try:
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL is not configured")
conn = psycopg.connect(DATABASE_URL)
yield conn
conn.commit()
except psycopg.Error as e:
if conn:
conn.rollback()
raise RuntimeError(f"Database error: {str(e)}")
except Exception as e:
if conn:
conn.rollback()
raise RuntimeError(f"Unexpected database error: {str(e)}")
finally:
if conn:
conn.close()