【发布时间】:2018-11-30 21:42:34
【问题描述】:
我将 alembic 与 flask-migrate 以及 Postgres 一起用于我的数据库。我已经运行了 db init 和 db migrate。但是,当我运行 db upgrade 命令时,出现以下错误:
cursor.execute(statement, parameters)
psycopg2.ProgrammingError: relation "event" does not exist
The above exception was the direct cause of the following exception:
我非常清楚为什么会发生错误。该脚本正在尝试创建参与者表,该表引用稍后在脚本中创建的事件表。
我的问题是我有很多关系,我认为重新排列脚本中的每个表以构建它是没有意义的。只要这些关系都在脚本中定义,alembic 和 flask-migrate 不应该能够执行一个标准的创建表脚本来列出多个关系而不会失败。这是我的 Alembic 脚本,做了一些修改。
op.create_table('attendee',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False),
sa.Column('event_plan_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['event_id'], ['event.id'], ),
sa.ForeignKeyConstraint(['event_plan_id'], ['event_plan.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('event',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_name', sa.String(length=128), nullable=False),
sa.Column('description', sa.String(length=128), nullable=False),
sa.Column('organizer_id', sa.Integer(), nullable=False),
sa.Column('location_id', sa.Integer(), nullable=False),
sa.Column('attendee_id', sa.Integer(), nullable=False),
sa.Column('group_chat_id', sa.Integer(), nullable=False),
sa.Column('event_type_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['attendee_id'], ['attendee.id'], ),
sa.ForeignKeyConstraint(['event_type_id'], ['event_type.id'], ),
sa.ForeignKeyConstraint(['group_chat_id'], ['group_chat.id'], ),
sa.ForeignKeyConstraint(['location_id'], ['location.id'], ),
sa.ForeignKeyConstraint(['organizer_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
要回答一个明显的问题,如果我在表格创建脚本中移动,它会在不同的表格中失败,因为与会者引用了 3 个其他表格,而这些表格也引用了其他表格,如果它们首先创建,则会失败。
【问题讨论】:
-
通常 PostgreSQL 数据库创建脚本(包括内置的导出/导入工具 - pg_dump)将它们的工作分为 3 个阶段 - 预数据(没有外键的表、函数、检查约束)、数据(插入)、后数据(外键、主键、索引、视图、物化视图等)。这样他们就可以避免你的问题。我不知道 Alembic 数据迁移,但应该可以让它像这样工作。
标签: postgresql alembic flask-migrate