'GO pg prevent default value
Struct sample
type Car struct {
ID uint64
Required bool `pg:"required,notnull"`
Name string `pg:"name"`
}
Migration:
BEGIN;
ALTER TABLE cars ADD COLUMN required BOOLEAN NOT NULL DEFAULT true;
END;
When I create car struct:
car = Car{Name:"Name",Required:false}
When i'm trying to add some new car by writing:
_, err = r.db.Model(&car).Insert()
SQL Query looks like this:
INSERT INTO "cars" ("id", "name", "required") VALUES (DEFAULT, "Name", DEFAULT)
The main problem that car has required field set as false, but when I inserting it - it changes to DEFAULT (true).
Solution 1:[1]
Because the value false will be read as a null value. Because null value your data will be change to the default value (TRUE)
You must change the struct to like this
type Car struct {
ID uint64
Required *bool `pg:"required,notnull,default:true"`
Name string `pg:"name"`
}
and define struct like this
required := false
car = Car{Name:"Name", Required: &required}
or you can also use data type sql.NullBool in your struct
type Car struct {
ID uint64
Required sql.NullBool `pg:"required,notnull,default:true"`
Name string `pg:"name"`
}
car = Car{Name:"Name", Required: sql.NullBool{Bool: false, Valid: true}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
