| 1 |
package schema_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"sync" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"gorm.io/gorm/schema" |
| 9 |
"gorm.io/gorm/utils/tests" |
| 10 |
) |
| 11 |
|
| 12 |
type UserCheck struct { |
| 13 |
Name string `gorm:"check:name_checker,name <> 'jinzhu'"` |
| 14 |
Name2 string `gorm:"check:name <> 'jinzhu'"` |
| 15 |
Name3 string `gorm:"check:,name <> 'jinzhu'"` |
| 16 |
} |
| 17 |
|
| 18 |
func TestParseCheck(t *testing.T) { |
| 19 |
user, err := schema.Parse(&UserCheck{}, &sync.Map{}, schema.NamingStrategy{}) |
| 20 |
if err != nil { |
| 21 |
t.Fatalf("failed to parse user check, got error %v", err) |
| 22 |
} |
| 23 |
|
| 24 |
results := map[string]schema.CheckConstraint{ |
| 25 |
"name_checker": { |
| 26 |
Name: "name_checker", |
| 27 |
Constraint: "name <> 'jinzhu'", |
| 28 |
}, |
| 29 |
"chk_user_checks_name2": { |
| 30 |
Name: "chk_user_checks_name2", |
| 31 |
Constraint: "name <> 'jinzhu'", |
| 32 |
}, |
| 33 |
"chk_user_checks_name3": { |
| 34 |
Name: "chk_user_checks_name3", |
| 35 |
Constraint: "name <> 'jinzhu'", |
| 36 |
}, |
| 37 |
} |
| 38 |
|
| 39 |
checks := user.ParseCheckConstraints() |
| 40 |
|
| 41 |
for k, result := range results { |
| 42 |
v, ok := checks[k] |
| 43 |
if !ok { |
| 44 |
t.Errorf("Failed to found check %v from parsed checks %+v", k, checks) |
| 45 |
} |
| 46 |
|
| 47 |
for _, name := range []string{"Name", "Constraint"} { |
| 48 |
if reflect.ValueOf(result).FieldByName(name).Interface() != reflect.ValueOf(v).FieldByName(name).Interface() { |
| 49 |
t.Errorf( |
| 50 |
"check %v %v should equal, expects %v, got %v", |
| 51 |
k, name, reflect.ValueOf(result).FieldByName(name).Interface(), reflect.ValueOf(v).FieldByName(name).Interface(), |
| 52 |
) |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
func TestParseUniqueConstraints(t *testing.T) { |
| 59 |
type UserUnique struct { |
| 60 |
Name1 string `gorm:"unique"` |
| 61 |
Name2 string `gorm:"uniqueIndex"` |
| 62 |
} |
| 63 |
|
| 64 |
user, err := schema.Parse(&UserUnique{}, &sync.Map{}, schema.NamingStrategy{}) |
| 65 |
if err != nil { |
| 66 |
t.Fatalf("failed to parse user unique, got error %v", err) |
| 67 |
} |
| 68 |
constraints := user.ParseUniqueConstraints() |
| 69 |
|
| 70 |
results := map[string]schema.UniqueConstraint{ |
| 71 |
"uni_user_uniques_name1": { |
| 72 |
Name: "uni_user_uniques_name1", |
| 73 |
Field: &schema.Field{Name: "Name1", Unique: true}, |
| 74 |
}, |
| 75 |
} |
| 76 |
for k, result := range results { |
| 77 |
v, ok := constraints[k] |
| 78 |
if !ok { |
| 79 |
t.Errorf("Failed to found unique constraint %v from parsed constraints %+v", k, constraints) |
| 80 |
} |
| 81 |
tests.AssertObjEqual(t, result, v, "Name") |
| 82 |
tests.AssertObjEqual(t, result.Field, v.Field, "Name", "Unique", "UniqueIndex") |
| 83 |
} |
| 84 |
} |