51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
var defaultClient *Client
|
|
|
|
type Client struct {
|
|
pool *pgxpool.Pool
|
|
tx pgx.Tx
|
|
}
|
|
|
|
// Init 初始化(只调用一次)
|
|
func Init(pool *pgxpool.Pool) {
|
|
defaultClient = &Client{pool: pool}
|
|
}
|
|
|
|
// New 获取全局 client
|
|
func New() *Client {
|
|
if defaultClient == nil {
|
|
panic("db not initialized, call db.Init(pool) first")
|
|
}
|
|
return defaultClient
|
|
}
|
|
|
|
func (c *Client) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
|
|
if c.tx != nil {
|
|
return c.tx.Exec(ctx, sql, args...)
|
|
}
|
|
return c.pool.Exec(ctx, sql, args...)
|
|
}
|
|
|
|
func (c *Client) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
|
|
if c.tx != nil {
|
|
return c.tx.Query(ctx, sql, args...)
|
|
}
|
|
return c.pool.Query(ctx, sql, args...)
|
|
}
|
|
|
|
func (c *Client) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
|
|
if c.tx != nil {
|
|
return c.tx.QueryRow(ctx, sql, args...)
|
|
}
|
|
return c.pool.QueryRow(ctx, sql, args...)
|
|
}
|