-
Notifications
You must be signed in to change notification settings - Fork 2
/
benchmark-pg.go
258 lines (245 loc) · 6.06 KB
/
benchmark-pg.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
package main
import (
"database/sql"
"flag"
"fmt"
"time"
"github.com/lib/pq"
)
var (
User = flag.String("user", "", "username to connect as")
Password = flag.String("password", "", "password for the user")
Prepared = flag.Bool("prepared", false, "use a prepared statement for one-by-one insertion")
Copy = flag.Bool("copy", false, "use COPY FROM instead of INSERT")
Count = flag.Int("count", 1000, "number to insert")
Start = flag.Int("start", 0, "starting offset")
OneTrans = flag.Bool("one-trans", false, "Use beginTransaction/commitTransaction across all inserts.")
EachTrans = flag.Bool("each-trans", false, "Use beginTransaction/commitTransaction across each single call (bulk or one-by-one each gets a separate transaction).")
Verify = flag.Bool("verify", false, "After inserting, verify all documents are correct and new docs are inserted.")
Verbose = flag.Bool("verbose", false, "Print more information.")
Setup = flag.Bool("setup", false, "Just create the tables and exit")
Cleanup = flag.Bool("cleanup", false, "destroy all the tables and exit")
)
var RetryCount = 0
type TxOrDB interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Prepare(query string) (*sql.Stmt, error)
}
func oneByOneDirect(db *sql.DB) error {
var execer TxOrDB
var tx *sql.Tx
var prepared *sql.Stmt
if *OneTrans {
var err error
tx, err = db.Begin()
if err != nil {
// retry?
return err
}
execer = tx
} else {
execer = db
}
if *Prepared {
var err error
prepared, err = execer.Prepare("INSERT INTO foo (id, val) VALUES ($1, $2)")
if err != nil {
return err
}
} else {
execer = db
}
for i := 0; i < *Count; i++ {
val := *Start + i
strVal := fmt.Sprintf("%07d", val)
var err error
if prepared != nil {
_, err = prepared.Exec(val, strVal)
} else {
if *EachTrans {
var err error
tx, err = db.Begin()
if err != nil {
return err
}
execer = tx
} else {
execer = db
}
_, err = execer.Exec("INSERT INTO foo (id, val) VALUES ($1, $2)", val, strVal)
}
if err != nil {
fmt.Printf("could not insert doc %d\n%s\n", val, err)
if tx != nil {
tx.Rollback()
}
return err
}
if *EachTrans {
if err := tx.Commit(); err != nil {
return err
}
}
}
if prepared != nil {
if err := prepared.Close(); err != nil {
return err
}
}
if *OneTrans {
return tx.Commit()
}
return nil
}
func bulkDirect(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare(pq.CopyIn("foo", "id", "val"))
if err != nil {
tx.Rollback()
return err
}
// Build up the COPY FROM by repeated Exec calls
for i := 0; i < *Count; i++ {
val := *Start + i
strVal := fmt.Sprintf("%07d", val)
if _, err := stmt.Exec(val, strVal); err != nil {
fmt.Printf("error while building up COPY: %s\n", err)
tx.Rollback()
return err
}
}
// Flush the COPY FROM to postgres
if _, err := stmt.Exec(); err != nil {
fmt.Printf("error while copying data: %s\n", err)
return err
}
if err := stmt.Close(); err != nil {
fmt.Printf("error during stmt.Close(): %s\n", err)
return err
}
if err := tx.Commit(); err != nil {
fmt.Printf("could not commit transaction: %s\n", err)
return err
}
return nil
}
type ValDoc struct {
val string `bson:"val"`
}
func setupDirectTable(db *sql.DB) error {
_, err := db.Exec("CREATE TABLE foo(id INTEGER PRIMARY KEY, val TEXT)")
return err
}
func setupJSONTable(db *sql.DB) error {
_, err := db.Exec("CREATE TABLE fooJSON (id INTEGER PRIMARY KEY, val JSON)")
return err
}
func cleanupTables(db *sql.DB) error {
if _, err := db.Exec("DROP TABLE foo"); err != nil {
if pqerr, ok := err.(*pq.Error); ok {
if pqerr.Code.Name() == "undefined_table" {
// dropping a table that doesn't exist is fine
fmt.Printf("tables already deleted\n")
return nil
}
}
return err
} else {
fmt.Printf("tables deleted\n")
}
return nil
}
func verifyNewDocs(db *sql.DB) error {
rows, err := db.Query(
"SELECT id, val"+
" FROM foo"+
" WHERE id >= ? AND id < ?"+
" ORDER BY id INCR",
*Start, *Start+*Count)
if err != nil {
return err
}
expected := *Start
for rows.Next() {
var id int
var val string
if err = rows.Scan(&id, &val); err != nil {
return err
}
if id != expected {
return fmt.Errorf("expected id %d found %d", expected, id)
}
strVal := fmt.Sprintf("%07d", id)
if val != strVal {
return fmt.Errorf("expected id %d to have val %s not %s", expected, strVal, val)
}
expected++
}
return rows.Err()
}
func main() {
flag.Parse()
connString := "sslmode=disable"
if *User != "" {
connString += fmt.Sprintf(" user='%s'", *User)
}
if *Password != "" {
connString += fmt.Sprintf(" password='%s'", *Password)
}
db, err := sql.Open("postgres", connString)
if err != nil {
fmt.Printf("Failed to open database: %s\n", err)
return
}
if *OneTrans && *EachTrans {
fmt.Printf("--one-trans and --each-trans are mutually exclusive\n")
return
}
if *EachTrans && *Prepared {
fmt.Printf("--each-trans and --prepare doesn't make sense\n")
return
}
if *Cleanup {
if err := cleanupTables(db); err != nil {
fmt.Printf("failed to clean up tables: %s\n", err)
}
}
if *Setup {
if err := setupDirectTable(db); err != nil {
fmt.Printf("failed to set up table: %s\n", err)
} else {
fmt.Printf("set up direct tables\n")
}
}
if *Cleanup && !*Setup {
// No reason to run if we just nuked the tables
return
}
if *Count == 0 {
return
}
if *Verbose {
fmt.Printf("inserting docs from %d to %d\n", *Start, *Start+*Count-1)
}
start := time.Now()
if *Copy {
err = bulkDirect(db)
} else {
err = oneByOneDirect(db)
}
if err != nil {
fmt.Printf("%.3fms to insert %d documents (FAILED: %s)\n", float64(time.Since(start))/float64(time.Millisecond), *Count, err)
} else {
fmt.Printf("%.3fms to insert %d documents\n", float64(time.Since(start))/float64(time.Millisecond), *Count)
}
if *Verify {
if err := verifyNewDocs(db); err != nil {
fmt.Printf("verification failed: %s\n", err.Error())
return
}
fmt.Printf("verification succeeded.\n")
}
}