parse.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package dolphin
  2. import (
  3. "errors"
  4. "io"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "github.com/pingcap/parser"
  9. _ "github.com/pingcap/parser/test_driver"
  10. "github.com/kyleconroy/sqlc/internal/metadata"
  11. "github.com/kyleconroy/sqlc/internal/sql/ast"
  12. "github.com/kyleconroy/sqlc/internal/sql/sqlerr"
  13. )
  14. func NewParser() *Parser {
  15. return &Parser{parser.New()}
  16. }
  17. type Parser struct {
  18. pingcap *parser.Parser
  19. }
  20. var lineColumn = regexp.MustCompile(`^line (\d+) column (\d+) (.*)`)
  21. func normalizeErr(err error) error {
  22. if err == nil {
  23. return err
  24. }
  25. parts := strings.Split(err.Error(), "\n")
  26. msg := strings.TrimSpace(parts[0] + "\"")
  27. out := lineColumn.FindStringSubmatch(msg)
  28. if len(out) == 4 {
  29. line, lineErr := strconv.Atoi(out[1])
  30. col, colErr := strconv.Atoi(out[2])
  31. if lineErr != nil || colErr != nil {
  32. return errors.New(msg)
  33. }
  34. return &sqlerr.Error{
  35. Message: "syntax error",
  36. Err: errors.New(out[3]),
  37. Line: line,
  38. Column: col,
  39. }
  40. }
  41. return errors.New(msg)
  42. }
  43. func (p *Parser) Parse(r io.Reader) ([]ast.Statement, error) {
  44. blob, err := io.ReadAll(r)
  45. if err != nil {
  46. return nil, err
  47. }
  48. stmtNodes, _, err := p.pingcap.Parse(string(blob), "", "")
  49. if err != nil {
  50. return nil, normalizeErr(err)
  51. }
  52. var stmts []ast.Statement
  53. for i := range stmtNodes {
  54. converter := &cc{}
  55. out := converter.convert(stmtNodes[i])
  56. if _, ok := out.(*ast.TODO); ok {
  57. continue
  58. }
  59. // TODO: Attach the text directly to the ast.Statement node
  60. text := stmtNodes[i].Text()
  61. loc := strings.Index(string(blob), text)
  62. stmtLen := len(text)
  63. if text[stmtLen-1] == ';' {
  64. stmtLen -= 1 // Subtract one to remove semicolon
  65. }
  66. stmts = append(stmts, ast.Statement{
  67. Raw: &ast.RawStmt{
  68. Stmt: out,
  69. StmtLocation: loc,
  70. StmtLen: stmtLen,
  71. },
  72. })
  73. }
  74. return stmts, nil
  75. }
  76. // https://dev.mysql.com/doc/refman/8.0/en/comments.html
  77. func (p *Parser) CommentSyntax() metadata.CommentSyntax {
  78. return metadata.CommentSyntax{
  79. Dash: true,
  80. SlashStar: true,
  81. Hash: true,
  82. }
  83. }