github.com/sereiner/library@v0.0.0-20200518095232-1fa3e640cc5f/db/tpl/tpl.at.go (about)

     1  package tpl
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  //ATTPLContext 参数化时使用@+参数名作为占位符的SQL数据库如:oracle,sql server
    11  type ATTPLContext struct {
    12  	name   string
    13  	prefix string
    14  }
    15  
    16  func (o ATTPLContext) getSPName(query string) string {
    17  	return fmt.Sprintf("begin %s;end;", strings.Trim(strings.Trim(query, ";"), ","))
    18  }
    19  
    20  //GetSQLContext 获取查询串
    21  func (o ATTPLContext) GetSQLContext(tpl string, input map[string]interface{}) (sql string, args []interface{}) {
    22  	index := 0
    23  	f := func() string {
    24  		index++
    25  		return fmt.Sprint(o.prefix, index)
    26  	}
    27  	return AnalyzeTPLFromCache(o.name, tpl, input, f)
    28  }
    29  
    30  //GetSPContext 获取
    31  func (o ATTPLContext) GetSPContext(tpl string, input map[string]interface{}) (sql string, args []interface{}) {
    32  	q, args := o.GetSQLContext(tpl, input)
    33  	sql = o.getSPName(q)
    34  	return
    35  }
    36  
    37  //Replace 替换SQL中的占位符
    38  func (o ATTPLContext) Replace(sql string, args []interface{}) (r string) {
    39  	if sql == "" || args == nil {
    40  		return sql
    41  	}
    42  	word, _ := regexp.Compile(fmt.Sprintf(`%s\d+([,|\) ;]|$)`, o.prefix))
    43  	sql = word.ReplaceAllStringFunc(sql, func(s string) string {
    44  		c := len(s)
    45  		num := s[1 : c-1]
    46  		// 处理匹配到结尾
    47  		if num == "" {
    48  			num = s[1:c]
    49  			c++
    50  		}
    51  		k, err := strconv.Atoi(num)
    52  		if err != nil || len(args) < k {
    53  			return "NULL" + s[c-1:]
    54  		}
    55  		return fmt.Sprintf("'%v'%s", args[k-1], s[c-1:])
    56  	})
    57  	/*end*/
    58  	return sql
    59  }