gormx

package module
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 19 Imported by: 0

README

gormx

基于 gorm 的工程化封装,提供:

  • MySQL/Postgres 初始化(TLS、连接池、命名策略、可选 AutoMigrate)
  • SQL 日志输出(控制台/回调)
  • 常用模型基类(自增主键、UUIDv7 主键、软删除)
  • 常用 scope(分页)

安装

go get github.com/fireflycore/gormx

快速开始

MySQL

package main

import (
	"github.com/fireflycore/gormx"
)

func main() {
	conf := &gormx.MysqlConf{
		Conf: gormx.Conf{
			Type:            gormx.Mysql,
			Address:         "127.0.0.1:3306",
			Database:        "demo",
			Username:        "root",
			Password:        "root",
			MaxOpenConnects: 100,
			MaxIdleConnects: 10,
			ConnMaxLifeTime: 600,
			SingularTable:   true,
			PrepareStmt:     true,
			Logger:          true,
		},
	}

	conf.WithLoggerConsole(true)
	conf.WithAutoMigrate(true)

	db, err := gormx.NewMysql(conf, []interface{}{})
	if err != nil {
		panic(err)
	}

	_ = db.DB
}

Postgres

package main

import (
	"github.com/fireflycore/gormx"
)

func main() {
	conf := &gormx.PostgresConf{
		Conf: gormx.Conf{
			Type:            gormx.Postgres,
			Address:         "127.0.0.1:5432",
			Database:        "demo",
			Username:        "postgres",
			Password:        "postgres",
			MaxOpenConnects: 100,
			MaxIdleConnects: 10,
			ConnMaxLifeTime: 600,
			SingularTable:   true,
			PrepareStmt:     true,
			Logger:          true,
		},
	}

	conf.WithLoggerConsole(true)
	conf.WithAutoMigrate(true)

	db, err := gormx.NewPostgres(conf, []interface{}{})
	if err != nil {
		panic(err)
	}

	_ = db.DB
}

配置说明

初始化配置为 gormx.Conf,MySQL/Postgres 的配置结构分别为 gormx.MysqlConf / gormx.PostgresConf(匿名嵌入 Conf)。

常用字段:

  • Address:MySQL 为 host:port;Postgres 可为 host 或 host:port(未带端口默认 5432)
  • Database/Username/Password:连接信息
  • MaxOpenConnects/MaxIdleConnects/ConnMaxLifeTime:连接池(ConnMaxLifeTime 单位为秒,<=0 表示不限制)
  • TablePrefix/SingularTable:命名策略
  • DisableForeignKeyConstraintWhenMigrating:AutoMigrate 时不创建物理外键
  • SkipDefaultTransaction:跳过 gorm 默认事务
  • PrepareStmt:启用预处理语句缓存
  • Logger:启用 SQL 日志(配合 WithLoggerConsole / WithLoggerHandle)

TLS

当 Conf.Tls 同时配置了 CaCert / ClientCert / ClientCertKey 三个文件路径时启用 TLS,否则视为不启用:

conf := &gormx.PostgresConf{
	Conf: gormx.Conf{
		Type:     gormx.Postgres,
		Address:  "127.0.0.1",
		Database: "demo",
		Username: "postgres",
		Password: "postgres",
		Tls: &gormx.TLS{
			CaCert:        "/path/to/ca.pem",
			ClientCert:    "/path/to/client.pem",
			ClientCertKey: "/path/to/client.key",
		},
	},
}

SQL 日志回调

开启 Logger 后,你可以把 SQL 日志输出到控制台,或写入自定义回调:

conf := &gormx.MysqlConf{
	Conf: gormx.Conf{
		Type:     gormx.Mysql,
		Address:  "127.0.0.1:3306",
		Database: "demo",
		Username: "root",
		Password: "root",
		Logger:   true,
	},
}

conf.WithLoggerConsole(true)
conf.WithLoggerHandle(func(b []byte) {
	_ = b
})

回调收到的是一段 JSON bytes。若 gorm 操作使用了 db.WithContext(ctx),并且 ctx 中包含 gRPC incoming metadata,则会尝试从 metadata 里读取链路字段:

  • gormx.TraceId(trace-id)
  • gormx.UserId(user-id)
  • gormx.AppId(app-id)

模型基类

gormx 提供了一组可直接嵌入的模型基类:

  • gormx.Table:uint64 主键 + 软删除
  • gormx.TableUnique:uint64 主键 + 软删除(DeletedAt 上 uniqueIndex:idx_unique)
  • gormx.TableUUID:string 主键(UUIDv7)+ 软删除
  • gormx.TableUUIDUnique:string 主键(UUIDv7)+ 软删除(DeletedAt 上 uniqueIndex:idx_unique)

分页 Scope

import "github.com/fireflycore/gormx/scope"

db = db.Scopes(scope.WithPagination(1, 20))

分页规则:

  • page 从 1 开始(0 会被修正为 1)
  • size 范围为 [5, 100](小于 5 修正为 5,大于 100 修正为 100)

Documentation

Index

Constants

View Source
const (
	// Postgres 表示 Postgres 数据库类型。
	Postgres int32 = iota + 1
	// Oracle 表示 Oracle 数据库类型。
	Oracle
	// Sqlite 表示 Sqlite 数据库类型。
	Sqlite
	// Mysql 表示 MySQL 数据库类型。
	Mysql
	// Mssql 表示 Microsoft SQL Server 数据库类型。
	Mssql
)
View Source
const (
	// ResultSuccess 表示成功执行 SQL 的结果标记。
	ResultSuccess = "success"

	// TraceId 为从 metadata 读取 trace id 的 key。
	TraceId = "trace-id"
	// UserId 为从 metadata 读取 user id 的 key。
	UserId = "user-id"
	// AppId 为从 metadata 读取调用方 app id 的 key。
	AppId = "app-id"
)

