-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_repo_test.go
516 lines (470 loc) · 9.58 KB
/
model_repo_test.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package model
import (
"database/sql"
"encoding/json"
"errors"
_ "github.com/go-sql-driver/mysql"
. "github.com/yang-zzhong/go-querybuilder"
"log"
. "testing"
"time"
)
type handler func(*T) error
type User struct {
Id string `db:"id | varchar(128) | pk"`
Name string `db:"name | varchar(32) | uk"`
Age int `db:"age | int"`
Level int `db:"level | int"`
Optional string `db:"optional | varchar(256) | nil"`
CreatedAt time.Time `db:"created_at | datetime | nil"`
*Base
}
func (u *User) TableName() string {
return "user"
}
func (u *User) Prepare() {
u.OnCreate(func(m interface{}) error {
if m.(*User).CreatedAt.IsZero() {
m.(*User).CreatedAt = time.Now()
}
return nil
})
u.DeclareMany("books", new(Book), Nexus{
"user_id": "id",
"id": NWhere{GT, 0},
})
}
func NewUser() *User {
return New(new(User)).(*User)
}
type Book struct {
Id string `db:"id | varchar(128) | pk"`
UserId string `db:"user_id | varchar(128)"`
Name string `db:"name | varchar(128)"`
*Base
}
func (b *Book) TableName() string {
return "book"
}
func (b *Book) Prepare() {
b.DeclareOne("author", new(User), Nexus{
"id": "user_id",
})
}
func NewBook() *Book {
return New(new(Book)).(*Book)
}
type withCustomCount struct {
data []map[string]interface{}
}
func (wc *withCustomCount) DataOf(m interface{}, _ Nexus) interface{} {
for _, item := range wc.data {
if m.(*User).Id == item["user_id"].(string) {
return item["number"]
}
}
return 0
}
func TestFill(t *T) {
suit(func(t *T) error {
user := NewUser()
user.Fill(map[string]interface{}{
"id": "1",
"name": "yang-zhong",
"age": 17,
"level": 1,
})
if !isUser(user) {
return errors.New("fill error")
}
return nil
}, t, "fill")
}
func TestIsModelErr(t *T) {
if IsModelErr(&Error{ERR_SQL, errors.New("fake error sql")}) {
log.Printf("%v\t\tOK", "is model err")
}
}
func TestCreate(t *T) {
suit(func(t *T) error {
user := NewUser()
if err := insertUser(user); err != nil {
return err
}
return nil
}, t, "create")
}
func TestHas(t *T) {
suit(func(t *T) error {
user := NewUser()
if !user.Has("id") {
return errors.New("has error when had")
}
if user.Has("no") {
return errors.New("has error when not had")
}
return nil
}, t, "has")
}
func TestGet(t *T) {
suit(func(t *T) error {
user := NewUser()
user.Id = "100"
if user.Get("id").(string) != "100" {
return errors.New("get error")
}
return nil
}, t, "get")
}
func TestSet(t *T) {
suit(func(t *T) error {
user := NewUser()
if err := user.Set("id", "100"); err != nil {
return err
}
if user.Get("id").(string) != "100" {
return errors.New("set error")
}
return nil
}, t, "set")
}
func TestCreates(t *T) {
suit(func(t *T) error {
var err error
user := NewUser()
if err = insertUser(user); err != nil {
return err
}
books := []map[string]interface{}{
{
"id": "1",
"name": "1",
"published_at": time.Now(),
"user_id": user.Id,
},
{
"id": "2",
"name": "2",
"published_at": time.Now(),
"user_id": user.Id,
},
}
data := []interface{}{}
for _, b := range books {
item := NewBook()
item.Fill(b)
data = append(data, item)
}
return NewBook().Repo().Creates(data)
}, t, "create slice")
}
func TestUpdate(t *T) {
suit(func(t *T) error {
var err error
user := NewUser()
insertUser(user)
user.Name = "fixed name"
if err = user.Save(); err != nil {
return err
}
if u, ok, err := user.Repo().Find("1"); err != nil {
return err
} else if ok {
if u.(*User).Name != "fixed name" {
return errors.New("save error")
}
} else {
return errors.New("save error")
}
return nil
}, t, "update")
}
func TestCount(t *T) {
suit(func(t *T) error {
user := NewUser()
insertUser(user)
if count, err := user.Repo().Count(); err != nil {
return err
} else if count != 1 {
return errors.New("count error")
}
return nil
}, t, "count")
}
func TestFetchNexus(t *T) {
suit(func(t *T) error {
user := NewUser()
book := NewBook()
insertUser(user)
insertBook(book)
if users, err := user.Repo().With("books").Fetch(); err != nil {
return err
} else {
for _, user := range users {
var many interface{}
if many, err = user.(*User).Many("books"); err != nil {
return err
}
for _, m := range many.(map[interface{}]interface{}) {
if !isBook(m) {
return err
}
}
}
}
if books, err := book.Repo().With("author").Fetch(); err != nil {
return err
} else {
for _, book := range books {
var one interface{}
if one, err = book.(*Book).One("author"); err != nil {
return err
}
if !isUser(one) {
return err
}
}
}
return nil
}, t, "fetch nexus")
}
func TestWithMany(t *T) {
suit(func(t *T) error {
user := NewUser()
book := NewBook()
insertUser(user)
insertBook(book)
if many, err := user.Many("books"); err != nil {
return err
} else {
for _, m := range many.(map[interface{}]interface{}) {
if !isBook(m) {
return err
}
}
}
return nil
}, t, "with many")
}
func TestWithCustom(t *T) {
suit(func(t *T) error {
user := NewUser()
book := NewBook()
insertUser(user)
insertBook(book)
user.Repo().WithCustom("books", func(m interface{}) (val NexusValues, err error) {
repo := m.(Model).Repo()
repo.Select(E{"count(1) as number"}, "user_id")
repo.GroupBy("user_id")
data := []map[string]interface{}{}
err = repo.Query(func(rows *sql.Rows, _ []string) error {
var number int
var user_id string
if err = rows.Scan(&number, &user_id); err != nil {
return err
}
data = append(data, map[string]interface{}{
"number": number,
"user_id": user_id,
})
return nil
})
if err == nil {
val = &withCustomCount{data}
}
return
})
if ms, err := user.Repo().Fetch(); err != nil {
return err
} else {
for _, m := range ms {
if count, e := m.(*User).Many("books"); e != nil {
return e
} else if count != 1 {
t.Fatal("with custom count error")
}
}
}
return nil
}, t, "with custom")
}
func TestWithOne(t *T) {
suit(func(t *T) error {
user := NewUser()
book := NewBook()
insertUser(user)
insertBook(book)
if one, err := book.One("author"); err != nil {
return err
} else if !isUser(one) {
return errors.New("with one error")
}
return nil
}, t, "with one")
}
func TestFetch(t *T) {
suit(func(t *T) error {
user := NewUser()
insertUser(user)
if rows, err := user.Repo().Fetch(); err != nil {
return err
} else {
for _, row := range rows {
if !isUser(row) {
return errors.New("fetch error")
}
}
}
return nil
}, t, "fetch")
}
func TestTx(t *T) {
suit(func(t *T) error {
user := NewUser()
book := NewBook()
insertUser(user)
insertBook(book)
user.DB().Tx(func(_ *sql.Tx) error {
if err := user.Delete(); err != nil {
return err
}
return errors.New("for test tx")
})
ms := user.Repo().MustFetch()
if len(ms) == 0 {
return errors.New("tx error")
}
return nil
}, t, "tx")
}
func TestFind(t *T) {
suit(func(t *T) error {
user := NewUser()
insertUser(user)
if model, ok, err := user.Repo().Find("1"); err != nil {
return err
} else if ok {
if !isUser(model) {
return errors.New("find error")
}
} else {
return errors.New("find error")
}
return nil
}, t, "find")
}
func TestMarsha1(t *T) {
suit(func(t *T) error {
user := NewUser()
insertUser(user)
if _, err := json.Marshal(user); err != nil {
return err
}
return nil
}, t, "marsha1")
}
func insertUser(user *User) error {
user.Id = "1"
user.Name = "yang-zhong"
user.Age = 17
user.Level = 1
return user.Create()
}
func insertBook(book *Book) error {
book.UserId = "1"
book.Name = "hello world"
book.Id = "1"
return book.Create()
}
func createUserRepo() *Repo {
repo := NewUser().Repo()
var err error
if err = repo.CreateRepo(); err != nil {
panic(err)
}
return repo
}
func createBookRepo() *Repo {
repo := NewBook().Repo()
var err error
if err = repo.CreateRepo(); err != nil {
panic(err)
}
return repo
}
func clearRepo(repo *Repo) {
if err := repo.DropRepo(); err != nil {
panic(err)
}
}
func isUser(m interface{}) bool {
if _, ok := m.(*User); !ok {
return false
}
vals := map[string]interface{}{
"id": "1",
"name": "yang-zhong",
"age": 17,
"level": 1,
}
return rightModel(m, vals)
}
func isBook(m interface{}) bool {
if _, ok := m.(*Book); !ok {
return false
}
vals := map[string]interface{}{
"id": "1",
"name": "hello world",
}
return rightModel(m, vals)
}
func rightModel(m interface{}, vals map[string]interface{}) bool {
result := true
m.(Mapable).Mapper().each(func(fd *fieldDescriptor) bool {
if _, ok := vals[fd.colname]; !ok {
return true
} else if val, err := m.(Mapable).Mapper().colValue(m, fd.colname); err != nil {
result = false
} else {
if val != vals[fd.colname] {
result = false
}
}
return result
})
return result
}
func initConn() *sql.DB {
var err error
var db *sql.DB
db, err = sql.Open("mysql", "root:young159357789@/test_go?parseTime=true")
if err != nil {
panic(err)
}
RegisterDefaultDB(db, &MysqlModifier{})
return db
}
func suit(handle handler, t *T, name string) {
db := initConn()
defer func() {
db.Close()
UnregisterDefaultDB()
}()
ur := createUserRepo()
br := createBookRepo()
defer func() {
if e := recover(); e != nil {
clearRepo(ur)
clearRepo(br)
t.Error(e)
}
}()
err := handle(t)
if err != nil {
panic(err)
}
clearRepo(ur)
clearRepo(br)
log.Printf("%v\t\tOK", name)
}