Add Alembic for database migrations and initial migration scripts

- Created alembic.ini configuration file for Alembic migrations.
- Added README file for Alembic with a brief description.
- Implemented env.py for Alembic to manage database migrations.
- Created script.py.mako template for migration scripts.
- Added initial migration script to create database tables.
- Created a migration script to add initial plan and playlist data.
- Updated database initialization to run Alembic migrations.
- Enhanced credit service to automatically recharge user credits based on their plan.
- Implemented delete_task method in scheduler service to remove scheduled tasks.
- Updated scheduler API to reflect task deletion instead of cancellation.
- Added CLI tool for managing database migrations.
- Updated tests to cover new functionality for task deletion and credit recharge.
- Updated pyproject.toml and lock files to include Alembic as a dependency.
This commit is contained in:
JSC
2025-09-16 13:45:14 +02:00
parent e8f979c137
commit 83239cb4fa
16 changed files with 828 additions and 29 deletions

View File

@@ -8,7 +8,6 @@ from sqlmodel.ext.asyncio.session import AsyncSession
import app.models # noqa: F401
from app.core.config import settings
from app.core.logging import get_logger
from app.core.seeds import seed_all_data
engine: AsyncEngine = create_async_engine(
settings.DATABASE_URL,
@@ -40,26 +39,23 @@ def get_session_factory() -> Callable[[], AsyncSession]:
async def init_db() -> None:
"""Initialize the database and create tables if they do not exist."""
"""Initialize the database using Alembic migrations."""
logger = get_logger(__name__)
try:
logger.info("Initializing database tables")
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
logger.info("Database tables created successfully")
logger.info("Running database migrations")
# Run Alembic migrations programmatically
from alembic import command
from alembic.config import Config
# Seed initial data
await seed_initial_data()
# Get the alembic config
alembic_cfg = Config("alembic.ini")
# Run migrations to the latest revision
command.upgrade(alembic_cfg, "head")
logger.info("Database migrations completed successfully")
except Exception:
logger.exception("Failed to initialize database")
raise
async def seed_initial_data() -> None:
"""Seed initial data into the database."""
logger = get_logger(__name__)
logger.info("Starting initial data seeding")
async with AsyncSession(engine) as session:
await seed_all_data(session)