sql_parser.go 2.0 KB

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