database

package
v0.0.0-...-f63be61 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 18 Imported by: 0

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

View Source
const (
	DriverMySQL    = "mysql"
	DriverSQLite   = "sqlite" // modernc.org/sqlite
	DriverPostgres = "pgx"    // github.com/jackc/pgx/v5/stdlib
	DriverRedis    = "redis"
	DriverLevelDB  = "leveldb"
	DriverMemory   = "memory"
)

Variables

View Source
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 Count

func Count(ctx context.Context, db SQLDB, query string, args ...any) (int64, error)

Count 执行返回单列计数的查询(如 SELECT COUNT(*) ...)。

func CurrentVersion

func CurrentVersion(ctx context.Context, db SQLDB) (int, error)

CurrentVersion 返回已应用的最大版本;无记录返回 0。

func ExecScripts

func ExecScripts(ctx context.Context, db SQLDB, scripts ...string) error

ExecScripts 按顺序执行多条 SQL(非事务);任一步失败即返回。

func Exists

func Exists(ctx context.Context, db SQLDB, query string, args ...any) (bool, error)

Exists 判断查询是否至少返回一行。

func ForEachRow

func ForEachRow(ctx context.Context, db SQLDB, query string, args []any, fn func(rows *sql.Rows) error) error

ForEachRow 遍历查询结果;fn 返回错误则中止。

func Migrate

func Migrate(ctx context.Context, db SQLDB, migrations []Migration) error

Migrate 按 Version 升序应用尚未执行的 Up 脚本。

func MySQLDSN

func MySQLDSN(address, user, password, dbName, charset string) string

MySQLDSN 构造 MySQL DSN。 charset 为空时默认 utf8mb4,并启用 parseTime。

func PostgresDSN

func PostgresDSN(address, user, password, dbName, sslmode string) string

PostgresDSN 构造 PostgreSQL URL DSN(pgx 驱动)。 sslmode 为空时默认 disable;address 形如 host:port(缺省端口 5432)。

func RedisAddr

func RedisAddr(host string, port int) string

RedisAddr 将 host 与 port 格式化为 addr。

func RollbackLast

func RollbackLast(ctx context.Context, db SQLDB, migrations []Migration) error

RollbackLast 回滚最近一条有 Down 脚本的迁移。

func ScanRow

func ScanRow(ctx context.Context, db SQLDB, query string, dest []any, args ...any) error

ScanRow 执行 QueryRow 并 Scan 到 dest。

Types

type CacheOptions

type CacheOptions struct {
	RedisPoolSize int
	Logger        *slog.Logger
}

CacheOptions 缓存连接选项。

func DefaultCacheOptions

func DefaultCacheOptions() CacheOptions

DefaultCacheOptions 默认缓存选项。

type CacheProxy

type CacheProxy struct {
	// contains filtered or unexported fields
}

CacheProxy 统一 KV 封装(Redis / LevelDB)。

func OpenLevelDB

func OpenLevelDB(path string) (*CacheProxy, error)

OpenLevelDB 打开 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) Get

func (this *CacheProxy) Get(key string) (string, error)

func (*CacheProxy) LevelDB

func (this *CacheProxy) LevelDB() *leveldb.DB

func (*CacheProxy) MDel

func (this *CacheProxy) MDel(keys []string) error

MDel 批量删除。

func (*CacheProxy) MGet

func (this *CacheProxy) MGet(keys []string) (map[string]string, error)

MGet 批量获取;缺失键不出现在结果中。

func (*CacheProxy) MSet

func (this *CacheProxy) MSet(kvs map[string]string, ttl time.Duration) error

MSet 批量写入;同一 ttl 应用于全部键(LevelDB 忽略 ttl)。

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),适合测试与本地缓存。

func (*MemoryKV) Backend

func (this *MemoryKV) Backend() string

func (*MemoryKV) Close

func (this *MemoryKV) Close() error

func (*MemoryKV) Connected

func (this *MemoryKV) Connected() bool

func (*MemoryKV) Constructor

func (this *MemoryKV) Constructor()

Constructor 初始化内存 KV。

func (*MemoryKV) Del

