File: schema.go

package info (click to toggle)
golang-github-ovn-org-libovsdb 0.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 1,440 kB
  • sloc: makefile: 52; sh: 14
file content (641 lines) | stat: -rw-r--r-- 17,472 bytes parent folder | download | duplicates (2)
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
package ovsdb

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"os"
	"strings"
)

// DatabaseSchema is a database schema according to RFC7047
type DatabaseSchema struct {
	Name          string                 `json:"name"`
	Version       string                 `json:"version"`
	Tables        map[string]TableSchema `json:"tables"`
	allTablesRoot *bool
}

// UUIDColumn is a static column that represents the _uuid column, common to all tables
var UUIDColumn = ColumnSchema{
	Type: TypeUUID,
}

// Table returns a TableSchema Schema for a given table and column name
func (schema DatabaseSchema) Table(tableName string) *TableSchema {
	if table, ok := schema.Tables[tableName]; ok {
		return &table
	}
	return nil
}

// IsRoot whether a table is root or not
func (schema DatabaseSchema) IsRoot(tableName string) (bool, error) {
	t := schema.Table(tableName)
	if t == nil {
		return false, fmt.Errorf("Table %s not in schame", tableName)
	}
	if t.IsRoot {
		return true, nil
	}
	// As per RFC7047, for compatibility with schemas created before
	// "isRoot" was introduced, if "isRoot" is omitted or false in every
	// <table-schema> in a given <database-schema>, then every table is part
	// of the root set.
	if schema.allTablesRoot == nil {
		allTablesRoot := true
		for _, tSchema := range schema.Tables {
			if tSchema.IsRoot {
				allTablesRoot = false
				break
			}
		}
		schema.allTablesRoot = &allTablesRoot
	}
	return *schema.allTablesRoot, nil
}

// Print will print the contents of the DatabaseSchema
func (schema DatabaseSchema) Print(w io.Writer) {
	fmt.Fprintf(w, "%s, (%s)\n", schema.Name, schema.Version)
	for table, tableSchema := range schema.Tables {
		fmt.Fprintf(w, "\t %s", table)
		if len(tableSchema.Indexes) > 0 {
			fmt.Fprintf(w, "(%v)\n", tableSchema.Indexes)
		} else {
			fmt.Fprintf(w, "\n")
		}
		for column, columnSchema := range tableSchema.Columns {
			fmt.Fprintf(w, "\t\t %s => %s\n", column, columnSchema)
		}
	}
}

// SchemaFromFile returns a DatabaseSchema from a file
func SchemaFromFile(f *os.File) (DatabaseSchema, error) {
	data, err := ioutil.ReadAll(f)
	if err != nil {
		return DatabaseSchema{}, err
	}
	var schema DatabaseSchema
	err = json.Unmarshal(data, &schema)
	if err != nil {
		return DatabaseSchema{}, err
	}
	return schema, nil
}

// ValidateOperations performs basic validation for operations against a DatabaseSchema
func (schema DatabaseSchema) ValidateOperations(operations ...Operation) bool {
	for _, op := range operations {
		switch op.Op {
		case OperationAbort, OperationAssert, OperationComment, OperationCommit, OperationWait:
			continue
		case OperationInsert, OperationSelect, OperationUpdate, OperationMutate, OperationDelete:
			table, ok := schema.Tables[op.Table]
			if ok {
				for column := range op.Row {
					if _, ok := table.Columns[column]; !ok {
						if column != "_uuid" && column != "_version" {
							return false
						}
					}
				}
				for _, row := range op.Rows {
					for column := range row {
						if _, ok := table.Columns[column]; !ok {
							if column != "_uuid" && column != "_version" {
								return false
							}
						}
					}
				}
				for _, column := range op.Columns {
					if _, ok := table.Columns[column]; !ok {
						if column != "_uuid" && column != "_version" {
							return false
						}
					}
				}
			} else {
				return false
			}
		}
	}
	return true
}

// TableSchema is a table schema according to RFC7047
type TableSchema struct {
	Columns map[string]*ColumnSchema `json:"columns"`
	Indexes [][]string               `json:"indexes,omitempty"`
	IsRoot  bool                     `json:"isRoot,omitempty"`
}

