named_args.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. package pgx
  2. import (
  3. "context"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "unicode/utf8"
  8. )
  9. // NamedArgs can be used as the first argument to a query method. It will replace every '@' named placeholder with a '$'
  10. // ordinal placeholder and construct the appropriate arguments.
  11. //
  12. // For example, the following two queries are equivalent:
  13. //
  14. // conn.Query(ctx, "select * from widgets where foo = @foo and bar = @bar", pgx.NamedArgs{"foo": 1, "bar": 2})
  15. // conn.Query(ctx, "select * from widgets where foo = $1 and bar = $2", 1, 2)
  16. //
  17. // Named placeholders are case sensitive and must start with a letter or underscore. Subsequent characters can be
  18. // letters, numbers, or underscores.
  19. type NamedArgs map[string]any
  20. // RewriteQuery implements the QueryRewriter interface.
  21. func (na NamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) {
  22. return rewriteQuery(na, sql, false)
  23. }
  24. // StrictNamedArgs can be used in the same way as NamedArgs, but provided arguments are also checked to include all
  25. // named arguments that the sql query uses, and no extra arguments.
  26. type StrictNamedArgs map[string]any
  27. // RewriteQuery implements the QueryRewriter interface.
  28. func (sna StrictNamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) {
  29. return rewriteQuery(sna, sql, true)
  30. }
  31. type namedArg string
  32. type sqlLexer struct {
  33. src string
  34. start int
  35. pos int
  36. nested int // multiline comment nesting level.
  37. stateFn stateFn
  38. parts []any
  39. nameToOrdinal map[namedArg]int
  40. }
  41. type stateFn func(*sqlLexer) stateFn
  42. func rewriteQuery(na map[string]any, sql string, isStrict bool) (newSQL string, newArgs []any, err error) {
  43. l := &sqlLexer{
  44. src: sql,
  45. stateFn: rawState,
  46. nameToOrdinal: make(map[namedArg]int, len(na)),
  47. }
  48. for l.stateFn != nil {
  49. l.stateFn = l.stateFn(l)
  50. }
  51. sb := strings.Builder{}
  52. for _, p := range l.parts {
  53. switch p := p.(type) {
  54. case string:
  55. sb.WriteString(p)
  56. case namedArg:
  57. sb.WriteRune('$')
  58. sb.WriteString(strconv.Itoa(l.nameToOrdinal[p]))
  59. }
  60. }
  61. newArgs = make([]any, len(l.nameToOrdinal))
  62. for name, ordinal := range l.nameToOrdinal {
  63. var found bool
  64. newArgs[ordinal-1], found = na[string(name)]
  65. if isStrict && !found {
  66. return "", nil, fmt.Errorf("argument %s found in sql query but not present in StrictNamedArgs", name)
  67. }
  68. }
  69. if isStrict {
  70. for name := range na {
  71. if _, found := l.nameToOrdinal[namedArg(name)]; !found {
  72. return "", nil, fmt.Errorf("argument %s of StrictNamedArgs not found in sql query", name)
  73. }
  74. }
  75. }
  76. return sb.String(), newArgs, nil
  77. }
  78. func rawState(l *sqlLexer) stateFn {
  79. for {
  80. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  81. l.pos += width
  82. switch r {
  83. case 'e', 'E':
  84. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  85. if nextRune == '\'' {
  86. l.pos += width
  87. return escapeStringState
  88. }
  89. case '\'':
  90. return singleQuoteState
  91. case '"':
  92. return doubleQuoteState
  93. case '@':
  94. nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
  95. if isLetter(nextRune) || nextRune == '_' {
  96. if l.pos-l.start > 0 {
  97. l.parts = append(l.parts, l.src[l.start:l.pos-width])
  98. }
  99. l.start = l.pos
  100. return namedArgState
  101. }
  102. case '-':
  103. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  104. if nextRune == '-' {
  105. l.pos += width
  106. return oneLineCommentState
  107. }
  108. case '/':
  109. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  110. if nextRune == '*' {
  111. l.pos += width
  112. return multilineCommentState
  113. }
  114. case utf8.RuneError:
  115. if l.pos-l.start > 0 {
  116. l.parts = append(l.parts, l.src[l.start:l.pos])
  117. l.start = l.pos
  118. }
  119. return nil
  120. }
  121. }
  122. }
  123. func isLetter(r rune) bool {
  124. return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
  125. }
  126. func namedArgState(l *sqlLexer) stateFn {
  127. for {
  128. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  129. l.pos += width
  130. if r == utf8.RuneError {
  131. if l.pos-l.start > 0 {
  132. na := namedArg(l.src[l.start:l.pos])
  133. if _, found := l.nameToOrdinal[na]; !found {
  134. l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1
  135. }
  136. l.parts = append(l.parts, na)
  137. l.start = l.pos
  138. }
  139. return nil
  140. } else if !(isLetter(r) || (r >= '0' && r <= '9') || r == '_') {
  141. l.pos -= width
  142. na := namedArg(l.src[l.start:l.pos])
  143. if _, found := l.nameToOrdinal[na]; !found {
  144. l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1
  145. }
  146. l.parts = append(l.parts, namedArg(na))
  147. l.start = l.pos
  148. return rawState
  149. }
  150. }
  151. }
  152. func singleQuoteState(l *sqlLexer) stateFn {
  153. for {
  154. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  155. l.pos += width
  156. switch r {
  157. case '\'':
  158. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  159. if nextRune != '\'' {
  160. return rawState
  161. }
  162. l.pos += width
  163. case utf8.RuneError:
  164. if l.pos-l.start > 0 {
  165. l.parts = append(l.parts, l.src[l.start:l.pos])
  166. l.start = l.pos
  167. }
  168. return nil
  169. }
  170. }
  171. }
  172. func doubleQuoteState(l *sqlLexer) stateFn {
  173. for {
  174. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  175. l.pos += width
  176. switch r {
  177. case '"':
  178. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  179. if nextRune != '"' {
  180. return rawState
  181. }
  182. l.pos += width
  183. case utf8.RuneError:
  184. if l.pos-l.start > 0 {
  185. l.parts = append(l.parts, l.src[l.start:l.pos])
  186. l.start = l.pos
  187. }
  188. return nil
  189. }
  190. }
  191. }
  192. func escapeStringState(l *sqlLexer) stateFn {
  193. for {
  194. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  195. l.pos += width
  196. switch r {
  197. case '\\':
  198. _, width = utf8.DecodeRuneInString(l.src[l.pos:])
  199. l.pos += width
  200. case '\'':
  201. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  202. if nextRune != '\'' {
  203. return rawState
  204. }
  205. l.pos += width
  206. case utf8.RuneError:
  207. if l.pos-l.start > 0 {
  208. l.parts = append(l.parts, l.src[l.start:l.pos])
  209. l.start = l.pos
  210. }
  211. return nil
  212. }
  213. }
  214. }
  215. func oneLineCommentState(l *sqlLexer) stateFn {
  216. for {
  217. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  218. l.pos += width
  219. switch r {
  220. case '\\':
  221. _, width = utf8.DecodeRuneInString(l.src[l.pos:])
  222. l.pos += width
  223. case '\n', '\r':
  224. return rawState
  225. case utf8.RuneError:
  226. if l.pos-l.start > 0 {
  227. l.parts = append(l.parts, l.src[l.start:l.pos])
  228. l.start = l.pos
  229. }
  230. return nil
  231. }
  232. }
  233. }
  234. func multilineCommentState(l *sqlLexer) stateFn {
  235. for {
  236. r, width := utf8.DecodeRuneInString(l.src[l.pos:])
  237. l.pos += width
  238. switch r {
  239. case '/':
  240. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  241. if nextRune == '*' {
  242. l.pos += width
  243. l.nested++
  244. }
  245. case '*':
  246. nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:])
  247. if nextRune != '/' {
  248. continue
  249. }
  250. l.pos += width
  251. if l.nested == 0 {
  252. return rawState
  253. }
  254. l.nested--
  255. case utf8.RuneError:
  256. if l.pos-l.start > 0 {
  257. l.parts = append(l.parts, l.src[l.start:l.pos])
  258. l.start = l.pos
  259. }
  260. return nil
  261. }
  262. }
  263. }