From 34e2b26b99d377af4d15e261085dba0350e2ecd3 Mon Sep 17 00:00:00 2001 From: Dusan Kasan Date: Mon, 28 Nov 2016 09:49:06 +0100 Subject: [PATCH] resolves #2291, introduces AndNotCond/OrNotCond to orm.Condition --- orm/orm_conds.go | 26 ++++++++++++++++++++++++++ orm/orm_test.go | 10 ++++++++++ 2 files changed, 36 insertions(+) diff --git a/orm/orm_conds.go b/orm/orm_conds.go index e56d6fbb..f6e389ec 100644 --- a/orm/orm_conds.go +++ b/orm/orm_conds.go @@ -75,6 +75,19 @@ func (c *Condition) AndCond(cond *Condition) *Condition { return c } +// AndNotCond combine a AND NOT condition to current condition +func (c *Condition) AndNotCond(cond *Condition) *Condition { + c = c.clone() + if c == cond { + panic(fmt.Errorf(" cannot use self as sub cond")) + } + + if cond != nil { + c.params = append(c.params, condValue{cond: cond, isCond: true, isNot: true}) + } + return c +} + // Or add OR expression to condition func (c Condition) Or(expr string, args ...interface{}) *Condition { if expr == "" || len(args) == 0 { @@ -105,6 +118,19 @@ func (c *Condition) OrCond(cond *Condition) *Condition { return c } +// OrNotCond combine a OR NOT condition to current condition +func (c *Condition) OrNotCond(cond *Condition) *Condition { + c = c.clone() + if c == cond { + panic(fmt.Errorf(" cannot use self as sub cond")) + } + + if cond != nil { + c.params = append(c.params, condValue{cond: cond, isCond: true, isNot: true, isOr: true}) + } + return c +} + // IsEmpty check the condition arguments are empty or not. func (c *Condition) IsEmpty() bool { return len(c.params) == 0 diff --git a/orm/orm_test.go b/orm/orm_test.go index fbf4768d..adfe0066 100644 --- a/orm/orm_test.go +++ b/orm/orm_test.go @@ -909,6 +909,16 @@ func TestSetCond(t *testing.T) { num, err = qs.SetCond(cond2).Count() throwFail(t, err) throwFail(t, AssertIs(num, 2)) + + cond3 := cond.AndNotCond(cond.And("status__in", 1)) + num, err = qs.SetCond(cond3).Count() + throwFail(t, err) + throwFail(t, AssertIs(num, 2)) + + cond4 := cond.And("user_name", "slene").OrNotCond(cond.And("user_name", "slene")) + num, err = qs.SetCond(cond4).Count() + throwFail(t, err) + throwFail(t, AssertIs(num, 3)) } func TestLimit(t *testing.T) {