cond_eq.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. // Incr implements a type used by Eq
  7. type Incr int
  8. // Decr implements a type used by Eq
  9. type Decr int
  10. // Eq defines equals conditions
  11. type Eq map[string]interface{}
  12. var _ Cond = Eq{}
  13. func (eq Eq) opWriteTo(op string, w Writer) error {
  14. var i = 0
  15. for k, v := range eq {
  16. switch v.(type) {
  17. case []int, []int64, []string, []int32, []int16, []int8, []uint, []uint64, []uint32, []uint16, []interface{}:
  18. if err := In(k, v).WriteTo(w); err != nil {
  19. return err
  20. }
  21. case expr:
  22. if _, err := fmt.Fprintf(w, "%s=(", k); err != nil {
  23. return err
  24. }
  25. if err := v.(expr).WriteTo(w); err != nil {
  26. return err
  27. }
  28. if _, err := fmt.Fprintf(w, ")"); err != nil {
  29. return err
  30. }
  31. case *Builder:
  32. if _, err := fmt.Fprintf(w, "%s=(", k); err != nil {
  33. return err
  34. }
  35. if err := v.(*Builder).WriteTo(w); err != nil {
  36. return err
  37. }
  38. if _, err := fmt.Fprintf(w, ")"); err != nil {
  39. return err
  40. }
  41. case Incr:
  42. if _, err := fmt.Fprintf(w, "%s=%s+?", k, k); err != nil {
  43. return err
  44. }
  45. w.Append(int(v.(Incr)))
  46. case Decr:
  47. if _, err := fmt.Fprintf(w, "%s=%s-?", k, k); err != nil {
  48. return err
  49. }
  50. w.Append(int(v.(Decr)))
  51. default:
  52. if _, err := fmt.Fprintf(w, "%s=?", k); err != nil {
  53. return err
  54. }
  55. w.Append(v)
  56. }
  57. if i != len(eq)-1 {
  58. if _, err := fmt.Fprint(w, op); err != nil {
  59. return err
  60. }
  61. }
  62. i = i + 1
  63. }
  64. return nil
  65. }
  66. // WriteTo writes SQL to Writer
  67. func (eq Eq) WriteTo(w Writer) error {
  68. return eq.opWriteTo(" AND ", w)
  69. }
  70. // And implements And with other conditions
  71. func (eq Eq) And(conds ...Cond) Cond {
  72. return And(eq, And(conds...))
  73. }
  74. // Or implements Or with other conditions
  75. func (eq Eq) Or(conds ...Cond) Cond {
  76. return Or(eq, Or(conds...))
  77. }
  78. // IsValid tests if this Eq is valid
  79. func (eq Eq) IsValid() bool {
  80. return len(eq) > 0
  81. }