Skip to content

Commit

Permalink
db uses async operations
Browse files Browse the repository at this point in the history
  • Loading branch information
sarfarazsiddiquii committed Nov 16, 2024
1 parent ba80b71 commit 9e2333f
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions app/core/database.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import os

from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

load_dotenv(override=True)

ASYNC_POSTGRES_URL = os.getenv("POSTGRES_SERVER").replace(
"postgresql://", "postgresql+asyncpg://"
)

# Create engine with connection pooling and best practices
engine = create_engine(
os.getenv("POSTGRES_SERVER"),
engine = create_async_engine(
ASYNC_POSTGRES_URL,
pool_size=10, # Initial number of connections in the pool
max_overflow=10, # Maximum number of connections beyond pool_size
pool_timeout=30, # Timeout in seconds for getting a connection from the pool
Expand All @@ -19,15 +23,15 @@
)

# Create session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False, bind=engine)

# Base class for all ORM models
Base = declarative_base()


# Dependency to be used in routes
def get_db():
db = SessionLocal()
async def get_db():
db = AsyncSessionLocal()
try:
yield db
finally:
Expand Down

0 comments on commit 9e2333f

Please sign in to comment.