Documentation
¶
Index ¶
- Constants
- Variables
- func NewDB(URL string, dopts *Options) (*bun.DB, error)
- func RedactDSN(dsn string) string
- func RegisterDriver(d Driver)
- func RegisteredSchemes() []string
- func SanitizeSQL(query string) string
- func SetPool(sqldb *sql.DB, opts *Options)
- func WithCallbackTimeout(d time.Duration) optparams.Option[Options]
- func WithCallbackTimeoutMS(ms int) optparams.Option[Options]
- func WithConnMaxIdleTime(ConnMaxIdleTime time.Duration) optparams.Option[Options]
- func WithConnMaxIdleTimeMS(ConnMaxIdleTimeMS int) optparams.Option[Options]
- func WithConnMaxLifetime(ConnMaxLifetime time.Duration) optparams.Option[Options]
- func WithConnMaxLifetimeMS(ConnMaxLifetimeMS int) optparams.Option[Options]
- func WithConnectRetry(attempts int, interval time.Duration) optparams.Option[Options]
- func WithDefaultOpts() optparams.Option[Options]
- func WithDisablePingOnInit() optparams.Option[Options]
- func WithDiscardUnknownColumns() optparams.Option[Options]
- func WithIgnoreCallbackError() optparams.Option[Options]
- func WithMaxIdleConns(MaxIdleConns int) optparams.Option[Options]
- func WithMaxOpenConns(MaxOpenConns int) optparams.Option[Options]
- func WithOptions(opts Options) optparams.Option[Options]
- func WithParallelCallback() optparams.Option[Options]
- func WithPingTimeoutMS(PingTimeoutMS int) optparams.Option[Options]
- func WithPoolConfig(MaxOpenConns int, MaxIdleConns int, ConnMaxLifetime time.Duration, ...) optparams.Option[Options]
- func WithQueryLog() optparams.Option[Options]
- func WithQueryLogArgs() optparams.Option[Options]
- func WithQueryTimeout(QueryTimeout time.Duration) optparams.Option[Options]
- func WithQueryTimeoutMS(QueryTimeout int) optparams.Option[Options]
- type Callback
- type CallbackContext
- type CallbackError
- type CallbackPanicError
- type Driver
- type Options
- type Proxy
- func (proxy *Proxy) Client() *bun.DB
- func (proxy *Proxy) Close() error
- func (proxy *Proxy) DefaultQueryTimeout() time.Duration
- func (proxy *Proxy) Health(ctx context.Context) error
- func (proxy *Proxy) Init(URL string, opts ...optparams.Option[Options]) error
- func (proxy *Proxy) InitContext(ctx context.Context, URL string, opts ...optparams.Option[Options]) error
- func (proxy *Proxy) IsOk() booldeprecated
- func (proxy *Proxy) IsReady() bool
- func (proxy *Proxy) NewCtx() (ctx context.Context, cancel context.CancelFunc)
- func (proxy *Proxy) NewCtxWithParent(parent context.Context) (ctx context.Context, cancel context.CancelFunc)
- func (proxy *Proxy) PingContext(ctx context.Context) error
- func (proxy *Proxy) PingTimeout() time.Duration
- func (proxy *Proxy) Regist(cb Callback) errordeprecated
- func (proxy *Proxy) Register(cb Callback) error
- func (proxy *Proxy) RegisterContext(cb CallbackContext) error
- func (proxy *Proxy) SetConnect(cli *bun.DB) error
Examples ¶
Constants ¶
const DefaultConnectRetryInterval = 500 * time.Millisecond
DefaultConnectRetryInterval 建立连接重试的默认首次等待时间
const DefaultPingTimeout = 5 * time.Second
DefaultPingTimeout Init时探测连接可用性的默认超时时间
const RedactedPlaceholder = "REDACTED"
RedactedPlaceholder 连接串脱敏后替换密码的占位符 这里不使用"******"是为了避免url编码后变成"%2A%2A%2A%2A%2A%2A"
Variables ¶
var ( //ErrProxyAlreadySetClient 代理已经设置过客户端对象 ErrProxyAlreadySetClient = errors.New("代理不能重复设置客户端对象") //ErrProxyNotSetClient 代理还未设置客户端对象 ErrProxyNotSetClient = errors.New("代理还未设置客户端对象") //ErrUnsupportedSchema 未支持的数据库管理服务类型 //通常意味着对应驱动子模块没有导入,错误信息中会给出已注册的驱动列表 ErrUnsupportedSchema = errors.New("未支持的数据库管理服务类型") //ErrNilDB 客户端对象为nil ErrNilDB = errors.New("客户端对象不能为nil") //ErrNilCallback 回调函数为nil ErrNilCallback = errors.New("回调函数不能为nil") //ErrEmptyURL 数据库连接地址为空 ErrEmptyURL = errors.New("数据库连接地址不能为空") //ErrPingFailed Init时校验连接可用性失败 ErrPingFailed = errors.New("数据库连接校验失败") //ErrCallbackPanic 回调函数执行时发生panic ErrCallbackPanic = errors.New("回调函数执行时发生panic") )
本包中的错误变量分为两组:
- ErrProxy.../ErrUnsupportedSchema 等为v3的规范命名,推荐使用
- Err...Allready.../ErrUnSupport... 为v2的历史命名,保留用于兼容,后续版本会移除
var ( //Deprecated: 拼写错误,请使用 ErrProxyAlreadySetClient ErrProxyAllreadySettedUniversalClient = ErrProxyAlreadySetClient //Deprecated: 命名不一致,请使用 ErrProxyNotSetClient ErrProxyNotYetSettedUniversalClient = ErrProxyNotSetClient //Deprecated: 拼写错误,请使用 ErrUnsupportedSchema ErrUnSupportSchema = ErrUnsupportedSchema )
以下变量为v2的历史命名,存在拼写或语义问题,保留用于兼容
var Default = New()
Default 默认的数据库代理对象
var DefaultOpts = Options{ MaxOpenConns: 10, MaxIdleConns: 10, ConnMaxLifetime: time.Hour, ConnMaxIdleTime: 10 * time.Minute, PingTimeout: DefaultPingTimeout, }
DefaultOpts 当NewDB未传入配置时使用的默认配置 注意Init方法不会使用该配置,以保证Options零值时的行为与老版本一致
var Logger = log.Export()
Logger 本包使用的日志对象
Functions ¶
func NewDB ¶
NewDB 根据连接串创建bun.DB对象 opts为nil时使用DefaultOpts,调用方负责在不再使用时调用Close释放连接池
具体数据库由已注册的驱动决定:需要空导入对应的驱动子模块,例如
import _ "github.com/Golang-Tools/sqlhelper/driver/postgres/v4"
未注册的 scheme 会返回 ErrUnsupportedSchema,错误信息中会带上当前已注册的驱动列表
func RedactDSN ¶
RedactDSN 隐藏连接串中的密码等敏感信息,用于日志和错误输出
Example ¶
package main
import (
"fmt"
"github.com/Golang-Tools/sqlhelper/v4/bunproxy"
)
func main() {
fmt.Println(bunproxy.RedactDSN("postgres://user:secret@localhost:5432/db"))
fmt.Println(bunproxy.RedactDSN("sqlite://:memory:"))
}
Output: postgres://user:REDACTED@localhost:5432/db sqlite://:memory:
func RegisterDriver ¶
func RegisterDriver(d Driver)
RegisterDriver 注册一个数据库驱动,供 driver 子模块在 init 中调用。 重复注册同一个 scheme 会 panic;nil 驱动会被忽略。
func RegisteredSchemes ¶
func RegisteredSchemes() []string
RegisteredSchemes 返回当前已注册的 scheme 列表(按字典序排列)。 适合在服务启动时打印,用于确认二进制内实际包含哪些数据库后端。
func SanitizeSQL ¶
SanitizeSQL 脱敏SQL语句,遮蔽字面量并压缩空白,用于日志输出 字符串字面量替换为'?',数字字面量替换为?;SQL关键字、标识符(含带数字的列名)与 位置占位符($1)保持原样,NULL/TRUE/FALSE等关键字不做替换(不包含敏感信息)
Example ¶
package main
import (
"fmt"
"github.com/Golang-Tools/sqlhelper/v4/bunproxy"
)
func main() {
fmt.Println(bunproxy.SanitizeSQL("SELECT * FROM users WHERE name = 'alice' AND age > 18"))
fmt.Println(bunproxy.SanitizeSQL("SELECT * FROM users WHERE id = $1"))
}
Output: SELECT * FROM users WHERE name = '?' AND age > ? SELECT * FROM users WHERE id = $1
func WithCallbackTimeout ¶
WithCallbackTimeout 设置回调函数执行的超时时间,只对RegisterContext注册的回调生效
func WithCallbackTimeoutMS ¶
WithCallbackTimeoutMS 设置回调函数执行的超时时间,单位ms
func WithConnMaxIdleTime ¶
WithConnMaxIdleTime 设置连接池的最大空闲连接超时时间
func WithConnMaxIdleTimeMS ¶
WithConnMaxIdleTimeMS 设置连接池的最大空闲连接超时时间,单位ms
func WithConnMaxLifetime ¶
WithConnMaxLifetime 设置连接池的最大连接超时时间
func WithConnMaxLifetimeMS ¶
WithConnMaxLifetimeMS 设置连接池的最大连接超时时间,单位ms
func WithConnectRetry ¶
WithConnectRetry 设置建立连接的重试次数与首次重试等待时间 attempts为总尝试次数(含首次),interval为0时使用DefaultConnectRetryInterval
func WithDefaultOpts ¶
WithDefaultOpts 整体套用DefaultOpts中的推荐默认值(连接池参数等) Init在未显式指定连接池参数时不会干预database/sql的默认行为,需要一键套用推荐 默认值(与NewDB(url, nil)一致)时使用本选项;由于是整体覆盖,建议放在选项列表最前
func WithDisablePingOnInit ¶
WithDisablePingOnInit 关闭Init时的连接可用性校验
func WithDiscardUnknownColumns ¶
WithDiscardUnknownColumns 设置当有未知列时不报错
func WithIgnoreCallbackError ¶
WithIgnoreCallbackError 让Init忽略回调函数的错误,兼容旧版本行为
func WithMaxIdleConns ¶
WithMaxIdleConns 设置连接池的最大空闲连接数
func WithMaxOpenConns ¶
WithMaxOpenConns 设置连接池的最大连接数
func WithOptions ¶
WithOptions 用给定配置整体覆盖已有配置 选项是合并语义,单个WithXxx无法把布尔开关改回false, 需要关闭某个开关时(例如WithParallelCallback之后改回串行)可以用本选项重置配置
func WithParallelCallback ¶
WithParallelCallback 设置初始化后回调并行执行而非串行执行
func WithPingTimeoutMS ¶
WithPingTimeoutMS 设置Init时校验连接可用性的超时时间,单位ms
func WithPoolConfig ¶
func WithPoolConfig(MaxOpenConns int, MaxIdleConns int, ConnMaxLifetime time.Duration, ConnMaxIdleTime time.Duration) optparams.Option[Options]
WithPoolConfig 一次性设置连接池的核心参数
func WithQueryLog ¶
WithQueryLog 开启SQL日志,日志中只包含脱敏后的SQL模板
func WithQueryLogArgs ¶
WithQueryLogArgs 让SQL日志带上参数值,存在敏感信息泄漏风险,请谨慎使用
func WithQueryTimeout ¶
WithQueryTimeout 设置最大请求超时
Types ¶
type CallbackContext ¶
CallbackContext 带上下文的回调函数 适合需要超时保护的操作;超时时间由CallbackTimeout/WithCallbackTimeout配置,为0表示不限制
type CallbackError ¶
CallbackError 回调函数执行失败的错误 可以通过 errors.As 获取失败的回调下标与原始错误
func (*CallbackError) Unwrap ¶
func (e *CallbackError) Unwrap() error
Unwrap 支持 errors.Is/errors.As 链式判断
type CallbackPanicError ¶
CallbackPanicError 回调函数panic产生的错误
func (*CallbackPanicError) Unwrap ¶
func (e *CallbackPanicError) Unwrap() error
Unwrap 支持 errors.Is 判断为 ErrCallbackPanic
type Driver ¶
type Driver interface {
// Scheme 返回该驱动支持的 URL scheme,例如 "postgres"、"sqlite"
Scheme() string
// NewPool 依据连接串创建底层连接池,并按驱动自身特性应用连接池配置
// 实现方应在创建失败时保证不泄漏连接池,并自行处理该数据库特有的 DSN 规则
NewPool(rawURL string, opts *Options) (*sql.DB, error)
// Dialect 返回该驱动对应的 bun 方言
Dialect() schema.Dialect
}
Driver 描述一个数据库驱动实现。
核心包不再内置任何具体数据库实现,postgres/mysql/sqlserver/sqlite 分别由 github.com/Golang-Tools/sqlhelper/driver/<name>/v4 子模块实现并在 init 中 调用 RegisterDriver 注册;应用侧按需空导入对应驱动包即可启用。
同一个 scheme 只允许注册一次,重复注册会 panic,避免静默覆盖。
type Options ¶
type Options struct {
//Parallelcallback 为true时Init执行后的回调函数并行执行,默认串行执行
Parallelcallback bool
//QueryTimeout 默认的查询超时时间,为0表示不设置超时
//只在Init方法中生效
QueryTimeout time.Duration
//MaxOpenConns 连接池的最大连接数,为0表示使用database/sql的默认行为
MaxOpenConns int
//ConnMaxLifetime 连接的最大存活时间,为0表示不设置
ConnMaxLifetime time.Duration
//MaxIdleConns 连接池的最大空闲连接数,为0表示使用database/sql的默认行为
MaxIdleConns int
//ConnMaxIdleTime 连接的最大空闲时间,为0表示不设置
ConnMaxIdleTime time.Duration
//DiscardUnknownColumns 为true时查询结果中存在未知列不会报错
DiscardUnknownColumns bool
//QueryLog 为true时开启SQL日志,默认关闭以避免SQL与参数泄漏
QueryLog bool
//QueryLogArgs 为true时SQL日志会带上参数值,默认只记录脱敏后的SQL模板
//QueryLogArgs 只在QueryLog为true时生效
QueryLogArgs bool
//DisablePingOnInit 为true时Init不再校验连接的可用性
DisablePingOnInit bool
//PingTimeout Init时校验连接可用性的超时时间,为0时使用DefaultPingTimeout
PingTimeout time.Duration
//IgnoreCallbackError 为true时Init不会因为回调函数报错而失败
//该配置用于兼容旧版本"回调错误只记日志"的行为
IgnoreCallbackError bool
//CallbackTimeout 回调函数执行的超时时间,为0表示不限制
//只对RegisterContext注册的带上下文回调真正生效(普通Callback不接收上下文)
CallbackTimeout time.Duration
//ConnectRetryAttempts 建立连接的总尝试次数(含首次),0或1表示不重试
//只有连通性校验失败才会重试,DSN非法等配置类错误不会重试
ConnectRetryAttempts int
//ConnectRetryInterval 重试的首次等待时间,为0时使用DefaultConnectRetryInterval
//后续重试按指数退避增长,单次等待上限为maxConnectRetryInterval
ConnectRetryInterval time.Duration
}
Options 数据库代理的配置项
type Proxy ¶
Proxy bun客户端的代理 除Init/Close外的方法都是并发安全的,Init与Close应在应用启动/退出阶段串行调用 内嵌的*bun.DB在初始化成功后不再变更(Close只关闭连接池并置位closed),因此 业务查询与外发提升方法在稳态下不会因为Close而产生数据竞争 但直接访问proxy.DB仍然会绕过内部读锁,并发Init场景请改用Client()
func New ¶
func New() *Proxy
New 创建一个新的数据库客户端代理
Example ¶
package main
import (
"fmt"
"github.com/Golang-Tools/sqlhelper/v4/bunproxy"
)
func main() {
//代理对象在初始化之前就可以创建并持有,业务代码无需等待数据库连接
proxy := bunproxy.New()
fmt.Println("新创建的代理是否可用:", proxy.IsOk())
}
Output: 新创建的代理是否可用: false
func (*Proxy) Close ¶
Close 关闭代理持有的连接并释放连接池 关闭后代理会回到未初始化状态(Client/IsOk 不再返回连接),可以重新Init 已注册的回调会在关闭时被清空,避免重新Init时重复执行回调中的副作用操作 重复调用Close会返回ErrProxyNotSetClient
func (*Proxy) DefaultQueryTimeout ¶
DefaultQueryTimeout 返回配置的默认查询超时时间
func (*Proxy) Init ¶
Init 初始化代理对象,等价于使用 context.Background 的 InitContext 初始化时会校验连接可用性,校验失败或回调失败都会释放已创建的连接 已经初始化过时直接返回ErrProxyAlreadySetClient,不会重复创建连接
Init/Close 属于生命周期操作,约定只在应用启动/退出阶段串行调用
func (*Proxy) InitContext ¶
func (proxy *Proxy) InitContext(ctx context.Context, URL string, opts ...optparams.Option[Options]) error
InitContext 与 Init 相同,但支持通过 ctx 取消初始化或为整个初始化设置超时 重试等待与连通性校验都会受 ctx 约束
func (*Proxy) NewCtx ¶
func (proxy *Proxy) NewCtx() (ctx context.Context, cancel context.CancelFunc)
NewCtx 根据注册的超时时间构造一个上下文
func (*Proxy) NewCtxWithParent ¶
func (proxy *Proxy) NewCtxWithParent(parent context.Context) (ctx context.Context, cancel context.CancelFunc)
NewCtxWithParent 基于父上下文构造一个带超时的上下文 父上下文为nil时会退化为context.Background
func (*Proxy) PingContext ¶
PingContext 检查底层连接是否可用
func (*Proxy) PingTimeout ¶
PingTimeout 返回实际生效的连通性探测超时时间
func (*Proxy) RegisterContext ¶
func (proxy *Proxy) RegisterContext(cb CallbackContext) error
RegisterContext 注册带上下文的回调函数 与Regist注册的回调按注册顺序统一执行,执行时会带上CallbackTimeout配置的超时