-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
95 lines (74 loc) · 2.16 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package nodedb
// uses go text/template for primite string replacement
import (
"bytes"
"fmt"
"strings"
"text/template"
)
//SQLString provide changed text replacements to form a valid sql string
type SQLString string
func process(t *template.Template, vars interface{}) string {
var tmplBytes bytes.Buffer
err := t.Execute(&tmplBytes, vars)
if err != nil {
panic(err) // TODO better error handling
}
return tmplBytes.String()
}
func processString(str string, vars interface{}) string {
tmpl, err := template.New("tmpl").Parse(str)
if err != nil {
panic(err) // TODO better error handling
}
return process(tmpl, vars)
}
func intSliceToString(ints []int64) string {
s := make([]string, len(ints), len(ints))
for i, n := range ints {
s[i] = fmt.Sprint(n)
}
return strings.Join(s, ",")
}
// helper: replaces collection name template
func (sql SQLString) Collection(collectionname string) SQLString {
values := baseMap()
values["collection"] = collectionname
return processSQLString(sql, values)
}
// helper: replaces commaContent, handles with or without content variations
func (sql SQLString) WithContent(withContent bool) SQLString {
values := baseMap()
values["commaContent"] = ""
values["commaQuestionMark"] = ""
if withContent {
values["commaContent"] = ",content"
values["commaQuestionMark"] = ",?"
}
return processSQLString(sql, values)
}
// helper: replaces nodeids, handles 'id in (...)' clauses
func (sql SQLString) NodeIDs(nodeIDs []int64) SQLString {
values := baseMap()
values["nodeids"] = intSliceToString(nodeIDs)
return processSQLString(sql, values)
}
func (sql SQLString) String() string {
return string(sql)
}
func baseMap() map[string]string { // replacement invariants
result := make(map[string]string)
result["collection"] = "{{.collection}}"
result["commaContent"] = "{{.commaContent}}"
result["commaQuestionMark"] = "{{.commaQuestionMark}}"
result["nodeids"] = "{{.nodeids}}"
return result
}
func processSQLString(sql SQLString, vars interface{}) SQLString {
str := string(sql)
tmpl, err := template.New("tmpl").Parse(str)
if err != nil {
panic(err) // TODO better error handling
}
return SQLString(process(tmpl, vars))
}