Fred808 commited on
Commit
d4356af
·
verified ·
1 Parent(s): b026e0c

Update app/db/database.py

Browse files
Files changed (1) hide show
  1. app/db/database.py +21 -20
app/db/database.py CHANGED
@@ -1,9 +1,10 @@
1
  from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
2
  from sqlalchemy.orm import declarative_base
3
  from ..core.config import settings
 
4
  import contextlib
5
 
6
- # Create async engine for FastAPI
7
  async_engine = create_async_engine(
8
  settings.DATABASE_URL,
9
  echo=True,
@@ -12,31 +13,42 @@ async_engine = create_async_engine(
12
  )
13
 
14
  # Create async session factory
15
- AsyncSessionLocal = async_sessionmaker(
16
  bind=async_engine,
17
  class_=AsyncSession,
18
  expire_on_commit=False
19
  )
20
 
21
- # Create declarative base for models
22
  Base = declarative_base()
23
 
24
- # Database dependency for FastAPI routes
25
  async def get_db():
26
- async with AsyncSessionLocal() as session:
27
  try:
28
  yield session
29
  finally:
30
  await session.close()
31
 
32
- # Database access for background tasks and services
 
 
 
 
 
 
 
 
 
 
 
 
33
  class Database:
34
  def __init__(self):
35
- self._session_factory = AsyncSessionLocal
36
 
37
  @contextlib.asynccontextmanager
38
  async def session(self):
39
- """Get a database session with automatic commit/rollback"""
40
  session = self._session_factory()
41
  try:
42
  yield session
@@ -48,18 +60,7 @@ class Database:
48
  await session.close()
49
 
50
  async def get_session(self):
51
- """Get a session for manual management"""
52
  return self._session_factory()
53
 
54
- from sqlalchemy import text
55
-
56
- async def verify_connection():
57
- async with async_session_maker() as session:
58
- try:
59
- await session.execute(text("SELECT 1"))
60
- except Exception as e:
61
- raise ConnectionError(f"Database connection verification failed: {str(e)}")
62
-
63
-
64
- # Create singleton instance for database access
65
  db = Database()
 
1
  from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
2
  from sqlalchemy.orm import declarative_base
3
  from ..core.config import settings
4
+ from sqlalchemy import text
5
  import contextlib
6
 
7
+ # Create async engine
8
  async_engine = create_async_engine(
9
  settings.DATABASE_URL,
10
  echo=True,
 
13
  )
14
 
15
  # Create async session factory
16
+ async_session_maker = async_sessionmaker(
17
  bind=async_engine,
18
  class_=AsyncSession,
19
  expire_on_commit=False
20
  )
21
 
22
+ # Declarative base for models
23
  Base = declarative_base()
24
 
25
+ # FastAPI dependency for DB access
26
  async def get_db():
27
+ async with async_session_maker() as session:
28
  try:
29
  yield session
30
  finally:
31
  await session.close()
32
 
33
+ # Verify DB connection
34
+ async def verify_connection():
35
+ async with async_session_maker() as session:
36
+ try:
37
+ await session.execute(text("SELECT 1"))
38
+ except Exception as e:
39
+ raise ConnectionError(f"Database connection verification failed: {str(e)}")
40
+
41
+ # Init DB (called during app startup)
42
+ async def init_db():
43
+ await verify_connection()
44
+
45
+ # Optional: Custom DB access class
46
  class Database:
47
  def __init__(self):
48
+ self._session_factory = async_session_maker
49
 
50
  @contextlib.asynccontextmanager
51
  async def session(self):
 
52
  session = self._session_factory()
53
  try:
54
  yield session
 
60
  await session.close()
61
 
62
  async def get_session(self):
 
63
  return self._session_factory()
64
 
65
+ # Singleton DB instance
 
 
 
 
 
 
 
 
 
 
66
  db = Database()