【发布时间】:2017-05-11 15:08:39
【问题描述】:
我们正在使用 SQLAlchemy 和 Alembic(以及 Flask-SQLAlchemy 和 Flask-Migrate)。如何检查是否有待处理的迁移?
我尝试查看 Alembic 和 Flask-Migrate 的文档,但没有找到答案。
【问题讨论】:
标签: python sqlalchemy flask-sqlalchemy alembic flask-migrate
我们正在使用 SQLAlchemy 和 Alembic(以及 Flask-SQLAlchemy 和 Flask-Migrate)。如何检查是否有待处理的迁移?
我尝试查看 Alembic 和 Flask-Migrate 的文档,但没有找到答案。
【问题讨论】:
标签: python sqlalchemy flask-sqlalchemy alembic flask-migrate
您可以使用current 子命令确定您的项目是否为最新迁移:
最新迁移时的示例输出:
(venv) $ python app.py db current
f4b4aa1dedfd (head)
关键是出现在修订号之后的(head)。这告诉您这是最近的迁移。
以下是我添加新迁移后、升级数据库之前的变化:
(venv) $ python app.py db current
f4b4aa1dedfd
在我运行db upgrade 之后,我得到:
(venv) $ python app.py db current
f3cd9734f9a3 (head)
希望这会有所帮助!
【讨论】:
# flask db current 给了我INFO [alembic.runtime.migration] Context impl MySQLImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL.
8ca18d2d21bf (head)被附加到上面
您可以通过以下方式以编程方式进行操作:
from alembic import config
from alembic import script
from alembic.runtime import migration
import sqlalchemy
import exceptions
engine = sqlalchemy.create_engine(DATABASE_URL)
alembic_cfg = config.Config('alembic.ini')
script_ = script.ScriptDirectory.from_config(alembic_cfg)
with engine.begin() as conn:
context = migration.MigrationContext.configure(conn)
if context.get_current_revision() != script_.get_current_head():
raise exceptions.DatabaseIsNotUpToDate('Upgrade the database.')
我还发布了gist with this check。
【讨论】:
有一个工具可以解决这个问题https://github.com/4Catalyzer/alembic-autogen-check
像这样工作
$ > alembic-autogen-check
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
INFO [alembic.autogenerate.compare] Detected NULL on column 'user.is_superuser'
ERROR: Migrations are out of sync with models. Diff:
[ [ ( 'modify_nullable',
None,
'user',
'is_superuser',
{ 'existing_comment': None,
'existing_server_default': False,
'existing_type': BOOLEAN()},
False,
True)]]
You may need to run `PYTHONPATH=. alembic revision --autogenerate -m 'Your message'`.
【讨论】: