mysql

package module
v0.0.0-...-2f48a34 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

README

github.com/taouniverse/tao-mysql

Go Report Card GoDoc

Tao Universe 组件单元(Unit),基于泛型工厂模式封装 MySQL 数据库。

安装

go get github.com/taouniverse/tao-mysql

使用

导入
import _ "github.com/taouniverse/tao-mysql"
配置
# 单实例配置
mysql:
  host: localhost
  port: 3306
  user: tao
  password: 123456qwe
  db: test
  charset: utf8mb4,utf8
  parse_time: true
  local: UTC

# 多实例配置(如主从分离)
mysql:
  default_instance: master
  master:
    host: localhost
    port: 3306
    user: tao
    password: 123456qwe
    db: mydb
  replica:
    host: backup.example.com
    port: 3306
    user: readonly
    password: ro_pass
    db: mydb
配置字段说明
字段 类型 默认值 说明
host string localhost MySQL 服务器地址
port int 3306 MySQL 端口
user string root 用户名
password string - 密码
db string - 数据库名
charset string utf8mb4,utf8 字符集
parse_time bool true 解析时间类型
local string UTC 时区
max_idle int 10 空闲连接池大小
max_open int 100 最大打开连接数
max_lifetime duration 1h 连接最大生命周期

工厂模式 API

API 说明
mysql.M 配置实例 *Config
mysql.Factory *tao.BaseFactory[*gorm.DB] 工厂实例
mysql.DB() 获取默认数据库连接 (*gorm.DB, error)
mysql.GetDB(name) 获取指定名称的连接 (*gorm.DB, error)

使用示例

获取连接并执行操作
package main

import (
    "log"
    
    "github.com/taouniverse/tao-mysql"
)

func main() {
    // 获取默认实例
    db, err := mysql.DB()
    if err != nil {
        log.Fatal(err)
    }
    
    // 获取底层 sql.DB 进行 Ping 测试
    sqlDB, err := db.DB()
    if err != nil {
        log.Fatal(err)
    }
    
    err = sqlDB.Ping()
    if err != nil {
        log.Fatal(err)
    }
    log.Println("MySQL 连接成功")
}
GORM 操作
db, _ := mysql.DB()

// 自动迁移
db.AutoMigrate(&User{})

// 创建记录
db.Create(&User{Name: "tao", Age: 18})

// 查询记录
var user User
db.First(&user, "name = ?", "tao")

// 更新记录
db.Model(&user).Update("age", 20)

// 删除记录
db.Delete(&user)
多实例使用
// 获取主库连接(读写)
master, _ := mysql.GetDB("master")

// 获取从库连接(只读)
replica, _ := mysql.GetDB("replica")

// 主库写入
master.Create(&Order{Amount: 100})

// 从库查询
var orders []Order
replica.Find(&orders)

单元测试

快速测试(无需 Docker)
# 仅运行配置相关测试
go test -v -run "TestConfig" ./...
完整集成测试(需要 Docker)
# 启动 MySQL 并运行单实例测试
make test

# 启动 MySQL 并运行多实例测试
make test-multi

# 启动 MySQL 并运行所有测试
make test-all

# 生成覆盖率报告
make coverage

# 停止 MySQL 服务
make down
手动测试
# 1. 启动 MySQL
docker-compose up -d

# 2. 运行单实例测试
go test -v ./...

# 3. 运行多实例测试
TAO_TEST_MULTI_INSTANCE=true go test -v ./...

# 4. 停止 MySQL
docker-compose down

开发指南

文件 说明
config.go InstanceConfig 字段 + ValidSelf 默认值
mysql.go NewMySQL 构造器 + 工厂注册

Documentation

Index

Constants

View Source
const ConfigKey = "mysql"

ConfigKey for this repo

Variables

View Source
var Factory *tao.BaseFactory[*gorm.DB]

Factory is the global factory instance for managing gorm.DB

View Source
var M = &Config{}

M is the global config instance for tao-mysql

Functions

func DB

func DB() (*gorm.DB, error)

DB returns the default gorm DB instance

func GetDB

func GetDB(name string) (*gorm.DB, error)

GetDB returns the gorm DB instance by name

func NewMySQL

func NewMySQL(name string, config InstanceConfig) (*gorm.DB, func() error, error)

NewMySQL creates a new MySQL client for factory pattern

Types

type Config

type Config struct {
	tao.BaseMultiConfig[InstanceConfig]
	RunAfters []string `json:"run_after,omitempty" yaml:"run_after,omitempty"`
}

Config 总配置,实现 tao.MultiConfig 接口

func (*Config) Name

func (c *Config) Name() string

Name of Config

func (*Config) RunAfter

func (c *Config) RunAfter() []string

RunAfter defines pre task names

func (*Config) ToTask

func (c *Config) ToTask() tao.Task

ToTask transform itself to Task

func (*Config) ValidSelf

func (c *Config) ValidSelf()

ValidSelf with some default values

type InstanceConfig

type InstanceConfig struct {
	Host      string `json:"host" yaml:"host"`
	Port      int    `json:"port" yaml:"port"`
	User      string `json:"user" yaml:"user"`
	Password  string `json:"password" yaml:"password"`
	DB        string `json:"db" yaml:"db"`
	Charset   string `json:"charset" yaml:"charset"`
	ParseTime *bool  `json:"parse_time" yaml:"parse_time"`
	Location  string `json:"local" yaml:"local"`
}

InstanceConfig 单实例配置

Jump to

Keyboard shortcuts

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