You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.0 KiB

  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 (
  6. "fmt"
  7. "sort"
  8. )
  9. // Neq defines not equal conditions
  10. type Neq map[string]interface{}
  11. var _ Cond = Neq{}
  12. // WriteTo writes SQL to Writer
  13. func (neq Neq) WriteTo(w Writer) error {
  14. var args = make([]interface{}, 0, len(neq))
  15. var i = 0
  16. for _, k := range neq.sortedKeys() {
  17. v := neq[k]
  18. switch v.(type) {
  19. case []int, []int64, []string, []int32, []int16, []int8:
  20. if err := NotIn(k, v).WriteTo(w); err != nil {
  21. return err
  22. }
  23. case expr:
  24. if _, err := fmt.Fprintf(w, "%s<>(", k); err != nil {
  25. return err
  26. }
  27. if err := v.(expr).WriteTo(w); err != nil {
  28. return err
  29. }
  30. if _, err := fmt.Fprintf(w, ")"); err != nil {
  31. return err
  32. }
  33. case *Builder:
  34. if _, err := fmt.Fprintf(w, "%s<>(", k); err != nil {
  35. return err
  36. }
  37. if err := v.(*Builder).WriteTo(w); err != nil {
  38. return err
  39. }
  40. if _, err := fmt.Fprintf(w, ")"); err != nil {
  41. return err
  42. }
  43. default:
  44. if _, err := fmt.Fprintf(w, "%s<>?", k); err != nil {
  45. return err
  46. }
  47. args = append(args, v)
  48. }
  49. if i != len(neq)-1 {
  50. if _, err := fmt.Fprint(w, " AND "); err != nil {
  51. return err
  52. }
  53. }
  54. i = i + 1
  55. }
  56. w.Append(args...)
  57. return nil
  58. }
  59. // And implements And with other conditions
  60. func (neq Neq) And(conds ...Cond) Cond {
  61. return And(neq, And(conds...))
  62. }
  63. // Or implements Or with other conditions
  64. func (neq Neq) Or(conds ...Cond) Cond {
  65. return Or(neq, Or(conds...))
  66. }
  67. // IsValid tests if this condition is valid
  68. func (neq Neq) IsValid() bool {
  69. return len(neq) > 0
  70. }
  71. // sortedKeys returns all keys of this Neq sorted with sort.Strings.
  72. // It is used internally for consistent ordering when generating
  73. // SQL, see https://github.com/go-xorm/builder/issues/10
  74. func (neq Neq) sortedKeys() []string {
  75. keys := make([]string, 0, len(neq))
  76. for key := range neq {
  77. keys = append(keys, key)
  78. }
  79. sort.Strings(keys)
  80. return keys
  81. }