go-vise

Constrained Size Output Virtual Machine
Info | Log | Files | Refs | README | LICENSE

commit 9e9ee5bdfa7af9d79694d9cc3f12af9574167f81
parent 1757ba50d6a03e1cd0b294925bf94d8bf7f3c568
Author: Mohammed Sohail <sohailsameja@gmail.com>
Date:   Fri, 22 Nov 2024 11:33:19 +0300

fix: multiple pg fixes

fix: consecutive calls to Db.Connect() should be ignored

* Instead of panicking, which could crash the process, we warn and return nil.

fix: set prepared flag only after a successful tx commit

fix: safely close pgx pool

feat: healthcheck the db before attempting to interact with it through prepare

* This prevents any panics downstream as an error is returned early on

Signed-off-by: Mohammed Sohail <sohailsameja@gmail.com>

Diffstat:
Mdb/postgres/pg.go | 15++++++++++-----
1 file changed, 10 insertions(+), 5 deletions(-)

diff --git a/db/postgres/pg.go b/db/postgres/pg.go @@ -17,6 +17,7 @@ var ( type PgInterface interface { BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error) + Close() } // pgDb is a Postgres backend implementation of the Db interface. @@ -53,14 +54,18 @@ func(pdb *pgDb) WithConnection(pi PgInterface) *pgDb { // Connect implements Db. func(pdb *pgDb) Connect(ctx context.Context, connStr string) error { if pdb.conn != nil { - logg.WarnCtxf(ctx, "already connected", "conn", pdb.conn) - panic("already connected") + logg.WarnCtxf(ctx, "Pg already connected") + return nil } - var err error conn, err := pgxpool.New(ctx, connStr) if err != nil { return err } + + if err := conn.Ping(ctx); err != nil { + return fmt.Errorf("connection to postgres could not be established: %w", err) + } + pdb.conn = conn return pdb.Prepare(ctx) } @@ -143,7 +148,7 @@ func (pdb *pgDb) Get(ctx context.Context, key []byte) ([]byte, error) { // Close implements Db. func(pdb *pgDb) Close() error { - pdb.Close() + pdb.conn.Close() return nil } @@ -153,7 +158,6 @@ func(pdb *pgDb) Prepare(ctx context.Context) error { logg.WarnCtxf(ctx, "Prepare called more than once") return nil } - pdb.prepd = true tx, err := pdb.conn.BeginTx(ctx, defaultTxOptions) if err != nil { tx.Rollback(ctx) @@ -177,5 +181,6 @@ func(pdb *pgDb) Prepare(ctx context.Context) error { tx.Rollback(ctx) return err } + pdb.prepd = true return nil }