Skip to content
This repository was archived by the owner on Jun 14, 2019. It is now read-only.

Commit 2d4759f

Browse files
authored
add CondIf interface (#53)
* add CondIf interface * fix comment
1 parent 1d658d7 commit 2d4759f

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

cond_if.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Copyright 2019 The Xorm Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package builder
6+
7+
type condIf struct {
8+
condition bool
9+
condTrue Cond
10+
condFalse Cond
11+
}
12+
13+
var _ Cond = condIf{}
14+
15+
// If returns Cond via condition
16+
func If(condition bool, condTrue Cond, condFalse ...Cond) Cond {
17+
var c = condIf{
18+
condition: condition,
19+
condTrue: condTrue,
20+
}
21+
if len(condFalse) > 0 {
22+
c.condFalse = condFalse[0]
23+
}
24+
return c
25+
}
26+
27+
func (condIf condIf) WriteTo(w Writer) error {
28+
if condIf.condition {
29+
return condIf.condTrue.WriteTo(w)
30+
} else if condIf.condFalse != nil {
31+
return condIf.condFalse.WriteTo(w)
32+
}
33+
return nil
34+
}
35+
36+
func (condIf condIf) And(conds ...Cond) Cond {
37+
return And(condIf, And(conds...))
38+
}
39+
40+
func (condIf condIf) Or(conds ...Cond) Cond {
41+
return Or(condIf, Or(conds...))
42+
}
43+
44+
func (condIf condIf) IsValid() bool {
45+
return condIf.condTrue != nil
46+
}

cond_if_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2019 The Xorm Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package builder
6+
7+
import (
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestCond_If(t *testing.T) {
14+
var cond = If(1 > 0, Eq{"a": 1}, Eq{"b": 1})
15+
sql, err := ToBoundSQL(cond)
16+
assert.NoError(t, err)
17+
assert.EqualValues(t, "a=1", sql)
18+
19+
cond = If(1 < 0, Eq{"a": 1}, Eq{"b": 1})
20+
sql, err = ToBoundSQL(cond)
21+
assert.NoError(t, err)
22+
assert.EqualValues(t, "b=1", sql)
23+
24+
cond = If(1 > 0, cond, Eq{"c": 1})
25+
sql, err = ToBoundSQL(cond)
26+
assert.NoError(t, err)
27+
assert.EqualValues(t, "b=1", sql)
28+
}

0 commit comments

Comments
 (0)