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

     1  package tpl
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  //MTPLContext  SQLite模板
    10  type MTPLContext struct {
    11  	name   string
    12  	prefix string
    13  }
    14  
    15  //GetSQLContext 获取查询串
    16  func (o MTPLContext) GetSQLContext(tpl string, input map[string]interface{}) (query string, args []interface{}) {
    17  	f := func() string {
    18  		return o.prefix
    19  	}
    20  	return AnalyzeTPLFromCache(o.name, tpl, input, f)
    21  }
    22  
    23  //GetSPContext 获取存储过程
    24  func (o MTPLContext) GetSPContext(tpl string, input map[string]interface{}) (query string, args []interface{}) {
    25  	return o.GetSQLContext(tpl, input)
    26  }
    27  
    28  //Replace 替换SQL中的占位符
    29  func (o MTPLContext) Replace(sql string, args []interface{}) (r string) {
    30  	if strings.EqualFold(sql, "") || args == nil {
    31  		return sql
    32  	}
    33  	word, _ := regexp.Compile(fmt.Sprintf(`\%s([,|\ ;)]|$)`, o.prefix))
    34  	index := -1
    35  	sql = word.ReplaceAllStringFunc(sql, func(s string) string {
    36  		index++
    37  		if index >= len(args) {
    38  			return "NULL" + s[1:]
    39  		}
    40  		return fmt.Sprintf("'%v'%s", args[index], s[1:])
    41  	})
    42  	return sql
    43  }