env.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. """Alembic environment configuration for SquidStats.
  2. This module configures Alembic to work with the SquidStats database models
  3. and supports multiple database backends (SQLite, MySQL/MariaDB, PostgreSQL).
  4. """
  5. import os
  6. # Import the database configuration and models
  7. import sys
  8. from logging.config import fileConfig
  9. from sqlalchemy import engine_from_config, pool
  10. from alembic import context
  11. # Add the project root to the path
  12. sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
  13. from config import Config
  14. # Import all models to ensure they're registered with Base.metadata
  15. from database.database import (
  16. Base,
  17. get_database_url,
  18. )
  19. # this is the Alembic Config object, which provides
  20. # access to the values within the .ini file in use.
  21. config = context.config
  22. # Interpret the config file for Python logging.
  23. # This line sets up loggers basically.
  24. if config.config_file_name is not None:
  25. fileConfig(config.config_file_name)
  26. # add your model's MetaData object here
  27. # for 'autogenerate' support
  28. target_metadata = Base.metadata
  29. # other values from the config, defined by the needs of env.py,
  30. # can be acquired:
  31. # my_important_option = config.get_main_option("my_important_option")
  32. # ... etc.
  33. def get_url():
  34. """Get database URL from application configuration."""
  35. return get_database_url()
  36. def run_migrations_offline() -> None:
  37. """Run migrations in 'offline' mode.
  38. This configures the context with just a URL
  39. and not an Engine, though an Engine is acceptable
  40. here as well. By skipping the Engine creation
  41. we don't even need a DBAPI to be available.
  42. Calls to context.execute() here emit the given string to the
  43. script output.
  44. """
  45. url = get_url()
  46. context.configure(
  47. url=url,
  48. target_metadata=target_metadata,
  49. literal_binds=True,
  50. dialect_opts={"paramstyle": "named"},
  51. # Include object names for better migration tracking
  52. include_object=include_object,
  53. compare_type=True,
  54. compare_server_default=True,
  55. )
  56. with context.begin_transaction():
  57. context.run_migrations()
  58. def include_object(object, name, type_, reflected, compare_to):
  59. """Filter which database objects to include in migrations.
  60. This function excludes dynamic tables (user_YYYYMMDD, log_YYYYMMDD)
  61. from automatic migrations since they are created programmatically.
  62. """
  63. # Exclude dynamic tables from migrations
  64. if type_ == "table":
  65. # Skip daily user and log tables (they're created dynamically)
  66. if name.startswith("user_") and name[5:].isdigit() and len(name) == 13:
  67. return False
  68. if name.startswith("log_") and name[4:].isdigit() and len(name) == 12:
  69. return False
  70. return True
  71. def run_migrations_online() -> None:
  72. """Run migrations in 'online' mode.
  73. In this scenario we need to create an Engine
  74. and associate a connection with the context.
  75. """
  76. # Override the sqlalchemy.url in alembic.ini with our dynamic URL
  77. configuration = config.get_section(config.config_ini_section)
  78. configuration["sqlalchemy.url"] = get_url()
  79. connectable = engine_from_config(
  80. configuration,
  81. prefix="sqlalchemy.",
  82. poolclass=pool.NullPool,
  83. )
  84. with connectable.connect() as connection:
  85. context.configure(
  86. connection=connection,
  87. target_metadata=target_metadata,
  88. # Include object names for better migration tracking
  89. include_object=include_object,
  90. # Compare types to detect schema changes
  91. compare_type=True,
  92. # Compare server defaults
  93. compare_server_default=True,
  94. # Render as batch for SQLite support
  95. render_as_batch=Config.DATABASE_TYPE == "SQLITE",
  96. )
  97. with context.begin_transaction():
  98. context.run_migrations()
  99. if context.is_offline_mode():
  100. run_migrations_offline()
  101. else:
  102. run_migrations_online()