|
| 1 | +from sqlalchemy import create_engine |
| 2 | +from sqlalchemy.ext.declarative import declarative_base |
| 3 | +from sqlalchemy.orm import sessionmaker |
| 4 | + |
| 5 | +from .config import get_settings |
| 6 | + |
| 7 | +SQLALCHEMY_DATABASE_URL = get_settings().SQLALCHEMY_DATABASE_URL |
| 8 | + |
| 9 | +# Check if the database URL is for SQLite |
| 10 | +is_sqlite = SQLALCHEMY_DATABASE_URL.startswith("sqlite") |
| 11 | + |
| 12 | +if is_sqlite: |
| 13 | + engine = create_engine( |
| 14 | + SQLALCHEMY_DATABASE_URL, |
| 15 | + connect_args={"check_same_thread": False}, # SQLite specific argument |
| 16 | + ) |
| 17 | + |
| 18 | +else: |
| 19 | + # PostgreSQL configuration |
| 20 | + engine = create_engine( |
| 21 | + SQLALCHEMY_DATABASE_URL, |
| 22 | + connect_args={}, |
| 23 | + future=True, |
| 24 | + # Common PostgreSQL settings |
| 25 | + pool_size=5, # Maximum number of permanent connections |
| 26 | + max_overflow=10, # Maximum number of additional connections |
| 27 | + pool_timeout=30, # Timeout in seconds for getting a connection from pool |
| 28 | + pool_recycle=1800, # Recycle connections after 30 minutes |
| 29 | + ) |
| 30 | + |
| 31 | + |
| 32 | +Session_Local = sessionmaker(bind=engine, autocommit=False, autoflush=False) |
| 33 | + |
| 34 | + |
| 35 | +Base = declarative_base() |
| 36 | + |
| 37 | + |
| 38 | +def get_db(): |
| 39 | + db = Session_Local() |
| 40 | + try: |
| 41 | + yield db |
| 42 | + finally: |
| 43 | + db.close() |
| 44 | + |
| 45 | + |
| 46 | +# Example database URLs in config.py: |
| 47 | +# SQLite: "sqlite:///./sql_app.db" |
| 48 | +# PostgreSQL: "postgresql://user:password@localhost:5432/db_name" |
0 commit comments