utils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package dao
  2. import "fmt"
  3. const (
  4. //logicNoOp = 0
  5. logicOpAnd = 1
  6. logicOpOr = 2
  7. )
  8. const (
  9. //AppID appid
  10. AppID = "main.archive.up-service"
  11. //UatToken uat token
  12. UatToken = "5f1660060bb011e8865c66d44b23cda7"
  13. //TreeID uat treeid
  14. TreeID = "15572"
  15. )
  16. // Condition 生成的condition为
  17. // [before] [key] [operator] ? [after]
  18. // 如
  19. // [(] [id] [=] ? [and]
  20. // [ctime] [>] ? [)]
  21. // [order by] [time] nil [] //如果value是nil,不会设置placeholder ?
  22. type Condition struct {
  23. logicOp int
  24. Before string
  25. Key string
  26. Operator string
  27. Value interface{}
  28. After string
  29. }
  30. //ConcatCondition concat conditions
  31. func ConcatCondition(conditions ...Condition) (conditionStr string, args []interface{}, hasOperator bool) {
  32. hasOperator = false
  33. for _, c := range conditions {
  34. var questionMark = "?"
  35. if c.Value == nil {
  36. questionMark = ""
  37. }
  38. if c.Operator != "" {
  39. hasOperator = true
  40. }
  41. var logicOp = ""
  42. switch c.logicOp {
  43. case logicOpAnd:
  44. logicOp = " and "
  45. case logicOpOr:
  46. logicOp = " or "
  47. }
  48. conditionStr += fmt.Sprintf(" %s %s %s %s %s %s", logicOp, c.Before, c.Key, c.Operator, questionMark, c.After)
  49. if c.Value != nil {
  50. args = append(args, c.Value)
  51. }
  52. }
  53. return
  54. }
  55. //AndCondition and condition
  56. func AndCondition(conditions ...Condition) (result []Condition) {
  57. return addLogicOperator(logicOpAnd, conditions...)
  58. }
  59. //OrCondition or condition
  60. func OrCondition(conditions ...Condition) (result []Condition) {
  61. return addLogicOperator(logicOpOr, conditions...)
  62. }
  63. func addLogicOperator(operator int, conditions ...Condition) (result []Condition) {
  64. var isFirst = true
  65. for _, v := range conditions {
  66. if isFirst {
  67. isFirst = false
  68. } else {
  69. v.logicOp = operator
  70. }
  71. result = append(result, v)
  72. }
  73. return
  74. }
  75. // Split split num by size; size should be positive
  76. func Split(start int, end int, size int, f func(start int, end int)) {
  77. for s := start; s < end; s += size {
  78. e := s + size
  79. if e > end {
  80. e = end
  81. }
  82. f(s, e)
  83. }
  84. }