func (this *MemoryKV) Del(key string) error

func (*MemoryKV) Get

func (this *MemoryKV) Get(key string) (string, error)

func (*MemoryKV) Len

func (this *MemoryKV) Len() int

Len 返回当前未过期条目数(会顺带清理过期项)。

func (*MemoryKV) MDel

func (this *MemoryKV) MDel(keys []string) error

MDel 批量删除(MemoryKV)。

func (*MemoryKV) MGet

func (this *MemoryKV) MGet(keys []string) (map[string]string, error)

MGet 批量获取(MemoryKV)。

func (*MemoryKV) MSet

func (this *MemoryKV) MSet(kvs map[string]string, ttl time.Duration) error

MSet 批量写入(MemoryKV)。

func (*MemoryKV) Set

func (this *MemoryKV) Set(key, value string, ttl time.Duration) error

type Migration

type Migration struct {
	Version int
	Name    string
	Up      string
	Down    string // 可选;RollbackLast 时使用
}

Migration 一条 SQL 迁移。

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 连接池与健康检查。

func DefaultSQLOptions

func DefaultSQLOptions() SQLOptions

DefaultSQLOptions 返回偏保守的默认池参数。

type SQLProxy

type SQLProxy struct {
	// contains filtered or unexported fields
}

SQLProxy 封装 database/sql。

func OpenMySQL

func OpenMySQL(dsn string) (*SQLProxy, error)

OpenMySQL 使用默认选项连接 MySQL。

func OpenPostgres

func OpenPostgres(dsn string) (*SQLProxy, error)

OpenPostgres 使用默认选项连接 PostgreSQL(pgx)。

func OpenSQL

func OpenSQL(driver, dsn string, opts SQLOptions) (*SQLProxy, error)

OpenSQL 打开指定驱动的数据库。

func OpenSQLite

func OpenSQLite(path string) (*SQLProxy, error)

OpenSQLite 使用默认选项连接 SQLite(纯 Go / modernc)。

func (*SQLProxy) Begin

func (this *SQLProxy) Begin() (*sql.Tx, error)

func (*SQLProxy) BeginTx

func (this *SQLProxy) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

func (*SQLProxy) Close

func (this *SQLProxy) Close() error

func (*SQLProxy) Connected

func (this *SQLProxy) Connected() bool

Connected 是否处于已连接状态。

func (*SQLProxy) DB

func (this *SQLProxy) DB() *sql.DB

DB 返回底层 *sql.DB;未连接时为 nil。

func (*SQLProxy) Driver

func (this *SQLProxy) Driver() string

Driver 返回驱动名。

func (*SQLProxy) Exec

func (this *SQLProxy) Exec(query string, args ...any) (sql.Result, error)

func (*SQLProxy) ExecContext

func (this *SQLProxy) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*SQLProxy) InTx

func (this *SQLProxy) InTx(ctx context.Context, opts *sql.TxOptions, fn func(tx *sql.Tx) error) (err error)

InTx 在事务中执行 fn,成功提交,失败回滚。

func (*SQLProxy) Ping

func (this *SQLProxy) Ping() error

func (*SQLProxy) PingContext

func (this *SQLProxy) PingContext(ctx context.Context) error

func (*SQLProxy) Prepare

func (this *SQLProxy) Prepare(query string) (*sql.Stmt, error)

func (*SQLProxy) PrepareContext

func (this *SQLProxy) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

func (*SQLProxy) Query

func (this *SQLProxy) Query(query string, args ...any) (*sql.Rows, error)

func (*SQLProxy) QueryContext

func (this *SQLProxy) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

func (*SQLProxy) QueryRow

func (this *SQLProxy) QueryRow(query string, args ...any) (*sql.Row, error)

func (*SQLProxy) QueryRowContext

func (this *SQLProxy) QueryRowContext(ctx context.Context, query string, args ...any) (*sql.Row, error)

func (*SQLProxy) Reconnect

func (this *SQLProxy) Reconnect() error

Reconnect 使用保存的 driver/dsn 重建连接(不停止健康检查协程)。

Directories

Path Synopsis
examples
kv command
migrate command
remote command
sqlite command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL