feat: dbcontext implements DBTX interface
This commit is contained in:
@@ -3,41 +3,47 @@ package database
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"easywish/config"
|
"easywish/config"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DbContext interface {
|
type DbContext interface {
|
||||||
|
DBTX
|
||||||
Close()
|
Close()
|
||||||
|
BeginTx(ctx context.Context) (pgx.Tx, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type dbContextImpl struct {
|
type dbContextImpl struct {
|
||||||
Pool *pgxpool.Pool
|
Pool *pgxpool.Pool
|
||||||
Context context.Context
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDbContext() DbContext {
|
func NewDbContext() DbContext {
|
||||||
|
pool, err := pgxpool.New(context.Background(), config.GetConfig().DatabaseUrl)
|
||||||
ctx := context.Background()
|
|
||||||
pool, err := pgxpool.New(ctx, config.GetConfig().DatabaseUrl)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err.Error())
|
panic("db connection failed: " + err.Error())
|
||||||
}
|
|
||||||
|
|
||||||
if err := pool.Ping(context.Background()); err != nil {
|
|
||||||
panic(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return &dbContextImpl{
|
|
||||||
Pool: pool,
|
|
||||||
Context: ctx,
|
|
||||||
}
|
}
|
||||||
|
return &dbContextImpl{Pool: pool}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close implements DbContext.
|
|
||||||
func (d *dbContextImpl) Close() {
|
func (d *dbContextImpl) Close() {
|
||||||
d.Pool.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