migrate_db.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import asyncio
  2. import aiosqlite
  3. from pathlib import Path
  4. async def main():
  5. """
  6. Applies database migrations to an existing SQLite database.
  7. - Adds indexes for performance.
  8. - Ensures all columns exist.
  9. """
  10. base_dir = Path(__file__).resolve().parent.parent
  11. db_path = base_dir / "data.sqlite3"
  12. if not db_path.exists():
  13. print(f"Database not found at {db_path}, skipping migration.")
  14. return
  15. print(f"Applying migrations to {db_path}...")
  16. async with aiosqlite.connect(db_path) as conn:
  17. # 1. Add indexes
  18. print("Creating indexes...")
  19. await conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_enabled ON accounts (enabled);")
  20. await conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_created_at ON accounts (created_at);")
  21. await conn.execute("CREATE INDEX IF NOT EXISTS idx_accounts_success_count ON accounts (success_count);")
  22. print("Indexes created successfully.")
  23. # 2. Add missing columns (idempotent)
  24. print("Checking for missing columns...")
  25. try:
  26. async with conn.execute("PRAGMA table_info(accounts)") as cursor:
  27. rows = await cursor.fetchall()
  28. cols = [row[1] for row in rows]
  29. if "enabled" not in cols:
  30. print("Adding 'enabled' column...")
  31. await conn.execute("ALTER TABLE accounts ADD COLUMN enabled INTEGER DEFAULT 1")
  32. if "error_count" not in cols:
  33. print("Adding 'error_count' column...")
  34. await conn.execute("ALTER TABLE accounts ADD COLUMN error_count INTEGER DEFAULT 0")
  35. if "success_count" not in cols:
  36. print("Adding 'success_count' column...")
  37. await conn.execute("ALTER TABLE accounts ADD COLUMN success_count INTEGER DEFAULT 0")
  38. print("Column check complete.")
  39. except Exception as e:
  40. print(f"Error checking/adding columns: {e}")
  41. await conn.commit()
  42. print("Migrations applied successfully.")
  43. if __name__ == "__main__":
  44. asyncio.run(main())