-
Notifications
You must be signed in to change notification settings - Fork 4
/
validate.go
76 lines (70 loc) · 2.32 KB
/
validate.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
package model
import (
"strings"
"github.com/pkg/errors"
"github.com/samber/lo"
)
var goKeywords = []string{
"break", "case", "chan", "const", "continue", "default", "defer", "else",
"fallthrough", "for", "func", "go", "goto", "if", "import", "interface",
"map", "package", "range", "return", "select", "struct", "switch", "type", "var",
}
var reservedNames = map[string][]string{"audit": {"audit", "audit_record"}}
func (m *Model) Validate(mods []string, models Models, groups Groups) error {
if err := validateBasic(m); err != nil {
return err
}
for _, mod := range mods {
if lo.Contains(reservedNames[mod], m.Name) {
return errors.Errorf("model [%s] uses name which is reserved by [%s]", m.Name, mod)
}
}
if len(m.Group) > 0 && groups.Get(m.Group...) == nil {
if len(m.Group) == 1 && models.Get(m.Group[0]) == nil {
return errors.Errorf("model [%s] references undefined group [%s], and no model matches", m.Name, strings.Join(m.Group, "/"))
}
if len(m.Group) > 1 {
var cool bool
for _, x := range models {
mg := strings.Join(m.Group, "/")
xg := strings.Join(x.Group, "/") + "/" + x.Name
if mg == xg {
cool = true
}
}
if !cool {
return errors.Errorf("model [%s] references undefined group [%s], and no model matches", m.Name, strings.Join(m.Group, "/"))
}
}
}
return nil
}
func validateBasic(m *Model) error {
if len(m.PKs()) == 0 {
return errors.Errorf("model [%s] has no primary key", m.Name)
}
if m.Package == "vendor" {
return errors.Errorf("model [%s] uses [vendor] package, which is reserved by Go", m.Name)
}
if m.IsSoftDelete() {
if d := m.Columns.WithTag("deleted"); len(d) != 1 {
return errors.Errorf("when set to soft delete, model [%s] must have one column tagged [deleted]", m.Name)
}
}
if dupes := lo.FindDuplicates(m.Columns.Names()); len(dupes) > 0 {
return errors.Errorf("model [%s] has duplicates columns [%s]", m.Name, strings.Join(dupes, ", "))
}
for _, col := range m.Columns {
if lo.Contains(goKeywords, col.Name) {
return errors.Errorf("model [%s] column [%s] uses reserved keyword", m.Name, col.Name)
}
}
for _, rel := range m.Relations {
for _, s := range rel.Src {
if m.Columns.Get(s) == nil {
return errors.Errorf("model [%s] relation [%s] references missing source column [%s]", m.Name, rel.Name, s)
}
}
}
return nil
}