Documentation
¶
Overview ¶
Package database 提供 SQL(MySQL / SQLite / PostgreSQL)与 KV(Redis / LevelDB / Memory)封装。
SQL ¶
db, err := database.OpenSQLite("file:demo.db")
db, err = database.OpenPostgres(database.PostgresDSN("127.0.0.1:5432", "u", "p", "db", ""))
err = db.InTx(ctx, nil, func(tx *sql.Tx) error { ... })
可选 AutoReconnect:健康检查失败后自动重建连接(见 SQLOptions)。
Scan 辅助:ScanRow / Exists / Count / ForEachRow;迁移:Migrate / RollbackLast。
KV ¶
mem := &database.MemoryKV{}
mem.Constructor()
var store database.KVStore = mem
_ = store.Set("k", "v", 0)
批量:KVBatch(MGet/MSet/MDel);Redis 可用 WithRedisPipeline。
Redis / LevelDB 通过 CacheProxy 实现同一接口。
Examples ¶
go run ./database/examples/sqlite go run ./database/examples/migrate go run ./database/examples/kv go run ./database/examples/remote # 需设置 MYSQL_* / POSTGRES_* / REDIS_* 环境变量
Index ¶
- Constants
- Variables
- func Count(ctx context.Context, db SQLDB, query string, args ...any) (int64, error)
- func CurrentVersion(ctx context.Context, db SQLDB) (int, error)
- func ExecScripts(ctx context.Context, db SQLDB, scripts ...string) error
- func Exists(ctx context.Context, db SQLDB, query string, args ...any) (bool, error)
- func ForEachRow(ctx context.Context, db SQLDB, query string, args []any, ...) error
- func Migrate(ctx context.Context, db SQLDB, migrations []Migration) error
- func MySQLDSN(address, user, password, dbName, charset string) string
- func PostgresDSN(address, user, password, dbName, sslmode string) string
- func RedisAddr(host string, port int) string
- func RollbackLast(ctx context.Context, db SQLDB, migrations []Migration) error
- func ScanRow(ctx context.Context, db SQLDB, query string, dest []any, args ...any) error
- type CacheOptions
- type CacheProxy
- func (this *CacheProxy) Backend() string
- func (this *CacheProxy) Close() error
- func (this *CacheProxy) Connected() bool
- func (this *CacheProxy) Del(key string) error
- func (this *CacheProxy) Get(key string) (string, error)
- func (this *CacheProxy) LevelDB() *leveldb.DB
- func (this *CacheProxy) MDel(keys []string) error
- func (this *CacheProxy) MGet(keys []string) (map[string]string, error)
- func (this *CacheProxy) MSet(kvs map[string]string, ttl time.Duration) error
- func (this *CacheProxy) Redis() *redis.Client
- func (this *CacheProxy) Set(key, value string, ttl time.Duration) error
- func (this *CacheProxy) WithRedisPipeline(ctx context.Context, fn func(pipe redis.Pipeliner) error) error
- type KVBatch
- type KVStore
- type MemoryKV
- func (this *MemoryKV) Backend() string
- func (this *MemoryKV) Close() error
- func (this *MemoryKV) Connected() bool
- func (this *MemoryKV) Constructor()
- func (this *MemoryKV) Del(key string) error
- func (this *MemoryKV) Get(key string) (string, error)
- func (this *MemoryKV) Len() int
- func (this *MemoryKV) MDel(keys []string) error
- func (this *MemoryKV) MGet(keys []string) (map[string]string, error)
- func (this *MemoryKV) MSet(kvs map[string]string, ttl time.Duration) error
- func (this *MemoryKV) Set(key, value string, ttl time.Duration) error
- type Migration
- type SQLDB
- type SQLOptions
- type SQLProxy
- func (this *SQLProxy) Begin() (*sql.Tx, error)
- func (this *SQLProxy) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (this *SQLProxy) Close() error
- func (this *SQLProxy) Connected() bool
- func (this *SQLProxy) DB() *sql.DB
- func (this *SQLProxy) Driver() string
- func (this *SQLProxy) Exec(query string, args ...any) (sql.Result, error)
- func (this *SQLProxy) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (this *SQLProxy) InTx(ctx context.Context, opts *sql.TxOptions, fn func(tx *sql.Tx) error) (err error)
- func (this *SQLProxy) Ping() error
- func (this *SQLProxy) PingContext(ctx context.Context) error
- func (this *SQLProxy) Prepare(query string) (*sql.Stmt, error)
- func (this *SQLProxy) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
- func (this *SQLProxy) Query(query string, args ...any) (*sql.Rows, error)
- func (this *SQLProxy) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (this *SQLProxy) QueryRow(query string, args ...any) (*sql.Row, error)
- func (this *SQLProxy) QueryRowContext(ctx context.Context, query string, args ...any) (*sql.Row, error)
- func (this *SQLProxy) Reconnect() error
Constants ¶
const ( DriverMySQL = "mysql" DriverSQLite = "sqlite" // modernc.org/sqlite DriverPostgres = "pgx" // github.com/jackc/pgx/v5/stdlib DriverRedis = "redis" DriverLevelDB = "leveldb" DriverMemory = "memory" )
Variables ¶
var ( // ErrNotConnected 表示尚未连接或已关闭。 ErrNotConnected = errors.New("database: not connected") // ErrNotFound 表示键不存在。 ErrNotFound = errors.New("database: not found") // ErrUnsupported 表示当前后端不支持该操作。 ErrUnsupported = errors.New("database: unsupported") // ErrInvalidArgument 表示参数非法。 ErrInvalidArgument = errors.New("database: invalid argument") )
Functions ¶
func CurrentVersion ¶
CurrentVersion 返回已应用的最大版本;无记录返回 0。
func ExecScripts ¶
ExecScripts 按顺序执行多条 SQL(非事务);任一步失败即返回。
func ForEachRow ¶
func ForEachRow(ctx context.Context, db SQLDB, query string, args []any, fn func(rows *sql.Rows) error) error
ForEachRow 遍历查询结果;fn 返回错误则中止。
func PostgresDSN ¶
PostgresDSN 构造 PostgreSQL URL DSN(pgx 驱动)。 sslmode 为空时默认 disable;address 形如 host:port(缺省端口 5432)。
func RollbackLast ¶
RollbackLast 回滚最近一条有 Down 脚本的迁移。
Types ¶
type CacheOptions ¶
CacheOptions 缓存连接选项。
type CacheProxy ¶
type CacheProxy struct {
// contains filtered or unexported fields
}
CacheProxy 统一 KV 封装(Redis / LevelDB)。
func OpenRedis ¶
func OpenRedis(address, password string, db int) (*CacheProxy, error)
OpenRedis 连接 Redis(默认选项)。
func OpenRedisOpts ¶
func OpenRedisOpts(address, password string, db int, opts CacheOptions) (*CacheProxy, error)
OpenRedisOpts 按选项连接 Redis。
func (*CacheProxy) Backend ¶
func (this *CacheProxy) Backend() string
func (*CacheProxy) Close ¶
func (this *CacheProxy) Close() error
func (*CacheProxy) Connected ¶
func (this *CacheProxy) Connected() bool
func (*CacheProxy) Del ¶
func (this *CacheProxy) Del(key string) error
func (*CacheProxy) LevelDB ¶
func (this *CacheProxy) LevelDB() *leveldb.DB
func (*CacheProxy) MGet ¶
func (this *CacheProxy) MGet(keys []string) (map[string]string, error)
MGet 批量获取;缺失键不出现在结果中。
func (*CacheProxy) Redis ¶
func (this *CacheProxy) Redis() *redis.Client
func (*CacheProxy) Set ¶
func (this *CacheProxy) Set(key, value string, ttl time.Duration) error
Set 写入;ttl=0 表示不过期(LevelDB 忽略 ttl)。
func (*CacheProxy) WithRedisPipeline ¶
func (this *CacheProxy) WithRedisPipeline(ctx context.Context, fn func(pipe redis.Pipeliner) error) error
WithRedisPipeline 在 Redis Pipeline 中执行自定义命令。
type KVBatch ¶
type KVBatch interface {
KVStore
MGet(keys []string) (map[string]string, error)
MSet(kvs map[string]string, ttl time.Duration) error
MDel(keys []string) error
}
KVBatch 批量键值操作(可选能力)。
type KVStore ¶
type KVStore interface {
Backend() string
Connected() bool
Set(key, value string, ttl time.Duration) error
Get(key string) (string, error)
Del(key string) error
Close() error
}
KVStore 键值存储抽象。
type MemoryKV ¶
type MemoryKV struct {
// contains filtered or unexported fields
}
MemoryKV 进程内 KV(支持 TTL),适合测试与本地缓存。
type SQLDB ¶
type SQLDB interface {
Driver() string
Connected() bool
Ping() error
PingContext(ctx context.Context) error
Exec(query string, args ...any) (sql.Result, error)
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
Query(query string, args ...any) (*sql.Rows, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...any) (*sql.Row, error)
QueryRowContext(ctx context.Context, query string, args ...any) (*sql.Row, error)
Prepare(query string) (*sql.Stmt, error)
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
Begin() (*sql.Tx, error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
InTx(ctx context.Context, opts *sql.TxOptions, fn func(tx *sql.Tx) error) error
Close() error
}
SQLDB SQL 访问抽象,便于替换实现与单测。
type SQLOptions ¶
type SQLOptions struct {
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
ConnMaxIdleTime time.Duration
// PingInterval >0 时启用后台 Ping;<=0 关闭。
PingInterval time.Duration
// AutoReconnect 在 Ping 失败或断线后尝试重建连接(需保留 dsn)。
AutoReconnect bool
// ReconnectWait 重连失败后的等待间隔;<=0 且开启 AutoReconnect 时默认 2s。
ReconnectWait time.Duration
Logger *slog.Logger
}
SQLOptions 配置 SQL 连接池与健康检查。
type SQLProxy ¶
type SQLProxy struct {
// contains filtered or unexported fields
}
SQLProxy 封装 database/sql。
func OpenPostgres ¶
OpenPostgres 使用默认选项连接 PostgreSQL(pgx)。
func OpenSQL ¶
func OpenSQL(driver, dsn string, opts SQLOptions) (*SQLProxy, error)
OpenSQL 打开指定驱动的数据库。
func OpenSQLite ¶
OpenSQLite 使用默认选项连接 SQLite(纯 Go / modernc)。
func (*SQLProxy) ExecContext ¶
func (*SQLProxy) InTx ¶
func (this *SQLProxy) InTx(ctx context.Context, opts *sql.TxOptions, fn func(tx *sql.Tx) error) (err error)
InTx 在事务中执行 fn,成功提交,失败回滚。