-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_test.go
446 lines (417 loc) · 15.1 KB
/
model_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
package psql
import (
"fmt"
"strings"
"testing"
"time"
)
func init() {
DefaultColumnNamer = ToUnderscore
}
type (
test struct {
*testing.T
i int
}
userAlike struct {
Id int
Name string
Password string
}
admin struct {
userAlike
}
user struct {
userAlike
Phone string
}
category struct {
Id int
Names []map[string]string `jsonb:"meta"`
Picture string `jsonb:"meta"`
CreatedAt time.Time
UpdatedAt time.Time
}
product struct {
Id int `json:"id"`
Name string `json:"name"`
Price int `json:"PRICE"`
}
)
func TestModel(_t *testing.T) {
t := test{_t, 0}
m1 := NewModel(admin{})
t.String(strings.Join(m1.Columns(), ","), "id,name,password")
t.String(m1.ToColumnName("FooBar"), "foo_bar")
m1.SetColumnNamer(nil)
t.String(strings.Join(m1.Columns(), ","), "Id,Name,Password")
t.String(m1.ToColumnName("FooBar"), "FooBar")
m1.SetColumnNamer(DefaultColumnNamer)
t.String(m1.FieldByName("Name").ColumnName, "name")
t.Nil(m1.FieldByName("name"), (*Field)(nil))
t.String(m1.tableName, "admins")
t.Int(len(m1.modelFields), 3)
t.Int(len(m1.WithoutFields("Name").modelFields), 2)
t.Int(len(m1.WithoutFields("Name", "Password").modelFields), 1)
t.Int(len(m1.modelFields), 3)
p := m1.Permit()
t.Int(len(p.PermittedFields()), 0)
p = m1.Permit("Invalid")
t.Int(len(p.PermittedFields()), 0)
p = m1.Permit("Id")
t.Int(len(p.PermittedFields()), 1)
p = m1.Permit("Id", "Id")
t.Int(len(p.PermittedFields()), 1)
t.Int(len(p.Filter(RawChanges{
"Id": 1,
"Name": "haha",
})), 1)
t.Int(len(p.Filter(`{
"Id": 1,
"Name": "haha"
}`)), 1)
t.Int(len(p.Filter([]byte(`{
"Id": 1,
"Name": "haha"
}`))), 1)
t.Int(len(p.Filter(strings.NewReader(`{
"Id": 1,
"Name": "haha"
}`))), 1)
t.Int(len(p.Filter(struct {
Id int
Name string
}{})), 1)
p = m1.Permit()
t.Int(len(p.PermittedFields()), 0)
t.Int(len(p.Filter(map[string]interface{}{
"Name": "haha",
})), 0)
p = m1.PermitAllExcept("Password")
t.Int(len(p.PermittedFields()), 2)
p = m1.PermitAllExcept("Password", "Password")
t.Int(len(p.PermittedFields()), 2)
t.Int(len(p.Filter(map[string]interface{}{
"Name": "haha",
"Password": "reset",
"BadData": "foobar",
})), 1)
p = m1.PermitAllExcept()
t.Int(len(p.PermittedFields()), 3)
p = m1.PermitAllExcept("Invalid")
t.Int(len(p.PermittedFields()), 3)
p = m1.Permit()
c := m1.Changes(RawChanges{
"Name": "test",
"BadData": "foobar",
})
t.Int(len(c), 1)
var f Field
for _f := range c {
f = _f
break
}
t.String(f.Name, "Name")
t.String(m1.Find().String(), "SELECT id, name, password FROM admins")
t.String(m1.Find(AddTableName).String(), "SELECT admins.id, admins.name, admins.password FROM admins")
t.String(m1.Find().Where("id = $1", 1).String(), "SELECT id, name, password FROM admins WHERE id = $1")
t.String(m1.Find().Select("name").String(), "SELECT id, name, password, name FROM admins")
t.String(m1.Select("id").Where("id = $? AND id = $?", 1).String(), "SELECT id FROM admins WHERE id = $1 AND id = $1")
t.String(m1.Select("id").Where("id = $? AND id = $?", 1, 2).String(), "SELECT id FROM admins WHERE id = $? AND id = $?")
t.Strings(
m1.Select("id").Where("id = $?", 1).Where("name = $?", "a").String(),
m1.Select("id").WHERE("id", "=", 1, "name", "=", "a").String(),
"SELECT id FROM admins WHERE (id = $1) AND (name = $2)",
)
t.String(m1.Select("name").Find().String(), "SELECT id, name, password FROM admins")
t.String(m1.Select("name").Find("--no-reset").String(), "SELECT name, id, name, password FROM admins")
t.String(m1.Where("id = $1", 1).Find().String(), "SELECT id, name, password FROM admins WHERE id = $1")
t.String(m1.Where("id = $1", 1).Find(AddTableName).String(), "SELECT admins.id, admins.name, admins.password FROM admins WHERE id = $1")
t.String(m1.Select("id", "name").String(), "SELECT id, name FROM admins")
t.String(m1.Select("id", "name").Where("status = $1", "new").String(), "SELECT id, name FROM admins WHERE status = $1")
t.String(m1.Where("status = $1", "new").Select("id", "name").String(), "SELECT id, name FROM admins WHERE status = $1")
t.String(m1.Select("id").OrderBy("id DESC").String(), "SELECT id FROM admins ORDER BY id DESC")
t.String(m1.Select("id").OrderBy("id DESC").Limit(2).String(), "SELECT id FROM admins ORDER BY id DESC LIMIT 2")
t.String(m1.Select("id").OrderBy("id DESC").Limit(2).Limit(nil).String(), "SELECT id FROM admins ORDER BY id DESC")
t.String(m1.Select("id").Offset("10").Limit(2).String(), "SELECT id FROM admins LIMIT 2 OFFSET 10")
t.String(m1.Select("array_agg(id)").GroupBy("name", "status").String(), "SELECT array_agg(id) FROM admins GROUP BY name, status")
t.Strings(
m1.Select("sum(price)").Where("id > $1", 1).GroupBy("kind").Having("sum(price) < $2", 3).String(),
m1.Select("sum(price)").WHERE("id", ">", 1).GroupBy("kind").Having("sum(price) < $?", 3).String(),
"SELECT sum(price) FROM admins WHERE id > $1 GROUP BY kind HAVING sum(price) < $2",
)
t.String(m1.Select("id").Join("JOIN a ON a.id = admins.id").String(), "SELECT id FROM admins JOIN a ON a.id = admins.id")
t.String(m1.Select("id").Join("JOIN a ON a.id = admins.id").Join("JOIN b ON b.id = admins.id").String(),
"SELECT id FROM admins JOIN a ON a.id = admins.id JOIN b ON b.id = admins.id")
t.String(m1.Select("id").Join("JOIN a ON a.id = admins.id").ResetJoin("JOIN b ON b.id = admins.id").String(),
"SELECT id FROM admins JOIN b ON b.id = admins.id")
t.String(m1.Delete().String(), "DELETE FROM admins")
t.String(m1.Delete().Returning("id").String(), "DELETE FROM admins RETURNING id")
t.String(m1.Delete().Using("users", "orders").
Where("admins.user_id = users.id").Where("admins.order_id = orders.id").
Where("orders.name = $1", "foobar").Returning("admins.id").String(),
"DELETE FROM admins USING users, orders WHERE (admins.user_id = users.id) "+
"AND (admins.order_id = orders.id) AND (orders.name = $1) RETURNING admins.id")
t.Strings(
m1.Where("id = $1", 1).Delete().String(),
m1.WHERE("id", "=", 1).Delete().String(),
"DELETE FROM admins WHERE id = $1",
)
t.Strings(
m1.Delete().Where("id = $1", 1).String(),
m1.Delete().WHERE("id", "=", 1).String(),
"DELETE FROM admins WHERE id = $1",
)
t.Strings(
m1.Delete().Where("id = $1", 1).Where("name = $2", "foobar").String(),
m1.Delete().WHERE("id", "=", 1, "name", "=", "foobar").String(),
"DELETE FROM admins WHERE (id = $1) AND (name = $2)",
)
t.String(m1.Insert(c).String(), "INSERT INTO admins (name) VALUES ($1)")
t.String(m1.Insert(c).Returning("id").String(), "INSERT INTO admins (name) VALUES ($1) RETURNING id")
t.String(m1.Insert(c).Returning("id AS foobar", "name").String(), "INSERT INTO admins (name) VALUES ($1) RETURNING id AS foobar, name")
t.String(m1.Insert(c).OnConflict().String(), "INSERT INTO admins (name) VALUES ($1)")
t.String(m1.Insert(c).DoNothing().String(), "INSERT INTO admins (name) VALUES ($1)")
t.String(m1.Insert(c).OnConflict().DoNothing().String(), "INSERT INTO admins (name) VALUES ($1) ON CONFLICT DO NOTHING")
t.String(m1.Insert(c).DoNothing().OnConflict().String(), "INSERT INTO admins (name) VALUES ($1) ON CONFLICT DO NOTHING")
t.String(m1.Insert(c).Returning("id").OnConflict().DoNothing().String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT DO NOTHING RETURNING id")
t.String(m1.Insert(c).OnConflict("name").DoNothing().String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (name) DO NOTHING")
t.String(m1.Insert(c).OnConflict("lower(name)").DoNothing().String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (lower(name)) DO NOTHING")
t.String(m1.Insert(c).OnConflict("(name) WHERE TRUE").DoNothing().String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (name) WHERE TRUE DO NOTHING")
t.String(m1.Insert(c).OnConflict("name", "password").DoNothing().String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (name, password) DO NOTHING")
t.String(m1.Insert(c).OnConflict("name").DoUpdate("password = NULL").String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (name) DO UPDATE SET password = NULL")
t.String(m1.Insert(c).OnConflict("name").DoUpdateAll().String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name")
t.String(m1.Insert(c).OnConflict("name").DoUpdateAll().DoUpdate("password = NULL").String(),
"INSERT INTO admins (name) VALUES ($1) ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, password = NULL")
t.String(m1.Update(c).String(), "UPDATE admins SET name = $1")
t.String(m1.Update(c).Returning("id").String(), "UPDATE admins SET name = $1 RETURNING id")
t.String(m1.Where("id = $1", 1).Update(c).String(),
"UPDATE admins SET name = $2 WHERE id = $1")
t.String(m1.Update(c).Where("id = $1", 1).String(),
"UPDATE admins SET name = $2 WHERE id = $1")
t.Strings(
m1.Update(c).Where("name = $1", "foo").Where("id = $2", 1).String(),
m1.Update(c).WHERE("name", "=", "foo", "id", "=", 1).String(),
"UPDATE admins SET name = $3 WHERE (name = $1) AND (id = $2)",
)
t.String(m1.Update("Name", String("CONCAT(name, '1')")).String(),
"UPDATE admins SET name = CONCAT(name, '1')")
m2 := NewModel(category{})
t.String(m2.Find().String(), "SELECT id, created_at, updated_at, meta FROM categories")
t.String(m2.Find().Select("id").String(), "SELECT id, created_at, updated_at, id, meta FROM categories")
t.String(m2.Find(AddTableName).Select("id").String(),
"SELECT categories.id, categories.created_at, categories.updated_at, id, categories.meta FROM categories")
t.String(m2.TypeName(), "category")
t.String(m2.tableName, "categories")
p = m2.Permit("Names", "Picture")
t.Int(len(p.PermittedFields()), 2)
m2c := m2.Changes(RawChanges{
"Picture": "https://hello/world",
})
t.String(m2.Insert(m2c).String(), "INSERT INTO categories (meta) VALUES ($1)")
t.String(m2.Insert(m2c).values[0].(string), `{"picture":"https://hello/world"}`)
t.String(m2.Update(m2c).String(), "UPDATE categories SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{picture}', $1)")
t.String(m2.Update("Picture", String("to_jsonb(UPPER(COALESCE(meta->>'picture', '')))")).String(),
"UPDATE categories SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{picture}', to_jsonb(UPPER(COALESCE(meta->>'picture', ''))))")
t.String(m2.Update(
"Id", String("id + 1"),
"Picture", String("'null'::jsonb"),
"CreatedAt", String("now()"),
).String(),
"UPDATE categories SET id = id + 1, created_at = now(), meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{picture}', 'null'::jsonb)")
t.String(m2.Update(m2c).values[0].(string), `"https://hello/world"`)
t.String(m2.Update(m2c).Where("id = $1", 1).String(),
"UPDATE categories SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{picture}', $2) WHERE id = $1")
m2c2 := m2.Changes(RawChanges{
"Names": []map[string]string{
{
"key": "en_US",
"value": "Category",
},
},
})
t.String(m2.Insert(m2c2).String(), "INSERT INTO categories (meta) VALUES ($1)")
t.String(m2.Insert(m2c2).values[0].(string), `{"names":[{"key":"en_US","value":"Category"}]}`)
t.String(m2.Update(m2c2).String(), "UPDATE categories SET meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{names}', $1)")
t.String(m2.Update(m2c2).values[0].(string), `[{"key":"en_US","value":"Category"}]`)
t.String(m2.Insert(
m2c2,
m2.CreatedAt(),
m2.UpdatedAt(),
).String(), "INSERT INTO categories (created_at, updated_at, meta) VALUES ($1, $2, $3)")
t.String(m2.Update(
m2c2,
m2.CreatedAt(),
m2.UpdatedAt(),
).String(), "UPDATE categories SET created_at = $1, updated_at = $2, meta = jsonb_set(COALESCE(meta, '{}'::jsonb), '{names}', $3)")
m3 := NewModel(user{})
t.String(m3.TypeName(), "user")
t.String(m3.tableName, "users")
t.Int(len(m3.modelFields), 4)
m4 := NewModel(product{})
t.String(m4.TypeName(), "product")
t.String(m4.tableName, "products")
t.Int(len(m4.modelFields), 3)
x0 := "INSERT INTO products (name, price) VALUES ($1, $2)"
x1 := m4.Insert(
m4.Changes(RawChanges{"name": "test"}),
m4.Changes(RawChanges{"PRICE": 2}),
)
t.String(x1.String(), x0)
x2 := m4.Insert(
m4.FieldChanges(RawChanges{"Name": "test"}),
m4.FieldChanges(RawChanges{"Price": 2}),
)
t.String(x2.String(), x0)
x3 := m4.Insert("Name", "test", "Price", 2)
t.String(x3.String(), x0)
x4 := m4.Insert(
"PRICE", 1,
m4.Changes(RawChanges{
"name": "test",
}),
"Price", 2,
)
t.String(x4.String(), x0)
x5 := m4.Insert(
"Name", "foobar",
"Price", 2, 3, 4,
"Price", 10,
)
t.String(x5.String(), x0)
t.String(fmt.Sprint(x5.values), "[foobar 10]")
x6 := m4.Insert(
m4.FieldChanges(RawChanges{"Name": "foobar"}),
m4.FieldChanges(RawChanges{"Price": 10}),
)
t.String(x6.String(), x5.String())
t.String(fmt.Sprint(x6.values), fmt.Sprint(x5.values))
x7 := m4.Update(
"Price", 1,
)
t.String(x7.String(), "UPDATE products SET price = $1")
t.String(m4.Update("Price", String("price + 1")).String(), "UPDATE products SET price = price + 1")
var pp product
m4.MustAssign(
&pp,
"Price", 100,
)
t.Int(pp.Price, 100)
}
type (
dataTypeTest struct {
Test0 string
Test1 string
Test2 string `dataType:"test"`
Test3 string `dataType:"hello"`
}
)
func (dataTypeTest) DataType(m Model, fieldName string) string {
if fieldName == "Test1" {
return "foo"
}
if fieldName == "Test3" {
return "world"
}
return ""
}
func TestDataType(_t *testing.T) {
t := test{_t, 0}
m := NewModel(dataTypeTest{})
dataTypes := m.ColumnDataTypes()
t.String(dataTypes["test0"], "text DEFAULT ''::text NOT NULL")
t.String(dataTypes["test1"], "foo")
t.String(dataTypes["test2"], "test")
t.String(dataTypes["test3"], "world")
}
type (
schema0Test struct {
Test0 string
}
schema1Test struct {
Test0 string
}
schema2Test struct {
Test0 string
}
)
func (schema1Test) Schema() string {
return `CREATE VIEW schema1Tests AS SELECT 'yes' AS test0;`
}
func (schema2Test) BeforeCreateSchema() string {
return `-- comment b`
}
func (schema2Test) AfterCreateSchema() string {
return `-- comment a`
}
func TestSchema(_t *testing.T) {
t := test{_t, 0}
t.String(NewModel(schema0Test{}).Schema(), `CREATE TABLE schema0Tests (
test0 text DEFAULT ''::text NOT NULL
);
`)
t.String(NewModel(schema1Test{}).Schema(), `CREATE VIEW schema1Tests AS SELECT 'yes' AS test0;
`)
t.String(NewModel(schema2Test{}).Schema(), `-- comment b
CREATE TABLE schema2Tests (
test0 text DEFAULT ''::text NOT NULL
);
-- comment a
`)
}
func (t *test) String(got, expected string) {
t.Helper()
if got == expected {
t.Logf("case %d passed", t.i)
} else {
t.Errorf("case %d failed, got %s", t.i, got)
}
t.i++
}
func (t *test) Strings(inputs ...string) {
t.Helper()
if len(inputs) < 2 {
t.Error("inputs should have at least 2 strings")
}
expected := inputs[len(inputs)-1]
allEqual := true
var badActual string
for _, s := range inputs[:len(inputs)-1] {
if s != expected {
allEqual = false
badActual = s
break
}
}
if allEqual {
t.Logf("case %d passed", t.i)
} else {
t.Errorf("case %d failed, got %s", t.i, badActual)
}
t.i++
}
func (t *test) Int(got, expected int) {
t.Helper()
if got == expected {
t.Logf("case %d passed", t.i)
} else {
t.Errorf("case %d failed, got %d", t.i, got)
}
t.i++
}
func (t *test) Nil(got, expected interface{}) {
t.Helper()
if got == expected {
t.Logf("case %d passed", t.i)
} else {
t.Errorf("case %d failed, not nil: %+v", t.i, got)
}
t.i++
}