db

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: GPL-3.0 Imports: 7 Imported by: 0

README

db

db 模块是对 gorm + mysql 驱动的轻量封装,提供统一的初始化入口、连接池配置、自动迁移和事务执行能力。

包名与导入

  • 目录:db
  • 包名:db
  • 导入:
import "gitee.com/mstes/base-framework/db"

适用场景

  • 需要快速连接 MySQL 并统一 GORM 初始化参数
  • 希望在初始化时自动迁移某个模型
  • 希望用统一入口执行事务

目录结构

  • config.go:数据库配置、连接池配置、DSN 构造
  • db.go:驱动初始化、GORM 选项、事务执行
  • errors.go:错误定义
  • test/main.go:最小可运行示例

核心类型

类型 说明
UniversalConfig 驱动配置接口,要求实现 BuildDsn() 和 ConnectionPoolConfig()
MysqlConfig MySQL 连接配置
ConnectionPoolConfig 连接池参数,时间单位为分钟
Driver[T any] 泛型数据库驱动,包含 Controller、Config、OrmConfig

MysqlConfig 字段说明

字段 说明
Username 数据库用户名
Password 数据库密码
Host 数据库主机
Port 数据库端口
Database 数据库名
SSL 是否启用 TLS,启用时 DSN 使用 tls=skip-verify
ConnectionPool 连接池配置,必填
Charset 当前实现未参与 BuildDsn(),DSN 固定写死为 utf8mb4

ConnectionPoolConfig 字段说明

字段 说明
MaxOpenConns 最大打开连接数
MaxIdleConns 最大空闲连接数
ConnMaxLifetime 连接最大生命周期,单位分钟
ConnMaxIdleTime 空闲连接最大存活时间,单位分钟

默认初始化行为

New[T] 内部会默认设置以下 GORM 选项:

  • SkipDefaultTransaction = true
  • DisableAutomaticPing = false
  • DisableForeignKeyConstraintWhenMigrating = true
  • DisableNestedTransaction = true

创建成功后还会自动执行:

  • 连接数据库
  • 配置连接池
  • AutoMigrate(new(T))

快速示例

package main

import (
    "context"

    "gitee.com/mstes/base-framework/db"
    "gorm.io/gorm"
)

type User struct {
    gorm.Model
    Name string
}

func main() {
    driver, err := db.New(
        db.WithProductLogModel[User](),
        db.WithDriverWithDefaultMode[User](&db.MysqlConfig{
            Host:     "127.0.0.1",
            Port:     "3306",
            Username: "root",
            Password: "123456",
            Database: "demo",
            SSL:      false,
            ConnectionPool: &db.ConnectionPoolConfig{
                MaxOpenConns:    20,
                MaxIdleConns:    10,
                ConnMaxLifetime: 10,
                ConnMaxIdleTime: 5,
            },
        }),
    )
    if err != nil {
        panic(err)
    }

    err = driver.Execute(context.Background(), func(tx *gorm.DB) error {
        return tx.Create(&User{Name: "alice"}).Error
    })
    if err != nil {
        panic(err)
    }
}

常用 API

API 说明
WithProductLogModel[T any]() 关闭 GORM 默认日志输出
WithDriverWithDefaultMode[T any](config UniversalConfig) 注入驱动配置
New[T any](opts ...NewOption[T]) 创建数据库驱动并自动迁移模型
(d *Driver[T]) Execute(ctx, callback) 在事务中执行回调

使用建议

  • 如果你只想使用 GORM 原生能力,可以直接通过 driver.Controller 继续调用底层 API。
  • 如果你不希望自动迁移,可以考虑在业务侧自行封装,而不是直接调用当前 New[T]。
  • 事务回调签名是 func(db *gorm.DB) error,返回 nil 时提交,否则回滚。

注意事项

  • ConnectionPool 不能为空,否则返回 ErrNotFoundConnectionPool。
  • 当前实现只提供了 MySQL 配置结构,UniversalConfig 主要用于保留扩展入口。
  • MysqlConfig.BuildDsn() 固定追加 charset=utf8mb4&parseTime=True&loc=Local。
  • Charset 字段虽然存在,但当前版本不会覆盖默认 DSN 编码。

示例入口

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFoundConnectionPool error = errors.New("connection pool config is nil")
)

Functions

This section is empty.

Types

type ConnectionPoolConfig

type ConnectionPoolConfig struct {
	//最大打开连接数
	MaxOpenConns int
	//最大空闲连接数
	MaxIdleConns int
	//连接超时时间-单位/分钟
	ConnMaxLifetime int
	//连接的最大存活时间-单位/分钟
	ConnMaxIdleTime int
}

type Driver

type Driver[T any] struct {
	//gorm的实际驱动对象
	Controller *gorm.DB
	//驱动配置
	Config UniversalConfig
	//gorm配置
	OrmConfig gorm.Config
}

func New

func New[T any](opts ...NewOption[T]) (*Driver[T], error)

创建数据库驱动

func (*Driver[T]) Execute

func (d *Driver[T]) Execute(ctx context.Context, callback TransactionCallBack) error

执行操作

type MysqlConfig

type MysqlConfig struct {
	// 数据库用户名
	Username string
	// 数据库密码
	Password string
	// 数据库地址
	Host string
	// 数据库端口
	Port string
	// 数据库名称
	Database string
	// 是否开启ssl加密
	SSL bool
	// 连接池配置
	ConnectionPool *ConnectionPoolConfig
	//字符串编码-大多数时候不需要手动配置
	Charset string
}

mysql的驱动配置

func (*MysqlConfig) BuildDsn

func (c *MysqlConfig) BuildDsn() string

构建dsn

func (*MysqlConfig) ConnectionPoolConfig

func (c *MysqlConfig) ConnectionPoolConfig() *ConnectionPoolConfig

获取连接池配置对象

type NewOption

type NewOption[T any] = func(*Driver[T]) error

func WithDriverWithDefaultMode

func WithDriverWithDefaultMode[T any](config UniversalConfig) NewOption[T]

使用单节点驱动

func WithProductLogModel

func WithProductLogModel[T any]() NewOption[T]

关闭gorm默认日志器

type TransactionCallBack

type TransactionCallBack = func(db *gorm.DB) error

执行的回调函数 返回的err为nil时,事务提交,否则回滚

type UniversalConfig

type UniversalConfig interface {
	// 构建dsn
	BuildDsn() string
	//获取连接池配置对象
	ConnectionPoolConfig() *ConnectionPoolConfig
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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