20260507213409
This commit is contained in:
1 parent
3070eac71b
commit
4c7f516a03
204 files changed
+3623
No files matched your search
@@ -0,0 +1,50 @@
|
||||
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...)
|
||||
}
|
||||
Reference in new issue
Block a user