-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
89 lines (79 loc) · 2.21 KB
/
validation.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
package pgtest
import (
"context"
"fmt"
"strings"
"github.com/charlieparkes/go-structs"
"github.com/iancoleman/strcase"
)
type model interface {
TableName() string
}
// ValidateModels checks that the given structs are valid representations of a database tables.
// 1. Validate table name (using gorm-style TableName() or name-to-snake)
// 2. Validate columns exist.
func ValidateModels(ctx context.Context, f *Postgres, databaseName string, i ...interface{}) error {
for _, iface := range i {
if err := ValidateModel(ctx, f, databaseName, iface); err != nil {
return err
}
}
return nil
}
// ValidateModel checks that a given struct is a valid representation of a database table.
// 1. Validate table name (using gorm-style TableName() or name-to-snake)
// 2. Validate columns exist.
func ValidateModel(ctx context.Context, f *Postgres, databaseName string, i interface{}) error {
var tableName string
switch v := i.(type) {
case model:
tableName = strings.Trim(v.TableName(), "\"")
default:
tableName = strcase.ToSnake(structs.Name(v))
}
var schemaName string = "public"
if s, t, found := strings.Cut(tableName, "."); found {
schemaName = strings.Trim(s, "\"")
tableName = strings.Trim(t, "\"")
}
exists, err := f.TableExists(ctx, databaseName, schemaName, tableName)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("table %v.%v does not exist", schemaName, tableName)
}
fieldNames := Columns(i)
columnNames, err := f.TableColumns(ctx, databaseName, schemaName, tableName)
if err != nil {
return err
}
for _, f := range fieldNames {
found := false
for _, c := range columnNames {
if f == c {
found = true
break
}
}
if !found {
return fmt.Errorf("struct %v contains field %v which does not exist in table: %v.%v{%v}", structs.Name(i), f, schemaName, tableName, columnNames)
}
}
return nil
}
// Given a struct, return the expected column names.
func Columns(i interface{}) []string {
sf := structs.Fields(i)
fields := []string{}
for _, f := range sf {
if tag := f.Tag.Get("db"); tag == "-" {
continue
} else if tag == "" {
fields = append(fields, strcase.ToSnake(f.Name))
} else {
fields = append(fields, tag)
}
}
return fields
}