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

db

package
v0.32.21 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

README

repo/db/ - 数据库访问层

此目录存放关系型数据库相关代码。

目录结构

db/
├── database.go     # 数据库连接初始化
├── model/          # GORM 数据模型
└── dao/            # 数据访问对象(Data Access Object)

支持的数据库

  • MySQL
  • PostgreSQL
  • SQLite(纯 Go 实现,无 CGO)

文件说明

database.go
  • 数据库连接初始化
  • 连接池配置
  • GetDB() 获取数据库实例
model/
  • GORM 模型定义
  • 数据库表映射
  • 模型转换方法
dao/
  • 数据访问对象
  • CRUD 操作封装
  • 复杂查询实现

使用示例

// 获取数据库实例
db := db.GetDB()

// 使用 DAO
userRepo := dao.NewUserRepository()
user, err := userRepo.GetByID(ctx, 1)

Documentation

Overview

Package db 提供数据库连接与迁移。

本文件实现轻量级版本化数据库迁移器(无需外部 CLI 依赖):

  • migrations/ 目录下的 SQL 文件用 //go:embed 嵌入二进制
  • schema_migrations 表记录已执行的迁移版本
  • 启动时按版本号顺序执行未应用的 up 迁移

命名约定:<version>_<name>.up.sql / <version>_<name>.down.sql version 为零填充整数(000001、000002…),确保字典序=数值序。

用法(bootstrap):

migrator, err := db.NewMigrator(database, db.DriverSQLite)
if err != nil { return err }
if err := migrator.Up(); err != nil { return err }

Index

Constants

This section is empty.

Variables

View Source
var DB *gorm.DB

DB 全局数据库实例——**装配层显式句柄**(dao 去全局化终态): dao 与 app/ 一律构造注入 *gorm.DB,不读全局;本句柄仅供 bootstrap 初始化 结果出口(identity loader/定时任务/库式下游 fnos·qnap SSO 显式取用)。

Functions

func Close

func Close() error

func GetDB

func GetDB() *gorm.DB

func Init

func Init(cfg *conf.DatabaseConfig) error

func SetDatabaseInstance

func SetDatabaseInstance(db *gorm.DB)

Types

type Migrator

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

Migrator 版本化迁移器。

func NewMigrator

func NewMigrator(gormDB *gorm.DB, dialect string) (*Migrator, error)

NewMigrator 创建迁移器并确保 schema_migrations 表存在。

func (*Migrator) Up

func (m *Migrator) Up() ([]string, error)

Up 执行所有未应用的 up 迁移,返回应用的版本列表。

每个 up 文件在一个独立事务中执行;若某个迁移失败则停止并返回错误, 已成功提交的迁移保持有效(事务粒度=单文件)。

Directories

Path Synopsis
Package dao 数据访问对象层:各域模型的 GORM 持久化实现。
Package dao 数据访问对象层:各域模型的 GORM 持久化实现。
suffix.go — 扩展名推导(仪表盘「文件类型分布」用)。
suffix.go — 扩展名推导(仪表盘「文件类型分布」用)。

Jump to

Keyboard shortcuts

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