github.com/qxnw/lib4go@v0.0.0-20180426074627-c80c7e84b925/db/tpl/tpl.analyze.go (about) 1 package tpl 2 3 import ( 4 "fmt" 5 "regexp" 6 ) 7 8 func isNil(input interface{}) bool { 9 return input == nil || fmt.Sprintf("%v", input) == "" 10 } 11 12 type tplCache struct { 13 sql string 14 params []interface{} 15 names []string 16 } 17 18 //AnalyzeTPLFromCache 从缓存中获取已解析的SQL语句 19 func AnalyzeTPLFromCache(name string, tpl string, input map[string]interface{}, prefix func() string) (sql string, params []interface{}) { 20 sql, params, _ = AnalyzeTPL(tpl, input, prefix) 21 return 22 /*key := fmt.Sprintf("%s_%s", name, tpl) 23 b, cache, _ := tplCaches.SetIfAbsentCb(key, func(i ...interface{}) (interface{}, error) { 24 sql, params, names := AnalyzeTPL(tpl, input, prefix) 25 return &tplCache{sql: sql, params: params, names: names}, nil 26 }) 27 value := cache.(*tplCache) 28 if b { 29 return value.sql, value.params 30 } 31 params = make([]interface{}, 0, len(value.names)) 32 for _, v := range value.names { 33 va := input[v] 34 if !isNil(va) { 35 params = append(params, va) 36 } else { 37 params = append(params, nil) 38 } 39 } 40 return value.sql, params*/ 41 } 42 43 //AnalyzeTPL 解析模板内容,并返回解析后的SQL语句,入输入参数 44 //@表达式,替换为参数化字符如: :1,:2,:3 45 //#表达式,替换为指定值,值为空时返回NULL 46 //~表达式,检查值,值为空时返加"",否则返回: , name=value 47 //&条件表达式,检查值,值为空时返加"",否则返回: and name=value 48 //|条件表达式,检查值,值为空时返回"", 否则返回: or name=value 49 func AnalyzeTPL(tpl string, input map[string]interface{}, prefix func() string) (sql string, params []interface{}, names []string) { 50 params = make([]interface{}, 0) 51 names = make([]string, 0) 52 word, _ := regexp.Compile(`[@|#|&|~|\||!]\w+`) 53 //@变量, 将数据放入params中 54 sql = word.ReplaceAllStringFunc(tpl, func(s string) string { 55 //fullKey := s[1:] 56 key := s[1:] 57 //if strings.Index(fullKey, ".") > 0 { 58 //key = strings.Split(fullKey, ".")[1] 59 //} 60 pre := s[:1] 61 value := input[key] 62 switch pre { 63 case "@": 64 if !isNil(value) { 65 names = append(names, key) 66 params = append(params, value) 67 } else { 68 names = append(names, key) 69 params = append(params, nil) 70 } 71 72 return prefix() 73 case "#": 74 if !isNil(value) { 75 return fmt.Sprintf("%v", value) 76 } 77 return "NULL" 78 case "&": 79 if !isNil(value) { 80 names = append(names, key) 81 params = append(params, value) 82 return fmt.Sprintf("and %s=%s", key, prefix()) 83 } 84 return "" 85 case "|": 86 if !isNil(value) { 87 names = append(names, key) 88 params = append(params, value) 89 return fmt.Sprintf("or %s=%s", key, prefix()) 90 } 91 return "" 92 case "~": 93 if !isNil(value) { 94 names = append(names, key) 95 params = append(params, value) 96 return fmt.Sprintf(",%s=%s", key, prefix()) 97 } 98 return "" 99 default: 100 return s 101 } 102 }) 103 return 104 }