File: parse.go

package info (click to toggle)
incus 6.0.5-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 25,788 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (625 lines) | stat: -rw-r--r-- 14,648 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
//go:build linux && cgo && !agent

package db

import (
	"fmt"
	"go/ast"
	"go/types"
	"net/url"
	"reflect"
	"slices"
	"sort"
	"strconv"
	"strings"

	"golang.org/x/tools/go/packages"

	"github.com/lxc/incus/v6/cmd/generate-database/lex"
	"github.com/lxc/incus/v6/shared/util"
)

// FiltersFromStmt parses all filtering statement defined for the given entity. It
// returns all supported combinations of filters, sorted by number of criteria, and
// the corresponding set of unused filters from the Filter struct.
func FiltersFromStmt(pkgs []*types.Package, kind string, entity string, filters []*Field, registeredSQLStmts map[string]string) ([][]string, [][]string) {
	for _, pkg := range pkgs {
		objects := pkg.Scope().Names()
		stmtFilters := [][]string{}

		prefix := fmt.Sprintf("%s%sBy", lex.CamelCase(entity), lex.PascalCase(kind))

		seenNames := make(map[string]struct{}, len(objects))

		for _, name := range objects {
			if !strings.HasPrefix(name, prefix) {
				continue
			}

			rest := name[len(prefix):]
			stmtFilters = append(stmtFilters, strings.Split(rest, "And"))
			seenNames[rest] = struct{}{}
		}

		for name := range registeredSQLStmts {
			if !strings.HasPrefix(name, prefix) {
				continue
			}

			rest := name[len(prefix):]

			_, ok := seenNames[rest]
			if ok {
				continue
			}

			stmtFilters = append(stmtFilters, strings.Split(rest, "And"))
		}

		stmtFilters = sortFilters(stmtFilters)
		ignoredFilters := [][]string{}

		for _, filterGroup := range stmtFilters {
			ignoredFilterGroup := []string{}
			for _, filter := range filters {
				if !slices.Contains(filterGroup, filter.Name) {
					ignoredFilterGroup = append(ignoredFilterGroup, filter.Name)
				}
			}
			ignoredFilters = append(ignoredFilters, ignoredFilterGroup)
		}

		return stmtFilters, ignoredFilters
	}

	return nil, nil
}

// RefFiltersFromStmt parses all filtering statement defined for the given entity reference.
func RefFiltersFromStmt(pkg *types.Package, entity string, ref string, filters []*Field, registeredSQLStmts map[string]string) ([][]string, [][]string) {
	objects := pkg.Scope().Names()
	stmtFilters := [][]string{}

	prefix := fmt.Sprintf("%s%sRefBy", lex.CamelCase(entity), lex.Capital(ref))

	seenNames := make(map[string]struct{}, len(objects))

	for _, name := range objects {
		if !strings.HasPrefix(name, prefix) {
			continue
		}

		rest := name[len(prefix):]
		stmtFilters = append(stmtFilters, strings.Split(rest, "And"))
		seenNames[rest] = struct{}{}
	}

	for name := range registeredSQLStmts {
		if !strings.HasPrefix(name, prefix) {
			continue
		}

		rest := name[len(prefix):]

		_, ok := seenNames[rest]
		if ok {
			continue
		}

		stmtFilters = append(stmtFilters, strings.Split(rest, "And"))
	}

	stmtFilters = sortFilters(stmtFilters)
	ignoredFilters := [][]string{}

	for _, filterGroup := range stmtFilters {
		ignoredFilterGroup := []string{}
		for _, filter := range filters {
			if !slices.Contains(filterGroup, filter.Name) {
				ignoredFilterGroup = append(ignoredFilterGroup, filter.Name)
			}
		}
		ignoredFilters = append(ignoredFilters, ignoredFilterGroup)
	}

	return stmtFilters, ignoredFilters
}

func sortFilters(filters [][]string) [][]string {
	sort.Slice(filters, func(i, j int) bool {
		n1 := len(filters[i])
		n2 := len(filters[j])
		if n1 != n2 {
			return n1 > n2
		}

		f1 := sortFilter(filters[i])
		f2 := sortFilter(filters[j])
		for k := range f1 {
			if f1[k] == f2[k] {
				continue
			}

			return f1[k] > f2[k]
		}

		panic("duplicate filter")
	})
	return filters
}

