From e20e9e7cecd1963aa9c7768cd0e2607cc328f027 Mon Sep 17 00:00:00 2001 From: Egor Date: Mon, 10 Nov 2025 04:06:28 +0300 Subject: [PATCH] Fix init_db index creation on fresh databases --- app/database/database.py | 44 +++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/app/database/database.py b/app/database/database.py index f198a944..93d8a057 100644 --- a/app/database/database.py +++ b/app/database/database.py @@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import ( AsyncEngine ) from sqlalchemy.pool import NullPool, AsyncAdaptedQueuePool -from sqlalchemy import event, text, bindparam +from sqlalchemy import event, text, bindparam, inspect from sqlalchemy.engine import Engine import time from app.config import settings @@ -258,22 +258,42 @@ async def init_db(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) - - if not settings.get_database_url().startswith("sqlite"): - logger.info("πŸ“Š Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ индСксов для ΠΎΠΏΡ‚ΠΈΠΌΠΈΠ·Π°Ρ†ΠΈΠΈ...") - + + if not settings.get_database_url().startswith("sqlite"): + logger.info("πŸ“Š Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ индСксов для ΠΎΠΏΡ‚ΠΈΠΌΠΈΠ·Π°Ρ†ΠΈΠΈ...") + + async with engine.begin() as conn: indexes = [ - "CREATE INDEX IF NOT EXISTS idx_users_telegram_id ON users(telegram_id)", - "CREATE INDEX IF NOT EXISTS idx_subscriptions_user_id ON subscriptions(user_id)", - "CREATE INDEX IF NOT EXISTS idx_subscriptions_status ON subscriptions(status) WHERE status = 'active'", - "CREATE INDEX IF NOT EXISTS idx_payments_created_at ON payments(created_at DESC)", + ("users", "CREATE INDEX IF NOT EXISTS idx_users_telegram_id ON users(telegram_id)"), + ( + "subscriptions", + "CREATE INDEX IF NOT EXISTS idx_subscriptions_user_id ON subscriptions(user_id)", + ), + ( + "subscriptions", + "CREATE INDEX IF NOT EXISTS idx_subscriptions_status ON subscriptions(status) WHERE status = 'active'", + ), + ( + "payments", + "CREATE INDEX IF NOT EXISTS idx_payments_created_at ON payments(created_at DESC)", + ), ] - - for index_sql in indexes: + + for table_name, index_sql in indexes: + table_exists = await conn.run_sync(lambda sync_conn: inspect(sync_conn).has_table(table_name)) + + if not table_exists: + logger.debug( + "ΠŸΡ€ΠΎΠΏΡƒΡΠΊΠ°Π΅ΠΌ созданиС индСкса %s: Ρ‚Π°Π±Π»ΠΈΡ†Π° %s отсутствуСт", + index_sql, + table_name, + ) + continue + try: await conn.execute(text(index_sql)) except Exception as e: - logger.debug(f"Index creation skipped: {e}") + logger.debug("Index creation skipped for %s: %s", table_name, e) logger.info("βœ… Π‘Π°Π·Π° Π΄Π°Π½Π½Ρ‹Ρ… ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½Π°")