env.py 2.3 KB

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