Skip to content

Commit cbce8f4

Browse files
authored
Merge pull request #16 from secondwindoss/fix/910-connectcontext-close
Close the DB in ConnectContext when the ping fails (upstream #561).
2 parents 7274608 + 1331fca commit cbce8f4

3 files changed

Lines changed: 28 additions & 11 deletions

File tree

‎connect_context_test.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package sqlx
2+
3+
import (
4+
"context"
5+
"testing"
6+
)
7+
8+
// ConnectContext closes the DB and returns nil when the ping fails
9+
// (upstream #910).
10+
func TestConnectContextClosesOnPingFailure(t *testing.T) {
11+
ctx, cancel := context.WithCancel(context.Background())
12+
cancel()
13+
db, err := ConnectContext(ctx, "sqlite3", ":memory:")
14+
if err == nil {
15+
t.Fatal("expected a ping error with a cancelled context")
16+
}
17+
if db != nil {
18+
t.Errorf("ConnectContext returned a non-nil *DB together with the error: %v", err)
19+
db.Close()
20+
}
21+
}

‎sqlx.go‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sqlx
22

33
import (
4+
"context"
45
"database/sql"
56
"database/sql/driver"
67
"errors"
@@ -638,16 +639,7 @@ func (r *Rows) StructScan(dest interface{}) error {
638639

639640
// Connect to a database and verify with a ping.
640641
func Connect(driverName, dataSourceName string) (*DB, error) {
641-
db, err := Open(driverName, dataSourceName)
642-
if err != nil {
643-
return nil, err
644-
}
645-
err = db.Ping()
646-
if err != nil {
647-
db.Close()
648-
return nil, err
649-
}
650-
return db, nil
642+
return ConnectContext(context.Background(), driverName, dataSourceName)
651643
}
652644

653645
// MustConnect connects to a database and panics on error.

‎sqlx_context.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ func ConnectContext(ctx context.Context, driverName, dataSourceName string) (*DB
1919
return db, err
2020
}
2121
err = db.PingContext(ctx)
22-
return db, err
22+
if err != nil {
23+
db.Close()
24+
return nil, err
25+
}
26+
return db, nil
2327
}
2428

2529
// QueryerContext is an interface used by GetContext and SelectContext

0 commit comments

Comments
 (0)