gormx

package module
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2025 License: MIT Imports: 22 Imported by: 0

README

特性

  • 🚀 重新实现了 gorm 的日志记录器,采用 github.com/itmisx/logger
  • 🚀 实现了读写分离
  • 🚀 实现了数据库的自动分区管理
  • 🚀 实现了数据库结构在线变更(online ddl)
  • 🚀 版本控制
一、安装
go get -u -v github.com/itmisx/gormx
二、配置
type Config struct {
  Username     string   `mapstructure:"username" yaml:"username"`             // 用户名
  Password     string   `mapstructure:"password" yaml:"password"`             // 密码
  Addrs        []string `mapstructure:"addrs" yaml:"addrs"`                   // 连接地址(host:port),Addrs[0]为. master,其余为slave
  Database     string   `mapstructure:"database" yaml:"database"`             // 要连接的数据库
  Charset      string   `mapstructure:"charset" yaml:"charset"`               // 字符集
  Debug        bool     `mapstructure:"debug" yaml:"debug"`                   // 是否开启调试模式
  MaxOpenConns int      `mapstructure:"max_open_conns" yaml:"max_open_conns"` // 设置数据库的最大打开连接数
  MaxLifetime  int      `mapstructure:"max_lifetime" yaml:"max_lifetime"`     // 设置连接可以重用的最长时间(单位:秒)
  MaxIdleConns int      `mapstructure:"max_idle_conns" yaml:"max_idle_conns"` // 设置空闲连接池中的最大连接数
  MaxIdleTime  int      `mapstructure:"max_idle_time" yaml:"max_idle_time"`   // 设置空闲连接池中的最大连接数
}
三、使用
db, _ := gormx.New(cfg)
// 通过WithContext传入追踪参数
db.Where(……).WithContext(spanCtx).Find(&users)
四、读写分离

通过配置参数 addrs 配置

五、分区

这里主要是指按创建时间进行分区

示例
partition := gormx.NewPartition(
    db,
    database,
    "device_status_snapshot",
    gormx.PartitionUnitMonth,
    6,
)
partition.Start()
参数说明
  • db,gorm 连接
  • database,操作的数据库
  • table,操作的表
  • partitionUnit,分区单位。支持按天、按月、按年分区
  • retentionMonths,分区数据保留的时长,单位月
自动分区说明
  • 调用 partition.Start() 启动自动分区
  • 并自动 drop 过期的分区
六、Online DDL
  • 待迁移的model嵌入匿名gormx.Migration
  • 表需要使用 id(int)作为主键
  • 自动判断是否支持 Online ddl,如果不支持则自动创建新表,并通过 gorm 的钩子进行双写,并自动进行工作表切换。旧表需要手动删除
  • 示例
// 待迁移的model嵌入匿名Migration
type migrationTest struct {
 	ID        int    `json:"id" gorm:"column:id;type:int(8);primaryKey;autoIncrement"`
 	Name      string `json:"name" gorm:"column:name;type:varchar(20)"`
 	Migration `gorm:"-"`
}
// 启动迁移
migration := NewMigration(
  db,
  "migration_test",
  nil, nil, nil,
  `alter table migration_test
  drop primary key,
  add primary key(id,created_at)
  PARTITION BY RANGE (created_at) (
      PARTITION p20241101 VALUES LESS THAN (UNIX_TIMESTAMP('2024-11-01')),
      PARTITION p20241201 VALUES LESS THAN (UNIX_TIMESTAMP('2024-12-01')),
      PARTITION p20250101 VALUES LESS THAN (UNIX_TIMESTAMP('2025-01-01')),
      PARTITION p20250201 VALUES LESS THAN (UNIX_TIMESTAMP('2025-02-01')),
      PARTITION p20250301 VALUES LESS THAN (UNIX_TIMESTAMP('2025-03-01')),
      PARTITION p20250401 VALUES LESS THAN (UNIX_TIMESTAMP('2025-04-01')),
      PARTITION p20250501 VALUES LESS THAN (UNIX_TIMESTAMP('2025-05-01')),
      PARTITION p20250601 VALUES LESS THAN (UNIX_TIMESTAMP('2025-06-01')),
      PARTITION p20250701 VALUES LESS THAN (UNIX_TIMESTAMP('2025-07-01'))
  )`,
)
migration.Start()
七、版本控制
// 定义初始化安装
func install(){
  // 创建表1
  // 创建表2
  // ...
  fmt.Println("intall")
}

// 定义升级方法
type Upgrade struct{}

func (Upgrade)V1(){
  fmt.Println("upgrade v1")
}

func (Upgrade)V2(){
  fmt.Println("upgrade v1")
}

// 使用gormx version controller
vc:= gormx.NewVersionController(db,Upgrade{},install)
vc.Upgrade()

Documentation

Index

Constants

