← full-stack-fastapi-template / backend/app/core/db.py
| 1 | from sqlmodel import Session, create_engine, select |
| 2 | |
| 3 | from app import crud |
| 4 | from app.core.config import settings |
| 5 | from app.models import User, UserCreate |
| 6 | |
| 7 | engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI)) |
| 8 | |
| 9 | |
| 10 | # make sure all SQLModel models are imported (app.models) before initializing DB |
| 11 | # otherwise, SQLModel might fail to initialize relationships properly |
| 12 | # for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28 |
| 13 | |
| 14 | |
| 15 | def init_db(session: Session) -> None: |
| 16 | # Tables should be created with Alembic migrations |
| 17 | # But if you don't want to use migrations, create |
| 18 | # the tables un-commenting the next lines |
| 19 | # from sqlmodel import SQLModel |
| 20 | |
| 21 | # This works because the models are already imported and registered from app.models |
| 22 | # SQLModel.metadata.create_all(engine) |
| 23 | |
| 24 | user = session.exec( |
| 25 | select(User).where(User.email == settings.FIRST_SUPERUSER) |
| 26 | ).first() |
| 27 | if not user: |
| 28 | user_in = UserCreate( |
| 29 | email=settings.FIRST_SUPERUSER, |
| 30 | password=settings.FIRST_SUPERUSER_PASSWORD, |
| 31 | is_superuser=True, |
| 32 | ) |
| 33 | user = crud.create_user(session=session, user_create=user_in) |
| 34 |