define a base table for attributes

When extra fields are fetched from the attributes column it must be
specified from which table that should be. If not done and another table
also has an attribute column, it will end in an error.
This commit is contained in:
Gibheer 2021-05-03 19:41:28 +02:00
parent c18d165a5f
commit 9e6a6fbe28
1 changed files with 7 additions and 5 deletions

View File

@ -21,26 +21,28 @@ import (
// that extra attributes can be selected dynamically. // that extra attributes can be selected dynamically.
// Each field will be selected with the requested name, so be careful to // Each field will be selected with the requested name, so be careful to
// avoid collisions. // avoid collisions.
func FieldListToSelect(fl types.FieldList, nameMap map[string]string) string { // 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{} res := []string{}
for _, name := range fl.Fields() { for _, name := range fl.Fields() {
if field, found := nameMap[name]; found { if field, found := nameMap[name]; found {
res = append(res, fmt.Sprintf(`%s as %s`, field, name)) res = append(res, fmt.Sprintf(`%s as %s`, field, name))
} else { } else {
res = append(res, fmt.Sprintf(`%s as %s`, nameToAttrPath(name), name)) res = append(res, fmt.Sprintf(`%s as %s`, nameToAttrPath(tableName, name), name))
} }
} }
return strings.Join(res, ",") return strings.Join(res, ",")
} }
// nameToAttrPath takes a dotted string and converts it into a json field path. // nameToAttrPath takes a dotted string and converts it into a json field path.
func nameToAttrPath(name string) string { func nameToAttrPath(tabName, name string) string {
if name == "" { if name == "" {
return "attributes" return tabName + ".attributes"
} }
parts := strings.Split(name, ".") parts := strings.Split(name, ".")
for i, part := range parts { for i, part := range parts {
parts[i] = fmt.Sprintf(`'%s'`, part) parts[i] = fmt.Sprintf(`'%s'`, part)
} }
return fmt.Sprintf("attributes->%s", strings.Join(parts, "->")) return fmt.Sprintf("%s.attributes->%s", tabName, strings.Join(parts, "->"))
} }