gen
gen copied to clipboard
I can't make OR clause work, maybe is there a bug?
GORM Playground Link
https://github.com/go-gorm/playground/pull/1
Description
I want to query using an or clause, but at the end is AND concatenating my conditions,
Imagine I have the following struct:
type MyStruct struct {
StartTime time.Time
DecommisionTime *time.Time
}
and I want to query all my structs that are valid for a timestamp, using the timestamp: 2023-01-01 00:00:00) the query would be something like this:
SELECT count(*) FROM "my_structs" WHERE
("decommission_time" IS NULL OR "decommission_time" > '2023-01-01 00:00:00')
AND "start_time" < '2023-01-01 00:00:00'
But then, if I try to use gen for this, in the following way:
var conditions = make([]gen.Condition, 2)
conditions = append(conditions, query.MyStruct.Or(query.MyStruct.DecommissionTime.IsNull(), query.MyStruct.DecommissionTime.Gt(period.StartTime)))
conditions = append(conditions, query.MyStruct.DeployTime.Lt(*period.EndTime))
return query.MyStruct.Debug().Where(conditions...).Count()
I get all the conditions with AND.
SELECT count(*) FROM "my_structs" WHERE "my_structs"."decommission_time" IS NULL AND "my_structs"."decommission_time" > '2023-01-01 00:00:00' AND "my_structs"."deploy_time" < '2023-01-01 00:00:00'
I checked the code and I see this in do.go:
return d.getInstance(d.db.Clauses(clause.Where{Exprs: []clause.Expression{clause.Or(clause.And(exprs...))}}))
Am I using the or condition wrong?
I'm not sure if there's a Or
method on your generated MyStruct
class.
But refering to gen doc, it seems you can group your conditions like:
query.MyStruct.Where(
// the first condition including an "OR"
query.MyStruct.
Where(query.MyStruct.DecommissionTime.IsNull()).
Or(query.MyStruct.DecommissionTime.Gt(period.StartTime)),
// the second condition, combined with the first one with an "AND"
query.MyStruct.DeployTime.Lt(*period.EndTime).
)