forked from ovn-org/libovsdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapper.go
317 lines (284 loc) · 9.45 KB
/
mapper.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package mapper
import (
"fmt"
"reflect"
"github.com/ovn-org/libovsdb/ovsdb"
)
// Mapper offers functions to interact with libovsdb through user-provided native structs.
// The way to specify what field of the struct goes
// to what column in the database id through field a field tag.
// The tag used is "ovsdb" and has the following structure
// 'ovsdb:"${COLUMN_NAME}"'
// where COLUMN_NAME is the name of the column and must match the schema
//
//Example:
// type MyObj struct {
// Name string `ovsdb:"name"`
// }
type Mapper struct {
Schema ovsdb.DatabaseSchema
}
// ErrMapper describes an error in an Mapper type
type ErrMapper struct {
objType string
field string
fieldType string
fieldTag string
reason string
}
func (e *ErrMapper) Error() string {
return fmt.Sprintf("Mapper Error. Object type %s contains field %s (%s) ovs tag %s: %s",
e.objType, e.field, e.fieldType, e.fieldTag, e.reason)
}
// NewMapper returns a new mapper
func NewMapper(schema ovsdb.DatabaseSchema) Mapper {
return Mapper{
Schema: schema,
}
}
// GetRowData transforms a Row to a struct based on its tags
// The result object must be given as pointer to an object with the right tags
func (m Mapper) GetRowData(row *ovsdb.Row, result *Info) error {
if row == nil {
return nil
}
return m.getData(*row, result)
}
// getData transforms a map[string]interface{} containing OvS types (e.g: a ResultRow
// has this format) to orm struct
// The result object must be given as pointer to an object with the right tags
func (m Mapper) getData(ovsData ovsdb.Row, result *Info) error {
for name, column := range result.Metadata.TableSchema.Columns {
if !result.hasColumn(name) {
// If provided struct does not have a field to hold this value, skip it
continue
}
ovsElem, ok := ovsData[name]
if !ok {
// Ignore missing columns
continue
}
nativeElem, err := ovsdb.OvsToNative(column, ovsElem)
if err != nil {
return fmt.Errorf("table %s, column %s: failed to extract native element: %s",
result.Metadata.TableName, name, err.Error())
}
if err := result.SetField(name, nativeElem); err != nil {
return err
}
}
return nil
}
// NewRow transforms an orm struct to a map[string] interface{} that can be used as libovsdb.Row
// By default, default or null values are skipped. This behavior can be modified by specifying
// a list of fields (pointers to fields in the struct) to be added to the row
func (m Mapper) NewRow(data *Info, fields ...interface{}) (ovsdb.Row, error) {
columns := make(map[string]*ovsdb.ColumnSchema)
for k, v := range data.Metadata.TableSchema.Columns {
columns[k] = v
}
columns["_uuid"] = &ovsdb.UUIDColumn
ovsRow := make(map[string]interface{}, len(columns))
for name, column := range columns {
nativeElem, err := data.FieldByColumn(name)
if err != nil {
// If provided struct does not have a field to hold this value, skip it
continue
}
// add specific fields
if len(fields) > 0 {
found := false
for _, f := range fields {
col, err := data.ColumnByPtr(f)
if err != nil {
return nil, err
}
if col == name {
found = true
break
}
}
if !found {
continue
}
}
if len(fields) == 0 && ovsdb.IsDefaultValue(column, nativeElem) {
continue
}
ovsElem, err := ovsdb.NativeToOvs(column, nativeElem)
if err != nil {
return nil, fmt.Errorf("table %s, column %s: failed to generate ovs element. %s", data.Metadata.TableName, name, err.Error())
}
ovsRow[name] = ovsElem
}
return ovsRow, nil
}
// NewEqualityCondition returns a list of equality conditions that match a given object
// A list of valid columns that shall be used as a index can be provided.
// If none are provided, we will try to use object's field that matches the '_uuid' ovsdb tag
// If it does not exist or is null (""), then we will traverse all of the table indexes and
// use the first index (list of simultaneously unique columns) for which the provided mapper
// object has valid data. The order in which they are traversed matches the order defined
// in the schema.
// By `valid data` we mean non-default data.
func (m Mapper) NewEqualityCondition(data *Info, fields ...interface{}) ([]ovsdb.Condition, error) {
var conditions []ovsdb.Condition
var condIndex [][]string
// If index is provided, use it. If not, obtain the valid indexes from the mapper info
if len(fields) > 0 {
providedIndex := []string{}
for i := range fields {
if col, err := data.ColumnByPtr(fields[i]); err == nil {
providedIndex = append(providedIndex, col)
} else {
return nil, err
}
}
condIndex = append(condIndex, providedIndex)
} else {
var err error
condIndex, err = data.getValidIndexes()
if err != nil {
return nil, err
}
}
if len(condIndex) == 0 {
return nil, fmt.Errorf("failed to find a valid index")
}
// Pick the first valid index
for _, col := range condIndex[0] {
field, err := data.FieldByColumn(col)
if err != nil {
return nil, err
}
column := data.Metadata.TableSchema.Column(col)
if column == nil {
return nil, fmt.Errorf("column %s not found", col)
}
ovsVal, err := ovsdb.NativeToOvs(column, field)
if err != nil {
return nil, err
}
conditions = append(conditions, ovsdb.NewCondition(col, ovsdb.ConditionEqual, ovsVal))
}
return conditions, nil
}
// EqualFields compares two mapped objects.
// The indexes to use for comparison are, the _uuid, the table indexes and the columns that correspond
// to the mapped fields pointed to by 'fields'. They must be pointers to fields on the first mapped element (i.e: one)
func (m Mapper) EqualFields(one, other *Info, fields ...interface{}) (bool, error) {
indexes := []string{}
for _, f := range fields {
col, err := one.ColumnByPtr(f)
if err != nil {
return false, err
}
indexes = append(indexes, col)
}
return m.equalIndexes(one, other, indexes...)
}
// NewCondition returns a ovsdb.Condition based on the model
func (m Mapper) NewCondition(data *Info, field interface{}, function ovsdb.ConditionFunction, value interface{}) (*ovsdb.Condition, error) {
column, err := data.ColumnByPtr(field)
if err != nil {
return nil, err
}
// Check that the condition is valid
columnSchema := data.Metadata.TableSchema.Column(column)
if columnSchema == nil {
return nil, fmt.Errorf("column %s not found", column)
}
if err := ovsdb.ValidateCondition(columnSchema, function, value); err != nil {
return nil, err
}
ovsValue, err := ovsdb.NativeToOvs(columnSchema, value)
if err != nil {
return nil, err
}
ovsdbCondition := ovsdb.NewCondition(column, function, ovsValue)
return &ovsdbCondition, nil
}
// NewMutation creates a RFC7047 mutation object based on an ORM object and the mutation fields (in native format)
// It takes care of field validation against the column type
func (m Mapper) NewMutation(data *Info, column string, mutator ovsdb.Mutator, value interface{}) (*ovsdb.Mutation, error) {
// Check the column exists in the object
if !data.hasColumn(column) {
return nil, fmt.Errorf("mutation contains column %s that does not exist in object %v", column, data)
}
// Check that the mutation is valid
columnSchema := data.Metadata.TableSchema.Column(column)
if columnSchema == nil {
return nil, fmt.Errorf("column %s not found", column)
}
if err := ovsdb.ValidateMutation(columnSchema, mutator, value); err != nil {
return nil, err
}
var ovsValue interface{}
var err error
// Usually a mutation value is of the same type of the value being mutated
// except for delete mutation of maps where it can also be a list of same type of
// keys (rfc7047 5.1). Handle this special case here.
if mutator == "delete" && columnSchema.Type == ovsdb.TypeMap && reflect.TypeOf(value).Kind() != reflect.Map {
// It's OK to cast the value to a list of elements because validation has passed
ovsSet, err := ovsdb.NewOvsSet(value)
if err != nil {
return nil, err
}
ovsValue = ovsSet
} else {
ovsValue, err = ovsdb.NativeToOvs(columnSchema, value)
if err != nil {
return nil, err
}
}
return &ovsdb.Mutation{Column: column, Mutator: mutator, Value: ovsValue}, nil
}
// equalIndexes returns whether both models are equal from the DB point of view
// Two objects are considered equal if any of the following conditions is true
// They have a field tagged with column name '_uuid' and their values match
// For any of the indexes defined in the Table Schema, the values all of its columns are simultaneously equal
// (as per RFC7047)
// The values of all of the optional indexes passed as variadic parameter to this function are equal.
func (m Mapper) equalIndexes(one, other *Info, indexes ...string) (bool, error) {
match := false
oneIndexes, err := one.getValidIndexes()
if err != nil {
return false, err
}
otherIndexes, err := other.getValidIndexes()
if err != nil {
return false, err
}
oneIndexes = append(oneIndexes, indexes)
otherIndexes = append(otherIndexes, indexes)
for _, lidx := range oneIndexes {
for _, ridx := range otherIndexes {
if reflect.DeepEqual(ridx, lidx) {
// All columns in an index must be simultaneously equal
for _, col := range lidx {
if !one.hasColumn(col) || !other.hasColumn(col) {
break
}
lfield, err := one.FieldByColumn(col)
if err != nil {
return false, err
}
rfield, err := other.FieldByColumn(col)
if err != nil {
return false, err
}
if reflect.DeepEqual(lfield, rfield) {
match = true
} else {
match = false
break
}
}
if match {
return true, nil
}
}
}
}
return false, nil
}