4
votes

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.

1
An empty string is the "not null" version of a string, no? - Cetin Basoz
its not enforcing it for me..If I got to my db manually and try to enter a null field then it says it violates not null constraint, but if I enter '' then it accepts it - Joff
@deltaskelta: That's exactly what it should do. What's your question? - Flimzy
the last line of my question is what I am asking. Is there a way to prevent an empty string from being valid without strictly enforcing it through application code? - Joff
No, there's no way within a struct definition to specify that some specific value is invalid. - Flimzy

1 Answers

11
votes

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.