func sortFilter(filter []string) []string {
	f := make([]string, len(filter))
	copy(f, filter)
	sort.Sort(sort.Reverse(sort.StringSlice(f)))
	return f
}

// Parse the structure declaration with the given name found in the given Go package.
// Any 'Entity' struct should also have an 'EntityFilter' struct defined in the same file.
func Parse(localPath string, pkgs []*types.Package, name string, kind string) (*Mapping, error) {
	m := &Mapping{}
	for _, pkg := range pkgs {
		// Find the package that has the main entity struct.
		str := findStruct(pkg.Scope(), name)
		if str == nil {
			continue
		}

		fields, err := parseStruct(str, kind, pkg.Name())
		if err != nil {
			return nil, fmt.Errorf("Failed to parse %q: %w", name, err)
		}

		m.Local = pkg.Path() == localPath
		m.Package = pkg.Name()
		m.Name = name
		m.Fields = fields
		m.Type = tableType(pkgs, fields)
		m.Filterable = true

		oldStructHasTags := false
		for _, f := range m.Fields {
			if len(f.Config) > 0 {
				oldStructHasTags = true
				break
			}
		}

		if oldStructHasTags {
			break
		}
	}

	if m.Package == "" {
		return nil, fmt.Errorf("No declaration found for %q", name)
	}

	if m.Filterable && m.Filters == nil {
		for _, pkg := range pkgs {
			filters, err := ParseFilter(m, kind, name, pkg)
			if err != nil {
				return nil, err
			}

			if filters != nil {
				m.Filters = filters
				m.FilterLocal = pkg.Path() == localPath
				break
			}
		}

		if m.Filters == nil {
			filterName := name + "Filter"
			return nil, fmt.Errorf("No declaration found for filter %q", filterName)
		}
	}

	return m, nil
}

// ParseFilter finds the <entity>Filter struct in the given package.
func ParseFilter(m *Mapping, kind string, name string, pkg *types.Package) ([]*Field, error) {
	// The 'EntityFilter' struct. This is used for filtering on specific fields of the entity.
	filterName := name + "Filter"
	filterStr := findStruct(pkg.Scope(), filterName)
	if filterStr == nil {
		return nil, nil
	}

	filters, err := parseStruct(filterStr, kind, pkg.Name())
	if err != nil {
		return nil, fmt.Errorf("Failed to parse %q: %w", name, err)
	}

	for i, filter := range filters {
		// Any field in EntityFilter must be present in the original struct.
		field := m.FieldByName(filter.Name)
		if field == nil {
			return nil, fmt.Errorf("Filter field %q is not in struct %q", filter.Name, name)
		}

		// Assign the config tags from the main entity struct to the Filter struct.
		filters[i].Config = field.Config

		// A Filter field and its indirect references must all be in the Filter struct.
		if field.IsIndirect() {
			indirectField := lex.PascalCase(field.Config.Get("via"))
			for i, f := range filters {
				if f.Name == indirectField {
					break
				}

				if i == len(filters)-1 {
					return nil, fmt.Errorf("Field %q requires field %q in struct %q", field.Name, indirectField, name+"Filter")
				}
			}
		}
	}

	return filters, nil
}

// ParseStmt returns the SQL string passed as an argument to a variable declaration of a call to RegisterStmt with the given name.
// e.g. the SELECT string from 'var instanceObjects = RegisterStmt(`SELECT * from instances...`)'.
func ParseStmt(name string, defs map[*ast.Ident]types.Object, registeredSQLStmts map[string]string) (string, error) {
	sql, ok := registeredSQLStmts[name]
	if ok {
		return sql, nil
	}

	for stmtVar := range defs {
		if stmtVar.Name != name {
			continue
		}

		spec, ok := stmtVar.Obj.Decl.(*ast.ValueSpec)
		if !ok {
			continue
		}

		if len(spec.Values) != 1 {
			continue
		}

		expr, ok := spec.Values[0].(*ast.CallExpr)
		if !ok {
			continue
		}

		if len(expr.Args) != 1 {
			continue
		}

		lit, ok := expr.Args[0].(*ast.BasicLit)
		if !ok {
			continue
		}

		return lit.Value, nil
	}

	return "", fmt.Errorf("Declaration for %q not found", name)
}

