sql_parser.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package dpsapi
  2. import (
  3. "github.com/auxten/postgresql-parser/pkg/sql/parser"
  4. "github.com/auxten/postgresql-parser/pkg/walk"
  5. "strings"
  6. )
  7. type insertClause struct {
  8. into string
  9. }
  10. type deleteClause struct {
  11. }
  12. type updateClause struct {
  13. }
  14. type selectClause struct {
  15. selectExpr []string
  16. from string
  17. where []string
  18. limit int
  19. offset int
  20. }
  21. func parseSql(sqlStr string) ([]any, error) {
  22. sqls := strings.Split(sqlStr, ";")
  23. sqlClauses := make([]any, 0)
  24. for _, sql := range sqls {
  25. stmts, err := parser.Parse(sql)
  26. if err != nil {
  27. return nil, err
  28. }
  29. trimSQL := strings.TrimSpace(sql)
  30. upperTrimSQL := strings.ToUpper(trimSQL)
  31. var clause any
  32. w := new(walk.AstWalker)
  33. if strings.HasPrefix(upperTrimSQL, "INSERT") {
  34. c := new(insertClause)
  35. clause = c
  36. w.Fn = insertWalkFunc(c)
  37. } else if strings.HasPrefix(upperTrimSQL, "DELETE") {
  38. c := new(deleteClause)
  39. clause = c
  40. w.Fn = deleteWalkFunc(c)
  41. } else if strings.HasPrefix(upperTrimSQL, "UPDATE") {
  42. c := new(updateClause)
  43. clause = c
  44. w.Fn = updateWalkFunc(c)
  45. } else if strings.HasPrefix(upperTrimSQL, "SELECT") {
  46. c := new(selectClause)
  47. clause = c
  48. w.Fn = selectWalkFunc(c)
  49. }
  50. _, err = w.Walk(stmts, nil)
  51. if err != nil {
  52. return nil, err
  53. }
  54. sqlClauses = append(sqlClauses, clause)
  55. }
  56. return sqlClauses, nil
  57. }
  58. func insertWalkFunc(clause *insertClause) func(ctx interface{}, node interface{}) (stop bool) {
  59. return func(ctx interface{}, node interface{}) (stop bool) {
  60. return false
  61. }
  62. }
  63. func deleteWalkFunc(clause *deleteClause) func(ctx interface{}, node interface{}) (stop bool) {
  64. return func(ctx interface{}, node interface{}) (stop bool) {
  65. return false
  66. }
  67. }
  68. func updateWalkFunc(clause *updateClause) func(ctx interface{}, node interface{}) (stop bool) {
  69. return func(ctx interface{}, node interface{}) (stop bool) {
  70. return false
  71. }
  72. }
  73. func selectWalkFunc(clause *selectClause) func(ctx interface{}, node interface{}) (stop bool) {
  74. return func(ctx interface{}, node interface{}) (stop bool) {
  75. return false
  76. }
  77. }