cond_or.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 condOr []Cond
  7. var _ Cond = condOr{}
  8. // Or sets OR conditions
  9. func Or(conds ...Cond) Cond {
  10. var result = make(condOr, 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. // WriteTo implments Cond
  20. func (o condOr) WriteTo(w Writer) error {
  21. for i, cond := range o {
  22. var needQuote bool
  23. switch cond.(type) {
  24. case condAnd, expr:
  25. needQuote = true
  26. case Eq:
  27. needQuote = (len(cond.(Eq)) > 1)
  28. case Neq:
  29. needQuote = (len(cond.(Neq)) > 1)
  30. }
  31. if needQuote {
  32. fmt.Fprint(w, "(")
  33. }
  34. err := cond.WriteTo(w)
  35. if err != nil {
  36. return err
  37. }
  38. if needQuote {
  39. fmt.Fprint(w, ")")
  40. }
  41. if i != len(o)-1 {
  42. fmt.Fprint(w, " OR ")
  43. }
  44. }
  45. return nil
  46. }
  47. func (o condOr) And(conds ...Cond) Cond {
  48. return And(o, And(conds...))
  49. }
  50. func (o condOr) Or(conds ...Cond) Cond {
  51. return Or(o, Or(conds...))
  52. }
  53. func (o condOr) IsValid() bool {
  54. return len(o) > 0
  55. }