50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
|
|
"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
|
|
}
|
|
|
|
func NewDbContext() DbContext {
|
|
pool, err := pgxpool.New(context.Background(), config.GetConfig().DatabaseUrl)
|
|
if err != nil {
|
|
panic("db connection failed: " + err.Error())
|
|
}
|
|
return &dbContextImpl{Pool: pool}
|
|
}
|
|
|
|
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)
|
|
}
|