env.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import asyncio
  2. from logging.config import fileConfig
  3. from sqlalchemy import engine_from_config, pool
  4. from alembic import context
  5. from app.core import config as app_config
  6. # this is the Alembic Config object, which provides
  7. # access to the values within the .ini file in use.
  8. config = context.config
  9. # Interpret the config file for Python logging.
  10. # This line sets up loggers basically.
  11. fileConfig(config.config_file_name) # type: ignore
  12. # add your model's MetaData object here
  13. # for 'autogenerate' support
  14. # from myapp import mymodel
  15. # target_metadata = mymodel.Base.metadata
  16. from app.models import Base # noqa
  17. target_metadata = Base.metadata
  18. # other values from the config, defined by the needs of env.py,
  19. # can be acquired:
  20. # my_important_option = config.get_main_option("my_important_option")
  21. # ... etc.
  22. def get_database_uri():
  23. return app_config.settings.DEFAULT_SQLALCHEMY_DATABASE_URI
  24. def run_migrations_offline():
  25. """Run migrations in 'offline' mode.
  26. This configures the context with just a URL
  27. and not an Engine, though an Engine is acceptable
  28. here as well. By skipping the Engine creation
  29. we don't even need a DBAPI to be available.
  30. Calls to context.execute() here emit the given string to the
  31. script output.
  32. """
  33. url = get_database_uri()
  34. context.configure(
  35. url=url,
  36. target_metadata=target_metadata,
  37. literal_binds=True,
  38. dialect_opts={"paramstyle": "named"},
  39. compare_type=True,
  40. compare_server_default=True,
  41. )
  42. with context.begin_transaction():
  43. context.run_migrations()
  44. def do_run_migrations(connection):
  45. context.configure(
  46. connection=connection, target_metadata=target_metadata, compare_type=True
  47. )
  48. with context.begin_transaction():
  49. context.run_migrations()
  50. async def run_migrations_online():
  51. """Run migrations in 'online' mode.
  52. In this scenario we need to create an Engine
  53. and associate a connection with the context.
  54. """
  55. configuration = config.get_section(config.config_ini_section)
  56. assert configuration
  57. configuration["sqlalchemy.url"] = get_database_uri()
  58. connectable = engine_from_config(
  59. configuration,
  60. prefix="sqlalchemy.",
  61. poolclass=pool.NullPool,
  62. future=True,
  63. ) # type: ignore
  64. with connectable.connect() as connection:
  65. do_run_migrations(connection)
  66. if context.is_offline_mode():
  67. run_migrations_offline()
  68. else:
  69. asyncio.run(run_migrations_online())