每个DDL SQL命令都是可逆的吗? [数据库版本控制]
时间:2020-03-06 14:40:10 来源:igfitidea点击:
我想设置一种跟踪数据库架构更改的机制,例如此答案中描述的一种:
For every change you make to the database, you write a new migration. Migrations typically have two methods: an "up" method in which the changes are applied and a "down" method in which the changes are undone. A single command brings the database up to date, and can also be used to bring the database to a specific version of the schema.
我的问题如下:"向上"方法中的每个DDL命令都是可逆的吗?换句话说,我们可以始终提供"下降"方法吗?我们能想象任何无法"关闭"的DDL命令吗?
请不要考虑" up"方法中数据丢失的典型数据迁移问题:将字段类型从" datetime"(" DateOfBirth")更改为" int"(" YearOfBirth"),我们丢失的数据无法恢复。
解决方案
在SQL Server中,我知道的每个DDL命令都是上/下对。
除了丢失数据之外,我所做的每一次迁移都是可逆的。也就是说,Rails提供了一种将迁移标记为"破坏性"的方法:
Some transformations are destructive in a manner that cannot be reversed. Migrations of that kind should raise an ActiveRecord::IrreversibleMigration exception in their down method.
请参阅此处的API文档。
是的,我们已经确定了丢失数据的情况,可以通过转换数据或者仅在"向上"迁移中删除DROP COLUMN来确定。
另一个示例是,我们可以删除SEQUENCE对象,从而丢失其状态。 "向下"迁移将重新创建序列,但它将从1开始。这可能导致序列生成重复的值。如果我们要在一个空的数据库上执行迁移,并且无论如何都希望序列从1开始不是问题,但是如果我们有一定数量的数据行,则希望将该序列重置为最大值当前正在使用,很难可靠地执行此操作,除非我们对该表具有排他锁。
依赖于数据库中数据状态的任何其他DDL都有类似的问题。首先,这可能不是一个好的模式设计,我只是想考虑适合我们问题的任何情况。