2017-04-19 16:03:53 +00:00
|
|
|
package influx
|
|
|
|
|
|
|
|
import "strings"
|
|
|
|
|
2017-04-19 16:08:14 +00:00
|
|
|
// TemplateValue is a value use to replace a template in an InfluxQL query
|
|
|
|
type TemplateValue struct {
|
2017-04-19 16:03:53 +00:00
|
|
|
Value string `json:"value"`
|
|
|
|
Type string `json:"type"`
|
|
|
|
}
|
|
|
|
|
2017-04-19 16:08:14 +00:00
|
|
|
// TemplateVar is a named variable within an InfluxQL query to be replaced with Values
|
|
|
|
type TemplateVar struct {
|
|
|
|
Var string `json:"tempVar"`
|
|
|
|
Values []TemplateValue `json:"values"`
|
2017-04-19 16:03:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// String converts the template variable into a correct InfluxQL string based
|
|
|
|
// on its type
|
2017-04-19 16:08:14 +00:00
|
|
|
func (t TemplateVar) String() string {
|
2017-04-19 16:03:53 +00:00
|
|
|
if len(t.Values) == 0 {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
switch t.Values[0].Type {
|
|
|
|
case "tagKey", "fieldKey":
|
|
|
|
return `"` + t.Values[0].Value + `"`
|
|
|
|
case "tagValue":
|
|
|
|
return `'` + t.Values[0].Value + `'`
|
|
|
|
case "csv":
|
|
|
|
return t.Values[0].Value
|
|
|
|
default:
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-19 16:08:14 +00:00
|
|
|
// TemplateVars are template variables to replace within an InfluxQL query
|
|
|
|
type TemplateVars struct {
|
|
|
|
Vars []TemplateVar `json:"tempVars"`
|
2017-04-19 16:03:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// TemplateReplace replaces templates with values within the query string
|
2017-04-19 16:08:14 +00:00
|
|
|
func TemplateReplace(query string, templates TemplateVars) string {
|
2017-04-19 16:03:53 +00:00
|
|
|
replacements := []string{}
|
|
|
|
for _, v := range templates.Vars {
|
|
|
|
newVal := v.String()
|
|
|
|
if newVal != "" {
|
|
|
|
replacements = append(replacements, v.Var, newVal)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
replacer := strings.NewReplacer(replacements...)
|
|
|
|
replaced := replacer.Replace(query)
|
|
|
|
return replaced
|
|
|
|
}
|