cond_or.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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:
  25. needQuote = true
  26. case Eq:
  27. needQuote = (len(cond.(Eq)) > 1)
  28. }
  29. if needQuote {
  30. fmt.Fprint(w, "(")
  31. }
  32. err := cond.WriteTo(w)
  33. if err != nil {
  34. return err
  35. }
  36. if needQuote {
  37. fmt.Fprint(w, ")")
  38. }
  39. if i != len(o)-1 {
  40. fmt.Fprint(w, " OR ")
  41. }
  42. }
  43. return nil
  44. }
  45. func (o condOr) And(conds ...Cond) Cond {
  46. return And(o, And(conds...))
  47. }
  48. func (o condOr) Or(conds ...Cond) Cond {
  49. return Or(o, Or(conds...))
  50. }
  51. func (o condOr) IsValid() bool {
  52. return len(o) > 0
  53. }