Skip to content

Commit

Permalink
Merge pull request #58 from DATA-DOG/driverContext
Browse files Browse the repository at this point in the history
Support the driver.DriverContext interface
  • Loading branch information
Yiling-J authored Nov 23, 2023
2 parents c347f3a + 71379a6 commit 244953c
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,14 @@ import (
// [database/sql.OpenDB]. This can be used in place of [Register].
// It takes the same arguments as [Register], with the omission of name.
func New(drv, dsn string, options ...func(*conn) error) driver.Connector {
return &TxDriver{
dsn: dsn,
drv: drv,
conns: make(map[string]*conn),
options: options,
return &txConnector{
driver: &TxDriver{
dsn: dsn,
drv: drv,
conns: make(map[string]*conn),
options: options,
},
name: "connector",
}
}

Expand Down Expand Up @@ -133,23 +136,43 @@ type TxDriver struct {
dsn string
}

var (
_ driver.Driver = (*TxDriver)(nil)
_ driver.DriverContext = (*TxDriver)(nil)
)

type txConnector struct {
driver *TxDriver
name string
}

var _ driver.Connector = (*txConnector)(nil)

// Connect satisfies the [database/sql/driver.Connector] interface.
func (d *TxDriver) Connect(context.Context) (driver.Conn, error) {
func (c *txConnector) Connect(context.Context) (driver.Conn, error) {
// The DSN passed here doesn't matter, since it's only used to disambiguate
// connections, but that disambiguation happens in the call to New() when
// used through the driver.Connector interface.
return d.Open("connector")
return c.driver.Open(c.name)
}

// Driver satisfies the [database/sql/driver.Connector] interface.
func (d *TxDriver) Driver() driver.Driver {
return d
func (c *txConnector) Driver() driver.Driver {
return c.driver
}

func (d *TxDriver) DB() *sql.DB {
return d.db
}

// OpenConnector satisfies the [database/sql/driver.DriverContext] interface.
func (d *TxDriver) OpenConnector(name string) (driver.Connector, error) {
return &txConnector{
driver: d,
name: name,
}, nil
}

func (d *TxDriver) Open(dsn string) (driver.Conn, error) {
d.Lock()
defer d.Unlock()
Expand Down

0 comments on commit 244953c

Please sign in to comment.