Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

database/sql: close driver.Connector if it implements io.Closer #41710

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/database/sql/driver/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ type DriverContext interface {
// DriverContext's OpenConnector method, to allow drivers
// access to context and to avoid repeated parsing of driver
// configuration.
//
// If a Connector implements io.Closer, the sql package's DB.Close
// method will call Close and return error (if any).
type Connector interface {
// Connect returns a connection to the database.
// Connect may return a cached connection (one previously
Expand Down
9 changes: 9 additions & 0 deletions src/database/sql/fakedb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type fakeConnector struct {
name string

waiter func(context.Context)
closed bool
}

func (c *fakeConnector) Connect(context.Context) (driver.Conn, error) {
Expand All @@ -68,6 +69,14 @@ func (c *fakeConnector) Driver() driver.Driver {
return fdriver
}

func (c *fakeConnector) Close() error {
if c.closed {
return errors.New("fakedb: connector is closed")
}
c.closed = true
return nil
}

type fakeDriverCtx struct {
fakeDriver
}
Expand Down
6 changes: 6 additions & 0 deletions src/database/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,12 @@ func (db *DB) Close() error {
}
}
db.stop()
if c, ok := db.connector.(io.Closer); ok {
err1 := c.Close()
if err1 != nil {
err = err1
}
}
return err
}

Expand Down
11 changes: 10 additions & 1 deletion src/database/sql/sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4059,9 +4059,18 @@ func TestOpenConnector(t *testing.T) {
}
defer db.Close()

if _, is := db.connector.(*fakeConnector); !is {
c, ok := db.connector.(*fakeConnector)
if !ok {
t.Fatal("not using *fakeConnector")
}

if err := db.Close(); err != nil {
t.Fatal(err)
}

if !c.closed {
t.Fatal("connector is not closed")
}
}

type ctxOnlyDriver struct {
Expand Down