// Column returns the Column object for a specific column name
func (t TableSchema) Column(columnName string) *ColumnSchema {
	if columnName == "_uuid" {
		return &UUIDColumn
	}
	if column, ok := t.Columns[columnName]; ok {
		return column
	}
	return nil
}

/*RFC7047 defines some atomic-types (e.g: integer, string, etc). However, the Column's type
can also hold other more complex types such as set, enum and map. The way to determine the type
depends on internal, not directly marshallable fields. Therefore, in order to simplify the usage
of this library, we define an ExtendedType that includes all possible column types (including
atomic fields).
*/

// ExtendedType includes atomic types as defined in the RFC plus Enum, Map and Set
type ExtendedType = string

// RefType is used to define the possible RefTypes
type RefType = string

// unlimited is not constant as we can't take the address of int constants
var (
	// Unlimited is used to express unlimited "Max"
	Unlimited = -1
)

const (
	unlimitedString = "unlimited"
	//Strong RefType
	Strong RefType = "strong"
	//Weak RefType
	Weak RefType = "weak"

	//ExtendedType associated with Atomic Types

	//TypeInteger is equivalent to 'int'
	TypeInteger ExtendedType = "integer"
	//TypeReal is equivalent to 'float64'
	TypeReal ExtendedType = "real"
	//TypeBoolean is equivalent to 'bool'
	TypeBoolean ExtendedType = "boolean"
	//TypeString is equivalent to 'string'
	TypeString ExtendedType = "string"
	//TypeUUID is equivalent to 'libovsdb.UUID'
	TypeUUID ExtendedType = "uuid"

	//Extended Types used to summarize the internal type of the field.

	//TypeEnum is an enumerator of type defined by Key.Type
	TypeEnum ExtendedType = "enum"
	//TypeMap is a map whose type depend on Key.Type and Value.Type
	TypeMap ExtendedType = "map"
	//TypeSet is a set whose type depend on Key.Type
	TypeSet ExtendedType = "set"
)

// BaseType is a base-type structure as per RFC7047
type BaseType struct {
	Type       string
	Enum       []interface{}
	minReal    *float64
	maxReal    *float64
	minInteger *int
	maxInteger *int64
	minLength  *int
	maxLength  *int
	refTable   *string
	refType    *RefType
}

func (b *BaseType) simpleAtomic() bool {
	return isAtomicType(b.Type) && b.Enum == nil && b.minReal == nil && b.maxReal == nil && b.minInteger == nil && b.maxInteger == nil && b.minLength == nil && b.maxLength == nil && b.refTable == nil && b.refType == nil
}

// MinReal returns the minimum real value
// RFC7047 does not define a default, but we assume this to be
// the smallest non zero value a float64 could hold
func (b *BaseType) MinReal() (float64, error) {
	if b.Type != TypeReal {
		return 0, fmt.Errorf("%s is not a real", b.Type)
	}
	if b.minReal != nil {
		return *b.minReal, nil
	}
	return math.SmallestNonzeroFloat64, nil
}

// MaxReal returns the maximum real value
// RFC7047 does not define a default, but this would be the maximum
// value held by a float64
func (b *BaseType) MaxReal() (float64, error) {
	if b.Type != TypeReal {
		return 0, fmt.Errorf("%s is not a real", b.Type)
	}
	if b.maxReal != nil {
		return *b.maxReal, nil
	}
	return math.MaxFloat64, nil
}

// MinInteger returns the minimum integer value
// RFC7047 specifies the minimum to be -2^63
func (b *BaseType) MinInteger() (int, error) {
	if b.Type != TypeInteger {
		return 0, fmt.Errorf("%s is not an integer", b.Type)
	}
	if b.minInteger != nil {
		return *b.minInteger, nil
	}
	return int(math.Pow(-2, 63)), nil
}

// MaxInteger returns the minimum integer value
// RFC7047 specifies the minimum to be 2^63-1
func (b *BaseType) MaxInteger() (int64, error) {
	if b.Type != TypeInteger {
		return 0, fmt.Errorf("%s is not an integer", b.Type)
	}
	if b.maxInteger != nil {
		return *b.maxInteger, nil
	}
	return int64(math.Pow(2, 63)) - 1, nil
}

