File size: 1,299 Bytes
321a7a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from sqlmodel import Session, SQLModel, create_engine

from app.core.config import settings


def _connect_args(db_url: str) -> dict:
    if db_url.startswith("sqlite"):
        # Add a busy timeout so concurrent startups/seed runs don't immediately fail with "database is locked".
        return {"check_same_thread": False, "timeout": 30}
    return {}


engine = create_engine(settings.DATABASE_URL, echo=False, connect_args=_connect_args(settings.DATABASE_URL))


def init_db() -> None:
    # For dev convenience. In production, prefer Alembic migrations.
    # Ensure all models are imported so SQLModel registers tables.
    # (If a model module is never imported, its table won't be created.)
    from app.models.product import Product  # noqa: F401
    from app.models.user import User  # noqa: F401
    from app.models.address import Address  # noqa: F401
    from app.models.variant import ProductVariant  # noqa: F401
    from app.models.review import Review  # noqa: F401
    from app.models.suggestion import SearchSuggestion  # noqa: F401
    from app.models.cart import Cart, CartItem  # noqa: F401
    from app.models.order import Order, OrderItem  # noqa: F401
    SQLModel.metadata.create_all(engine)


def get_session():
    with Session(engine) as session:
        yield session