I'm using PostgreSQL and GORM in my Go app.
I thought that using the sql tab of sql:"not null"
would do the trick of preventing a null entry, but when go initializes structs with a string type then it defaults to an empty string which is not the same as null in the db.
I am wondering if there is a way to prevent this from happening in a struct definition so I wouldn't have to strictly enforce it at all levels in the application code.
You can solve this problem of preventing '' (empty) string insertion into the database by using default: null
and not null
constraint together. SO if Struct field values are empty it will be consider as default value null
and gorm will throw an error.
gorm:"unique;not null;type:varchar(100);default:null"
Example is:
type User struct {
gorm.Model
Email string `gorm:"unique;not null;type:varchar(100);default:null"`
}
SO gorm for empty User.Email
will throw an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With