feat-db_abstraction #2
@@ -3,41 +3,47 @@ package database
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"easywish/config"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type DbContext interface {
|
||||
DBTX
|
||||
Close()
|
||||
BeginTx(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
type dbContextImpl struct {
|
||||
Pool *pgxpool.Pool
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
func NewDbContext() DbContext {
|
||||
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, config.GetConfig().DatabaseUrl)
|
||||
|
||||
pool, err := pgxpool.New(context.Background(), config.GetConfig().DatabaseUrl)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
if err := pool.Ping(context.Background()); err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
return &dbContextImpl{
|
||||
Pool: pool,
|
||||
Context: ctx,
|
||||
panic("db connection failed: " + err.Error())
|
||||
}
|
||||
return &dbContextImpl{Pool: pool}
|
||||
}
|
||||
|
||||
// Close implements DbContext.
|
||||
func (d *dbContextImpl) Close() {
|
||||
d.Pool.Close()
|
||||
}
|
||||
|
||||
func (d *dbContextImpl) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
|
||||
return d.Pool.Exec(ctx, sql, args...)
|
||||
}
|
||||
|
||||
func (d *dbContextImpl) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
|
||||
return d.Pool.Query(ctx, sql, args...)
|
||||
}
|
||||
|
||||
func (d *dbContextImpl) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
|
||||
return d.Pool.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
|
||||
func (d *dbContextImpl) BeginTx(ctx context.Context) (pgx.Tx, error) {
|
||||
return d.Pool.Begin(ctx)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user