Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing null (or empty string values in the db)

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.

like image 611
Joff Avatar asked Dec 14 '22 23:12

Joff


1 Answers

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.

like image 169
Umar Hayat Avatar answered Jan 11 '23 11:01

Umar Hayat