43 lines
765 B
Go
43 lines
765 B
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 Executor interface {
|
|
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
|
|
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
|
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
|
}
|
|
|
|
type Client struct {
|
|
pool *pgxpool.Pool
|
|
tx pgx.Tx
|
|
}
|
|
|
|
// Init 初始化
|
|
func Init(pool *pgxpool.Pool) {
|
|
defaultClient = &Client{pool: pool}
|
|
}
|
|
|
|
// New 创建会话
|
|
func New() *Client {
|
|
return &Client{
|
|
pool: defaultClient.pool,
|
|
}
|
|
}
|
|
|
|
// 内部获取执行器(关键)
|
|
func (c *Client) exec() Executor {
|
|
if c.tx != nil {
|
|
return c.tx
|
|
}
|
|
return c.pool
|
|
}
|