// tableType determines the TableType for the given struct fields.
func tableType(pkgs []*types.Package, fields []*Field) TableType {
	fieldNames := FieldNames(fields)
	idFields := []string{}
	for _, field := range fields {
		if field.Name == "ID" {
			idFields = nil
			break
		}

		if strings.HasSuffix(lex.SnakeCase(field.Name), "_id") {
			structName, ok := strings.CutSuffix(field.Name, "ID")
			if ok {
				idFields = append(idFields, structName)
			}
		}
	}

	if len(idFields) == 2 {
		var struct1 *types.Struct
		var struct2 *types.Struct
		for _, pkg := range pkgs {
			if struct1 == nil {
				struct1 = findStruct(pkg.Scope(), lex.PascalCase(lex.Singular(idFields[0])))
			}

			if struct2 == nil {
				struct2 = findStruct(pkg.Scope(), lex.PascalCase(lex.Singular(idFields[1])))
			}
		}

		if struct1 != nil && struct2 != nil {
			return AssociationTable
		}
	}

	if slices.Contains(fieldNames, "ReferenceID") {
		if slices.Contains(fieldNames, "Key") && slices.Contains(fieldNames, "Value") {
			return MapTable
		}

		return ReferenceTable
	}

	return EntityTable
}

func parsePkgDecls(entity string, kind string, pkgs []*packages.Package) ([]*types.Package, error) {
	structName := lex.PascalCase(entity)
	pkgTypes := make([]*types.Package, 0, len(pkgs))
	numSeenDecls := 0
	numTaggedDecls := 0
	for _, pkg := range pkgs {
		for _, decl := range pkg.Types.Scope().Names() {
			// Don't validate any structs beyond the one we care about.
			if decl != structName {
				continue
			}

			if numTaggedDecls > 1 {
				return nil, fmt.Errorf("Entity declaration exists in more than one package %q: %q. Remove db tags from one definition", pkg.Name, decl)
			}

			// If we encountered a non-struct declaration, just ignore it.
			obj := pkg.Types.Scope().Lookup(decl)
			structDecl, ok := obj.Type().Underlying().(*types.Struct)
			if !ok {
				continue
			}

			numSeenDecls++
			fields, err := parseStruct(structDecl, kind, pkg.Types.Name())
			if err != nil {
				return nil, err
			}

			for _, f := range fields {
				if len(f.Config) > 0 {
					numTaggedDecls++
					break
				}
			}
		}

		pkgTypes = append(pkgTypes, pkg.Types)
	}

	if numSeenDecls > 1 && numTaggedDecls != 1 {
		return nil, fmt.Errorf("Struct %q declaration exists in more than one package. Apply db tags to one definition", structName)
	}

	if numSeenDecls == 0 {
		return nil, fmt.Errorf("No declaration found for struct %q", structName)
	}

	return pkgTypes, nil
}

// Find the StructType node for the structure with the given name.
func findStruct(scope *types.Scope, name string) *types.Struct {
	obj := scope.Lookup(name)
	if obj == nil {
		return nil
	}

	typ, ok := obj.(*types.TypeName)
	if !ok {
		return nil
	}

	str, ok := typ.Type().Underlying().(*types.Struct)
	if !ok {
		return nil
	}

	return str
}

// Extract field information from the given structure.
func parseStruct(str *types.Struct, kind string, pkgName string) ([]*Field, error) {
	fields := make([]*Field, 0)

	for i := range str.NumFields() {
		f := str.Field(i)
		if f.Embedded() {
			// Check if this is a parent struct.
			parentStr, ok := f.Type().Underlying().(*types.Struct)
			if !ok {
				continue
			}

			parentFields, err := parseStruct(parentStr, kind, pkgName)
			if err != nil {
				return nil, fmt.Errorf("Failed to parse parent struct: %w", err)
			}

			fields = append(fields, parentFields...)

			continue
		}

		field, err := parseField(f, str.Tag(i), kind, pkgName)
		if err != nil {
			return nil, err
		}

		// Don't add field if it has been ignored.
		if field != nil {
			fields = append(fields, field)
		}
	}

	return fields, nil
}

