Debian Codegraph @

schema/schema_test.go

raw
1 package schema_test
2
3 import (
4 "strings"
5 "sync"
6 "testing"
7
8 "gorm.io/gorm"
9 "gorm.io/gorm/schema"
10 "gorm.io/gorm/utils/tests"
11 )
12
13 func TestParseSchema(t *testing.T) {
14 user, err := schema.Parse(&tests.User{}, &sync.Map{}, schema.NamingStrategy{})
15 if err != nil {
16 t.Fatalf("failed to parse user, got error %v", err)
17 }
18
19 checkUserSchema(t, user)
20 }
21
22 func TestParseSchemaWithMap(t *testing.T) {
23 type User struct {
24 tests.User
25 Attrs map[string]string `gorm:"type:Map(String,String);"`
26 }
27
28 user, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{})
29 if err != nil {
30 t.Fatalf("failed to parse user with map, got error %v", err)
31 }
32
33 if field := user.FieldsByName["Attrs"]; field.DataType != "Map(String,String)" {
34 t.Errorf("failed to parse user field Attrs")
35 }
36 }
37
38 func TestParseSchemaWithPointerFields(t *testing.T) {
39 user, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{})
40 if err != nil {
41 t.Fatalf("failed to parse pointer user, got error %v", err)
42 }
43
44 checkUserSchema(t, user)
45 }
46
47 func checkUserSchema(t *testing.T, user *schema.Schema) {
48 // check schema
49 checkSchema(t, user, &schema.Schema{Name: "User", Table: "users"}, []string{"ID"})
50
51 // check fields
52 fields := []schema.Field{
53 {Name: "ID", DBName: "id", BindNames: []string{"Model", "ID"}, DataType: schema.Uint, PrimaryKey: true, Tag: `gorm:"primarykey"`, TagSettings: map[string]string{"PRIMARYKEY": "PRIMARYKEY"}, Size: 64, HasDefaultValue: true, AutoIncrement: true},
54 {Name: "CreatedAt", DBName: "created_at", BindNames: []string{"Model", "CreatedAt"}, DataType: schema.Time},
55 {Name: "UpdatedAt", DBName: "updated_at", BindNames: []string{"Model", "UpdatedAt"}, DataType: schema.Time},
56 {Name: "DeletedAt", DBName: "deleted_at", BindNames: []string{"Model", "DeletedAt"}, Tag: `gorm:"index"`, DataType: schema.Time},
57 {Name: "Name", DBName: "name", BindNames: []string{"Name"}, DataType: schema.String},
58 {Name: "Age", DBName: "age", BindNames: []string{"Age"}, DataType: schema.Uint, Size: 64},
59 {Name: "Birthday", DBName: "birthday", BindNames: []string{"Birthday"}, DataType: schema.Time},
60 {Name: "CompanyID", DBName: "company_id", BindNames: []string{"CompanyID"}, DataType: schema.Int, Size: 64},
61 {Name: "ManagerID", DBName: "manager_id", BindNames: []string{"ManagerID"}, DataType: schema.Uint, Size: 64},
62 {Name: "Active", DBName: "active", BindNames: []string{"Active"}, DataType: schema.Bool},
63 }
64
65 for i := range fields {
66 checkSchemaField(t, user, &fields[i], func(f *schema.Field) {
67 f.Creatable = true
68 f.Updatable = true
69 f.Readable = true
70 })
71 }
72
73 // check relations
74 relations := []Relation{
75 {
76 Name: "Account", Type: schema.HasOne, Schema: "User", FieldSchema: "Account",
77 References: []Reference{{"ID", "User", "UserID", "Account", "", true}},
78 },
79 {
80 Name: "Pets", Type: schema.HasMany, Schema: "User", FieldSchema: "Pet",
81 References: []Reference{{"ID", "User", "UserID", "Pet", "", true}},
82 },
83 {
84 Name: "Toys", Type: schema.HasMany, Schema: "User", FieldSchema: "Toy",
85 Polymorphic: Polymorphic{ID: "OwnerID", Type: "OwnerType", Value: "users"},
86 References: []Reference{{"ID", "User", "OwnerID", "Toy", "", true}, {"", "", "OwnerType", "Toy", "users", false}},
87 },
88 {
89 Name: "Company", Type: schema.BelongsTo, Schema: "User", FieldSchema: "Company",
90 References: []Reference{{"ID", "Company", "CompanyID", "User", "", false}},
91 },
92 {
93 Name: "Manager", Type: schema.BelongsTo, Schema: "User", FieldSchema: "User",
94 References: []Reference{{"ID", "User", "ManagerID", "User", "", false}},
95 },
96 {
97 Name: "Team", Type: schema.HasMany, Schema: "User", FieldSchema: "User",
98 References: []Reference{{"ID", "User", "ManagerID", "User", "", true}},
99 },
100 {
101 Name: "Languages", Type: schema.Many2Many, Schema: "User", FieldSchema: "Language",
102 JoinTable: JoinTable{Name: "UserSpeak", Table: "user_speaks", Fields: []schema.Field{
103 {
104 Name: "UserID", DBName: "user_id", BindNames: []string{"UserID"}, DataType: schema.Uint,
105 Tag: `gorm:"primarykey"`, Creatable: true, Updatable: true, Readable: true, PrimaryKey: true, Size: 64,
106 },
107 {
108 Name: "LanguageCode", DBName: "language_code", BindNames: []string{"LanguageCode"}, DataType: schema.String,
109 Tag: `gorm:"primarykey"`, Creatable: true, Updatable: true, Readable: true, PrimaryKey: true,
110 },
111 }},
112 References: []Reference{{"ID", "User", "UserID", "UserSpeak", "", true}, {"Code", "Language", "LanguageCode", "UserSpeak", "", false}},
113 },
114 {
115 Name: "Friends", Type: schema.Many2Many, Schema: "User", FieldSchema: "User",
116 JoinTable: JoinTable{Name: "user_friends", Table: "user_friends", Fields: []schema.Field{
117 {
118 Name: "UserID", DBName: "user_id", BindNames: []string{"UserID"}, DataType: schema.Uint,
119 Tag: `gorm:"primarykey"`, Creatable: true, Updatable: true, Readable: true, PrimaryKey: true, Size: 64,
120 },
121 {
122 Name: "FriendID", DBName: "friend_id", BindNames: []string{"FriendID"}, DataType: schema.Uint,
123 Tag: `gorm:"primarykey"`, Creatable: true, Updatable: true, Readable: true, PrimaryKey: true, Size: 64,
124 },
125 }},
126 References: []Reference{{"ID", "User", "UserID", "user_friends", "", true}, {"ID", "User", "FriendID", "user_friends", "", false}},
127 },
128 }
129
130 for _, relation := range relations {
131 checkSchemaRelation(t, user, relation)
132 }
133 }
134
135 func TestParseSchemaWithAdvancedDataType(t *testing.T) {
136 user, err := schema.Parse(&AdvancedDataTypeUser{}, &sync.Map{}, schema.NamingStrategy{})
137 if err != nil {
138 t.Fatalf("failed to parse pointer user, got error %v", err)
139 }
140
141 // check schema
142 checkSchema(t, user, &schema.Schema{Name: "AdvancedDataTypeUser", Table: "advanced_data_type_users"}, []string{"ID"})
143
144 // check fields
145 fields := []schema.Field{
146 {Name: "ID", DBName: "id", BindNames: []string{"ID"}, DataType: schema.Int, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true},
147 {Name: "Name", DBName: "name", BindNames: []string{"Name"}, DataType: schema.String},
148 {Name: "Birthday", DBName: "birthday", BindNames: []string{"Birthday"}, DataType: schema.Time},
149 {Name: "RegisteredAt", DBName: "registered_at", BindNames: []string{"RegisteredAt"}, DataType: schema.Time},
150 {Name: "DeletedAt", DBName: "deleted_at", BindNames: []string{"DeletedAt"}, DataType: schema.Time},
151 {Name: "Active", DBName: "active", BindNames: []string{"Active"}, DataType: schema.Bool},
152 {Name: "Admin", DBName: "admin", BindNames: []string{"Admin"}, DataType: schema.Bool},
153 }
154
155 for i := range fields {
156 checkSchemaField(t, user, &fields[i], func(f *schema.Field) {
157 f.Creatable = true
158 f.Updatable = true
159 f.Readable = true
160 })
161 }
162 }
163
164 type CustomizeTable struct{}
165
166 func (CustomizeTable) TableName() string {
167 return "customize"
168 }
169
170 func TestCustomizeTableName(t *testing.T) {
171 customize, err := schema.Parse(&CustomizeTable{}, &sync.Map{}, schema.NamingStrategy{})
172 if err != nil {
173 t.Fatalf("failed to parse pointer user, got error %v", err)
174 }
175
176 if customize.Table != "customize" {
177 t.Errorf("Failed to customize table with TableName method")
178 }
179 }
180
181 func TestNestedModel(t *testing.T) {
182 versionUser, err := schema.Parse(&VersionUser{}, &sync.Map{}, schema.NamingStrategy{})
183 if err != nil {
184 t.Fatalf("failed to parse nested user, got error %v", err)
185 }
186
187 fields := []schema.Field{
188 {Name: "ID", DBName: "id", BindNames: []string{"VersionModel", "BaseModel", "ID"}, DataType: schema.Uint, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true},
189 {Name: "CreatedBy", DBName: "created_by", BindNames: []string{"VersionModel", "BaseModel", "CreatedBy"}, DataType: schema.Uint, Size: 64},
190 {Name: "Version", DBName: "version", BindNames: []string{"VersionModel", "Version"}, DataType: schema.Int, Size: 64},
191 }
192
193 for _, f := range fields {
194 checkSchemaField(t, versionUser, &f, func(f *schema.Field) {
195 f.Creatable = true
196 f.Updatable = true
197 f.Readable = true
198 })
199 }
200 }
201
202 func TestEmbeddedStruct(t *testing.T) {
203 type CorpBase struct {
204 gorm.Model
205 OwnerID string
206 }
207
208 type Company struct {
209 ID int
210 OwnerID int
211 Name string
212 Ignored string `gorm:"-"`
213 }
214
215 type Corp struct {
216 CorpBase
217 Base Company `gorm:"embedded;embeddedPrefix:company_"`
218 }
219
220 cropSchema, err := schema.Parse(&Corp{}, &sync.Map{}, schema.NamingStrategy{})
221 if err != nil {
222 t.Fatalf("failed to parse embedded struct with primary key, got error %v", err)
223 }
224
225 fields := []schema.Field{
226 {Name: "ID", DBName: "id", BindNames: []string{"CorpBase", "Model", "ID"}, DataType: schema.Uint, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true, TagSettings: map[string]string{"PRIMARYKEY": "PRIMARYKEY"}},
227 {Name: "ID", DBName: "company_id", BindNames: []string{"Base", "ID"}, DataType: schema.Int, Size: 64, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
228 {Name: "Name", DBName: "company_name", BindNames: []string{"Base", "Name"}, DataType: schema.String, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
229 {Name: "Ignored", BindNames: []string{"Base", "Ignored"}, TagSettings: map[string]string{"-": "-", "EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
230 {Name: "OwnerID", DBName: "company_owner_id", BindNames: []string{"Base", "OwnerID"}, DataType: schema.Int, Size: 64, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
231 {Name: "OwnerID", DBName: "owner_id", BindNames: []string{"CorpBase", "OwnerID"}, DataType: schema.String},
232 }
233
234 for _, f := range fields {
235 checkSchemaField(t, cropSchema, &f, func(f *schema.Field) {
236 if f.Name != "Ignored" {
237 f.Creatable = true
238 f.Updatable = true
239 f.Readable = true
240 }
241 })
242 }
243 }
244
245 type CustomizedNamingStrategy struct {
246 schema.NamingStrategy
247 }
248
249 func (ns CustomizedNamingStrategy) ColumnName(table, column string) string {
250 baseColumnName := ns.NamingStrategy.ColumnName(table, column)
251
252 if table == "" {
253 return baseColumnName
254 }
255
256 s := strings.Split(table, "_")
257
258 var prefix string
259 switch len(s) {
260 case 1:
261 prefix = s[0][:3]
262 case 2:
263 prefix = s[0][:1] + s[1][:2]
264 default:
265 prefix = s[0][:1] + s[1][:1] + s[2][:1]
266 }
267 return prefix + "_" + baseColumnName
268 }
269
270 func TestEmbeddedStructForCustomizedNamingStrategy(t *testing.T) {
271 type CorpBase struct {
272 gorm.Model
273 OwnerID string
274 }
275
276 type Company struct {
277 ID int
278 OwnerID int
279 Name string
280 Ignored string `gorm:"-"`
281 }
282
283 type Corp struct {
284 CorpBase
285 Base Company `gorm:"embedded;embeddedPrefix:company_"`
286 }
287
288 cropSchema, err := schema.Parse(&Corp{}, &sync.Map{}, CustomizedNamingStrategy{schema.NamingStrategy{}})
289 if err != nil {
290 t.Fatalf("failed to parse embedded struct with primary key, got error %v", err)
291 }
292
293 fields := []schema.Field{
294 {Name: "ID", DBName: "cor_id", BindNames: []string{"CorpBase", "Model", "ID"}, DataType: schema.Uint, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true, TagSettings: map[string]string{"PRIMARYKEY": "PRIMARYKEY"}},
295 {Name: "ID", DBName: "company_cor_id", BindNames: []string{"Base", "ID"}, DataType: schema.Int, Size: 64, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
296 {Name: "Name", DBName: "company_cor_name", BindNames: []string{"Base", "Name"}, DataType: schema.String, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
297 {Name: "Ignored", BindNames: []string{"Base", "Ignored"}, TagSettings: map[string]string{"-": "-", "EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
298 {Name: "OwnerID", DBName: "company_cor_owner_id", BindNames: []string{"Base", "OwnerID"}, DataType: schema.Int, Size: 64, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}},
299 {Name: "OwnerID", DBName: "cor_owner_id", BindNames: []string{"CorpBase", "OwnerID"}, DataType: schema.String},
300 }
301
302 for _, f := range fields {
303 checkSchemaField(t, cropSchema, &f, func(f *schema.Field) {
304 if f.Name != "Ignored" {
305 f.Creatable = true
306 f.Updatable = true
307 f.Readable = true
308 }
309 })
310 }
311 }
312
313 func TestCompositePrimaryKeyWithAutoIncrement(t *testing.T) {
314 type Product struct {
315 ProductID uint `gorm:"primaryKey;autoIncrement"`
316 LanguageCode uint `gorm:"primaryKey"`
317 Code string
318 Name string
319 }
320 type ProductNonAutoIncrement struct {
321 ProductID uint `gorm:"primaryKey;autoIncrement:false"`
322 LanguageCode uint `gorm:"primaryKey"`
323 Code string
324 Name string
325 }
326
327 product, err := schema.Parse(&Product{}, &sync.Map{}, schema.NamingStrategy{})
328 if err != nil {
329 t.Fatalf("failed to parse product struct with composite primary key, got error %v", err)
330 }
331
332 prioritizedPrimaryField := schema.Field{
333 Name: "ProductID", DBName: "product_id", BindNames: []string{"ProductID"}, DataType: schema.Uint, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true, TagSettings: map[string]string{"PRIMARYKEY": "PRIMARYKEY", "AUTOINCREMENT": "AUTOINCREMENT"},
334 }
335
336 product.Fields = []*schema.Field{product.PrioritizedPrimaryField}
337
338 checkSchemaField(t, product, &prioritizedPrimaryField, func(f *schema.Field) {
339 f.Creatable = true
340 f.Updatable = true
341 f.Readable = true
342 })
343
344 productNonAutoIncrement, err := schema.Parse(&ProductNonAutoIncrement{}, &sync.Map{}, schema.NamingStrategy{})
345 if err != nil {
346 t.Fatalf("failed to parse productNonAutoIncrement struct with composite primary key, got error %v", err)
347 }
348
349 if productNonAutoIncrement.PrioritizedPrimaryField != nil {
350 t.Fatalf("PrioritizedPrimaryField of non autoincrement composite key should be nil")
351 }
352 }