Skip to content
This repository was archived by the owner on Jun 14, 2019. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions cond_if.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package builder

type condIf struct {
condition bool
condTrue Cond
condFalse Cond
}

var _ Cond = condIf{}

// If returns Cond via condition
func If(condition bool, condTrue Cond, condFalse ...Cond) Cond {
var c = condIf{
condition: condition,
condTrue: condTrue,
}
if len(condFalse) > 0 {
c.condFalse = condFalse[0]
}
return c
}

func (condIf condIf) WriteTo(w Writer) error {
if condIf.condition {
return condIf.condTrue.WriteTo(w)
} else if condIf.condFalse != nil {
return condIf.condFalse.WriteTo(w)
}
return nil
}

func (condIf condIf) And(conds ...Cond) Cond {
return And(condIf, And(conds...))
}

func (condIf condIf) Or(conds ...Cond) Cond {
return Or(condIf, Or(conds...))
}

func (condIf condIf) IsValid() bool {
return condIf.condTrue != nil
}
28 changes: 28 additions & 0 deletions cond_if_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package builder

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestCond_If(t *testing.T) {
var cond = If(1 > 0, Eq{"a": 1}, Eq{"b": 1})
sql, err := ToBoundSQL(cond)
assert.NoError(t, err)
assert.EqualValues(t, "a=1", sql)

cond = If(1 < 0, Eq{"a": 1}, Eq{"b": 1})
sql, err = ToBoundSQL(cond)
assert.NoError(t, err)
assert.EqualValues(t, "b=1", sql)

cond = If(1 > 0, cond, Eq{"c": 1})
sql, err = ToBoundSQL(cond)
assert.NoError(t, err)
assert.EqualValues(t, "b=1", sql)
}