Debian Codegraph @

schema/constraint.go

raw
1 package schema
2
3 import (
4 "regexp"
5 "strings"
6
7 "gorm.io/gorm/clause"
8 )
9
10 // reg match english letters and midline
11 var regEnLetterAndMidline = regexp.MustCompile(`^[\w-]+$`)
12
13 type CheckConstraint struct {
14 Name string
15 Constraint string // length(phone) >= 10
16 *Field
17 }
18
19 func (chk *CheckConstraint) GetName() string { return chk.Name }
20
21 func (chk *CheckConstraint) Build() (sql string, vars []interface{}) {
22 return "CONSTRAINT ? CHECK (?)", []interface{}{clause.Column{Name: chk.Name}, clause.Expr{SQL: chk.Constraint}}
23 }
24
25 // ParseCheckConstraints parse schema check constraints
26 func (schema *Schema) ParseCheckConstraints() map[string]CheckConstraint {
27 checks := map[string]CheckConstraint{}
28 for _, field := range schema.FieldsByDBName {
29 if chk := field.TagSettings["CHECK"]; chk != "" {
30 names := strings.Split(chk, ",")
31 if len(names) > 1 && regEnLetterAndMidline.MatchString(names[0]) {
32 checks[names[0]] = CheckConstraint{Name: names[0], Constraint: strings.Join(names[1:], ","), Field: field}
33 } else {
34 if names[0] == "" {
35 chk = strings.Join(names[1:], ",")
36 }
37 name := schema.namer.CheckerName(schema.Table, field.DBName)
38 checks[name] = CheckConstraint{Name: name, Constraint: chk, Field: field}
39 }
40 }
41 }
42 return checks
43 }
44
45 type UniqueConstraint struct {
46 Name string
47 Field *Field
48 }
49
50 func (uni *UniqueConstraint) GetName() string { return uni.Name }
51
52 func (uni *UniqueConstraint) Build() (sql string, vars []interface{}) {
53 return "CONSTRAINT ? UNIQUE (?)", []interface{}{clause.Column{Name: uni.Name}, clause.Column{Name: uni.Field.DBName}}
54 }
55
56 // ParseUniqueConstraints parse schema unique constraints
57 func (schema *Schema) ParseUniqueConstraints() map[string]UniqueConstraint {
58 uniques := make(map[string]UniqueConstraint)
59 for _, field := range schema.Fields {
60 if field.Unique {
61 name := schema.namer.UniqueName(schema.Table, field.DBName)
62 uniques[name] = UniqueConstraint{Name: name, Field: field}
63 }
64 }
65 return uniques
66 }