github.com/qxnw/lib4go@v0.0.0-20180426074627-c80c7e84b925/db/tpl/tpl.go (about)

     1  package tpl
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/qxnw/lib4go/concurrent/cmap"
     8  )
     9  
    10  const (
    11  	cOra    = "ora"
    12  	cOracle = "oracle"
    13  	cSqlite = "sqlite"
    14  )
    15  
    16  var (
    17  	tpls      map[string]ITPLContext
    18  	tplCaches cmap.ConcurrentMap
    19  )
    20  
    21  //ITPLContext 模板上下文
    22  type ITPLContext interface {
    23  	GetSQLContext(tpl string, input map[string]interface{}) (query string, args []interface{})
    24  	GetSPContext(tpl string, input map[string]interface{}) (query string, args []interface{})
    25  	Replace(sql string, args []interface{}) (r string)
    26  }
    27  
    28  func init() {
    29  	tpls = make(map[string]ITPLContext)
    30  	tplCaches = cmap.New(8)
    31  
    32  	Register("oracle", ATTPLContext{name: "oracle"})
    33  	Register("ora", ATTPLContext{name: "ora"})
    34  	Register("mysql", MTPLContext{name: "mysql"})
    35  	Register("sqlite", MTPLContext{name: "sqlite"})
    36  }
    37  func Register(name string, tpl ITPLContext) {
    38  	if _, ok := tpls[name]; ok {
    39  		panic("重复的注册:" + name)
    40  	}
    41  	tpls[name] = tpl
    42  }
    43  
    44  //GetDBContext 获取数据库上下文操作
    45  func GetDBContext(name string) (ITPLContext, error) {
    46  	if v, ok := tpls[strings.ToLower(name)]; ok {
    47  		return v, nil
    48  	}
    49  	return nil, fmt.Errorf("不支持的数据库类型:%s", name)
    50  }