View Source
const (
	Reset       = "\033[0m"
	Red         = "\033[31m"
	Green       = "\033[32m"
	Yellow      = "\033[33m"
	Blue        = "\033[34m"
	Magenta     = "\033[35m"
	Cyan        = "\033[36m"
	White       = "\033[37m"
	BlueBold    = "\033[34;1m"
	MagentaBold = "\033[35;1m"
	RedBold     = "\033[31;1m"
	YellowBold  = "\033[33;1m"
)

Colors

Variables

View Source
var DefaultCronDuration = time.Hour

默认分区自动检查时间

View Source
var LocalDebug bool

Functions

func MigrateOnce added in v0.0.14

func MigrateOnce(
	db *gorm.DB,
	migrationName string,
	migrationFunc func(),
)

MigrateOnce 限制某些迁移语句只能执行一次 在升级函数中使用

func New

func New(cfg Config) (db *gorm.DB, err error)

New new *gorm.DB

func NewLogger

func NewLogger(writer logger.Writer, config logger.Config) logger.Interface

func NewPartition added in v0.0.5

func NewPartition(
	db *gorm.DB,
	database string,
	table string,
	partitionUnit PartitionUnitT,
	retentionMonths int,
) *partition

func NewVersionController added in v0.0.14

func NewVersionController(
	db *gorm.DB,
	upgradeStruct interface{},
	installFunc func(),
) *versionController

实例化版本控制实例

Types

type Config

type Config struct {
	Username     string   `mapstructure:"username" yaml:"username"`             // 用户名
	Password     string   `mapstructure:"password" yaml:"password"`             // 密码
	Addrs        []string `mapstructure:"addrs" yaml:"addrs"`                   // 连接地址(host:port),多个以逗号分隔,Addrs[0]为master,其余为slave
	Database     string   `mapstructure:"database" yaml:"database"`             // 要连接的数据库
	Charset      string   `mapstructure:"charset" yaml:"charset"`               // 字符集
	Debug        bool     `mapstructure:"debug" yaml:"debug"`                   // 是否开启调试模式
	MaxOpenConns int      `mapstructure:"max_open_conns" yaml:"max_open_conns"` // 设置数据库的最大打开连接数
	MaxLifetime  int      `mapstructure:"max_lifetime" yaml:"max_lifetime"`     // 设置连接可以重用的最长时间(单位:秒)
	MaxIdleConns int      `mapstructure:"max_idle_conns" yaml:"max_idle_conns"` // 设置空闲连接池中的最大连接数
	MaxIdleTime  int      `mapstructure:"max_idle_time" yaml:"max_idle_time"`   // 设置空闲连接池中的最大连接数
}

type LogLevel

type LogLevel int

type Migration added in v0.0.11

type Migration struct {
	DB              *gorm.DB // gorm Engine
	Database        string   // 数据库名称
	TableName       string   // 原始表名称
	AfterCreateHook func(*gorm.DB) error
	AfterUpdateHook func(*gorm.DB) error
	AfterDeleteHook func(*gorm.DB) error
	AlterSQL        string // 执行变更的sql语句
}

func NewMigration added in v0.0.11

func NewMigration(
	db *gorm.DB,
	tableName string,
	afterCreateHook func(*gorm.DB) error,
	afterUpdateHook func(*gorm.DB) error,
	afterDeleteHook func(*gorm.DB) error,
	alterSQL string,
) *Migration

func (*Migration) AfterCreate added in v0.0.11

func (m *Migration) AfterCreate(tx *gorm.DB) error

创建Hook

func (*Migration) AfterDelete added in v0.0.11

func (m *Migration) AfterDelete(tx *gorm.DB) error

删除Hook

func (*Migration) AfterUpdate added in v0.0.11

func (m *Migration) AfterUpdate(tx *gorm.DB) error

更新Hook

func (*Migration) GetMigrateTempTable added in v0.0.11

func (m *Migration) GetMigrateTempTable(status migrationStatus) string

获取迁移临时表

func (*Migration) Start added in v0.0.11

func (m *Migration) Start() error

Start 开始迁移

type PartitionUnitT added in v0.0.7

type PartitionUnitT int // 分区单元
const (
	PartitionUnitDay   PartitionUnitT = iota + 1 // 按天分区
	PartitionUnitMonth                           // 按月分区
	PartitionUnitYear                            // 按年分区
)

type VersionLog added in v0.0.14

type VersionLog struct {
	ID            string `json:"id" gorm:"column:id;type:int;size:64;primaryKey;autoIncrement"`
	Version       int64  `json:"version" gorm:"column:version;type:int;size:64;uniqueIndex:uk_migration,priority:1;comment:数据库版本"`
	MigrationName string `` /* 135-byte string literal not displayed */
	CreatedAt     int64  `json:"created_at" gorm:"column:created_at;type:int;size:64;autoCreateTime;comment:创建时间"`
}

func (VersionLog) TableName added in v0.0.14

func (VersionLog) TableName() string

Jump to

Keyboard shortcuts

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