/
go_pg_integration.go
99 lines (86 loc) · 1.83 KB
/
go_pg_integration.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
package main
import (
"context"
"fmt"
"github.com/bluele/factory-go/factory"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type Group struct {
ID int
Name string
}
type User struct {
ID int
Name string
Group *Group
}
var UserFactory = factory.NewFactory(
&User{},
).SeqInt("ID", func(n int) (interface{}, error) {
return n, nil
}).Attr("Name", func(args factory.Args) (interface{}, error) {
user := args.Instance().(*User)
return fmt.Sprintf("user-%d", user.ID), nil
}).OnCreate(func(args factory.Args) error {
tx := args.Context().Value("tx").(*pg.Tx)
return tx.Insert(args.Instance())
}).SubFactory("Group", GroupFactory)
var GroupFactory = factory.NewFactory(
&Group{},
).SeqInt("ID", func(n int) (interface{}, error) {
return n, nil
}).Attr("Name", func(args factory.Args) (interface{}, error) {
group := args.Instance().(*Group)
return fmt.Sprintf("group-%d", group.ID), nil
}).OnCreate(func(args factory.Args) error {
tx := args.Context().Value("tx").(*pg.Tx)
return tx.Insert(args.Instance())
})
func createTestSchema(db *pg.DB) error {
tables := []interface{}{
&Group{},
&User{},
}
for _, table := range tables {
err := db.DropTable(table, &orm.DropTableOptions{
IfExists: true,
Cascade: true,
})
if err != nil {
return err
}
err = db.CreateTable(table, nil)
if err != nil {
return err
}
}
return nil
}
func openDB() *pg.DB {
db := pg.Connect(&pg.Options{
User: "postgres",
})
err := createTestSchema(db)
if err != nil {
panic(err)
}
return db
}
func main() {
db := openDB()
for i := 0; i < 3; i++ {
tx, err := db.Begin()
if err != nil {
panic(err)
}
ctx := context.WithValue(context.Background(), "tx", tx)
v, err := UserFactory.CreateWithContext(ctx)
if err != nil {
panic(err)
}
user := v.(*User)
fmt.Println(user, *user.Group)
tx.Commit()
}
}