Skip to content

Commit 782c22a

Browse files
authored
test(coderd/database/dbtestutil): allow access to *sql.DB (#10238)
1 parent 7df40b8 commit 782c22a

File tree

1 file changed

+25
-0
lines changed
  • coderd/database/dbtestutil

1 file changed

+25
-0
lines changed

coderd/database/dbtestutil/db.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ func WillUsePostgres() bool {
3131
type options struct {
3232
fixedTimezone string
3333
dumpOnFailure bool
34+
returnSQLDB func(*sql.DB)
3435
}
3536

3637
type Option func(*options)
@@ -49,6 +50,27 @@ func WithDumpOnFailure() Option {
4950
}
5051
}
5152

53+
func withReturnSQLDB(f func(*sql.DB)) Option {
54+
return func(o *options) {
55+
o.returnSQLDB = f
56+
}
57+
}
58+
59+
func NewDBWithSQLDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub, *sql.DB) {
60+
t.Helper()
61+
62+
if !WillUsePostgres() {
63+
t.Fatal("cannot use NewDBWithSQLDB without PostgreSQL, consider adding `if !dbtestutil.WillUsePostgres() { t.Skip() }` to this test")
64+
}
65+
66+
var sqlDB *sql.DB
67+
opts = append(opts, withReturnSQLDB(func(db *sql.DB) {
68+
sqlDB = db
69+
}))
70+
db, ps := NewDB(t, opts...)
71+
return db, ps, sqlDB
72+
}
73+
5274
func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) {
5375
t.Helper()
5476

@@ -88,6 +110,9 @@ func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) {
88110
t.Cleanup(func() {
89111
_ = sqlDB.Close()
90112
})
113+
if o.returnSQLDB != nil {
114+
o.returnSQLDB(sqlDB)
115+
}
91116
if o.dumpOnFailure {
92117
t.Cleanup(func() { DumpOnFailure(t, connectionURL) })
93118
}

0 commit comments

Comments
 (0)