迁移后自动删除未使用列上的非空约束 [英] Automatically delete not-null constraints on unused columns after migration
问题描述
我有一个与GORM结合使用的模型:
I have a model which is used in combination with GORM:
type User struct {
gorm.Model
Name string
Age uint
}
当我现在想使用GORM Automigrate命令将 Name
字段与 FirstName
和 LastName
交换时,在下一个错误消息出现要求:
When I now want to exchange the Name
field with FirstName
and LastName
using the GORM Automigrate command I get the following error on the next request:
ERROR: null value in column "name" violates not-null constraint (SQLSTATE 23502)
很显然,AutoMigrate不会破坏用户表中的 Name
列(如docs中所述),但是也不会破坏not null约束,这会使该表在使用后无效.迁移.
Obviously, the AutoMigrate does not destroy the Name
column in the user table (as stated in the docs), but it also does not destroy the not-null constraint, which makes the table useless after migration.
如何自动销毁旧列上的非空约束?
How can I automatically destroy the not-null constraints on old columns?
推荐答案
据我所知,它不能自动完成.
It can't be done automatically as far as I can see.
您注意到,gorm不会删除表中的旧列,因此实质上,一旦删除了该字段,gorm就会忽略该列.清楚的是,在某些时候您已经用 gorm标记了
或不会施加该约束.因此,您可能会撤消的一种方法是恢复旧字段,但删除 Name
字段:"not null" not null
标记,然后运行迁移.这将删除非null约束.然后删除该字段,然后再次运行迁移.绝不是自动的.
As you note, gorm will not delete old columns in the table so in essence once you delete the field, gorm forgets about the column. What's clear is that at some point you had tagged your Name
field with gorm:"not null"
or that constraint wouldn't have been put on.
So one way you might reverse that would be to reinstate the old field, but remove the not null
tag, and run the migration. That will remove the not null constraint. Then remove the field, and run the migration again. Not automatic by any means.
您可能还会考虑使用迁移器创建自己的迁移删除约束甚至完全删除列的脚本.
You might also look at using the migrator to create your own migration script that drops the constraint or even drops the column entirely.
在我的拙见中,Gorm的自动迁移功能是目前仅适用于快速原型制作的功能.我认为除了玩具应用程序之外,它不能替代任何适当的迁移系统;迟早您会遇到这些问题,这些问题迫使您自己编写仔细的迁移脚本.要查找的软件包包括 github.com/pressly/goose
或 github.com/golang-migrate/migrate
.
In my humble opinion Gorm's auto-migrations is a feature that for now is only good for quick prototyping. I don't think it can replace a proper migration system in anything more than a toy app; sooner or later you run into these problems that force you to write careful migration scripts yourself. Packages to look at for that include github.com/pressly/goose
or github.com/golang-migrate/migrate
.
这篇关于迁移后自动删除未使用列上的非空约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!