-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgtest.go
262 lines (234 loc) · 6.39 KB
/
pgtest.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
package pgtest
import (
"context"
"database/sql"
"io/ioutil"
"log"
"math/rand"
"net/url"
"os"
"runtime"
"testing"
"time"
"github.com/lib/pq"
"chain/database/pg"
"chain/testutil"
)
var (
random = rand.New(rand.NewSource(time.Now().UnixNano()))
// dbpool contains initialized, pristine databases,
// as returned from open. It is the client's job to
// make sure a database is in this state
// (for example, by rolling back a transaction)
// before returning it to the pool.
dbpool = make(chan *sql.DB, 4)
)
// DefaultURL is used by NewTX and NewDB if DBURL is the empty string.
const DefaultURL = "postgres:///postgres?sslmode=disable"
var (
// DBURL should be a URL of the form "postgres://...".
// If it is the empty string, DefaultURL will be used.
// The functions NewTx and NewDB use it to create and connect
// to new databases by replacing the database name component
// with a randomized name.
DBURL = os.Getenv("DB_URL_TEST")
// SchemaPath is a file containing a schema to initialize
// a database in NewTx.
SchemaPath = os.Getenv("CHAIN") + "/core/schema.sql"
)
const (
gcDur = 3 * time.Minute
timeFormat = "20060102150405"
)
// NewDB creates a database initialized
// with the schema in schemaPath.
// It returns the resulting *sql.DB with its URL.
//
// It also registers a finalizer for the DB, so callers
// can discard it without closing it explicitly, and the
// test program is nevertheless unlikely to run out of
// connection slots in the server.
//
// Prefer NewTx whenever the caller can do its
// work in exactly one transaction.
func NewDB(f Fataler, schemaPath string) (url string, db *sql.DB) {
ctx := context.Background()
if os.Getenv("CHAIN") == "" {
log.Println("warning: $CHAIN not set; probably can't find schema")
}
url, db, err := open(ctx, DBURL, schemaPath)
if err != nil {
f.Fatal(err)
}
runtime.SetFinalizer(db, (*sql.DB).Close)
return url, db
}
// NewTx returns a new transaction on a database
// initialized with the schema in SchemaPath.
//
// It also registers a finalizer for the Tx, so callers
// can discard it without rolling back explicitly, and the
// test program is nevertheless unlikely to run out of
// connection slots in the server.
// The caller should not commit the returned Tx; doing so
// will prevent the underlying database from being reused
// and so cause future calls to NewTx to be slower.
func NewTx(f Fataler) *sql.Tx {
runtime.GC() // give the finalizers a better chance to run
ctx := context.Background()
if os.Getenv("CHAIN") == "" {
log.Println("warning: $CHAIN not set; probably can't find schema")
}
db, err := getdb(ctx, DBURL, SchemaPath)
if err != nil {
f.Fatal(err)
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
db.Close()
f.Fatal(err)
}
// NOTE(kr): we do not set a finalizer on the DB.
// It is closed explicitly, if necessary, by finalizeTx.
runtime.SetFinalizer(tx, finaldb{db}.finalizeTx)
return tx
}
// CloneDB creates a new database, using the database at the provided
// URL as a template. It returns the URL of the database clone.
func CloneDB(ctx context.Context, baseURL string) (newURL string, err error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", err
}
ctldb, err := sql.Open("postgres", baseURL)
if err != nil {
return "", err
}
defer ctldb.Close()
dbname := pickName("db")
_, err = ctldb.Exec("CREATE DATABASE " + pq.QuoteIdentifier(dbname) + " WITH TEMPLATE " + pq.QuoteIdentifier(u.Path[1:]))
if err != nil {
return "", err
}
u.Path = "/" + dbname
return u.String(), nil
}
// open derives a new randomized test database name from baseURL,
// initializes it with schemaFile, and opens it.
func open(ctx context.Context, baseURL, schemaFile string) (newurl string, db *sql.DB, err error) {
if baseURL == "" {
baseURL = DefaultURL
}
u, err := url.Parse(baseURL)
if err != nil {
return "", nil, err
}
ctldb, err := sql.Open("postgres", baseURL)
if err != nil {
return "", nil, err
}
defer ctldb.Close()
err = gcdbs(ctldb)
if err != nil {
log.Println(err)
}
dbname := pickName("db")
u.Path = "/" + dbname
_, err = ctldb.Exec("CREATE DATABASE " + pq.QuoteIdentifier(dbname))
if err != nil {
return "", nil, err
}
schema, err := ioutil.ReadFile(schemaFile)
if err != nil {
return "", nil, err
}
db, err = sql.Open("postgres", u.String())
if err != nil {
return "", nil, err
}
_, err = db.ExecContext(ctx, string(schema))
if err != nil {
db.Close()
return "", nil, err
}
return u.String(), db, nil
}
type finaldb struct{ db *sql.DB }
func (f finaldb) finalizeTx(tx *sql.Tx) {
go func() { // don't block the finalizer goroutine for too long
err := tx.Rollback()
if err != nil {
// If the tx has been committed (or if anything
// else goes wrong), we can't reuse db.
f.db.Close()
return
}
select {
case dbpool <- f.db:
default:
f.db.Close() // pool is full
}
}()
}
func getdb(ctx context.Context, url, path string) (*sql.DB, error) {
select {
case db := <-dbpool:
return db, nil
default:
_, db, err := open(ctx, url, path)
return db, err
}
}
func gcdbs(db *sql.DB) error {
gcTime := time.Now().Add(-gcDur)
const q = `
SELECT datname FROM pg_database
WHERE datname LIKE 'pgtest_%' AND datname < $1
`
rows, err := db.Query(q, formatPrefix("db", gcTime))
if err != nil {
return err
}
var names []string
for rows.Next() {
var name string
err = rows.Scan(&name)
if err != nil {
return err
}
names = append(names, name)
}
if rows.Err() != nil {
return rows.Err()
}
for i, name := range names {
if i > 5 {
break // drop up to five databases per test
}
go db.Exec("DROP DATABASE " + pq.QuoteIdentifier(name))
}
return nil
}
func pickName(prefix string) (s string) {
const chars = "abcdefghijklmnopqrstuvwxyz"
for i := 0; i < 10; i++ {
s += string(chars[random.Intn(len(chars))])
}
return formatPrefix(prefix, time.Now()) + s
}
func formatPrefix(prefix string, t time.Time) string {
return "pgtest_" + prefix + "_" + t.UTC().Format(timeFormat) + "Z_"
}
// Exec executes q in the database or transaction in ctx.
// If there is an error, it fails t.
func Exec(ctx context.Context, db pg.DB, t testing.TB, q string, args ...interface{}) {
_, err := db.ExecContext(ctx, q, args...)
if err != nil {
testutil.FatalErr(t, err)
}
}
// Fataler lets NewTx and NewDB signal immediate failure.
// It is satisfied by *testing.T, *testing.B, and *log.Logger.
type Fataler interface {
Fatal(...interface{})
}