// MinLength returns the minimum string length
// RFC7047 doesn't specify a default, but we assume
// that it must be >= 0
func (b *BaseType) MinLength() (int, error) {
	if b.Type != TypeString {
		return 0, fmt.Errorf("%s is not an string", b.Type)
	}
	if b.minLength != nil {
		return *b.minLength, nil
	}
	return 0, nil
}

// MaxLength returns the maximum string length
// RFC7047 doesn't specify a default, but we assume
// that it must 2^63-1
func (b *BaseType) MaxLength() (int, error) {
	if b.Type != TypeString {
		return 0, fmt.Errorf("%s is not an string", b.Type)
	}
	if b.maxLength != nil {
		return *b.maxLength, nil
	}
	return int(math.Pow(2, 63)) - 1, nil
}

// RefTable returns the table to which a UUID type refers
// It will return an empty string if not set
func (b *BaseType) RefTable() (string, error) {
	if b.Type != TypeUUID {
		return "", fmt.Errorf("%s is not a uuid", b.Type)
	}
	if b.refTable != nil {
		return *b.refTable, nil
	}
	return "", nil
}

// RefType returns the reference type for a UUID field
// RFC7047 infers the RefType is strong if omitted
func (b *BaseType) RefType() (RefType, error) {
	if b.Type != TypeUUID {
		return "", fmt.Errorf("%s is not a uuid", b.Type)
	}
	if b.refType != nil {
		return *b.refType, nil
	}
	return Strong, nil
}

// UnmarshalJSON unmarshals a json-formatted base type
func (b *BaseType) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err == nil {
		if isAtomicType(s) {
			b.Type = s
		} else {
			return fmt.Errorf("non atomic type %s in <base-type>", s)
		}
		return nil
	}
	// temporary type to avoid recursive call to unmarshal
	var bt struct {
		Type       string      `json:"type"`
		Enum       interface{} `json:"enum,omitempty"`
		MinReal    *float64    `json:"minReal,omitempty"`
		MaxReal    *float64    `json:"maxReal,omitempty"`
		MinInteger *int        `json:"minInteger,omitempty"`
		MaxInteger *int64      `json:"maxInteger,omitempty"`
		MinLength  *int        `json:"minLength,omitempty"`
		MaxLength  *int        `json:"maxLength,omitempty"`
		RefTable   *string     `json:"refTable,omitempty"`
		RefType    *RefType    `json:"refType,omitempty"`
	}
	err := json.Unmarshal(data, &bt)
	if err != nil {
		return err
	}

	if bt.Enum != nil {
		// 'enum' is a list or a single element representing a list of exactly one element
		switch bt.Enum.(type) {
		case []interface{}:
			// it's an OvsSet
			oSet := bt.Enum.([]interface{})
			innerSet := oSet[1].([]interface{})
			b.Enum = make([]interface{}, len(innerSet))
			copy(b.Enum, innerSet)
		default:
			b.Enum = []interface{}{bt.Enum}
		}
	}
	b.Type = bt.Type
	b.minReal = bt.MinReal
	b.maxReal = bt.MaxReal
	b.minInteger = bt.MinInteger
	b.maxInteger = bt.MaxInteger
	b.minLength = bt.MaxLength
	b.maxLength = bt.MaxLength
	b.refTable = bt.RefTable
	b.refType = bt.RefType
	return nil
}

