File: table.go

package info (click to toggle)
golang-github-socketplane-libovsdb 0.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,468 kB
  • sloc: makefile: 59; sh: 27
file content (697 lines) | stat: -rw-r--r-- 20,588 bytes parent folder | download | duplicates (3)
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
package modelgen

import (
	"fmt"
	"math"
	"sort"
	"strings"
	"text/template"

	"golang.org/x/text/cases"
	"golang.org/x/text/language"

	"github.com/ovn-kubernetes/libovsdb/ovsdb"
)

// extendedGenTemplate include additional code generation that is optional, like
// deep copy methods.
var extendedGenTemplate = `
{{- define "deepCopyExtraFields" }}{{ end }}
{{- define "equalExtraFields" }}{{ end }}
{{- define "extendedGenImports" }}
{{- if index . "WithExtendedGen" }}
import "github.com/ovn-kubernetes/libovsdb/model"
{{- end }}
{{- end }}
{{- define "extendedGen" }}
{{- if index . "WithExtendedGen" }}
{{- $tableName := index . "TableName" }}
{{- $structName := index . "StructName" }}
{{- range $field := index . "Fields" }}
{{- $fieldName := FieldName $field.Column }}
{{- $type := "" }}
{{- if index $ "WithEnumTypes" }}
{{- $type = FieldTypeWithEnums $tableName $field.Column $field.Schema }}
{{- else }}
{{- $type = FieldType $tableName $field.Column $field.Schema }}
{{- end }}

func (a *{{ $structName }}) Get{{ $fieldName }}() {{ $type }} {
	return a.{{ $fieldName }}
}

{{ if or (eq (index $type 0) '*') (eq (slice $type 0 2) "[]") (eq (slice $type 0 3) "map") }}
func copy{{ $structName }}{{ $fieldName }}(a {{ $type }}) {{ $type }} {
	if a == nil {
		return nil
	}
	{{- if eq (index $type 0) '*' }}
	b := *a
	return &b
	{{- else if eq (slice $type 0 2) "[]" }}
	b := make({{ $type }}, len(a))
	copy(b, a)
	return b
	{{- else }}
	b := make({{ $type }}, len(a))
	for k, v := range a {
		b[k] = v
	}
	return b
	{{- end }}
}

func equal{{ $structName }}{{ $fieldName }}(a, b {{ $type }}) bool {
	if (a == nil) != (b == nil) {
		return false
	}
	{{- if eq (index $type 0) '*' }}
	if a == b {
		return true
	}
	return *a == *b
	{{- else if eq (slice $type 0 2) "[]" }}
	if len(a) != len(b) {
		return false
	}
	for i, v := range a {
		if b[i] != v {
			return false
		}
	}
	return true
	{{- else }}
	if len(a) != len(b) {
		return false
	}
	for k, v := range a {
		if w, ok := b[k]; !ok || v != w {
			return false
		}
	}
	return true
	{{- end }}
}

{{ end }}
{{ end }}

func (a *{{ $structName }}) DeepCopyInto(b *{{ $structName }}) {
	*b = *a
	{{- range $field := index . "Fields" }}
	{{- $fieldName := FieldName $field.Column }}
	{{- $type := "" }}
	{{- if index $ "WithEnumTypes" }}
	{{- $type = FieldTypeWithEnums $tableName $field.Column $field.Schema }}
	{{- else }}
	{{- $type = FieldType $tableName $field.Column $field.Schema }}
	{{- end }}
	{{- if or (eq (index $type 0) '*') (eq (slice $type 0 2) "[]") (eq (slice $type 0 3) "map") }}
	b.{{ $fieldName }} = copy{{ $structName }}{{ $fieldName }}(a.{{ $fieldName }})
	{{- end }}
	{{- end }}
	{{- template "deepCopyExtraFields" . }}
}

func (a *{{ $structName }}) DeepCopy() *{{ $structName }} {
	b := new({{ $structName }})
	a.DeepCopyInto(b)
	return b
}

func (a *{{ $structName }}) CloneModelInto(b model.Model) {
	c := b.(*{{ $structName }})
	a.DeepCopyInto(c)
}

func (a *{{ $structName }}) CloneModel() model.Model {
	return a.DeepCopy()
}

func (a *{{ $structName }}) Equals(b *{{ $structName }}) bool {
	{{- range $i, $field := index . "Fields" }}
	{{- $fieldName := FieldName $field.Column }}
	{{- $type := "" }}
	{{- if index $ "WithEnumTypes" }}
	{{- $type = FieldTypeWithEnums $tableName $field.Column $field.Schema }}
	{{- else }}
	{{- $type = FieldType $tableName $field.Column $field.Schema }}
	{{- end }}
	{{- if $i }}&&
	{{ else }}return {{ end }}
	{{- if or (eq (index $type 0) '*') (eq (slice $type 0 2) "[]") (eq (slice $type 0 3) "map") -}}
	equal{{ $structName }}{{ $fieldName }}(a.{{ $fieldName }}, b.{{ $fieldName }})
	{{- else -}}
	a.{{ $fieldName }} == b.{{ $fieldName }}
	{{- end }}
	{{- end }}
	{{- template "equalExtraFields" . }}
}

func (a *{{ $structName }}) EqualsModel(b model.Model) bool {
	c := b.(*{{ $structName }})
	return a.Equals(c)
}

var _ model.CloneableModel = &{{ $structName }}{}
var _ model.ComparableModel = &{{ $structName }}{}
{{- end }}
{{- end }}
`

