env.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import with_statement
  2. import asyncio
  3. from logging.config import fileConfig
  4. from sqlmodel import SQLModel, create_engine
  5. from alembic import context
  6. import sys
  7. import pathlib
  8. sys.path.append(str(pathlib.Path(__file__).resolve().parents[1]))
  9. from config.database import db_settings
  10. from app.models import * # noqa; necessarily to import something from file where your models are stored
  11. # this is the Alembic Config object, which provides
  12. # access to the values within the .ini file in use.
  13. config = context.config
  14. # Interpret the config file for Python logging.
  15. # This line sets up loggers basically.
  16. fileConfig(config.config_file_name)
  17. target_metadata = SQLModel.metadata
  18. db_url = db_settings.database_url
  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():
  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. context.configure(
  33. url=db_url,
  34. target_metadata=target_metadata,
  35. literal_binds=True,
  36. compare_type=True,
  37. dialect_opts={"paramstyle": "named"},
  38. )
  39. with context.begin_transaction():
  40. context.run_migrations()
  41. async def run_migrations_online():
  42. """Run migrations in 'online' mode.
  43. In this scenario we need to create an Engine
  44. and associate a connection with the context.
  45. """
  46. connectable = create_engine(db_url, echo=True)
  47. with connectable.connect() as connection:
  48. context.configure(connection=connection, target_metadata=target_metadata)
  49. with context.begin_transaction():
  50. context.run_migrations()
  51. if context.is_offline_mode():
  52. run_migrations_offline()
  53. else:
  54. asyncio.run(run_migrations_online())