Documentation
¶
Overview ¶
Package database 提供基于 gorm 的数据库接入封装。
核心包定义统一接口与全局连接管理: 所有驱动实现 Database 接口(DSN + Connect), 连接成功后注入全局, 任意位置通过 DB() 获取 gorm 句柄, AutoMigrate 自动迁移表结构; 另提供 Tx 闭包式事务助手(错误/panic 自动回滚, 支持 SAVEPOINT 嵌套) 与 Paginate 分页 scope(与 ginx.BindPage 配合)。 MySQL / PostgreSQL / SQLite 三种驱动各自独立成子包(mysql/postgres/sqlite), 业务项目仅 import 用到的驱动子包, 未使用的驱动不会进入依赖树。
app.Boot 场景经 Wire 一行接入(建连 + 可选迁移 + 关停释放):
app.MustRun(&app.Boot[Conf]{
Wire: func(c *Conf) []app.Component {
return []app.Component{database.NewBoot(&c.Database, &User{})}
},
})
数据库为全局单数据源约定: Connect 注入包级全局 DB(), Wire 中放置多个 database.Boot 会互相覆盖(多数据源请直接使用 gorm 多实例)。
独立使用(以 MySQL 为例, 其余驱动仅 import 路径与配置字段不同):
db := &mysql.MySQL{
Host: "127.0.0.1",
Port: 3306,
User: "root",
Password: "123456",
DB: "note",
Charset: "utf8mb4",
}
if err := db.Connect(); err != nil { // 建连(含连接池配置与 Ping 探活), 成功后注入全局
panic(err)
}
defer database.Close()
database.DB().Create(&User{Name: "note"}) // 任意位置获取 gorm 句柄
_ = database.AutoMigrate(&User{}) // 自动迁移表结构
Index ¶
- Variables
- func AutoMigrate(dist ...any) error
- func Close() error
- func DB() *gorm.DB
- func NewLogger(level string) logger.Interface
- func Paginate(page, size int) func(db *gorm.DB) *gorm.DB
- func SetDB(d *gorm.DB)
- func Tx(fn func(tx *gorm.DB) error) error
- func TxWith(conn *gorm.DB, fn func(tx *gorm.DB) error) error
- type Boot
- type Database
- type DatabasePool
Constants ¶
This section is empty.
Variables ¶
var ErrNotConnected = errors.New("database: 未连接数据库, 请先调用驱动子包的 Connect")
ErrNotConnected 未建立数据库连接, 需先调用驱动子包的 Connect
Functions ¶
func Paginate ¶ added in v1.0.4
Paginate 分页查询 scope, 与 gorm 的 Scopes 配合按 offset/limit 截取当前页:
page := ginx.BindPage(c) // page/size 已归一化
var (
total int64
users []User
)
database.DB().Model(&User{}).Count(&total)
database.DB().Scopes(database.Paginate(page.Page, page.Size)).Find(&users)
page 从 1 开始(<=0 按 1 计); size<=0 时默认 20, 超过上限按 100 截断。
func Tx ¶ added in v1.0.4
Tx 闭包式事务: 在全局连接上开启事务执行 fn, 免去手动 Begin/Commit/Rollback 样板:
err := database.Tx(func(tx *gorm.DB) error {
if err := tx.Create(&order).Error; err != nil {
return err // 返回错误即回滚
}
return tx.Model(&user).Update("balance", gorm.Expr("balance - ?", amount)).Error
})
fn 返回 nil 时提交; 返回 error 或 panic 时自动回滚(panic 不会击穿进程)。
嵌套收敛: fn 内需要嵌套事务时, 直接对 tx 调用 TxWith(tx, ...) 即可, gorm 检测到事务句柄后会以 SAVEPOINT 嵌套, 内层回滚不影响外层; 也可将 tx 直接传给内部函数, 与外层收敛为同一个事务(推荐, 更简单)。
Types ¶
type Boot ¶ added in v1.0.4
type Boot struct {
// DSN 数据库驱动配置, *mysql.MySQL / *postgres.PostgreSQL / *sqlite.SQLite 均满足
DSN Database
// Models 建连后自动迁移的表模型, 为空则跳过迁移
Models []any
}
Boot 组件适配器: 一行接入 app.Boot 的 Wire 装配钩子(结构化匹配 app.Component 约定, 无需 import app), 也可用于任何"按序初始化、 逆序释放"的装配场景。
数据库为全局单数据源约定: Connect 注入包级全局 DB(), Wire 中放置多个 database.Boot 会互相覆盖(多数据源支持见 ROADMAP 待开发项)。
func NewBoot ¶ added in v1.0.4
NewBoot 构建数据库组件适配器: Init 建立全局连接并按需 AutoMigrate, Close 释放连接。
database.NewBoot(&c.Database, &User{}) // 连接 + 迁移 + 关停释放, 一行接入
type DatabasePool ¶
type DatabasePool struct {
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time" toml:"conn_max_idle_time" json:"conn_max_idle_time" mapstructure:"conn_max_idle_time"` // 数据库连接最大空闲时间
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" toml:"conn_max_lifetime" json:"conn_max_lifetime" mapstructure:"conn_max_lifetime"` // 数据库连接最大生命周期
MaxIdleConns int `yaml:"max_idle_conns" toml:"max_idle_conns" json:"max_idle_conns" mapstructure:"max_idle_conns"` // 数据库连接池最大空闲连接数
MaxOpenConns int `yaml:"max_open_conns" toml:"max_open_conns" json:"max_open_conns" mapstructure:"max_open_conns"` // 数据库连接池最大打开连接数
}
DatabasePool 数据库连接池