cond_and.go 1009 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2016 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. package builder
  5. import "fmt"
  6. type condAnd []Cond
  7. var _ Cond = condAnd{}
  8. // And generates AND conditions
  9. func And(conds ...Cond) Cond {
  10. var result = make(condAnd, 0, len(conds))
  11. for _, cond := range conds {
  12. if cond == nil || !cond.IsValid() {
  13. continue
  14. }
  15. result = append(result, cond)
  16. }
  17. return result
  18. }
  19. func (and condAnd) WriteTo(w Writer) error {
  20. for i, cond := range and {
  21. _, isOr := cond.(condOr)
  22. if isOr {
  23. fmt.Fprint(w, "(")
  24. }
  25. err := cond.WriteTo(w)
  26. if err != nil {
  27. return err
  28. }
  29. if isOr {
  30. fmt.Fprint(w, ")")
  31. }
  32. if i != len(and)-1 {
  33. fmt.Fprint(w, " AND ")
  34. }
  35. }
  36. return nil
  37. }
  38. func (and condAnd) And(conds ...Cond) Cond {
  39. return And(and, And(conds...))
  40. }
  41. func (and condAnd) Or(conds ...Cond) Cond {
  42. return Or(and, Or(conds...))
  43. }
  44. func (and condAnd) IsValid() bool {
  45. return len(and) > 0
  46. }