Variables

This section is empty.

Functions

func NewLogger

func NewLogger(c *Conf) loger.Interface

NewLogger 根据 Config 构造 gorm logger。

func NewUUIDv7

func NewUUIDv7() string

NewUUIDv7 生成一个 UUIDv7 字符串

Types

type Conf

type Conf struct {
	// 1-postgres 2-oracle 3-sqlite 4-mysql 5-mssql
	// Type 表示数据库类型枚举。
	Type uint32 `json:"type"`
	// TLS加密配置(生产环境建议启用),如果不为null则启用tls加密
	// Tls 为 TLS 配置,非空时启用 TLS。
	Tls *tlsx.TLS `json:"tls"`

	// Address 为数据库地址,一般为 host:port。
	Address string `json:"address"`
	// Database 为数据库名称。
	Database string `json:"database"`
	// Username 为数据库用户名。
	Username string `json:"username"`
	// Password 为数据库密码。
	Password string `json:"password"`

	// 表名前缀
	// TablePrefix 会拼接到 gorm 的表名之前。
	TablePrefix string `json:"table_prefix"`

	// 最大打开连接数(建议:根据负载设置,默认100),0表示无限制(不推荐生产环境使用)
	// MaxOpenConnects 会设置到 database/sql 连接池的 MaxOpenConns。
	MaxOpenConnects int `json:"max_open_connects"`
	// 最大空闲连接数(建议:保持适当空闲连接减少握手开销),0表示无限制(需配合max_open_connects使用)
	// MaxIdleConnects 会设置到 database/sql 连接池的 MaxIdleConns。
	MaxIdleConnects int `json:"max_idle_connects"`
	// 连接最大生命周期(单位:秒,建议:300-600秒),超时后连接会被强制回收重建
	// ConnMaxLifeTime 会设置到 database/sql 连接池的 ConnMaxLifetime(按秒)。
	ConnMaxLifeTime int `json:"conn_max_life_time"`

	// 是否为单数表名
	// SingularTable 为 true 时,表名不做复数化。
	SingularTable bool `json:"singular_table"`
	// 是否禁用物理外键
	// DisableForeignKeyConstraintWhenMigrating 为 true 时,自动迁移时不创建物理外键。
	DisableForeignKeyConstraintWhenMigrating bool `json:"disable_foreign_key_constraint_when_migrating"`
	// 是否跳过默认事务(特殊场景使用,如批量导入)
	// SkipDefaultTransaction 为 true 时,gorm 默认写操作不启事务。
	SkipDefaultTransaction bool `json:"skip_default_transaction"`
	// 是否启用预处理语句(安全建议:始终开启防止SQL注入)
	// PrepareStmt 为 true 时,gorm 将启用预处理语句缓存。
	PrepareStmt bool `json:"prepare_stmt"`

	// 是否启用SQL日志(调试建议开启,生产环境建议关闭)
	// Logger 为 true 时启用 gorm logger,并可通过 WithLoggerConsole/WithLoggerHandle 控制输出。
	Logger bool `json:"logger"`
	// contains filtered or unexported fields
}

Conf 为 gorm 初始化所需的配置项集合。

func (*Conf) WithAutoMigrate

func (c *Conf) WithAutoMigrate(state bool)

WithAutoMigrate 设置是否在初始化连接后自动迁移表结构。

func (*Conf) WithLoggerConsole

func (c *Conf) WithLoggerConsole(state bool)

WithLoggerConsole 设置是否将 SQL 日志输出到控制台。

func (*Conf) WithLoggerHandle

func (c *Conf) WithLoggerHandle(handle func(b []byte))

WithLoggerHandle 设置日志回调,用于将 SQL 日志写入你的日志系统。

type MysqlConf

type MysqlConf struct {
	Conf
}

type MysqlDB

type MysqlDB struct {
	DB *gorm.DB
}

func NewMysql

func NewMysql(mc *MysqlConf, tables []interface{}) (*MysqlDB, error)

NewMysql 使用配置初始化 MySQL 的 gorm.DB,并可选执行 AutoMigrate。

type PostgresConf

type PostgresConf struct {
	Conf
}

type PostgresDB

type PostgresDB struct {
	DB *gorm.DB
}

func NewPostgres

func NewPostgres(mc *PostgresConf, tables []interface{}) (*PostgresDB, error)

NewPostgres 使用配置初始化 Postgres 的 gorm.DB,并可选执行 AutoMigrate。

type Table

type Table struct {
	Id        uint64                `json:"id" gorm:"primarykey"`
	CreatedAt time.Time             `json:"created_at"`
	UpdatedAt time.Time             `json:"updated_at"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"default:0;index"`
}

Table 为常用的 uint64 主键基类(带软删除)。

type TableUUID

type TableUUID struct {
	Id        string                `json:"id" gorm:"type:uuid;primaryKey;default:uuidv7()"`
	CreatedAt time.Time             `json:"created_at"`
	UpdatedAt time.Time             `json:"updated_at"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"default:0;index"`
}

TableUUID 为 string 主键基类(使用 UUIDv7,数据库自动生成)。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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