// NewTableTemplate returns a new table template. It includes the following
// other templates that can be overridden to customize the generated file:
//
//   - `header`: override the comment as header before package definition
//   - `preStructDefinitions`: deprecated in favor of `extraImports`
//   - `extraImports`: include additional imports
//   - `structComment`: override the comment generated for the table
//   - `extraFields`: add extra fields to the table
//   - `extraTags`: add tags to the extra fields
//   - `deepCopyExtraFields`: copy extra fields when copying a table
//   - `equalExtraFields`: compare extra fields when comparing a table
//   - `postStructDefinitions`: deprecated in favor of `extraDefinitions`
//   - `extraDefinitions`: include additional definitions like functions etc.
//
// It is designed to be used with a map[string] interface and some defined keys
// (see GetTableTemplateData). In addition, the following functions can be used
// within the template:
//
//   - `PrintVal`: prints a field value
//   - `FieldName`: prints the name of a field based on its column
//   - `FieldType`: prints the field type based on its column and schema
//   - `FieldTypeWithEnums`: same as FieldType but with enum type expansion
//   - `OvsdbTag`: prints the ovsdb tag
//   - `ValidationTag`: generates the 'validate' struct tag based on OVSDB schema constraints
func NewTableTemplate() *template.Template {
	return template.Must(template.New("").Funcs(
		template.FuncMap{
			"PrintVal":           printVal,
			"FieldName":          FieldName,
			"FieldType":          FieldType,
			"FieldTypeWithEnums": FieldTypeWithEnums,
			"OvsdbTag":           Tag,
			"ValidationTag":      ValidationTag,
		},
	).Parse(extendedGenTemplate + `
{{- define "header" }}
// Code generated by "libovsdb.modelgen"
// DO NOT EDIT.
{{- end }}
{{ define "extraImports" }}{{ end }}
{{ define "preStructDefinitions" }}{{ end }}
{{- define "structComment" }}
// {{ index . "StructName" }} defines an object in {{ index . "TableName" }} table
{{- end }}
{{- define "showTableName" }}
const {{ index . "StructName" }}Table = "{{ index . "TableName" }}"
{{- end }}
{{ define "extraTags" }}{{ end }}
{{ define "extraFields" }}{{ end }}
{{ define "extraDefinitions" }}{{ end }}
{{ define "postStructDefinitions" }}{{ end }}
{{ template "header" . }}
{{ define "enums" }}
{{ if index . "WithEnumTypes" }}
{{ if index . "Enums" }}
type (
{{ range index . "Enums" }}
{{ .Alias }} = {{ .Type }}
{{- end }}
)

var (
{{ range  index . "Enums" }}
{{- $e := . }}
{{- range .Sets }}
{{ $e.Alias }}{{ FieldName . }} {{ $e.Alias }} = {{ PrintVal . $e.Type }}
{{- end }}
{{- end }}
)
{{- end }}
{{- end }}
{{- end }}
package {{ index . "PackageName" }}
{{ template "extendedGenImports" . }}
{{ template "extraImports" . }}
{{ template "preStructDefinitions" . }}
{{ template "showTableName" . }}
{{ template "enums" . }}
{{ template "structComment" . }}
type {{ index . "StructName" }} struct {
{{- $tableName := index . "TableName" }}
{{ if index . "WithEnumTypes" }}
{{ range $field := index . "Fields" }}	{{ FieldName $field.Column }}  {{ FieldTypeWithEnums $tableName $field.Column $field.Schema }} ` + "`" + `{{ OvsdbTag $field.Column }}{{ ValidationTag $field.Schema }}{{ template "extraTags" . }}` + "`" + `
{{ end }}
{{ else }}
{{ range  $field := index . "Fields" }}	{{ FieldName $field.Column }}  {{ FieldType $tableName $field.Column $field.Schema }} ` + "`" + `{{ OvsdbTag $field.Column }}{{ ValidationTag $field.Schema }}{{ template "extraTags" . }}` + "`" + `
{{ end }}
{{ end }}
{{ template "extraFields" . }}
}
{{ template "postStructDefinitions" . }}
{{ template "extraDefinitions" . }}
{{ template "extendedGen" . }}
`))
}

// Enum represents the enum schema type
type Enum struct {
	Type  string
	Alias string
	Sets  []any
}

// Field represents the field information
type Field struct {
	Column string
	Schema *ovsdb.ColumnSchema
}

// TableTemplateData represents the data used by the Table Template
type TableTemplateData map[string]any

// WithEnumTypes configures whether the Template should expand enum types or not
// Enum expansion (true by default) makes the template define an type alias for each enum type
// and a const for each possible enum value
func (t TableTemplateData) WithEnumTypes(val bool) {
	t["WithEnumTypes"] = val
}

// WithExtendedGen configures whether the Template should generate code to deep
// copy models.
func (t TableTemplateData) WithExtendedGen(val bool) {
	t["WithExtendedGen"] = val
}

// GetTableTemplateData returns the TableTemplateData map. It has the following
// keys:
//
//   - `TableName`: (string) the table name
//   - `TPackageName`: (string) the package name
//   - `TStructName`: (string) the struct name
//   - `TFields`: []Field a list of Fields that the struct has
func GetTableTemplateData(pkg, name string, table *ovsdb.TableSchema) TableTemplateData {
	data := map[string]any{}
	data["TableName"] = name
	data["PackageName"] = pkg
	data["StructName"] = StructName(name)
	Fields := []Field{}
	Enums := []Enum{}

	// Map iteration order is random, so for predictable generation
	// lets sort fields by name
	var order sort.StringSlice
	for columnName := range table.Columns {
		order = append(order, columnName)
	}
	order.Sort()

	for _, columnName := range append([]string{"_uuid"}, order...) {
		columnSchema := table.Column(columnName)
		Fields = append(Fields, Field{
			Column: columnName,
			Schema: columnSchema,
		})
		if enum := FieldEnum(name, columnName, columnSchema); enum != nil {
			Enums = append(Enums, *enum)
		}
	}
	data["Fields"] = Fields
	data["Enums"] = Enums
	data["WithEnumTypes"] = true
	data["WithExtendedGen"] = false
	return data
}

// FieldName returns the name of a column field
func FieldName(column string) string {
	return camelCase(strings.Trim(column, "_"))
}

// StructName returns the name of the table struct
func StructName(tableName string) string {
	return cases.Title(language.Und, cases.NoLower).String(strings.ReplaceAll(tableName, "_", ""))
}

