db

package
v0.0.0-...-2ddb557 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 15 Imported by: 0

README

internal/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 全局数据库实例。 设计权衡:采用全局单例避免 service/dao 层构造期依赖注入复杂度——dao.NewXxxRepository() 内部调 GetDB() 获取连接,无需每个 service 持有 *gorm.DB。测试时用 SetDatabaseInstance 注入内存 sqlite。未来若迁移到 DI 容器(如 wire/fx),可改为构造注入。

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

Jump to

Keyboard shortcuts

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