cond_and.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. _, isExpr := cond.(expr)
  23. wrap := isOr || isExpr
  24. if wrap {
  25. fmt.Fprint(w, "(")
  26. }
  27. err := cond.WriteTo(w)
  28. if err != nil {
  29. return err
  30. }
  31. if wrap {
  32. fmt.Fprint(w, ")")
  33. }
  34. if i != len(and)-1 {
  35. fmt.Fprint(w, " AND ")
  36. }
  37. }
  38. return nil
  39. }
  40. func (and condAnd) And(conds ...Cond) Cond {
  41. return And(and, And(conds...))
  42. }
  43. func (and condAnd) Or(conds ...Cond) Cond {
  44. return Or(and, Or(conds...))
  45. }
  46. func (and condAnd) IsValid() bool {
  47. return len(and) > 0
  48. }