func fieldType(tableName, columnName string, column *ovsdb.ColumnSchema, enumTypes bool) string {
	switch column.Type {
	case ovsdb.TypeEnum:
		if enumTypes {
			return enumName(tableName, columnName)
		}
		return AtomicType(column.TypeObj.Key.Type)
	case ovsdb.TypeMap:
		return fmt.Sprintf("map[%s]%s", AtomicType(column.TypeObj.Key.Type),
			AtomicType(column.TypeObj.Value.Type))
	case ovsdb.TypeSet:
		// optional with max 1 element
		if column.TypeObj.Min() == 0 && column.TypeObj.Max() == 1 {
			if enumTypes && FieldEnum(tableName, columnName, column) != nil {
				return fmt.Sprintf("*%s", enumName(tableName, columnName))
			}
			return fmt.Sprintf("*%s", AtomicType(column.TypeObj.Key.Type))
		}
		// required, max 1 element
		if column.TypeObj.Min() == 1 && column.TypeObj.Max() == 1 {
			if enumTypes && FieldEnum(tableName, columnName, column) != nil {
				return enumName(tableName, columnName)
			}
			return AtomicType(column.TypeObj.Key.Type)
		}
		// use a slice
		if enumTypes && FieldEnum(tableName, columnName, column) != nil {
			return fmt.Sprintf("[]%s", enumName(tableName, columnName))
		}
		return fmt.Sprintf("[]%s", AtomicType(column.TypeObj.Key.Type))
	default:
		return AtomicType(column.Type)
	}
}

// EnumName returns the name of the enum field
func enumName(tableName, columnName string) string {
	return cases.Title(language.Und, cases.NoLower).String(StructName(tableName)) + camelCase(columnName)
}

// FieldType returns the string representation of a column type without enum types expansion
func FieldType(tableName, columnName string, column *ovsdb.ColumnSchema) string {
	return fieldType(tableName, columnName, column, false)
}

// FieldTypeWithEnums returns the string representation of a column type where Enums
// are expanded into their own types
func FieldTypeWithEnums(tableName, columnName string, column *ovsdb.ColumnSchema) string {
	return fieldType(tableName, columnName, column, true)
}

// FieldEnum returns the Enum if the column is an enum type
func FieldEnum(tableName, columnName string, column *ovsdb.ColumnSchema) *Enum {
	if column.TypeObj == nil || column.TypeObj.Key.Enum == nil {
		return nil
	}
	return &Enum{
		Type:  column.TypeObj.Key.Type,
		Alias: enumName(tableName, columnName),
		Sets:  column.TypeObj.Key.Enum,
	}
}

// AtomicType returns the string type of an AtomicType
func AtomicType(atype string) string {
	switch atype {
	case ovsdb.TypeInteger:
		return "int"
	case ovsdb.TypeReal:
		return "float64"
	case ovsdb.TypeBoolean:
		return "bool"
	case ovsdb.TypeString:
		return "string"
	case ovsdb.TypeUUID:
		return "string"
	}
	return ""
}

// Tag returns the Tag string of a column
func Tag(column string) string {
	return fmt.Sprintf(`ovsdb:"%s"`, column)
}

