-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery_test.go
287 lines (241 loc) · 5.05 KB
/
query_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
package queryfunc
import (
"encoding/json"
"fmt"
"testing"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
)
type GDB struct {
*gorm.DB
}
func (gdb *GDB) GormDB() *gorm.DB {
return gdb.DB
}
type Model struct {
ID uint `gorm:"primarykey" json:"id,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
type User struct {
Model
Name string `json:"name"`
Email string `json:"email"`
CompanyID string `json:"company_id"`
Company *Company `json:"company"`
Devices []*Device `json:"devices"`
}
type Company struct {
Model
Name string `json:"name"`
}
type Device struct {
Model
UserID uint `json:"user_id"`
Token string `json:"token"`
Platform string `json:"platform"`
}
/// Test start
var db *gorm.DB
var schemes = []interface{}{
&User{},
&Device{},
&Company{},
}
func init() {
var err error
db, err = gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
PrepareStmt: true,
DisableForeignKeyConstraintWhenMigrating: true,
SkipDefaultTransaction: true,
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic(err)
}
db.AutoMigrate(schemes...)
var users []*User
for i := 0; i < 25; i++ {
var user = &User{
Model: Model{
ID: uint(i),
},
Name: fmt.Sprintf("User %d", i),
Email: fmt.Sprintf("user_%[email protected]", i),
Devices: []*Device{
{
Model: Model{
ID: uint(i),
},
Token: fmt.Sprintf("token_%d_1", i),
Platform: "iOS",
},
{
Model: Model{
ID: uint(i + 1),
},
Token: fmt.Sprintf("token_%d_2", i),
Platform: "Android",
},
},
Company: &Company{
Model: Model{
ID: 1,
},
Name: "Test Company 1",
},
}
if i > 10 {
user.Company = &Company{
Model: Model{
ID: 2,
},
Name: "Test Company 2",
}
}
users = append(users, user)
}
err = db.Clauses(clause.OnConflict{DoNothing: true}).Create(&users).Error
if err != nil {
panic(err)
}
}
func printJSON(i interface{}) {
data, _ := json.MarshalIndent(&i, "", " ")
fmt.Println(string(data))
}
/// Builders
func NewDeviceQueryBuilder() *Builder {
const rawSQL = `
SELECT d.*
FROM devices d
`
const countSQL = `
SELECT 1
FROM devices d
`
return NewBuilder(rawSQL, countSQL).
WithPaginationFunc(func(db DB, rawSQL *gorm.DB) (interface{}, error) {
var records []*Device
var err = rawSQL.Find(&records).Error
return &records, err
})
}
func NewUserQueryBuilder() *Builder {
const rawSQL = `
SELECT u.*,
c.id AS c__id,
c.created_at AS c__created_at,
c.updated_at AS c__updated_at,
c.name AS c__name
FROM users u
LEFT JOIN companies c ON c.id = u.company_id
`
const countSQL = `
SELECT 1
FROM users u
LEFT JOIN companies c ON c.id = u.company_id
`
return NewBuilder(rawSQL, countSQL).
WithPaginationFunc(func(db DB, rawSQL *gorm.DB) (interface{}, error) {
type userCopy struct {
*User
Company *Company `gorm:"embedded;embeddedPrefix:c__"`
}
var records = make([]*User, rawSQL.RowsAffected)
rows, err := rawSQL.Rows()
if err != nil {
return nil, err
}
defer rows.Close()
var userID []uint
for rows.Next() {
var copy userCopy
err = db.GormDB().ScanRows(rows, ©)
if err != nil {
continue
}
copy.User.Company = copy.Company
records = append(records, copy.User)
userID = append(userID, copy.User.ID)
}
if len(userID) > 0 {
var devices []*Device
var err = New(db, NewDeviceQueryBuilder()).FindFunc(&devices)
if err == nil {
for _, record := range records {
for _, device := range devices {
if device.UserID == record.ID {
record.Devices = append(record.Devices, device)
}
}
}
}
}
return &records, err
})
}
func TestPagination1(t *testing.T) {
var gdb = &GDB{
DB: db,
}
var result = New(gdb, NewUserQueryBuilder()).
Page(1).
Limit(5).
WhereFunc(func(builder *config) {
builder.Where("c.name = ?", "Test Company 1")
}).
PagingFunc()
printJSON(result)
}
func TestPagination2(t *testing.T) {
var gdb = &GDB{
DB: db,
}
var result = New(gdb, NewDeviceQueryBuilder()).
Page(1).
Limit(5).
WhereFunc(func(builder *config) {
builder.Where("d.user_id = ?", 1)
}).
PagingFunc()
printJSON(result)
}
func TestFirstFunc(t *testing.T) {
var gdb = &GDB{
DB: db,
}
var user User
var err = New(gdb, NewUserQueryBuilder()).
Page(1).
Limit(5).
WhereFunc(func(builder *config) {
builder.Where("u.id = ?", 1)
}).
FirstFunc(&user)
if err != nil {
panic(err)
}
printJSON(user)
}
func TestFindFunc(t *testing.T) {
var gdb = &GDB{
DB: db,
}
var users []*User
var err = New(gdb, NewUserQueryBuilder()).
Page(1).
Limit(5).
WhereFunc(func(builder *config) {
builder.Where("u.id IN ?", []uint{1, 2})
}).
FindFunc(&users)
if err != nil {
panic(err)
}
printJSON(users)
}