dim/query/query.go

49 lines
1.5 KiB
Go
Raw Normal View History

/*
Package query provides functions useful for building database queries.
It contains functions to build select clauses or where clauses together
with the necessary parameter keys.
*/
package query
import (
"fmt"
"strings"
"dim/types"
)
// FieldListToSelect converts the fieldlist to a select clause.
//
// It takes a fieldField and tries to find a matching name in the nameMap and
// uses the provided name.
// Any field that is not found will be converted to an attributes selector, so
// that extra attributes can be selected dynamically.
// Each field will be selected with the requested name, so be careful to
// avoid collisions.
// The tableName will be used as a prefix to the attributes field. Only one
// attributes field can be used at the same time.
func FieldListToSelect(tableName string, fl types.FieldList, nameMap map[string]string) string {
res := []string{}
for _, name := range fl.Fields() {
if field, found := nameMap[name]; found {
res = append(res, fmt.Sprintf(`%s as %s`, field, name))
} else {
res = append(res, fmt.Sprintf(`%s as %s`, nameToAttrPath(tableName, name), name))
}
}
return strings.Join(res, ",")
}
// nameToAttrPath takes a dotted string and converts it into a json field path.
func nameToAttrPath(tabName, name string) string {
if name == "" {
return tabName + ".attributes"
}
parts := strings.Split(name, ".")
for i, part := range parts {
parts[i] = fmt.Sprintf(`'%s'`, part)
}
return fmt.Sprintf("%s.attributes->%s", tabName, strings.Join(parts, "->"))
}