|
1 |
| -from functools import lru_cache |
| 1 | +from sqlalchemy import create_engine |
| 2 | +from sqlalchemy.orm import sessionmaker, Session |
2 | 3 | from typing import Iterator
|
3 |
| - |
4 |
| -from fastapi_utils.session import FastAPISessionMaker |
5 |
| -from sqlalchemy.orm import Session |
6 |
| - |
7 |
| -from application.settings import get_settings |
8 | 4 | import logging
|
| 5 | +from application.settings import get_settings |
9 | 6 |
|
| 7 | +# Set up logging |
10 | 8 | logger = logging.getLogger(__name__)
|
11 | 9 |
|
12 | 10 |
|
13 |
| -# this can be used in fast api path functions using Depends to inject a db session |
14 |
| -def get_session() -> Iterator[Session]: |
| 11 | +def _create_engine(): |
| 12 | + settings = get_settings() |
| 13 | + engine = create_engine( |
| 14 | + settings.READ_DATABASE_URL, |
| 15 | + pool_size=settings.DB_POOL_SIZE, |
| 16 | + max_overflow=settings.DB_POOL_MAX_OVERFLOW, |
| 17 | + ) |
| 18 | + |
15 | 19 | logger.info(
|
16 |
| - f"Database engine created with pool_size={get_settings().DB_POOL_SIZE}, " |
17 |
| - f"max_overflow={get_settings().DB_POOL_MAX_OVERFLOW}" |
| 20 | + f"Engine created with pool_size={engine.pool.size()}, " |
| 21 | + f"max_overflow={engine.pool._max_overflow}, " |
18 | 22 | )
|
19 |
| - yield from _get_fastapi_sessionmaker().get_db() |
20 | 23 |
|
| 24 | + return engine |
| 25 | + |
| 26 | + |
| 27 | +# Create session factory |
| 28 | +engine = _create_engine() |
| 29 | +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) |
21 | 30 |
|
22 |
| -# this can be used in non path functions to create a context manager for a db session |
23 |
| -# see https://github.com/dmontagu/fastapi-utils/blob/master/fastapi_utils/session.py#L77:L91 |
24 |
| -def get_context_session() -> Iterator[Session]: |
25 |
| - return _get_fastapi_sessionmaker().context_session() |
| 31 | + |
| 32 | +def get_session() -> Iterator[Session]: |
| 33 | + db = SessionLocal() |
| 34 | + try: |
| 35 | + yield db |
| 36 | + finally: |
| 37 | + db.close() |
26 | 38 |
|
27 | 39 |
|
28 |
| -@lru_cache() |
29 |
| -def _get_fastapi_sessionmaker() -> FastAPISessionMaker: |
30 |
| - database_uri = get_settings().READ_DATABASE_URL |
31 |
| - return FastAPISessionMaker(database_uri) |
| 40 | +def get_context_session() -> Iterator[Session]: |
| 41 | + with SessionLocal() as session: |
| 42 | + yield session |
0 commit comments