Alembic 未生成正确的更改

Alembic not generating correct changes

我正在使用 Flask-Migrate==2.0.0。它没有正确检测到变化。每次我 运行 python manage db migrate 它都会为所有模型生成一个脚本,尽管它们已在以前的版本中成功添加。我在 table 中添加了两个新列,迁移修订版应该只有这两个新列,而不是所有 table 都添加到其中。有什么我想念的吗?

编辑 1

事情是这样的。 我将 Flask_Migrate 添加到我的项目中。

python manage db init
python manage db migrate
python manage db upgrade

Flask-Migrate 为模型生成 tables 加上 alembic_version table 具有修订

985efbf37786

之后我做了一些修改。我在我的 table 和 运行 命令之一中添加了两个新列

python manage db migrate

它生成了新的修订版

934ba2ddbd44

但不是只添加这两个新列,修订版包含所有 table 的脚本以及这两个新列。因此,例如在我的第一次修订中,我有这样的东西

op.create_table('forex_costs',
sa.Column('code', sa.String(), nullable=False),
sa.Column('country', sa.String(), nullable=False),
sa.Column('rate', sa.Numeric(), nullable=False),
sa.PrimaryKeyConstraint('code', 'country', name='forex_costs_id'),
schema='regis'
)

第二次修订也包含完全相同的代码。我不明白为什么它已经生成了。

我用谷歌搜索了一下,我的问题看起来完全像这样 https://github.com/miguelgrinberg/Flask-Migrate/issues/93 但我没有使用 oracle DB。我正在使用 PostgreSQL。我也不知道它是否有任何影响,但我没有在默认 Public 架构中创建我的 tables,而是创建了两个新架构(schema_a 和 schema_b) 因为我有很多 tables(大约 100)。所以只是安排他们。

编辑 2

第一个问题似乎已通过添加

解决

include_schemas=True

在 env.py 中。

现在新的迁移不再尝试创建已经存在的 table,但是它在 外键 方面存在一些问题。每次我创建一个新的修订版时,它都会尝试删除已经存在的外键,然后尝试添加它们。日志看起来像这样

INFO  [alembic.autogenerate.compare] Detected removed foreign key (post_id)(post_id) on table album_photos
INFO  [alembic.autogenerate.compare] Detected removed foreign key (album_id)(album_id) on table album_photos
INFO  [alembic.autogenerate.compare] Detected removed foreign key (user_id)(user_id) on table album_photos
INFO  [alembic.autogenerate.compare] Detected added foreign key (album_id)(album_id) on table prodcat.album_photos
INFO  [alembic.autogenerate.compare] Detected added foreign key (post_id)(post_id) on table prodcat.album_photos
INFO  [alembic.autogenerate.compare] Detected added foreign key (user_id)(user_id) on table prodcat.album_photos

我已经尝试为每个外键约束添加名称,但这没有任何效果。

将 search_path 设置为 public 解决了这个问题。我一直认为除了在每个模型上显式设置模式信息外,我们还需要在 search_path 上添加这些模式。我错了。一旦在每个模型上明确定义了模式,就没有必要更改 postgresql search_path。

The search path means that reflected foreign key definitions will not match what you have in your model. This only applies to foreign keys because that's how Postgresql does it. Read through http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#remote-schema-table-introspection-and-postgresql-search-path for background. - Michael Bayer

感谢您在解决问题后回来提供反馈。使用 postgres

时,我为同样的问题苦恼了 2 个小时

顺便说一句,我想指出您必须在块 context.configure 中包含 include_schemas 选项,如下所示:

context.configure(connection=connection,
                  target_metadata=target_metadata,
                  include_schemas=True,
                  process_revision_directives=process_revision_directives,
                  **current_app.extensions['migrate'].configure_args)