Fix empty database migration

This commit is contained in:
2025-12-31 21:56:23 +03:00
Unverified
parent de34747a34
commit 16ae35b357
2 changed files with 23 additions and 7 deletions
+3 -2
View File
@@ -20,9 +20,10 @@ from slowapi.middleware import SlowAPIMiddleware
logger = logging.getLogger("uvicorn.error") logger = logging.getLogger("uvicorn.error")
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
# Startup - run migration in separate process to avoid logging interference # Startup - run migration in subprocess to avoid logging interference
try: try:
logger.info("Starting database migration check...") logger.info("Starting database migration check...")
# Run migration in a separate process # Run migration in a separate process
@@ -40,7 +41,7 @@ async def lifespan(app: FastAPI):
try: try:
with SessionLocal() as db: with SessionLocal() as db:
owner = db.query(User).filter(User.username == OWNER_USERNAME).first() owner = db.query(User).filter(User.id == 1).first()
if owner and not owner.verified: if owner and not owner.verified:
owner.verified = True owner.verified = True
db.commit() db.commit()
+15
View File
@@ -20,6 +20,21 @@ def run_migrations():
Fully automated - handles all scenarios automatically. Fully automated - handles all scenarios automatically.
""" """
try: try:
# FIRST: Check if database has any application tables (excluding alembic_version)
engine = create_engine(DATABASE_URL)
with engine.connect() as connection:
from sqlalchemy import inspect
inspector = inspect(connection)
existing_tables = [table for table in inspector.get_table_names()
if not table.startswith('sqlite_') and table != 'alembic_version']
# If no application tables exist, create them directly from models
if not existing_tables:
logger.info("No application tables found. Creating all tables directly from models...")
from models import Base
Base.metadata.create_all(bind=engine)
logger.info("All tables created successfully from models.")
# Get the directory where this script is located # Get the directory where this script is located
current_dir = os.path.dirname(os.path.abspath(__file__)) current_dir = os.path.dirname(os.path.abspath(__file__))