where.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package clause
  2. // Where where clause
  3. type Where struct {
  4. AndConditions AddConditions
  5. ORConditions []ORConditions
  6. builders []Expression
  7. }
  8. // Name where clause name
  9. func (where Where) Name() string {
  10. return "WHERE"
  11. }
  12. // Build build where clause
  13. func (where Where) Build(builder Builder) {
  14. var withConditions bool
  15. if len(where.AndConditions) > 0 {
  16. withConditions = true
  17. where.AndConditions.Build(builder)
  18. }
  19. if len(where.builders) > 0 {
  20. for _, b := range where.builders {
  21. if withConditions {
  22. builder.Write(" AND ")
  23. }
  24. withConditions = true
  25. b.Build(builder)
  26. }
  27. }
  28. var singleOrConditions []ORConditions
  29. for _, or := range where.ORConditions {
  30. if len(or) == 1 {
  31. if withConditions {
  32. builder.Write(" OR ")
  33. or.Build(builder)
  34. } else {
  35. singleOrConditions = append(singleOrConditions, or)
  36. }
  37. } else {
  38. withConditions = true
  39. builder.Write(" AND (")
  40. or.Build(builder)
  41. builder.WriteByte(')')
  42. }
  43. }
  44. for _, or := range singleOrConditions {
  45. if withConditions {
  46. builder.Write(" AND ")
  47. or.Build(builder)
  48. } else {
  49. withConditions = true
  50. or.Build(builder)
  51. }
  52. }
  53. if !withConditions {
  54. builder.Write(" FALSE")
  55. }
  56. return
  57. }
  58. // MergeExpression merge where clauses
  59. func (where Where) MergeExpression(expr Expression) {
  60. if w, ok := expr.(Where); ok {
  61. where.AndConditions = append(where.AndConditions, w.AndConditions...)
  62. where.ORConditions = append(where.ORConditions, w.ORConditions...)
  63. where.builders = append(where.builders, w.builders...)
  64. } else {
  65. where.builders = append(where.builders, expr)
  66. }
  67. }