1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
from.go 2.10 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-08-12 22:08 . sql & from
package wrapper
import (
"gitee.com/h79/goutils/dao/option"
"strings"
)
var _ IFrom = (*From)(nil)
var gFromBuilder FromBuilder
type FromBuilder func(table string, opts ...option.Option) (IFrom, bool)
// SetFromBuilder 表名检测,比如名称为 virtual表,返回真名表名是一个子查询
func SetFromBuilder(fn FromBuilder) {
gFromBuilder = fn
}
type From struct {
_from IFrom // for virtual table
From string `json:"from" yaml:"from"`
As string `json:"as" yaml:"as"`
}
func (f *From) Reset() {
f._from = nil
f.From = ""
f.As = ""
}
func (f *From) SetAs(as string) {
f.As = as
}
func (f *From) Is() bool {
return f.From != ""
}
func (f *From) Build(opts ...option.Option) string {
if !f.Is() {
return ""
}
table := f.getTableName(opts...)
child := f.checkChild(table)
builder := strings.Builder{}
builder.WriteString(" FROM ")
if child {
builder.WriteByte('(')
}
f.from(&builder, table, child)
if child {
builder.WriteByte(')')
}
if f.As != table {
AddAlias(&builder, f.As)
}
return builder.String()
}
func (f *From) from(builder *strings.Builder, table string, child bool) bool {
quo := !child
first := table[0]
end := table[len(table)-1]
if first == '`' {
quo = false
}
if quo {
builder.WriteByte('`')
first = '`'
}
builder.WriteString(table)
if first == '`' && end != '`' {
builder.WriteByte('`')
}
return true
}
func (f *From) getTableName(opts ...option.Option) string {
if gFromBuilder == nil {
return f.From
}
if f._from == nil {
from, ok := gFromBuilder(f.From, opts...)
if ok && from != nil {
f._from = from
}
}
if f._from != nil {
return f._from.Build(opts...)
}
return f.From
}
func (f *From) checkChild(table string) bool {
fm := strings.TrimSpace(table)
fm = strings.TrimLeft(fm, "(")
l := len(fm)
if l > 9 {
l = 9
}
up := strings.ToUpper(fm[0:l])
if strings.Contains(up, "DROP") ||
strings.Contains(up, "DELETE") ||
strings.Contains(up, "ALTER") ||
strings.Contains(up, "INSERT") {
strings.Contains(up, "UPDATE")
panic("may be illegal,lead to serious consequences")
}
return strings.Contains(up, "SELECT")
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.122

搜索帮助