【发布时间】:2014-04-01 10:45:07
【问题描述】:
alembic upgrade head 是否在事务中运行,以便所有数据库更改成功或失败?如果不是,为什么要这样设计?
【问题讨论】:
标签: transactions database-migration alembic
alembic upgrade head 是否在事务中运行,以便所有数据库更改成功或失败?如果不是,为什么要这样设计?
【问题讨论】:
标签: transactions database-migration alembic
我的理解是,alembic 在支持它的数据库(如 Postgres)的事务中运行。如果您使用的数据库不支持此功能(cough MySQL cough),则无法使用此功能。
【讨论】:
ALTER/CREATE/DROP TABLE 之类的 MySQL DDL 命令会自动提交任何正在进行的事务,因此根本不使用事务通常“更安全”(至少,更可预测)。换句话说,架构更改不包含在事务中。
CREATE TABLE,它在迁移失败后仍然存在。我认为这是因为"if you are within a transaction and issue a command like CREATE TABLE ..., VACUUM, PRAGMA, the sqlite3 module will commit implicitly before executing that command. There are two reasons for doing that. The first is that some of these commands don’t work within transactions.".
您可以在 env.py 中决定这一点,您可以在其中自定义迁移的行为以适应您的设置。您可以从作为通用数据库示例提供的模板中了解如何确保您的升级发生在事务中:https://github.com/zzzeek/alembic/blob/eaaafbca88f85f5432e04affe1f94cbf1ad06080/alembic/templates/generic/env.py#L64
def run_migrations_online():
# ...
with context.begin_transaction():
context.run_migrations()
【讨论】: