database

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 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 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