|
| 1 | +"""Database initialization script. |
| 2 | +
|
| 3 | +Checks if an initial superuser should be created and creates it if needed. |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import logging |
| 8 | + |
| 9 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 10 | +from sqlmodel import select |
| 11 | +from sqlmodel.ext.asyncio.session import AsyncSession |
| 12 | + |
| 13 | +from src.core.config import settings |
| 14 | +from src.models.user import User |
| 15 | +from src.schemas.user import UserIn |
| 16 | +from src.utils.password import get_password_hash |
| 17 | + |
| 18 | +logging.basicConfig(level=logging.INFO) |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +async def init_db() -> None: |
| 23 | + """Create the initial superuser if configured.""" |
| 24 | + if ( |
| 25 | + not settings.first_superuser_username |
| 26 | + or not settings.first_superuser_password |
| 27 | + ): |
| 28 | + logger.info( |
| 29 | + "First superuser credentials not configured. Skipping initialization." |
| 30 | + ) |
| 31 | + return |
| 32 | + |
| 33 | + engine = create_async_engine(settings.database_url) |
| 34 | + |
| 35 | + async with AsyncSession(engine) as session: |
| 36 | + statement = select(User).where( |
| 37 | + User.username == settings.first_superuser_username |
| 38 | + ) |
| 39 | + result = await session.exec(statement) |
| 40 | + user = result.first() |
| 41 | + |
| 42 | + if user: |
| 43 | + logger.info("Superuser already exists. Skipping creation.") |
| 44 | + else: |
| 45 | + logger.info("Creating initial superuser.") |
| 46 | + user_in = UserIn( |
| 47 | + username=settings.first_superuser_username, |
| 48 | + plain_password=settings.first_superuser_password, |
| 49 | + ) |
| 50 | + new_user = User(**user_in.model_dump(exclude={"plain_password"})) |
| 51 | + new_user.hashed_password = get_password_hash( |
| 52 | + user_in.plain_password |
| 53 | + ) |
| 54 | + session.add(new_user) |
| 55 | + await session.commit() |
| 56 | + logger.info("Initial superuser created successfully.") |
| 57 | + |
| 58 | + await engine.dispose() |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + asyncio.run(init_db()) |
0 commit comments