-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
84 lines (70 loc) · 1.54 KB
/
driver.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
package sqlcommenter
import (
"context"
"database/sql/driver"
)
// WrapDriver wraps sql driver with sqlcommenter support.
func WrapDriver(drv driver.Driver, opts ...Option) driver.Driver {
return &commentDriver{
drv: drv,
cmt: newCommenter(opts...),
}
}
type commentDriver struct {
drv driver.Driver
cmt *commenter
}
func (d *commentDriver) Open(name string) (driver.Conn, error) {
conn, err := d.drv.Open(name)
if err != nil {
return nil, err
}
return newConn(conn, d.cmt), nil
}
func (d *commentDriver) OpenConnector(name string) (driver.Connector, error) {
drvCtx, ok := d.drv.(driver.DriverContext)
if !ok {
return newDSNConnector(name, d), nil
}
ctr, err := drvCtx.OpenConnector(name)
if err != nil {
return nil, err
}
return newConnector(ctr, d), nil
}
func newConnector(ctr driver.Connector, drv *commentDriver) *connector {
return &connector{
ctr: ctr,
drv: drv,
}
}
type connector struct {
ctr driver.Connector
drv *commentDriver
}
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
conn, err := c.ctr.Connect(ctx)
if err != nil {
return nil, err
}
return newConn(conn, c.drv.cmt), nil
}
func (c *connector) Driver() driver.Driver {
return c.drv
}
func newDSNConnector(dsn string, drv *commentDriver) *dsnConnector {
return &dsnConnector{
dsn: dsn,
drv: drv,
}
}
type dsnConnector struct {
dsn string
drv *commentDriver
}
func (c *dsnConnector) Connect(context.Context) (driver.Conn, error) {
return c.drv.Open(c.dsn)
}
func (c *dsnConnector) Driver() driver.Driver {
return c.drv
}