|
1 | 1 | """Database connection management""" |
2 | 2 |
|
3 | | -from typing import Optional |
4 | | -from sqlalchemy.orm import scoped_session |
5 | | -from flask import Flask |
6 | | -from flask_sqlalchemy import SQLAlchemy |
7 | | -from flask_sqlalchemy.session import Session |
| 3 | +from sqlalchemy import create_engine |
| 4 | +from sqlalchemy.orm import sessionmaker, scoped_session, Session |
8 | 5 | from .base import Base |
9 | 6 |
|
10 | 7 | DATABASE_FILENAME = "project.db" |
11 | | -db: Optional[SQLAlchemy] = None |
12 | 8 |
|
13 | | - |
14 | | -def init_database(app: Flask, db_filename: str = DATABASE_FILENAME) -> SQLAlchemy: |
15 | | - global db |
16 | | - if db is None: |
17 | | - db = SQLAlchemy(model_class=Base) |
18 | | - db.init_app(app) |
19 | | - with app.app_context(): |
20 | | - db.create_all() |
21 | | - return db |
22 | | - |
23 | | - |
24 | | -def get_database() -> Optional[SQLAlchemy]: |
25 | | - return db |
26 | | - |
27 | | - |
28 | | -def get_session() -> Optional[scoped_session[Session]]: |
29 | | - return db.session if db else None |
| 9 | +engine = None |
| 10 | +session_factory = None |
| 11 | +scoped_session_registry = None |
| 12 | + |
| 13 | + |
| 14 | +def init_database(db_path: str = DATABASE_FILENAME, create_tables: bool = True) -> None: |
| 15 | + global engine, session_factory, scoped_session_registry |
| 16 | + |
| 17 | + if engine is None: |
| 18 | + engine = create_engine( |
| 19 | + f"sqlite:///{db_path}", |
| 20 | + connect_args={"check_same_thread": False}, |
| 21 | + ) |
| 22 | + print(f"Database engine created for {db_path}", flush=True) |
| 23 | + session_factory = sessionmaker(bind=engine) |
| 24 | + scoped_session_registry = scoped_session(session_factory) |
| 25 | + if create_tables: |
| 26 | + Base.metadata.create_all(engine) |
| 27 | + print(f"Database tables created for {db_path}", flush=True) |
| 28 | + else: |
| 29 | + print(f"Database connected (tables not created) for {db_path}", flush=True) |
| 30 | + else: |
| 31 | + print(f"Database engine already exists for {db_path}, reusing", flush=True) |
| 32 | + |
| 33 | + |
| 34 | +def get_session() -> Session: |
| 35 | + if scoped_session_registry is None: |
| 36 | + raise RuntimeError() |
| 37 | + return scoped_session_registry() |
0 commit comments