1 Star 0 Fork 0

kinwyb/godb

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sqlParser.go 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
package godb
import (
"errors"
"fmt"
"github.com/spf13/cast"
"github.com/xwb1989/sqlparser"
"regexp"
)
var reg = regexp.MustCompile(":v\\d")
type selectSQL struct {
selectColumns string
table string
where string
groupBy string
having string
orderBy string
limitStart int64
limitLen int64
}
// 解析mysql select语句
func mysqlSelectSQLParser(sql string) (selectSQL, error) {
ret := selectSQL{}
stmt, err := sqlparser.Parse(sql)
if err != nil {
return ret, fmt.Errorf("sql语句解析错误:%w", err)
}
switch stmt := stmt.(type) {
case *sqlparser.Select:
buf := sqlparser.NewTrackedBuffer(nil)
stmt.SelectExprs.Format(buf)
ret.selectColumns = buf.String()
buf.Reset()
stmt.From.Format(buf)
ret.table = buf.String()
buf.Reset()
where := stmt.Where
if where != nil {
stmt.Where.Format(buf)
ret.where = buf.String()
if ret.where != "" {
ret.where = regexp.MustCompile("(\\:v\\d+)").ReplaceAllString(ret.where, "?")
}
buf.Reset()
}
stmt.GroupBy.Format(buf)
ret.groupBy = buf.String()
buf.Reset()
having := stmt.Having
if having != nil {
stmt.Having.Format(buf)
ret.having = buf.String()
buf.Reset()
}
stmt.OrderBy.Format(buf)
ret.orderBy = buf.String()
buf.Reset()
limit := stmt.Limit
if limit != nil {
limit.Offset.Format(buf)
ret.limitStart = cast.ToInt64(buf.String())
buf.Reset()
limit.Rowcount.Format(buf)
ret.limitLen = cast.ToInt64(buf.String())
}
ret.table = reg.ReplaceAllString(ret.table, "?")
ret.where = reg.ReplaceAllString(ret.where, "?")
ret.having = reg.ReplaceAllString(ret.having, "?")
return ret, nil
default:
return ret, errors.New("只支持select语句")
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kinwyb/godb.git
git@gitee.com:kinwyb/godb.git
kinwyb
godb
godb
febe48a8ab41

搜索帮助

0d507c66 1850385 C8b1a773 1850385