-
Notifications
You must be signed in to change notification settings - Fork 28
/
labels.go
274 lines (244 loc) · 8.6 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
* Copyright 2018 The Service Manager Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package postgres
import (
"context"
"fmt"
"reflect"
"strings"
"time"
"github.com/Peripli/service-manager/pkg/util"
"github.com/Peripli/service-manager/pkg/query"
"github.com/gofrs/uuid"
"github.com/Peripli/service-manager/pkg/log"
"github.com/jmoiron/sqlx"
)
func updateLabelsAbstract(ctx context.Context, newLabelFunc func(labelID string, labelKey string, labelValue string) (PostgresLabel, error), pgDB pgDB, referenceID string, updateActions []*query.LabelChange) error {
for _, action := range updateActions {
switch action.Operation {
case query.AddLabelOperation:
fallthrough
case query.AddLabelValuesOperation:
for _, labelValue := range action.Values {
if err := addLabel(ctx, newLabelFunc, pgDB, action.Key, labelValue, referenceID); err != nil {
return err
}
}
case query.RemoveLabelOperation:
fallthrough
case query.RemoveLabelValuesOperation:
pgLabel, err := newLabelFunc("", "", "")
if err != nil {
return err
}
if err := removeLabel(ctx, pgDB, pgLabel, referenceID, action.Key, action.Values...); err != nil {
return err
}
}
}
return nil
}
func addLabel(ctx context.Context, newLabelFunc func(labelID string, labelKey string, labelValue string) (PostgresLabel, error), db pgDB, key string, value string, referenceID string) error {
uuids, err := uuid.NewV4()
if err != nil {
return fmt.Errorf("could not generate id for new label: %v", err)
}
labelID := uuids.String()
newLabel, err := newLabelFunc(labelID, key, value)
if err != nil {
return err
}
labelTable := newLabel.LabelsTableName()
referenceColumnName := newLabel.ReferenceColumn()
query := fmt.Sprintf("SELECT * FROM %s WHERE key=$1 and val=$2 and %s=$3", labelTable, referenceColumnName)
log.C(ctx).Debugf("Executing query %s", query)
err = db.GetContext(ctx, newLabel, query, key, value, referenceID)
if checkSQLNoRows(err) == util.ErrNotFoundInStorage {
if _, err := create(ctx, db, labelTable, newLabel); err != nil {
return err
}
} else {
log.C(ctx).Debugf("Nothing to create. Label with key=%s value=%s %s=%s already exists in table %s", key, value, referenceColumnName, referenceID, labelTable)
}
return nil
}
func removeLabel(ctx context.Context, execer sqlx.ExtContext, label PostgresLabel, referenceID, labelKey string, labelValues ...string) error {
labelTableName := label.LabelsTableName()
referenceColumnName := label.ReferenceColumn()
baseQuery := fmt.Sprintf("DELETE FROM %s WHERE key=? AND %s=?", labelTableName, referenceColumnName)
args := []interface{}{labelKey, referenceID}
// remove all labels with this key
if len(labelValues) == 0 {
if err := executeNew(ctx, execer, baseQuery, args); err != nil {
if err == util.ErrNotFoundInStorage {
log.C(ctx).Debugf("Nothing to delete. Label with key=%s %s=%s not found in table %s", labelKey, referenceColumnName, referenceID, labelTableName)
return nil
}
return err
}
return nil
}
// remove labels with a specific key and a value which is in the provided list
args = append(args, labelValues)
baseQuery += " AND val IN (?)"
sqlQuery, queryParams, err := sqlx.In(baseQuery, args...)
if err != nil {
return err
}
if err := executeNew(ctx, execer, sqlQuery, queryParams); err != nil {
if err == util.ErrNotFoundInStorage {
log.C(ctx).Debugf("Nothing to delete. Label with key=%s values in %s %s=%s not found in table %s", labelKey, labelValues, referenceColumnName, referenceID, labelTableName)
return nil
}
return err
}
return nil
}
func buildQueryWithParams(extContext sqlx.ExtContext, sqlQuery string, baseTableName string, labelEntity PostgresLabel, criteria []query.Criterion, dbTags []tagType, querySuffixes ...string) (string, []interface{}, error) {
if len(criteria) == 0 {
return sqlQuery + strings.Join(querySuffixes, " ") + ";", nil, nil
}
var queryParams []interface{}
var fieldQueries []string
var labelQueries []string
labelCriteria, fieldCriteria := splitCriteriaByType(criteria)
if len(labelCriteria) > 0 {
labelTableName := labelEntity.LabelsTableName()
referenceColumnName := labelEntity.ReferenceColumn()
labelSubQuery := fmt.Sprintf("(SELECT * FROM %[1]s WHERE %[2]s IN (SELECT %[2]s FROM %[1]s WHERE ", labelTableName, referenceColumnName)
for _, option := range labelCriteria {
rightOpBindVar, rightOpQueryValue := buildRightOp(option)
sqlOperation := translateOperationToSQLEquivalent(option.Operator)
labelQueries = append(labelQueries, fmt.Sprintf("(%[1]s.key = ? AND %[1]s.val %[2]s %s)", labelTableName, sqlOperation, rightOpBindVar))
queryParams = append(queryParams, option.LeftOp, rightOpQueryValue)
}
labelSubQuery += strings.Join(labelQueries, " OR ")
labelSubQuery += "))"
sqlQuery = strings.Replace(sqlQuery, "LEFT JOIN", "JOIN "+labelSubQuery, 1)
}
if len(fieldCriteria) > 0 {
sqlQuery += " WHERE "
for _, option := range fieldCriteria {
var ttype reflect.Type
if dbTags != nil {
var err error
ttype, err = findTagType(dbTags, option.LeftOp)
if err != nil {
return "", nil, err
}
}
rightOpBindVar, rightOpQueryValue := buildRightOp(option)
sqlOperation := translateOperationToSQLEquivalent(option.Operator)
dbCast := determineCastByType(ttype)
clause := fmt.Sprintf("%s.%s%s %s %s", baseTableName, option.LeftOp, dbCast, sqlOperation, rightOpBindVar)
if option.Operator.IsNullable() {
clause = fmt.Sprintf("(%s OR %s.%s IS NULL)", clause, baseTableName, option.LeftOp)
}
fieldQueries = append(fieldQueries, clause)
queryParams = append(queryParams, rightOpQueryValue)
}
sqlQuery += strings.Join(fieldQueries, " AND ")
}
sqlQuery += strings.Join(querySuffixes, " ") + ";"
if hasMultiVariateOp(criteria) {
var err error
// sqlx.In requires question marks(?) instead of positional arguments (the ones pgsql uses) in order to map the list argument to the IN operation
if sqlQuery, queryParams, err = sqlx.In(sqlQuery, queryParams...); err != nil {
return "", nil, err
}
}
sqlQuery = extContext.Rebind(sqlQuery)
return sqlQuery, queryParams, nil
}
func findTagType(tags []tagType, tagName string) (reflect.Type, error) {
for _, tag := range tags {
if strings.Split(tag.Tag, ",")[0] == tagName {
return tag.Type, nil
}
}
return nil, fmt.Errorf("could not find tag name: %s", tagName)
}
var (
intType = reflect.TypeOf(int(1))
int64Type = reflect.TypeOf(int64(1))
timeType = reflect.TypeOf(time.Time{})
)
func determineCastByType(tagType reflect.Type) string {
dbCast := ""
switch tagType {
case intType:
fallthrough
case int64Type:
fallthrough
case timeType:
dbCast = ""
default:
dbCast = "::text"
}
return dbCast
}
func splitCriteriaByType(criteria []query.Criterion) ([]query.Criterion, []query.Criterion) {
var labelQueries []query.Criterion
var fieldQueries []query.Criterion
for _, criterion := range criteria {
if criterion.Type == query.FieldQuery {
fieldQueries = append(fieldQueries, criterion)
} else {
labelQueries = append(labelQueries, criterion)
}
}
return labelQueries, fieldQueries
}
func buildRightOp(criterion query.Criterion) (string, interface{}) {
rightOpBindVar := "?"
var rhs interface{} = criterion.RightOp[0]
if criterion.Operator.IsMultiVariate() {
rightOpBindVar = "(?)"
rhs = criterion.RightOp
}
return rightOpBindVar, rhs
}
func hasMultiVariateOp(criteria []query.Criterion) bool {
for _, opt := range criteria {
if opt.Operator.IsMultiVariate() {
return true
}
}
return false
}
func translateOperationToSQLEquivalent(operator query.Operator) string {
switch operator {
case query.LessThanOperator:
return "<"
case query.GreaterThanOperator:
return ">"
case query.NotInOperator:
return "NOT IN"
case query.EqualsOrNilOperator:
return "="
default:
return strings.ToUpper(string(operator))
}
}
func executeNew(ctx context.Context, extContext sqlx.ExtContext, query string, args []interface{}) error {
query = extContext.Rebind(query)
log.C(ctx).Debugf("Executing query %s", query)
result, err := extContext.ExecContext(ctx, query, args...)
if err != nil {
return err
}
return checkRowsAffected(ctx, result)
}