manage_db.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env python3
  2. """Database management script for SquidStats.
  3. This script provides convenient commands for managing database migrations
  4. using Alembic. It wraps common Alembic operations with simplified commands.
  5. Usage:
  6. python manage_db.py init # Initialize (stamp) database as up-to-date
  7. python manage_db.py upgrade # Apply pending migrations
  8. python manage_db.py downgrade # Revert last migration
  9. python manage_db.py current # Show current migration version
  10. python manage_db.py history # Show migration history
  11. python manage_db.py create # Create a new migration
  12. """
  13. import os
  14. import sys
  15. from pathlib import Path
  16. from alembic.config import Config as AlembicConfig
  17. from dotenv import load_dotenv
  18. from loguru import logger
  19. from sqlalchemy import inspect
  20. from alembic import command
  21. from database.database import get_engine
  22. from database.models.models import BlacklistDomain
  23. from services.security.blacklist_service import merge_and_save_blacklist
  24. # Delay import of project modules until runtime (project root added to sys.path above)
  25. # Add project root to path
  26. project_root = Path(__file__).parent
  27. sys.path.insert(0, str(project_root))
  28. # Load environment variables
  29. load_dotenv()
  30. def get_alembic_config():
  31. """Get Alembic configuration."""
  32. alembic_ini_path = project_root / "alembic.ini"
  33. if not alembic_ini_path.exists():
  34. logger.error(f"alembic.ini not found at {alembic_ini_path}")
  35. sys.exit(1)
  36. config = AlembicConfig(str(alembic_ini_path))
  37. return config
  38. def init_database():
  39. """Mark database as up-to-date without running migrations.
  40. Use this for existing databases to initialize Alembic tracking.
  41. This stamps the database with the latest migration version without
  42. actually running the migrations (assumes schema already exists).
  43. """
  44. config = get_alembic_config()
  45. logger.info("Initializing database migration tracking...")
  46. logger.info("This will mark your database as up-to-date with the latest migration.")
  47. logger.info("Use this ONLY if your database schema is already correct.")
  48. response = input("Continue? (yes/no): ").lower().strip()
  49. if response != "yes":
  50. logger.info("Operation cancelled.")
  51. return
  52. try:
  53. # Stamp database with the latest revision
  54. command.stamp(config, "head")
  55. logger.info("✓ Database initialized successfully!")
  56. logger.info("Your database is now tracked by Alembic.")
  57. except Exception as e:
  58. logger.error(f"Failed to initialize database: {e}")
  59. sys.exit(1)
  60. def upgrade_database(revision="head"):
  61. """Apply pending migrations to the database.
  62. Args:
  63. revision: Target revision (default: 'head' for latest)
  64. """
  65. config = get_alembic_config()
  66. logger.info(f"Upgrading database to revision: {revision}")
  67. try:
  68. command.upgrade(config, revision)
  69. logger.info("✓ Database upgraded successfully!")
  70. except Exception as e:
  71. logger.error(f"Failed to upgrade database: {e}")
  72. sys.exit(1)
  73. def downgrade_database(revision="-1"):
  74. """Revert database migrations.
  75. Args:
  76. revision: Target revision (default: '-1' for one step back)
  77. """
  78. config = get_alembic_config()
  79. logger.warning(f"Downgrading database to revision: {revision}")
  80. logger.warning("This operation may result in data loss!")
  81. response = input("Continue? (yes/no): ").lower().strip()
  82. if response != "yes":
  83. logger.info("Operation cancelled.")
  84. return
  85. try:
  86. command.downgrade(config, revision)
  87. logger.info("✓ Database downgraded successfully!")
  88. except Exception as e:
  89. logger.error(f"Failed to downgrade database: {e}")
  90. sys.exit(1)
  91. def show_current():
  92. """Show current migration version."""
  93. config = get_alembic_config()
  94. try:
  95. command.current(config, verbose=True)
  96. except Exception as e:
  97. logger.error(f"Failed to show current version: {e}")
  98. sys.exit(1)
  99. def show_history():
  100. """Show migration history."""
  101. config = get_alembic_config()
  102. try:
  103. command.history(config, verbose=True)
  104. except Exception as e:
  105. logger.error(f"Failed to show history: {e}")
  106. sys.exit(1)
  107. def create_migration(message=None):
  108. """Create a new migration.
  109. Args:
  110. message: Migration message/description
  111. """
  112. config = get_alembic_config()
  113. if not message:
  114. message = input("Enter migration message: ").strip()
  115. if not message:
  116. logger.error("Migration message is required!")
  117. sys.exit(1)
  118. try:
  119. command.revision(config, message=message, autogenerate=True)
  120. logger.info("✓ Migration created successfully!")
  121. except Exception as e:
  122. logger.error(f"Failed to create migration: {e}")
  123. sys.exit(1)
  124. def migrate_env_blacklist(auto_confirm: bool = False):
  125. """Migrate domains listed in BLACKLIST_DOMAINS (from .env) into DB table.
  126. - Reads `BLACKLIST_DOMAINS` environment variable (comma separated)
  127. - Checks that the `blacklist_domains` table exists in the DB
  128. - Skips if the env var is empty or not set
  129. - Uses `services.security.blacklist_service.merge_and_save_blacklist` to insert/update rows
  130. """
  131. val = os.getenv("BLACKLIST_DOMAINS")
  132. if not val:
  133. logger.info("No BLACKLIST_DOMAINS found in environment; nothing to migrate.")
  134. return
  135. # Trim surrounding quotes if present
  136. if (val.startswith('"') and val.endswith('"')) or (
  137. val.startswith("'") and val.endswith("'")
  138. ):
  139. val = val[1:-1]
  140. items = [d.strip() for d in val.split(",") if d.strip()]
  141. if not items:
  142. logger.info("BLACKLIST_DOMAINS is empty after parsing; nothing to migrate.")
  143. return
  144. # Verify table exists
  145. engine = get_engine()
  146. inspector = inspect(engine)
  147. table_name = BlacklistDomain.__tablename__
  148. if not inspector.has_table(table_name):
  149. logger.error(
  150. f"Table '{table_name}' does not exist in the database. Run migrations first."
  151. )
  152. return
  153. # Confirm with user (or auto-confirm)
  154. logger.info(f"Found {len(items)} domains to migrate into '{table_name}'.")
  155. if not auto_confirm:
  156. ans = input("Proceed with migration? (yes/no): ").strip().lower()
  157. if ans != "yes":
  158. logger.info("Migration cancelled by user.")
  159. return
  160. # Use merge function which will avoid duplicates and reactivate entries
  161. try:
  162. merge_and_save_blacklist(
  163. set(items), source="env_migration", added_by="migrate_env"
  164. )
  165. logger.info("✓ BLACKLIST_DOMAINS migrated into database successfully.")
  166. except Exception:
  167. logger.exception("Failed migrating BLACKLIST_DOMAINS into DB")
  168. return
  169. def show_help():
  170. """Show help message."""
  171. help_text = """
  172. SquidStats Database Management Tool
  173. Commands:
  174. init Initialize database migration tracking (for existing databases)
  175. upgrade Apply pending migrations to the database
  176. downgrade Revert the last migration (use with caution!)
  177. current Show current database migration version
  178. history Show complete migration history
  179. create Create a new migration file
  180. help Show this help message
  181. Examples:
  182. python manage_db.py init # First time setup for existing database
  183. python manage_db.py upgrade # Apply all pending migrations
  184. python manage_db.py current # Check current version
  185. python manage_db.py create "add user email field" # Create new migration
  186. python manage_db.py migrate-env-blacklist # Migrate BLACKLIST_DOMAINS from .env to DB
  187. For more information, see the Alembic documentation:
  188. https://alembic.sqlalchemy.org/
  189. """
  190. print(help_text)
  191. def main():
  192. """Main entry point."""
  193. if len(sys.argv) < 2:
  194. show_help()
  195. sys.exit(1)
  196. command_name = sys.argv[1].lower()
  197. commands = {
  198. "init": init_database,
  199. "upgrade": upgrade_database,
  200. "downgrade": downgrade_database,
  201. "current": show_current,
  202. "history": show_history,
  203. "create": lambda: create_migration(sys.argv[2] if len(sys.argv) > 2 else None),
  204. "migrate-env-blacklist": migrate_env_blacklist,
  205. "help": show_help,
  206. }
  207. if command_name not in commands:
  208. logger.error(f"Unknown command: {command_name}")
  209. show_help()
  210. sys.exit(1)
  211. commands[command_name]()
  212. if __name__ == "__main__":
  213. main()