utils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package dao
  2. import "fmt"
  3. const (
  4. //logicNoOp = 0
  5. logicOpAnd = 1
  6. logicOpOr = 2
  7. )
  8. //Condition 生成的condition为
  9. // [before] [key] [operator] ? [after]
  10. // 如
  11. // [(] [id] [=] ? [and]
  12. // [ctime] [>] ? [)]
  13. // [order by] [time] nil [] //如果value是nil,不会设置placeholder ?
  14. type Condition struct {
  15. logicOp int
  16. Before string
  17. Key string
  18. Operator string
  19. Value interface{}
  20. After string
  21. }
  22. //ConcatCondition concat conditions
  23. func ConcatCondition(conditions ...Condition) (conditionStr string, args []interface{}, hasOperator bool) {
  24. hasOperator = false
  25. for _, c := range conditions {
  26. var questionMark = "?"
  27. if c.Value == nil {
  28. questionMark = ""
  29. }
  30. if c.Operator != "" {
  31. hasOperator = true
  32. }
  33. var logicOp = ""
  34. switch c.logicOp {
  35. case logicOpAnd:
  36. logicOp = " and "
  37. case logicOpOr:
  38. logicOp = " or "
  39. }
  40. conditionStr += fmt.Sprintf(" %s %s %s %s %s %s", logicOp, c.Before, c.Key, c.Operator, questionMark, c.After)
  41. if c.Value != nil {
  42. args = append(args, c.Value)
  43. }
  44. }
  45. return
  46. }
  47. //AndCondition and condition
  48. func AndCondition(conditions ...Condition) (result []Condition) {
  49. return addLogicOperator(logicOpAnd, conditions...)
  50. }
  51. //OrCondition or condition
  52. func OrCondition(conditions ...Condition) (result []Condition) {
  53. return addLogicOperator(logicOpOr, conditions...)
  54. }
  55. func addLogicOperator(operator int, conditions ...Condition) (result []Condition) {
  56. var isFirst = true
  57. for _, v := range conditions {
  58. if isFirst {
  59. isFirst = false
  60. } else {
  61. v.logicOp = operator
  62. }
  63. result = append(result, v)
  64. }
  65. return
  66. }