gormx

package module
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 20 Imported by: 0

README

gormx

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

  • MySQL/Postgres 初始化(TLS、连接池、命名策略、可选 AutoMigrate)
  • 全量可观测性集成(OpenTelemetry Logs + Traces)
  • 常用模型基类(自增主键、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, // 开启后自动启用 OTel Logs
		},
	}

	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, // 开启后自动启用 OTel Logs
		},
	}

	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 日志(自动上报 OpenTelemetry Logs,配合 WithLoggerConsole 可同时输出到控制台)

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",
		},
	},
}

可观测性 (Observability)

gormx 已全量集成 OpenTelemetry,无需手动配置插件,只需确保你的应用已初始化全局 OTel Tracer/Logger Provider(例如使用 go-micro 框架)。

1. Logs (日志审计)

开启 Conf.Logger = true 后,gormx 会自动通过 OTel Logs SDK 上报每条 SQL 执行记录(OperationLog)。

  • Log Type: operation
  • Fields: database, statement, result, duration, rows, trace_id, user_id, app_id, tenant_id 等。
  • Destination: 通常发往 OTel Collector -> Loki。

注意

  • 必须使用 db.WithContext(ctx) 执行 SQL,否则无法提取 TraceID 和 UserID。
  • UserID/TenantID 等字段会自动从 gRPC metadata 中提取(如果存在)。

2. Traces (链路追踪)

初始化数据库时,gormx 会自动挂载 otelgorm 插件。

  • 自动为每个 SQL 操作创建 Span。
  • Span 名称格式:SELECT demo.users
  • Destination: 通常发往 OTel Collector -> Tempo/Jaeger。

注意

  • 如果未初始化全局 TracerProvider,插件会自动静默,不会报错。
  • 同样需要 db.WithContext(ctx) 才能将 SQL Span 正确关联到父 Trace。

模型基类

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

This section is empty.

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 控制输出。
	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 日志输出到控制台。

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