sql_parser.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package api
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/auxten/postgresql-parser/pkg/sql/parser"
  6. "github.com/auxten/postgresql-parser/pkg/sql/sem/tree"
  7. "github.com/auxten/postgresql-parser/pkg/walk"
  8. "go/constant"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. const (
  14. clauseTableRowValueKindTime int = iota + 1
  15. clauseTableRowValueKindBool
  16. clauseTableRowValueKindString
  17. clauseTableRowValueKindUint64
  18. clauseTableRowValueKindFloat64
  19. )
  20. type clauseTableRowValue struct {
  21. kind int
  22. value any
  23. }
  24. type insertClause struct {
  25. table string
  26. tableRow map[string]clauseTableRowValue
  27. }
  28. type deleteClause struct {
  29. table string
  30. where string
  31. }
  32. type updateClause struct {
  33. table string
  34. where string
  35. newTableRow map[string]clauseTableRowValue
  36. }
  37. type selectClause struct {
  38. table string
  39. fromSubQuery string
  40. selectClause string
  41. where string
  42. orderBy string
  43. groupBy string
  44. having string
  45. pageNo int
  46. pageSize int
  47. }
  48. // 调试很重要的函数,可以看到一个节点的实际类型以及包含字段的类型
  49. func printNode(node any) {
  50. fmt.Printf("%+#v\n", node)
  51. }
  52. func parseSql(sqlStr string) ([]any, error) {
  53. sqls := strings.Split(sqlStr, ";")
  54. sqlClauses := make([]any, 0)
  55. for _, sql := range sqls {
  56. trimSQL := strings.TrimSpace(sql)
  57. upperTrimSQL := strings.ToUpper(trimSQL)
  58. var clause any
  59. if strings.HasPrefix(upperTrimSQL, "INSERT") {
  60. innerClause, err := insertWalk(sql)
  61. if err != nil {
  62. return nil, err
  63. }
  64. clause = innerClause
  65. } else if strings.HasPrefix(upperTrimSQL, "DELETE") {
  66. innerClause, err := deleteWalk(sql)
  67. if err != nil {
  68. return nil, err
  69. }
  70. clause = innerClause
  71. } else if strings.HasPrefix(upperTrimSQL, "UPDATE") {
  72. innerClause, err := updateWalk(sql)
  73. if err != nil {
  74. return nil, err
  75. }
  76. clause = innerClause
  77. } else if strings.HasPrefix(upperTrimSQL, "SELECT") {
  78. innerClause, err := selectWalk(sql)
  79. if err != nil {
  80. return nil, err
  81. }
  82. clause = innerClause
  83. }
  84. sqlClauses = append(sqlClauses, clause)
  85. }
  86. return sqlClauses, nil
  87. }
  88. func insertWalk(sql string) (*insertClause, error) {
  89. clause := new(insertClause)
  90. stmts, err := parser.Parse(sql)
  91. if err != nil {
  92. return nil, err
  93. }
  94. var walkFuncErr error
  95. w := &walk.AstWalker{
  96. Fn: func(ctx interface{}, node interface{}) (stop bool) {
  97. realNode := node.(*tree.Insert)
  98. // 获取table
  99. tableName, err := parseTableExpr(realNode.Table)
  100. if err != nil {
  101. walkFuncErr = err
  102. return true
  103. }
  104. clause.table = tableName
  105. // 获取table row
  106. clause.tableRow = make(map[string]clauseTableRowValue)
  107. columns := realNode.Columns.ToStrings()
  108. valuesClause := realNode.Rows.Select.(*tree.ValuesClause)
  109. for _, row := range valuesClause.Rows {
  110. for i, column := range row {
  111. columnValue, err := parseExpr(column)
  112. if err != nil {
  113. walkFuncErr = err
  114. return true
  115. }
  116. clause.tableRow[columns[i]] = *columnValue
  117. }
  118. }
  119. return true
  120. },
  121. }
  122. _, err = w.Walk(stmts, nil)
  123. if err != nil {
  124. return nil, err
  125. }
  126. if walkFuncErr != nil {
  127. return nil, walkFuncErr
  128. }
  129. return clause, nil
  130. }
  131. func deleteWalk(sql string) (*deleteClause, error) {
  132. clause := new(deleteClause)
  133. stmts, err := parser.Parse(sql)
  134. if err != nil {
  135. return nil, err
  136. }
  137. var walkFuncErr error
  138. w := &walk.AstWalker{
  139. Fn: func(ctx interface{}, node interface{}) (stop bool) {
  140. realNode := node.(*tree.Delete)
  141. // 获取table
  142. tableName, err := parseTableExpr(realNode.Table)
  143. if err != nil {
  144. walkFuncErr = err
  145. return true
  146. }
  147. clause.table = tableName
  148. // 获取where
  149. clause.where = parseWhere(realNode.Where)
  150. return true
  151. },
  152. }
  153. _, err = w.Walk(stmts, nil)
  154. if err != nil {
  155. return nil, err
  156. }
  157. if walkFuncErr != nil {
  158. return nil, walkFuncErr
  159. }
  160. return clause, nil
  161. }
  162. func updateWalk(sql string) (*updateClause, error) {
  163. clause := new(updateClause)
  164. stmts, err := parser.Parse(sql)
  165. if err != nil {
  166. return nil, err
  167. }
  168. var walkFuncErr error
  169. w := &walk.AstWalker{
  170. Fn: func(ctx interface{}, node interface{}) (stop bool) {
  171. realNode := node.(*tree.Update)
  172. // 获取table
  173. tableName, err := parseTableExpr(realNode.Table)
  174. if err != nil {
  175. walkFuncErr = err
  176. return true
  177. }
  178. clause.table = tableName
  179. // 获取where
  180. clause.where = parseWhere(realNode.Where)
  181. // 获取table row
  182. clause.newTableRow = make(map[string]clauseTableRowValue)
  183. for _, expr := range realNode.Exprs {
  184. value, err := parseExpr(expr.Expr)
  185. if err != nil {
  186. walkFuncErr = err
  187. return true
  188. }
  189. clause.newTableRow[fmt.Sprint(expr.Names[0])] = *value
  190. }
  191. return true
  192. },
  193. }
  194. _, err = w.Walk(stmts, nil)
  195. if err != nil {
  196. return nil, err
  197. }
  198. if walkFuncErr != nil {
  199. return nil, walkFuncErr
  200. }
  201. return clause, nil
  202. }
  203. func selectWalk(sql string) (*selectClause, error) {
  204. clause := new(selectClause)
  205. stmts, err := parser.Parse(sql)
  206. if err != nil {
  207. return nil, err
  208. }
  209. var walkFuncErr error
  210. w := &walk.AstWalker{
  211. Fn: func(ctx interface{}, node interface{}) (stop bool) {
  212. realNode := node.(*tree.Select)
  213. nodeSelectClause := realNode.Select.(*tree.SelectClause)
  214. // select
  215. clause.selectClause = parseSelect(nodeSelectClause.Exprs)
  216. if clause.selectClause == "*" {
  217. clause.selectClause = ""
  218. }
  219. // from
  220. asFromSubQuery, from, err := parseFrom(&nodeSelectClause.From)
  221. if err != nil {
  222. walkFuncErr = err
  223. return true
  224. }
  225. if asFromSubQuery {
  226. clause.fromSubQuery = from
  227. } else {
  228. clause.table = from
  229. }
  230. // where
  231. if nodeSelectClause.Where != nil {
  232. clause.where = parseWhere(nodeSelectClause.Where)
  233. }
  234. // order by
  235. if realNode.OrderBy != nil {
  236. clause.orderBy = parseOrderBy(realNode.OrderBy)
  237. }
  238. // limit
  239. if realNode.Limit != nil {
  240. pageNo, pageSize, err := parseLimit(realNode.Limit)
  241. if err != nil {
  242. walkFuncErr = err
  243. return true
  244. }
  245. clause.pageNo = pageNo
  246. clause.pageSize = pageSize
  247. }
  248. // group by
  249. if nodeSelectClause.GroupBy != nil {
  250. clause.groupBy = parseGroupBy(nodeSelectClause.GroupBy)
  251. }
  252. // having
  253. if nodeSelectClause.Having != nil {
  254. clause.having = parseWhere(nodeSelectClause.Having)
  255. }
  256. return true
  257. },
  258. }
  259. _, err = w.Walk(stmts, nil)
  260. if err != nil {
  261. return nil, err
  262. }
  263. if walkFuncErr != nil {
  264. return nil, walkFuncErr
  265. }
  266. return clause, nil
  267. }
  268. func parseTableExpr(tableExpr tree.TableExpr) (string, error) {
  269. switch table := tableExpr.(type) {
  270. case *tree.TableName:
  271. return table.String(), nil
  272. case *tree.AliasedTableExpr:
  273. return table.String(), nil
  274. default:
  275. return "", errors.New("不支持的TableExpr")
  276. }
  277. }
  278. func parseSelect(selectExprs tree.SelectExprs) string {
  279. selectFmtCtx := tree.NewFmtCtx(tree.FmtBareStrings)
  280. selectExprs.Format(selectFmtCtx)
  281. return selectFmtCtx.String()
  282. }
  283. func parseFrom(from *tree.From) (bool, string, error) {
  284. switch fromTable := from.Tables[0].(type) {
  285. case *tree.JoinTableExpr:
  286. return true, fromTable.String(), nil
  287. case *tree.AliasedTableExpr:
  288. _, ok := fromTable.Expr.(*tree.Subquery)
  289. if ok {
  290. return true, fromTable.String(), nil
  291. } else {
  292. return false, fromTable.String(), nil
  293. }
  294. default:
  295. return false, "", errors.New("不支持的From类型")
  296. }
  297. }
  298. func parseWhere(where *tree.Where) string {
  299. return where.Expr.String()
  300. }
  301. func parseOrderBy(orderBy tree.OrderBy) string {
  302. orderByFmtCtx := tree.NewFmtCtx(tree.FmtBareStrings)
  303. orderBy[0].Format(orderByFmtCtx)
  304. return orderByFmtCtx.String()
  305. }
  306. func parseLimit(limit *tree.Limit) (int, int, error) {
  307. pageNo, err := strconv.Atoi(limit.Offset.String())
  308. if err != nil {
  309. return 0, 0, err
  310. }
  311. pageSize, err := strconv.Atoi(limit.Count.String())
  312. if err != nil {
  313. return 0, 0, err
  314. }
  315. return pageNo, pageSize, nil
  316. }
  317. func parseGroupBy(groupBy tree.GroupBy) string {
  318. groupBySlice := make([]string, 0)
  319. for _, groupExpr := range groupBy {
  320. groupBySlice = append(groupBySlice, groupExpr.String())
  321. }
  322. return strings.Join(groupBySlice, ",")
  323. }
  324. func parseExpr(valueExpr tree.Expr) (*clauseTableRowValue, error) {
  325. switch realColumn := valueExpr.(type) {
  326. case *tree.FuncExpr:
  327. // 函数类型
  328. value, kind, err := evaluateFuncExpr(realColumn)
  329. if err != nil {
  330. return nil, err
  331. }
  332. return &clauseTableRowValue{
  333. kind: kind,
  334. value: value,
  335. }, nil
  336. case *tree.DBool:
  337. // 布尔类型
  338. var boolValue bool
  339. stringValue := realColumn.String()
  340. if stringValue == "true" {
  341. boolValue = true
  342. }
  343. return &clauseTableRowValue{
  344. kind: clauseTableRowValueKindBool,
  345. value: boolValue,
  346. }, nil
  347. case *tree.StrVal:
  348. // 字符串类型或者函数参数是字符串的类型,这里通过比较字符串value,排除了函数参数类型
  349. return &clauseTableRowValue{
  350. kind: clauseTableRowValueKindString,
  351. value: realColumn.RawString(),
  352. }, nil
  353. case *tree.NumVal:
  354. // 数值类型,可以是整形或浮点型
  355. numKind := realColumn.Kind()
  356. if numKind == constant.Int {
  357. valueUint64, err := strconv.ParseUint(realColumn.String(), 10, 64)
  358. if err != nil {
  359. return nil, err
  360. }
  361. return &clauseTableRowValue{
  362. kind: clauseTableRowValueKindUint64,
  363. value: valueUint64,
  364. }, nil
  365. } else if numKind == constant.Float {
  366. valueFloat64, err := strconv.ParseFloat(realColumn.String(), 64)
  367. if err != nil {
  368. return nil, err
  369. }
  370. return &clauseTableRowValue{
  371. kind: clauseTableRowValueKindFloat64,
  372. value: valueFloat64,
  373. }, nil
  374. } else {
  375. return nil, errors.New("不支持的数值类型")
  376. }
  377. case *tree.UnresolvedName:
  378. return nil, errors.New("存在无法解析的名字,是否应该使用单引号")
  379. default:
  380. return nil, errors.New("未支持的数据类型")
  381. }
  382. }
  383. func evaluateFuncExpr(expr *tree.FuncExpr) (any, int, error) {
  384. if strings.HasPrefix(expr.String(), "parse_time") {
  385. if expr.Exprs == nil || len(expr.Exprs) != 2 {
  386. return nil, 0, errors.New("parse_time(time_str, time_format)")
  387. }
  388. timeStrValue, err := parseExpr(expr.Exprs[0])
  389. if err != nil {
  390. return nil, 0, err
  391. }
  392. if timeStrValue.kind != clauseTableRowValueKindString {
  393. return nil, 0, errors.New("时间字符串不是字符串类型")
  394. }
  395. timeFormatValue, err := parseExpr(expr.Exprs[1])
  396. if err != nil {
  397. return nil, 0, err
  398. }
  399. if timeFormatValue.kind != clauseTableRowValueKindString {
  400. return nil, 0, errors.New("时间格式不是字符串类型")
  401. }
  402. parsedTime, err := time.ParseInLocation(timeFormatValue.value.(string), timeStrValue.value.(string), time.Local)
  403. if err != nil {
  404. return nil, 0, err
  405. }
  406. return parsedTime, clauseTableRowValueKindTime, nil
  407. } else {
  408. return nil, 0, errors.New("不支持的函数")
  409. }
  410. }