env.py 2.0 KB

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