Skip to content

Commit 0f887eb

Browse files
authored
Add NewFromDB (#34)
1 parent 6e372dc commit 0f887eb

File tree

2 files changed

+25
-14
lines changed

2 files changed

+25
-14
lines changed

mocks/pgmq.go

Lines changed: 14 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pgmq.go

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ type Message struct {
2727
}
2828

2929
type DB interface {
30+
Ping(ctx context.Context) error
3031
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
3132
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
3233
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
@@ -51,31 +52,27 @@ func New(ctx context.Context, connString string) (*PGMQ, error) {
5152
return nil, fmt.Errorf("error creating pool: %w", err)
5253
}
5354

54-
err = pool.Ping(ctx)
55-
if err != nil {
55+
return NewFromDB(ctx, pool)
56+
}
57+
58+
// NewFromDB is a bring your own DB version of New. Given an implementation
59+
// of DB, it will call Ping to ensure the connection has been established,
60+
// then create the PGMQ extension if it does not already exist.
61+
func NewFromDB(ctx context.Context, db DB) (*PGMQ, error) {
62+
if err := db.Ping(ctx); err != nil {
5663
return nil, err
5764
}
5865

59-
_, err = pool.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS pgmq CASCADE")
66+
_, err := db.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS pgmq CASCADE")
6067
if err != nil {
6168
return nil, fmt.Errorf("error creating pgmq extension: %w", err)
6269
}
6370

6471
return &PGMQ{
65-
db: pool,
72+
db: db,
6673
}, nil
6774
}
6875

69-
// MustNew is similar to New, but panics if it encounters an error.
70-
func MustNew(ctx context.Context, connString string) *PGMQ {
71-
q, err := New(ctx, connString)
72-
if err != nil {
73-
panic(err)
74-
}
75-
76-
return q
77-
}
78-
7976
// Close closes the underlying connection pool.
8077
func (p *PGMQ) Close() {
8178
p.db.Close()

0 commit comments

Comments
 (0)