Add database seeding functionality and enhance model relationships
- Implement initial data seeding for plans in the database. - Create a new `seed_all_data` function to manage seeding process. - Update `Sound` and `User` models to include relationships for `SoundPlayed` and `Stream`.
This commit is contained in:
65
app/core/seeds.py
Normal file
65
app/core/seeds.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""Database seeding functionality."""
|
||||
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.plan import Plan
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def seed_plans(session: AsyncSession) -> None:
|
||||
"""Seed initial plan data."""
|
||||
logger.info("Seeding plan data")
|
||||
|
||||
# Check if plans already exist
|
||||
existing_plans = await session.exec(select(Plan))
|
||||
if existing_plans.first():
|
||||
logger.info("Plans already exist, skipping seeding")
|
||||
return
|
||||
|
||||
# Define initial plans
|
||||
initial_plans = [
|
||||
Plan(
|
||||
code="free",
|
||||
name="Free Plan",
|
||||
description="Basic free plan with limited features",
|
||||
credits=25,
|
||||
max_credits=75,
|
||||
),
|
||||
Plan(
|
||||
code="premium",
|
||||
name="Premium Plan",
|
||||
description="Premium plan with more features",
|
||||
credits=50,
|
||||
max_credits=150,
|
||||
),
|
||||
Plan(
|
||||
code="pro",
|
||||
name="Pro Plan",
|
||||
description="Pro plan with unlimited features",
|
||||
credits=100,
|
||||
max_credits=300,
|
||||
),
|
||||
]
|
||||
|
||||
# Add plans to session
|
||||
for plan in initial_plans:
|
||||
session.add(plan)
|
||||
|
||||
await session.commit()
|
||||
logger.info("Successfully seeded %d plans", len(initial_plans))
|
||||
|
||||
|
||||
async def seed_all_data(session: AsyncSession) -> None:
|
||||
"""Seed all initial data."""
|
||||
logger.info("Starting data seeding")
|
||||
|
||||
try:
|
||||
await seed_plans(session)
|
||||
logger.info("Data seeding completed successfully")
|
||||
except Exception:
|
||||
logger.exception("Failed to seed data")
|
||||
await session.rollback()
|
||||
raise
|
||||
Reference in New Issue
Block a user