// getAtomicValidations generates validation tags for a single ovsdb.BaseType.
func getAtomicValidations(atomicSchema *ovsdb.BaseType) []string {
	if atomicSchema == nil {
		return nil
	}
	var validations []string
	switch atomicSchema.Type {
	case ovsdb.TypeInteger:
		if minVal, err := atomicSchema.MinInteger(); err == nil {
			defaultMinInteger := math.MinInt64
			if minVal != defaultMinInteger {
				validations = append(validations, fmt.Sprintf("min=%d", minVal))
			}
		}
		if maxVal, err := atomicSchema.MaxInteger(); err == nil {
			defaultMaxInteger := math.MaxInt64
			if maxVal != defaultMaxInteger {
				validations = append(validations, fmt.Sprintf("max=%d", maxVal))
			}
		}
	case ovsdb.TypeReal:
		if minVal, err := atomicSchema.MinReal(); err == nil {
			defaultMinReal := math.SmallestNonzeroFloat64
			if minVal != defaultMinReal { // This comparison might have precision issues
				validations = append(validations, fmt.Sprintf("min=%f", minVal))
			}
		}
		if maxVal, err := atomicSchema.MaxReal(); err == nil {
			defaultMaxReal := math.MaxFloat64
			if maxVal != defaultMaxReal {
				validations = append(validations, fmt.Sprintf("max=%f", maxVal))
			}
		}
	case ovsdb.TypeString:
		if maxVal, err := atomicSchema.MaxLength(); err == nil {
			if maxVal != math.MaxInt32 && maxVal != math.MaxInt64 {
				validations = append(validations, fmt.Sprintf("max=%d", maxVal))
			}
		}
		if len(atomicSchema.Enum) > 0 {
			var enumValuesForTag []string
			for _, val := range atomicSchema.Enum {
				if strVal, ok := val.(string); ok {
					enumValuesForTag = append(enumValuesForTag, fmt.Sprintf("'%s'", strVal))
				} else {
					enumValuesForTag = append(enumValuesForTag, fmt.Sprintf("'%v'", val))
				}
			}
			if len(enumValuesForTag) > 0 {
				validations = append(validations, "oneof="+strings.Join(enumValuesForTag, " "))
			}
		}
	case ovsdb.TypeUUID:
		// named-uuid, cannot validate in uuid
		break
	case ovsdb.TypeBoolean:
		// No specific value validations for boolean (e.g. min/max)
		break
	}
	return validations
}

func getCollectionSizeValidations(typeObj *ovsdb.ColumnType) []string {
	var validations []string
	minCount := typeObj.Min()
	maxCount := typeObj.Max()
	if minCount > 0 {
		validations = append(validations, fmt.Sprintf("min=%d", minCount))
	}
	if maxCount != ovsdb.Unlimited {
		validations = append(validations, fmt.Sprintf("max=%d", maxCount))
	}
	return validations
}

func getSetValidations(schema *ovsdb.ColumnSchema) []string {
	var validations []string
	validations = append(validations, getCollectionSizeValidations(schema.TypeObj)...)
	if schema.TypeObj.Key != nil {
		elementValidations := getAtomicValidations(schema.TypeObj.Key)
		if len(elementValidations) > 0 {
			validations = append(validations, "dive")
			validations = append(validations, elementValidations...)
		}
	}
	return validations
}

func getMapValidations(schema *ovsdb.ColumnSchema) []string {
	var validations []string
	validations = append(validations, getCollectionSizeValidations(schema.TypeObj)...)

	// Check if we have key or value validations
	var keyAtomValidations []string
	var valueAtomValidations []string

	if schema.TypeObj.Key != nil {
		keyAtomValidations = getAtomicValidations(schema.TypeObj.Key)
	}
	if schema.TypeObj.Value != nil {
		valueAtomValidations = getAtomicValidations(schema.TypeObj.Value)
	}

	hasKeyValidations := len(keyAtomValidations) > 0
	hasValueValidations := len(valueAtomValidations) > 0

	if !hasKeyValidations && !hasValueValidations {
		return validations
	}
	// Only add dive validations if we have key or value validations
	var diveValidations []string
	diveValidations = append(diveValidations, "dive")

	// Add key validations if they exist
	if hasKeyValidations {
		diveValidations = append(diveValidations, "keys")
		diveValidations = append(diveValidations, keyAtomValidations...)
	}
	if hasKeyValidations && hasValueValidations {
		diveValidations = append(diveValidations, "endkeys")
	}
	// Add value validations if they exist
	if hasValueValidations {
		diveValidations = append(diveValidations, valueAtomValidations...)
	}

	validations = append(validations, diveValidations...)

	return validations
}

func getAtomicTypeValidations(schema *ovsdb.ColumnSchema) []string {
	var baseTypeForAtomic *ovsdb.BaseType
	if schema.TypeObj != nil && schema.TypeObj.Key != nil {
		baseTypeForAtomic = schema.TypeObj.Key
	} else if schema.TypeObj == nil {
		baseTypeForAtomic = &ovsdb.BaseType{Type: schema.Type}
	}

	if baseTypeForAtomic != nil && baseTypeForAtomic.Type != ovsdb.TypeUUID {
		return getAtomicValidations(baseTypeForAtomic)
	}
	return nil
}

