Help us shape the future of Go! Take the 2026 Go Developer Survey

database

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package database 负责建立并持有数据库连接。

组合方式:pgx(stdlib 适配)提供 *sql.DB,bun 在其上提供查询构建器。 选 pgx 而非 bun 自带的 pgdriver,是因为 pgx 是 Go 生态里最完整的 PG 驱动, 且 goose 也基于 database/sql,两者共用同一连接池。

Index

Constants

View Source
const (
	CodeUniqueViolation     = "23505"
	CodeForeignKeyViolation = "23503"
	CodeCheckViolation      = "23514"
)

PostgreSQL SQLSTATE 约束冲突码。

Variables

This section is empty.

Functions

func ClaimRun added in v0.1.9

func ClaimRun(ctx context.Context, db bun.IDB, name string, every time.Duration) (bool, error)

ClaimRun 为名为 name 的周期任务认领本轮执行权,返回 true 表示本实例该执行。

多实例部署时每个实例的定时器都会触发。认领是一条原子的 UPSERT:距上次执行 不足 every 的认领落空,谁先把 last_run_at 推进到现在谁执行,其余实例跳过。 用它而不是 advisory lock,是因为各实例的定时器相位不同,锁只能挡住同一时刻的并发, 挡不住错开几分钟的重复执行。

认领后任务失败不回滚认领:下一轮再试,失败本身由调用方记日志。

func IsUniqueViolation

func IsUniqueViolation(err error) bool

IsUniqueViolation 报告 err 是否为唯一约束冲突。

Types

type ConstraintViolation

type ConstraintViolation struct {
	Code       string
	Constraint string
}

ConstraintViolation 描述一次约束冲突:SQLSTATE 码与触发的约束名。

约束名来自迁移里的显式命名,业务层据此把「哪个唯一键冲突了」翻译成具体错误, 而不是笼统的「已存在」。

func AsConstraintViolation

func AsConstraintViolation(err error) (*ConstraintViolation, bool)

AsConstraintViolation 从错误链中提取 PostgreSQL 的唯一、外键或检查约束冲突。

优先识别 pgx 的结构化错误;若驱动错误被转成了纯文本(极少见),回退到匹配 SQLSTATE 码, 此时约束名为空。

type DB

type DB struct {
	*bun.DB
}

DB 包装 bun 客户端与底层连接池。

func Open

func Open(ctx context.Context, cfg config.DatabaseConfig, debug bool) (*DB, error)

Open 建立连接池并验证连通性。

调用方负责 Close。debug 为真时打印 SQL,仅用于开发态。

func (*DB) CurrentDatabase

func (db *DB) CurrentDatabase(ctx context.Context) (string, error)

CurrentDatabase 返回当前连接的库名。

存在的意义是安全护栏:同一个 PostgreSQL 实例上往往还躺着别的项目库,库名 又常常只差一个后缀,一旦误连,迁移会破坏真实数据。启动时记录实际库名, 让误连在第一条日志就暴露。

func (*DB) LogInfo

func (db *DB) LogInfo(ctx context.Context, logger *slog.Logger)

LogInfo 输出连接信息,便于确认连到了预期的库。

func (*DB) SQLDB

func (db *DB) SQLDB() *sql.DB

SQLDB 暴露底层 *sql.DB,供 goose 等基于 database/sql 的组件使用。

func (*DB) Version

func (db *DB) Version(ctx context.Context) (string, error)

Version 返回服务端版本串,用于启动日志与诊断。

Jump to

Keyboard shortcuts

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