This commit is contained in:
oneao committed 2026-04-24 22:37:52 +08:00
1 parent 46cbb2f50d
commit e3d765a9d4
15 files changed
+903 -190

No files matched your search

+22 -14
View File
@@ -10,33 +10,41 @@ import (
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 初始化
// Init 初始化(只调用一次)
func Init(pool *pgxpool.Pool) {
defaultClient = &Client{pool: pool}
}
// New 创建会话
// New 获取全局 client
func New() *Client {
return &Client{
pool: defaultClient.pool,
if defaultClient == nil {
panic("db not initialized, call db.Init(pool) first")
}
return defaultClient
}
// 内部获取执行器(关键)
func (c *Client) exec() Executor {
func (c *Client) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
if c.tx != nil {
return c.tx
return c.tx.Exec(ctx, sql, args...)
}
return c.pool
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...)
}