func parseField(f *types.Var, structTag string, kind string, pkgName string) (*Field, error) {
	name := f.Name()

	if !f.Exported() {
		return nil, fmt.Errorf("Unexported field name %q", name)
	}

	// Ignore fields that are marked with a tag of `db:"ignore"`
	if structTag != "" {
		tagValue := reflect.StructTag(structTag).Get("db")
		if tagValue == "ignore" {
			return nil, nil
		}
	}

	typeName := parseType(f.Type(), pkgName)
	if typeName == "" {
		return nil, fmt.Errorf("Unsupported type for field %q", name)
	}

	typeObj := Type{
		Name: typeName,
	}

	var config url.Values
	if structTag != "" {
		var err error
		config, err = url.ParseQuery(reflect.StructTag(structTag).Get("db"))
		if err != nil {
			return nil, fmt.Errorf("Parse 'db' structure tag: %w", err)
		}

		err = validateFieldConfig(config)
		if err != nil {
			return nil, fmt.Errorf("Invalid struct tag for field %q: %v", name, err)
		}
	}

	typeObj.Code = TypeColumn
	if config.Get("marshal") == "" {
		if strings.HasPrefix(typeName, "[]") {
			typeObj.Code = TypeSlice
		} else if strings.HasPrefix(typeName, "map[") {
			typeObj.Code = TypeMap
		}
	}

	// Ignore fields that are marked with `db:"omit"`.
	omit := config.Get("omit")
	if omit != "" {
		omitFields := strings.Split(omit, ",")
		stmtKind := strings.ReplaceAll(lex.SnakeCase(kind), "_", "-")
		switch kind {
		case "URIs":
			stmtKind = "names"
		case "GetMany":
			stmtKind = "objects"
		case "GetOne":
			stmtKind = "objects"
		case "DeleteMany":
			stmtKind = "delete"
		case "DeleteOne":
			stmtKind = "delete"
		}

		if slices.Contains(omitFields, kind) || slices.Contains(omitFields, stmtKind) {
			return nil, nil
		} else if kind == "exists" && slices.Contains(omitFields, "id") {
			// Exists checks ID, so if we are omitting the field from ID, also omit it from Exists.
			return nil, nil
		}
	}

	field := Field{
		Name:   name,
		Type:   typeObj,
		Config: config,
	}

	return &field, nil
}

func parseType(x types.Type, pkgName string) string {
	switch t := x.(type) {
	case *types.Pointer:
		return parseType(t.Elem(), pkgName)
	case *types.Slice:
		return "[]" + parseType(t.Elem(), pkgName)
	case *types.Basic:
		s := t.String()
		if s == "byte" {
			return "uint8"
		}

		return s
	case *types.Array:
		return "[" + strconv.FormatInt(t.Len(), 10) + "]" + parseType(t.Elem(), pkgName)
	case *types.Map:
		return "map[" + t.Key().String() + "]" + parseType(t.Elem(), pkgName)
	case *types.Named:
		if pkgName == t.Obj().Pkg().Name() {
			return t.Obj().Name()
		}

		return t.Obj().Pkg().Name() + "." + t.Obj().Name()
	case nil:
		return ""
	default:
		return ""
	}
}

func validateFieldConfig(config url.Values) error {
	for tag, values := range config {
		switch tag {
		case
			"sql",
			"coalesce",
			"join",
			"leftjoin",
			"joinon",
			"omit":

			_, err := exactlyOneValue(tag, values)
			return err

		case
			"order",
			"primary",
			"ignore":

			value, err := exactlyOneValue(tag, values)
			if err != nil {
				return err
			}

			if !util.IsTrue(value) && !util.IsFalse(value) {
				return fmt.Errorf("Unexpected value %q for %q tag", value, tag)
			}

		case "marshal":
			value, err := exactlyOneValue(tag, values)
			if err != nil {
				return err
			}

			if !util.IsTrue(value) && !util.IsFalse(value) && strings.ToLower(value) != "json" {
				return fmt.Errorf("Unexpected value %q for %q tag", value, tag)
			}
		}
	}

	return nil
}

func exactlyOneValue(tag string, values []string) (string, error) {
	if len(values) == 0 {
		return "", fmt.Errorf("Missing value for %q tag", tag)
	}

	if len(values) > 1 {
		return "", fmt.Errorf("More than one value for %q tag", tag)
	}

	return values[0], nil
}