// MarshalJSON marshals a base type to JSON
func (b BaseType) MarshalJSON() ([]byte, error) {
	j := struct {
		Type       string   `json:"type,omitempty"`
		Enum       *OvsSet  `json:"enum,omitempty"`
		MinReal    *float64 `json:"minReal,omitempty"`
		MaxReal    *float64 `json:"maxReal,omitempty"`
		MinInteger *int     `json:"minInteger,omitempty"`
		MaxInteger *int64   `json:"maxInteger,omitempty"`
		MinLength  *int     `json:"minLength,omitempty"`
		MaxLength  *int     `json:"maxLength,omitempty"`
		RefTable   *string  `json:"refTable,omitempty"`
		RefType    *RefType `json:"refType,omitempty"`
	}{
		Type:       b.Type,
		MinReal:    b.minReal,
		MaxReal:    b.maxReal,
		MinInteger: b.minInteger,
		MaxInteger: b.maxInteger,
		MinLength:  b.maxLength,
		MaxLength:  b.maxLength,
		RefTable:   b.refTable,
		RefType:    b.refType,
	}
	if len(b.Enum) > 0 {
		set, err := NewOvsSet(b.Enum)
		if err != nil {
			return nil, err
		}
		j.Enum = &set
	}
	return json.Marshal(j)
}

// ColumnType is a type object as per RFC7047
// "key": <base-type>                 required
// "value": <base-type>               optional
// "min": <integer>                   optional (default: 1)
// "max": <integer> or "unlimited"    optional (default: 1)
type ColumnType struct {
	Key   *BaseType
	Value *BaseType
	min   *int
	max   *int
}

// Max returns the maximum value of a ColumnType. -1 is Unlimited
func (c *ColumnType) Max() int {
	if c.max == nil {
		return 1
	}
	return *c.max
}

// Min returns the minimum value of a ColumnType
func (c *ColumnType) Min() int {
	if c.min == nil {
		return 1
	}
	return *c.min
}

// UnmarshalJSON unmarshals a json-formatted column type
func (c *ColumnType) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err == nil {
		if isAtomicType(s) {
			c.Key = &BaseType{Type: s}
		} else {
			return fmt.Errorf("non atomic type %s in <type>", s)
		}
		return nil
	}
	var colType struct {
		Key   *BaseType   `json:"key"`
		Value *BaseType   `json:"value"`
		Min   *int        `json:"min"`
		Max   interface{} `json:"max"`
	}
	err := json.Unmarshal(data, &colType)
	if err != nil {
		return err
	}
	c.Key = colType.Key
	c.Value = colType.Value
	c.min = colType.Min
	switch v := colType.Max.(type) {
	case string:
		if v == unlimitedString {
			c.max = &Unlimited
		} else {
			return fmt.Errorf("unexpected string value in max field")
		}
	case float64:
		i := int(v)
		c.max = &i
	default:
		c.max = nil
	}
	return nil
}

// MarshalJSON marshalls a column type to JSON
func (c ColumnType) MarshalJSON() ([]byte, error) {
	if c.Value == nil && c.max == nil && c.min == nil && c.Key.simpleAtomic() {
		return json.Marshal(c.Key.Type)
	}
	if c.Max() == Unlimited {
		colType := struct {
			Key   *BaseType `json:"key"`
			Value *BaseType `json:"value,omitempty"`
			Min   *int      `json:"min,omitempty"`
			Max   string    `json:"max,omitempty"`
		}{
			Key:   c.Key,
			Value: c.Value,
			Min:   c.min,
			Max:   unlimitedString,
		}
		return json.Marshal(&colType)
	}
	colType := struct {
		Key   *BaseType `json:"key"`
		Value *BaseType `json:"value,omitempty"`
		Min   *int      `json:"min,omitempty"`
		Max   *int      `json:"max,omitempty"`
	}{
		Key:   c.Key,
		Value: c.Value,
		Min:   c.min,
		Max:   c.max,
	}
	return json.Marshal(&colType)
}

// ColumnSchema is a column schema according to RFC7047
type ColumnSchema struct {
	// According to RFC7047, "type" field can be, either an <atomic-type>
	// Or a ColumnType defined below. To try to simplify the usage, the
	// json message will be parsed manually and Type will indicate the "extended"
	// type. Depending on its value, more information may be available in TypeObj.
	// E.g: If Type == TypeEnum, TypeObj.Key.Enum contains the possible values
	Type      ExtendedType
	TypeObj   *ColumnType
	ephemeral *bool
	mutable   *bool
}

// Mutable returns whether a column is mutable
func (c *ColumnSchema) Mutable() bool {
	if c.mutable != nil {
		return *c.mutable
	}
	// default true
	return true
}

