-
Notifications
You must be signed in to change notification settings - Fork 27
/
fakedb_go110_test.go
102 lines (88 loc) · 1.77 KB
/
fakedb_go110_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
//go:build go1.10
// +build go1.10
package proxy
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
)
type fakeDriverCtx fakeDriver
type fakeConnector struct {
driver *fakeDriverCtx
opt *fakeConnOption
db *fakeDB
}
var fdriverctx = &fakeDriverCtx{}
var _ driver.DriverContext = (*fakeDriverCtx)(nil)
var _ driver.Connector = (*fakeConnector)(nil)
func init() {
sql.Register("fakedbctx", fdriverctx)
}
func (d *fakeDriverCtx) Open(name string) (driver.Conn, error) {
return nil, errors.New("not implemented")
}
func (d *fakeDriverCtx) OpenConnector(name string) (driver.Connector, error) {
var opt fakeConnOption
err := json.Unmarshal([]byte(name), &opt)
if err != nil {
return nil, err
}
// validate options
switch opt.ConnType {
case "", "fakeConn", "fakeConnExt", "fakeConnCtx":
// validation OK
default:
return nil, errors.New("known ConnType")
}
d.mu.Lock()
defer d.mu.Unlock()
db, ok := d.dbs[opt.Name]
if !ok {
db = &fakeDB{
log: &bytes.Buffer{},
}
if d.dbs == nil {
d.dbs = make(map[string]*fakeDB)
}
d.dbs[name] = db
}
return &fakeConnector{
driver: d,
opt: &opt,
db: db,
}, nil
}
func (d *fakeDriverCtx) DB(name string) *fakeDB {
d.mu.Lock()
defer d.mu.Unlock()
return d.dbs[name]
}
func (c *fakeConnector) Connect(ctx context.Context) (driver.Conn, error) {
var conn driver.Conn
switch c.opt.ConnType {
case "", "fakeConn":
conn = &fakeConn{
db: c.db,
opt: c.opt,
}
case "fakeConnExt":
conn = &fakeConnExt{
db: c.db,
opt: c.opt,
}
case "fakeConnCtx":
conn = &fakeConnCtx{
db: c.db,
opt: c.opt,
}
default:
return nil, errors.New("known ConnType")
}
return conn, nil
}
func (c *fakeConnector) Driver() driver.Driver {
return c.driver
}