Last active
April 30, 2021 05:56
-
-
Save sheminanto/cbde0911af460d86a3b6a01a75916ada to your computer and use it in GitHub Desktop.
Alembic Settings to Make Migrations Automatically from Models (SQLAlchemy)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from alembic import context | |
from sqlalchemy import pool | |
from sqlalchemy import engine_from_config | |
from logging.config import fileConfig | |
import os | |
import sys | |
sys.path.append(os.getcwd()) | |
if True: | |
from db.models import Base # import Base from your models.py here | |
""" | |
this is the Alembic Config object, which provides | |
access to the values within the .ini file in use. | |
""" | |
config = context.config | |
# Interpret the config file for Python logging. | |
# This line sets up loggers basically. | |
fileConfig(config.config_file_name) | |
""" | |
Add your model's MetaData object herefor 'autogenerate' support | |
""" | |
target_metadata = Base.metadata | |
""" | |
other values from the config, defined by the needs of env.py, can be acquired by | |
my_important_option = config.get_main_option("my_important_option") | |
... etc. | |
""" | |
def run_migrations_offline(): | |
url = config.get_main_option("sqlalchemy.url") | |
context.configure( | |
url=url, | |
target_metadata=target_metadata, | |
literal_binds=True, | |
dialect_opts={"paramstyle": "named"}, | |
) | |
with context.begin_transaction(): | |
context.run_migrations() | |
def run_migrations_online(): | |
connectable = engine_from_config( | |
config.get_section(config.config_ini_section), | |
prefix="sqlalchemy.", | |
poolclass=pool.NullPool, | |
) | |
with connectable.connect() as connection: | |
context.configure( | |
connection=connection, target_metadata=target_metadata | |
) | |
with context.begin_transaction(): | |
context.run_migrations() | |
if context.is_offline_mode(): | |
run_migrations_offline() | |
else: | |
run_migrations_online() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Make migrations | |
alembic revision --autogenerate -m "message" | |
# Migrate to latest version | |
alembic upgrade head |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment