Querying for bool struct elements via Struct does not generate correct query, omiting boolean part completely:
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"fmt"
)
type Message struct {
gorm.Model
Content string
Sth int
Sent bool
}
func main() {
db, err := gorm.Open("sqlite3", `test.db`)
if err != nil { fmt.Println(err)}
defer db.Close()
db.LogMode(true)
db.AutoMigrate(&Message{})
var m Message
db.Where(&Message{Content: "ttt",Sth: 5,Sent: false}).Find(&m)
db.Where(&Message{Sent: false}).Find(&m)
}
results in
(/home/xani/src/things/gorm_test/main.go:23)
[2017-04-20 14:36:46] [0.17ms] SELECT * FROM "messages" WHERE "messages".deleted_at IS NULL AND (("content" = 'ttt') AND ("sth" = '5'))
(/home/xani/src/things/gorm_test/main.go:24)
[2017-04-20 14:36:46] [0.87ms] SELECT * FROM "messages" WHERE "messages".deleted_at IS NULL
using go1.7.3/sqlite
False is the zero value of a boolean, so it gets ignored in the struct. If you want to search for a zero value you need to do something like db.Where("sent = ?", false).Find(&m).
http://jinzhu.me/gorm/crud.html#query-with-where-struct--map
@jinzhu cool but there is nothing in the doc about it
"GORM will only query with those fields has value"
int: 0 "has value"
bool: false "has value"
It probably should say "GORM will only query with those fields has non-default value"
@XANi Non-zero is probably better than non-default, default _could_ be something that's not a zero value.
@jbfm empty string is default but not zero, to give one example. Pointer will be nil too. Non-zero is only for numeric types (and time I guess).
@XANi An empty string is called a zero value in Golang. The zero value is simply what you get if you declare a variable and don't assign it a value on your own, and depends on the type of the variable.
I think this is a HUGE problem as I have to rewrite the entire codebase to have "strings" instead of booleans to prevent _false_ true and _false_ false (_love to say that_).
With Where it is excluding properties to be filtered, when those are set to false in the query.
It seems that this is impacting also when saving/updating and creating... Any suggestion? Is there a specific Type to prevent this and have real booleans?
In case please update the documentation to include examples to workaround
Hi All
Thank you for all your input, updated the document a little bit. http://gorm.io/crud.html#query-with-where-struct--map
Most helpful comment
@jinzhu cool but there is nothing in the doc about it
int: 0 "has value"
bool: false "has value"
It probably should say "GORM will only query with those fields has non-default value"