args.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Copyright 2018 Huan Du. All rights reserved.
  2. // Licensed under the MIT license that can be found in the LICENSE file.
  3. package sqlbuilder
  4. import (
  5. "bytes"
  6. "database/sql"
  7. "fmt"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. )
  12. // Args stores arguments associated with a SQL.
  13. type Args struct {
  14. // The default flavor used by `Args#Compile`
  15. Flavor Flavor
  16. args []interface{}
  17. namedArgs map[string]int
  18. sqlNamedArgs map[string]int
  19. onlyNamed bool
  20. }
  21. // Add adds an arg to Args and returns a placeholder.
  22. func (args *Args) Add(arg interface{}) string {
  23. return fmt.Sprintf("$%v", args.add(arg))
  24. }
  25. func (args *Args) add(arg interface{}) int {
  26. idx := len(args.args)
  27. switch a := arg.(type) {
  28. case sql.NamedArg:
  29. if args.sqlNamedArgs == nil {
  30. args.sqlNamedArgs = map[string]int{}
  31. }
  32. if p, ok := args.sqlNamedArgs[a.Name]; ok {
  33. arg = args.args[p]
  34. break
  35. }
  36. args.sqlNamedArgs[a.Name] = idx
  37. case namedArgs:
  38. if args.namedArgs == nil {
  39. args.namedArgs = map[string]int{}
  40. }
  41. if p, ok := args.namedArgs[a.name]; ok {
  42. arg = args.args[p]
  43. break
  44. }
  45. // Find out the real arg and add it to args.
  46. idx = args.add(a.arg)
  47. args.namedArgs[a.name] = idx
  48. return idx
  49. }
  50. args.args = append(args.args, arg)
  51. return idx
  52. }
  53. // Compile compiles builder's format to standard sql and returns associated args.
  54. //
  55. // The format string uses a special syntax to represent arguments.
  56. //
  57. // $? refers successive arguments passed in the call. It works similar as `%v` in `fmt.Sprintf`.
  58. // $0 $1 ... $n refers nth-argument passed in the call. Next $? will use arguments n+1.
  59. // ${name} refers a named argument created by `Named` with `name`.
  60. // $$ is a "$" string.
  61. func (args *Args) Compile(format string, intialValue ...interface{}) (query string, values []interface{}) {
  62. return args.CompileWithFlavor(format, args.Flavor, intialValue...)
  63. }
  64. // CompileWithFlavor compiles builder's format to standard sql with flavor and returns associated args.
  65. //
  66. // See doc for `Compile` to learn details.
  67. func (args *Args) CompileWithFlavor(format string, flavor Flavor, intialValue ...interface{}) (query string, values []interface{}) {
  68. buf := &bytes.Buffer{}
  69. idx := strings.IndexRune(format, '$')
  70. offset := 0
  71. values = intialValue
  72. if flavor == invalidFlavor {
  73. flavor = DefaultFlavor
  74. }
  75. for idx >= 0 && len(format) > 0 {
  76. if idx > 0 {
  77. buf.WriteString(format[:idx])
  78. }
  79. format = format[idx+1:]
  80. // Should not happen.
  81. if len(format) == 0 {
  82. break
  83. }
  84. if format[0] == '$' {
  85. buf.WriteRune('$')
  86. format = format[1:]
  87. } else if format[0] == '{' {
  88. format, values = args.compileNamed(buf, flavor, format, values)
  89. } else if !args.onlyNamed && '0' <= format[0] && format[0] <= '9' {
  90. format, values, offset = args.compileDigits(buf, flavor, format, values, offset)
  91. } else if !args.onlyNamed && format[0] == '?' {
  92. format, values, offset = args.compileSuccessive(buf, flavor, format[1:], values, offset)
  93. }
  94. idx = strings.IndexRune(format, '$')
  95. }
  96. if len(format) > 0 {
  97. buf.WriteString(format)
  98. }
  99. query = buf.String()
  100. if len(args.sqlNamedArgs) > 0 {
  101. // Stabilize the sequence to make it easier to write test cases.
  102. ints := make([]int, 0, len(args.sqlNamedArgs))
  103. for _, p := range args.sqlNamedArgs {
  104. ints = append(ints, p)
  105. }
  106. sort.Ints(ints)
  107. for _, i := range ints {
  108. values = append(values, args.args[i])
  109. }
  110. }
  111. return
  112. }
  113. func (args *Args) compileNamed(buf *bytes.Buffer, flavor Flavor, format string, values []interface{}) (string, []interface{}) {
  114. i := 1
  115. for ; i < len(format) && format[i] != '}'; i++ {
  116. // Nothing.
  117. }
  118. // Invalid $ format. Ignore it.
  119. if i == len(format) {
  120. return format, values
  121. }
  122. name := format[1:i]
  123. format = format[i+1:]
  124. if p, ok := args.namedArgs[name]; ok {
  125. format, values, _ = args.compileSuccessive(buf, flavor, format, values, p)
  126. }
  127. return format, values
  128. }
  129. func (args *Args) compileDigits(buf *bytes.Buffer, flavor Flavor, format string, values []interface{}, offset int) (string, []interface{}, int) {
  130. i := 1
  131. for ; i < len(format) && '0' <= format[i] && format[i] <= '9'; i++ {
  132. // Nothing.
  133. }
  134. digits := format[:i]
  135. format = format[i:]
  136. if pointer, err := strconv.Atoi(digits); err == nil {
  137. return args.compileSuccessive(buf, flavor, format, values, pointer)
  138. }
  139. return format, values, offset
  140. }
  141. func (args *Args) compileSuccessive(buf *bytes.Buffer, flavor Flavor, format string, values []interface{}, offset int) (string, []interface{}, int) {
  142. if offset >= len(args.args) {
  143. return format, values, offset
  144. }
  145. arg := args.args[offset]
  146. values = args.compileArg(buf, flavor, values, arg)
  147. return format, values, offset + 1
  148. }
  149. func (args *Args) compileArg(buf *bytes.Buffer, flavor Flavor, values []interface{}, arg interface{}) []interface{} {
  150. switch a := arg.(type) {
  151. case Builder:
  152. var s string
  153. s, values = a.BuildWithFlavor(flavor, values...)
  154. buf.WriteString(s)
  155. case sql.NamedArg:
  156. buf.WriteRune('@')
  157. buf.WriteString(a.Name)
  158. case rawArgs:
  159. buf.WriteString(a.expr)
  160. case listArgs:
  161. if len(a.args) > 0 {
  162. values = args.compileArg(buf, flavor, values, a.args[0])
  163. }
  164. for i := 1; i < len(a.args); i++ {
  165. buf.WriteString(", ")
  166. values = args.compileArg(buf, flavor, values, a.args[i])
  167. }
  168. default:
  169. switch flavor {
  170. case MySQL:
  171. buf.WriteRune('?')
  172. case PostgreSQL:
  173. fmt.Fprintf(buf, "$%v", len(values)+1)
  174. default:
  175. panic(fmt.Errorf("Args.CompileWithFlavor: invalid flavor %v (%v)", flavor, int(flavor)))
  176. }
  177. values = append(values, arg)
  178. }
  179. return values
  180. }
  181. // Copy is
  182. func (args *Args) Copy() *Args {
  183. return &Args{
  184. Flavor: args.Flavor,
  185. args: args.args,
  186. namedArgs: args.namedArgs,
  187. sqlNamedArgs: args.sqlNamedArgs,
  188. onlyNamed: args.onlyNamed,
  189. }
  190. }