parse.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package compiler
  2. import (
  3. "errors"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "github.com/kyleconroy/sqlc/internal/config"
  8. "github.com/kyleconroy/sqlc/internal/debug"
  9. "github.com/kyleconroy/sqlc/internal/metadata"
  10. "github.com/kyleconroy/sqlc/internal/opts"
  11. "github.com/kyleconroy/sqlc/internal/source"
  12. "github.com/kyleconroy/sqlc/internal/sql/ast"
  13. "github.com/kyleconroy/sqlc/internal/sql/astutils"
  14. "github.com/kyleconroy/sqlc/internal/sql/rewrite"
  15. "github.com/kyleconroy/sqlc/internal/sql/validate"
  16. )
  17. var ErrUnsupportedStatementType = errors.New("parseQuery: unsupported statement type")
  18. func rewriteNumberedParameters(refs []paramRef, raw *ast.RawStmt, sql string) ([]source.Edit, error) {
  19. edits := make([]source.Edit, len(refs))
  20. for i, ref := range refs {
  21. edits[i] = source.Edit{
  22. Location: ref.ref.Location - raw.StmtLocation,
  23. Old: fmt.Sprintf("$%d", ref.ref.Number),
  24. New: "?",
  25. }
  26. }
  27. return edits, nil
  28. }
  29. func (c *Compiler) parseQuery(stmt ast.Node, src string, o opts.Parser) (*Query, error) {
  30. if o.Debug.DumpAST {
  31. debug.Dump(stmt)
  32. }
  33. if err := validate.ParamStyle(stmt); err != nil {
  34. return nil, err
  35. }
  36. numbers, dollar, err := validate.ParamRef(stmt)
  37. if err != nil {
  38. return nil, err
  39. }
  40. raw, ok := stmt.(*ast.RawStmt)
  41. if !ok {
  42. return nil, errors.New("node is not a statement")
  43. }
  44. var table *ast.TableName
  45. switch n := raw.Stmt.(type) {
  46. case *ast.SelectStmt:
  47. case *ast.DeleteStmt:
  48. case *ast.InsertStmt:
  49. if err := validate.InsertStmt(n); err != nil {
  50. return nil, err
  51. }
  52. var err error
  53. table, err = ParseTableName(n.Relation)
  54. if err != nil {
  55. return nil, err
  56. }
  57. case *ast.TruncateStmt:
  58. case *ast.UpdateStmt:
  59. default:
  60. return nil, ErrUnsupportedStatementType
  61. }
  62. rawSQL, err := source.Pluck(src, raw.StmtLocation, raw.StmtLen)
  63. if err != nil {
  64. return nil, err
  65. }
  66. if rawSQL == "" {
  67. return nil, errors.New("missing semicolon at end of file")
  68. }
  69. if err := validate.FuncCall(c.catalog, c.combo, raw); err != nil {
  70. return nil, err
  71. }
  72. name, cmd, err := metadata.Parse(strings.TrimSpace(rawSQL), c.parser.CommentSyntax())
  73. if err != nil {
  74. return nil, err
  75. }
  76. if err := validate.Cmd(raw.Stmt, name, cmd); err != nil {
  77. return nil, err
  78. }
  79. raw, namedParams, edits := rewrite.NamedParameters(c.conf.Engine, raw, numbers, dollar)
  80. rvs := rangeVars(raw.Stmt)
  81. refs, err := findParameters(raw.Stmt)
  82. if err != nil {
  83. return nil, err
  84. }
  85. if o.UsePositionalParameters {
  86. edits, err = rewriteNumberedParameters(refs, raw, rawSQL)
  87. if err != nil {
  88. return nil, err
  89. }
  90. } else {
  91. refs = uniqueParamRefs(refs, dollar)
  92. if c.conf.Engine == config.EngineMySQL || !dollar {
  93. sort.Slice(refs, func(i, j int) bool { return refs[i].ref.Location < refs[j].ref.Location })
  94. } else {
  95. sort.Slice(refs, func(i, j int) bool { return refs[i].ref.Number < refs[j].ref.Number })
  96. }
  97. }
  98. qc, err := buildQueryCatalog(c.catalog, raw.Stmt)
  99. if err != nil {
  100. return nil, err
  101. }
  102. params, err := c.resolveCatalogRefs(qc, rvs, refs, namedParams)
  103. if err != nil {
  104. return nil, err
  105. }
  106. cols, err := outputColumns(qc, raw.Stmt)
  107. if err != nil {
  108. return nil, err
  109. }
  110. expandEdits, err := c.expand(qc, raw)
  111. if err != nil {
  112. return nil, err
  113. }
  114. edits = append(edits, expandEdits...)
  115. expanded, err := source.Mutate(rawSQL, edits)
  116. if err != nil {
  117. return nil, err
  118. }
  119. // If the query string was edited, make sure the syntax is valid
  120. if expanded != rawSQL {
  121. if _, err := c.parser.Parse(strings.NewReader(expanded)); err != nil {
  122. return nil, fmt.Errorf("edited query syntax is invalid: %w", err)
  123. }
  124. }
  125. trimmed, comments, err := source.StripComments(expanded)
  126. if err != nil {
  127. return nil, err
  128. }
  129. return &Query{
  130. Cmd: cmd,
  131. Comments: comments,
  132. Name: name,
  133. Params: params,
  134. Columns: cols,
  135. SQL: trimmed,
  136. InsertIntoTable: table,
  137. }, nil
  138. }
  139. func rangeVars(root ast.Node) []*ast.RangeVar {
  140. var vars []*ast.RangeVar
  141. find := astutils.VisitorFunc(func(node ast.Node) {
  142. switch n := node.(type) {
  143. case *ast.RangeVar:
  144. vars = append(vars, n)
  145. }
  146. })
  147. astutils.Walk(find, root)
  148. return vars
  149. }
  150. func uniqueParamRefs(in []paramRef, dollar bool) []paramRef {
  151. m := make(map[int]bool, len(in))
  152. o := make([]paramRef, 0, len(in))
  153. for _, v := range in {
  154. if !m[v.ref.Number] {
  155. m[v.ref.Number] = true
  156. if v.ref.Number != 0 {
  157. o = append(o, v)
  158. }
  159. }
  160. }
  161. if !dollar {
  162. start := 1
  163. for _, v := range in {
  164. if v.ref.Number == 0 {
  165. for m[start] {
  166. start++
  167. }
  168. v.ref.Number = start
  169. o = append(o, v)
  170. }
  171. }
  172. }
  173. return o
  174. }