I have a model which is used in combination with GORM:
type User struct {
gorm.Model
Name string
Age uint
}
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)
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.
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.
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
.