sql解析库可以解析update语句中的要改变的字段,可通过字段改变后的字段进行一个判断,来决定要不要继续往下执行 #1

Merged
shaojiacheng merged 1 commits from dev into master 2023-07-11 14:14:25 +08:00
3 changed files with 41 additions and 0 deletions

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module sql_prase_demo
go 1.20
require github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2

2
go.sum Normal file
View File

@ -0,0 +1,2 @@
github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2 h1:zzrxE1FKn5ryBNl9eKOeqQ58Y/Qpo3Q9QNxKHX5uzzQ=
github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2/go.mod h1:hzfGeIUDq/j97IG+FhNqkowIyEcD88LrW6fyU3K3WqY=

34
main.go Normal file
View File

@ -0,0 +1,34 @@
package main
import (
"fmt"
"github.com/xwb1989/sqlparser"
)
func main() {
sql := "UPDATE orders, inventory SET orders.status = 'Processed', inventory.stock = inventory.stock - orders.quantity WHERE orders.product_id = inventory.product_id AND orders.id = 1 AND inventory.stock >= orders.quantity"
stmt, err := sqlparser.Parse(sql)
if err != nil {
fmt.Println("Parse error: ", err.Error())
return
}
update, ok := stmt.(*sqlparser.Update)
if !ok {
fmt.Println("Not an UPDATE statement")
return
}
for _, table := range update.TableExprs {
switch t := table.(type) {
case *sqlparser.AliasedTableExpr:
fmt.Println("Table: ", sqlparser.String(t.Expr))
}
}
for _, expr := range update.Exprs {
fmt.Printf("Column: %s, New value: %s\n", expr.Name.Name, sqlparser.String(expr.Expr))
}
}