sql-builder/db/build.go

105 lines
2.9 KiB
Go

package db
import (
"fmt"
"regexp"
"strings"
"git.botann.com/lijun/sql-builder/util"
)
func (s *SqlBuilder[T]) buildSql() string {
s.DeletePlaceholderSymbol()
if s.Driver == util.DriverOracle {
s.Sql = fmt.Sprintf("select t.*,rownum rn from (%s) t", s.Sql)
}
return s.Sql
}
func (s *SqlBuilder[T]) buildPaginateSql(sqls string) string {
s.Opts.Page.Init()
pageIndex := s.Opts.Page.GetPageIndex()
pageSize := s.Opts.Page.GetPageSize()
if s.Driver == util.DriverMysql {
return fmt.Sprintf("%s limit %d offset %d", sqls, pageSize, (pageIndex-1)*pageSize)
} else if s.Driver == util.DriverOracle {
return fmt.Sprintf("select * from (%s where rownum <= %d) where rn > %d", sqls, pageIndex*pageSize, (pageIndex-1)*pageSize)
} else {
return fmt.Sprintf("%s limit %d offset %d", sqls, pageSize, (pageIndex-1)*pageSize)
}
}
func (s *SqlBuilder[T]) buildCountSql(sqls string) string {
return fmt.Sprintf("select count(1) from (%s) t", sqls)
}
func (s *SqlBuilder[T]) buildSelect(symbol string, selects ...string) {
for _, v := range selects {
if strings.HasPrefix(v, "select") {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf("%s", v), 1)
} else {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf(",%s", v), 1)
}
}
}
func (s *SqlBuilder[T]) buildCondition(symbol string, conds ...string) {
for _, v := range conds {
if strings.HasPrefix(v, "where") {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf(" %s", v), 1)
} else {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf(" and %s", v), 1)
}
}
}
func (s *SqlBuilder[T]) buildGroup(symbol string, groups ...string) {
for _, v := range groups {
if strings.HasPrefix(v, "group by") {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf("%s", v), 1)
} else {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf(",%s", v), 1)
}
}
}
func (s *SqlBuilder[T]) buildOrder(symbol string, orders ...string) {
for _, v := range orders {
if strings.HasPrefix(v, "order by") {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf("%s", v), 1)
} else {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf(",%s", v), 1)
}
}
}
// tdengine专用
func (s *SqlBuilder[T]) buildPartition(symbol string, partitions ...string) {
for _, v := range partitions {
if strings.HasPrefix(v, "partition by") {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf("%s", v), 1)
} else {
s.Sql = strings.Replace(s.Sql, symbol, fmt.Sprintf(",%s", v), 1)
}
}
}
func (s *SqlBuilder[T]) DeletePlaceholderSymbol() {
s.deleteSymbol(util.SelectPlaceholder)
s.deleteSymbol(util.ConditionPlaceholder)
s.deleteSymbol(util.GroupPlaceholder)
s.deleteSymbol(util.OrderPlaceholder)
s.deleteSymbol(util.PartitionPlaceholder)
}
func (s *SqlBuilder[T]) deleteSymbol(symbol string) {
pattern := fmt.Sprintf("%s\\d*", symbol)
re, err := regexp.Compile(pattern)
if err != nil {
fmt.Println("正则表达式编译错误:", err)
return
}
s.Sql = re.ReplaceAllString(s.Sql, "")
}