// Ephemeral returns whether a column is ephemeral
func (c *ColumnSchema) Ephemeral() bool {
	if c.ephemeral != nil {
		return *c.ephemeral
	}
	// default false
	return false
}

// UnmarshalJSON unmarshals a json-formatted column
func (c *ColumnSchema) UnmarshalJSON(data []byte) error {
	// ColumnJSON represents the known json values for a Column
	var colJSON struct {
		Type      *ColumnType `json:"type"`
		Ephemeral *bool       `json:"ephemeral,omitempty"`
		Mutable   *bool       `json:"mutable,omitempty"`
	}

	// Unmarshal known keys
	if err := json.Unmarshal(data, &colJSON); err != nil {
		return fmt.Errorf("cannot parse column object %s", err)
	}

	c.ephemeral = colJSON.Ephemeral
	c.mutable = colJSON.Mutable
	c.TypeObj = colJSON.Type

	// Infer the ExtendedType from the TypeObj
	if c.TypeObj.Value != nil {
		c.Type = TypeMap
	} else if c.TypeObj.Min() != 1 || c.TypeObj.Max() != 1 {
		c.Type = TypeSet
	} else if len(c.TypeObj.Key.Enum) > 0 {
		c.Type = TypeEnum
	} else {
		c.Type = c.TypeObj.Key.Type
	}
	return nil
}

// MarshalJSON marshalls a column schema to JSON
func (c ColumnSchema) MarshalJSON() ([]byte, error) {
	type colJSON struct {
		Type      *ColumnType `json:"type"`
		Ephemeral *bool       `json:"ephemeral,omitempty"`
		Mutable   *bool       `json:"mutable,omitempty"`
	}
	column := colJSON{
		Type:      c.TypeObj,
		Ephemeral: c.ephemeral,
		Mutable:   c.mutable,
	}
	return json.Marshal(column)
}

// String returns a string representation of the (native) column type
func (c *ColumnSchema) String() string {
	var flags []string
	var flagStr string
	var typeStr string
	if c.Ephemeral() {
		flags = append(flags, "E")
	}
	if c.Mutable() {
		flags = append(flags, "M")
	}
	if len(flags) > 0 {
		flagStr = fmt.Sprintf("[%s]", strings.Join(flags, ","))
	}

	switch c.Type {
	case TypeInteger, TypeReal, TypeBoolean, TypeString:
		typeStr = string(c.Type)
	case TypeUUID:
		if c.TypeObj != nil && c.TypeObj.Key != nil {
			// ignore err as we've already asserted this is a uuid
			reftable, _ := c.TypeObj.Key.RefTable()
			reftype := ""
			if s, err := c.TypeObj.Key.RefType(); err != nil {
				reftype = s
			}
			typeStr = fmt.Sprintf("uuid [%s (%s)]", reftable, reftype)
		} else {
			typeStr = "uuid"
		}

	case TypeEnum:
		typeStr = fmt.Sprintf("enum (type: %s): %v", c.TypeObj.Key.Type, c.TypeObj.Key.Enum)
	case TypeMap:
		typeStr = fmt.Sprintf("[%s]%s", c.TypeObj.Key.Type, c.TypeObj.Value.Type)
	case TypeSet:
		var keyStr string
		if c.TypeObj.Key.Type == TypeUUID {
			// ignore err as we've already asserted this is a uuid
			reftable, _ := c.TypeObj.Key.RefTable()
			reftype, _ := c.TypeObj.Key.RefType()
			keyStr = fmt.Sprintf(" [%s (%s)]", reftable, reftype)
		} else {
			keyStr = string(c.TypeObj.Key.Type)
		}
		typeStr = fmt.Sprintf("[]%s (min: %d, max: %d)", keyStr, c.TypeObj.Min(), c.TypeObj.Max())
	default:
		panic(fmt.Sprintf("Unsupported type %s", c.Type))
	}

	return strings.Join([]string{typeStr, flagStr}, " ")
}

func isAtomicType(atype string) bool {
	switch atype {
	case TypeInteger, TypeReal, TypeBoolean, TypeString, TypeUUID:
		return true
	default:
		return false
	}
}