// ValidationTag generates the 'validate' struct tag based on OVSDB schema constraints.
func ValidationTag(schema *ovsdb.ColumnSchema) string {
	var finalValidations []string

	if schema.TypeObj == nil {
		finalValidations = getAtomicTypeValidations(schema)
	} else {
		switch schema.Type {
		case ovsdb.TypeSet:
			isPointerForOptionalSet := schema.TypeObj.Min() == 0 && schema.TypeObj.Max() == 1
			isScalarFromSet := schema.TypeObj.Min() == 1 && schema.TypeObj.Max() == 1
			switch {
			case isPointerForOptionalSet:
				if schema.TypeObj.Key != nil {
					elementValidations := getAtomicValidations(schema.TypeObj.Key)
					if len(elementValidations) > 0 {
						finalValidations = append(finalValidations, "omitempty")
						finalValidations = append(finalValidations, elementValidations...)
					}
				}
			case isScalarFromSet:
				if schema.TypeObj.Key != nil {
					finalValidations = append(finalValidations, getAtomicValidations(schema.TypeObj.Key)...)
				}
			default:
				finalValidations = getSetValidations(schema)
			}
		case ovsdb.TypeMap:
			finalValidations = getMapValidations(schema)
		default:
			finalValidations = getAtomicTypeValidations(schema)
		}
	}

	// Filter out any genuinely empty strings that might have been added.
	var nonEmptyValidations []string
	for _, v := range finalValidations {
		if v != "" {
			nonEmptyValidations = append(nonEmptyValidations, v)
		}
	}

	if len(nonEmptyValidations) == 0 {
		return ""
	}

	return fmt.Sprintf(` validate:"%s"`, strings.Join(nonEmptyValidations, ","))
}

// FileName returns the filename of a table
func FileName(table string) string {
	return fmt.Sprintf("%s.go", strings.ToLower(table))
}

// common initialisms used in ovsdb schemas
var initialisms = map[string]bool{
	"ACL":   true,
	"BFD":   true,
	"CFM":   true,
	"CT":    true,
	"CVLAN": true,
	"DNS":   true,
	"DSCP":  true,
	"ID":    true,
	"IP":    true,
	"IPFIX": true,
	"LACP":  true,
	"LLDP":  true,
	"MAC":   true,
	"MTU":   true,
	"OVS":   true,
	"QOS":   true,
	"RSTP":  true,
	"SSL":   true,
	"STP":   true,
	"TCP":   true,
	"SCTP":  true,
	"UDP":   true,
	"UUID":  true,
	"VLAN":  true,
	"STT":   true,
	"DNAT":  true,
	"SNAT":  true,
	"ICMP":  true,
	"SLB":   true,
}

func camelCase(field string) string {
	s := strings.ToLower(field)
	parts := strings.FieldsFunc(s, func(r rune) bool {
		return r == '_' || r == '-'
	})
	if len(parts) > 1 {
		s = ""
		for _, p := range parts {
			s += cases.Title(language.Und, cases.NoLower).String(expandInitilaisms(p))
		}
	} else {
		s = cases.Title(language.Und, cases.NoLower).String(expandInitilaisms(s))
	}
	return s
}

func expandInitilaisms(s string) string {
	// check initialisms
	if u := strings.ToUpper(s); initialisms[u] {
		return strings.ToUpper(s)
	}
	// check for plurals too
	if strings.HasSuffix(s, "s") {
		sub := s[:len(s)-1]
		if u := strings.ToUpper(sub); initialisms[u] {
			return strings.ToUpper(sub) + "s"
		}
	}
	return s
}

func printVal(v any, t string) string {
	switch t {
	case "int":
		return fmt.Sprintf(`%d`, v)
	case "float64":
		return fmt.Sprintf(`%f`, v)
	case "bool":
		return fmt.Sprintf(`%t`, v)
	case "string":
		return fmt.Sprintf(`"%s"`, v)
	}
	return ""
}