/
labels.go
38 lines (30 loc) · 1.11 KB
/
labels.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
package store
import (
"fmt"
"strings"
"github.com/flightctl/flightctl/internal/util"
"gorm.io/gorm"
)
// LabelSelectionQuery applies a label-based selection query to the given GORM DB query.
// It takes a map of labels and a GORM DB query as input.
// The function returns the modified DB query.
func LabelSelectionQuery(query *gorm.DB, labels map[string]string, inverse bool) *gorm.DB {
if len(labels) == 0 {
return query
}
arrayLabels := util.LabelMapToArray(&labels)
// we do this instead of constructing the query string directly because of the Where
// function implementation, finding a ? in the string will trigger one path, @ in the
// string will trigger another path that looks for a pre-stored database query.
arrayPlaceholders := []string{}
arrayValues := []interface{}{}
for _, v := range arrayLabels {
arrayPlaceholders = append(arrayPlaceholders, "?")
arrayValues = append(arrayValues, v)
}
queryString := fmt.Sprintf("labels @> ARRAY[%s]", strings.Join(arrayPlaceholders, ","))
if inverse {
return query.Not(queryString, arrayValues...)
}
return query.Where(queryString, arrayValues...)
}