-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrap.go
63 lines (54 loc) · 1.37 KB
/
wrap.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
package pgtest
import (
"database/sql"
"database/sql/driver"
"runtime"
"testing"
"github.com/lib/pq"
)
// WrapDB opens a new connection to the database at the provided URL,
// but with a driver that calls wrapFn on every driver.Stmt.Exec call
// and driver.Stmt.Query call.
//
// It also registers a finalizer for the DB, so callers can discard
// it without closing it explicitly.
func WrapDB(t testing.TB, url string, wrapFn func(string)) *sql.DB {
// Register a new SQL driver that will wrapFn on every driver.Stmt
// Exec and Query call.
driverName := pickName("wrappeddriver")
sql.Register(driverName, &wrappedDriver{fn: wrapFn})
db, err := sql.Open(driverName, url)
if err != nil {
t.Fatal(err)
}
runtime.SetFinalizer(db, (*sql.DB).Close)
return db
}
type wrappedDriver struct {
fn func(string)
}
func (d *wrappedDriver) Open(name string) (driver.Conn, error) {
conn, err := pq.Open(name)
if err != nil {
return conn, err
}
return wrappedConn{fn: d.fn, backing: conn}, nil
}
type wrappedConn struct {
fn func(string)
backing driver.Conn
}
func (c wrappedConn) Prepare(query string) (driver.Stmt, error) {
c.fn(query)
stmt, err := c.backing.Prepare(query)
if err != nil {
return stmt, err
}
return stmt, nil
}
func (c wrappedConn) Close() error {
return c.backing.Close()
}
func (c wrappedConn) Begin() (driver.Tx, error) {
return c.backing.Begin()
}