Spaces:
Sleeping
Sleeping
vanitha commited on
Commit ·
8eeb6c1
1
Parent(s): 23641ce
added get_postgres_session()
Browse files- app/sql.py +28 -1
app/sql.py
CHANGED
|
@@ -8,12 +8,14 @@ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
| 8 |
from sqlalchemy.orm import sessionmaker
|
| 9 |
from sqlalchemy import MetaData, text
|
| 10 |
|
|
|
|
|
|
|
| 11 |
from app.core.config import settings
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
# Database URL validation
|
| 16 |
-
DATABASE_URI = settings.
|
| 17 |
if not DATABASE_URI:
|
| 18 |
logger.error("POSTGRES_URI is empty or missing from settings")
|
| 19 |
raise ValueError("POSTGRES_URI is not set. Check environment variables.")
|
|
@@ -305,3 +307,28 @@ try:
|
|
| 305 |
return _is_postgres_connected()
|
| 306 |
except Exception:
|
| 307 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from sqlalchemy.orm import sessionmaker
|
| 9 |
from sqlalchemy import MetaData, text
|
| 10 |
|
| 11 |
+
from contextlib import asynccontextmanager
|
| 12 |
+
|
| 13 |
from app.core.config import settings
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
# Database URL validation
|
| 18 |
+
DATABASE_URI = settings.DATABASE_URL
|
| 19 |
if not DATABASE_URI:
|
| 20 |
logger.error("POSTGRES_URI is empty or missing from settings")
|
| 21 |
raise ValueError("POSTGRES_URI is not set. Check environment variables.")
|
|
|
|
| 307 |
return _is_postgres_connected()
|
| 308 |
except Exception:
|
| 309 |
pass
|
| 310 |
+
|
| 311 |
+
@asynccontextmanager
|
| 312 |
+
async def get_postgres_session():
|
| 313 |
+
"""
|
| 314 |
+
Get PostgreSQL session context manager.
|
| 315 |
+
|
| 316 |
+
Usage:
|
| 317 |
+
async with get_postgres_session() as session:
|
| 318 |
+
await session.execute(...)
|
| 319 |
+
await session.commit()
|
| 320 |
+
"""
|
| 321 |
+
if not async_session:
|
| 322 |
+
logger.warning("PostgreSQL session maker not initialized")
|
| 323 |
+
yield None
|
| 324 |
+
return
|
| 325 |
+
|
| 326 |
+
session = async_session()
|
| 327 |
+
try:
|
| 328 |
+
yield session
|
| 329 |
+
except Exception as e:
|
| 330 |
+
await session.rollback()
|
| 331 |
+
logger.error(f"Session error, rolled back: {e}")
|
| 332 |
+
raise
|
| 333 |
+
finally:
|
| 334 |
+
await session.close()
|