gormPool

package
v1.64.50 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

GORMPool 使用说明

  1. 初始化

    package main
    
    import `github.com/aid297/aid/gormPool`
    
    func main() {
    	dbSetting, err := gormPool.APP.DBSetting.New("db.yaml") // 读取配置文件
    	if err != nil {
    		panic(err) // 读取配置文件失败,程序无法继续运行
    	}
    	mysqlPool := gormPool.APP.MySQLPool.Once(dbSetting) // 创建 orm 连接池
    	db := mysqlPool.GetConn()
    
    	var ret any
    	if err = db.Find(&ret).Error; err != nil { // 进行数据库操作
    		panic(err) // 异常处理
    	}
    }
    
  2. 配置文件

    common:
      driver: "mysql"
      maxOpenConns: 100
      maxIdleConns: 20
      maxLifetime: 100
      maxIdleTime: 10
    ar-sql:
      database: "cbit_db"
      rws: false
      main:
        username: "yjz"
        password: "123123"
        host: 127.0.0.1
        port: 12344
       sources:
       replicas:
    mysql:
      database: "tbl_test"
      charset: "utf8mb4"
      collation: "utf8mb4_general_ci"
      rws: true
      main:
        username: "root"
        password: "root"
        host: 127.0.0.1
        port: 3308
      sources:
        conn1:
          username: "root"
          password: "root"
          host: 127.0.0.1
          port: 3308
        conn2:
          username: "root"
          password: "root"
          host: 127.0.0.1
          port: 3308
      replicas:
        conn3:
          username: "root"
          password: "root"
          host: 127.0.0.1
          port: 3308
        conn4:
          username: "root"
          password: "root"
          host: 127.0.0.1
          port: 3308
        conn5:
          username: "root"
          password: "root"
          host: 127.0.0.1
          port: 3308
    postgres:
      main:
        username: "postgres"
        password: "postgres"
        host: 127.0.0.1
        port: 5432
        database: "tbl_test"
        sslmode: "disable"
        timezone: "Asia/Shanghai"
    sql-server:
      main:
        username: "admin"
        password: "Admin@1234"
        host: 127.0.0.1
        port: 9930
        database: "tbl_test"
    
  3. 高级用法:Finder

    package main
    
    import (
    	`github.com/aid297/aid/gormPool`
    	`gorm.io/gorm`
    )
    
    type (
    	UserModel struct {
    		ID       uint            `gorm:"type:bigint unsigned;primaryKey;autoIncrement"`
    		Username string          `gorm:"type:varchar(64);not null;unique;default:''"`
    		Password string          `gorm:"type:varchar(255);not null;default:''"`
    		Age      uint            `gorm:"type:bigint unsigned;not null;default:0"`
    		Articles []*ArticleModel `gorm:"foreignKey:AuthorID;references:ID"`
    	}
    
    	ArticleModel struct {
    		Title    string     `gorm:"type:varchar(255);not null;unique;default:''"`
    		AuthorID int        `gorm:"type:bigint unsigned;not null;default:0"`
    		Author   *UserModel `gorm:"foreignKey:AuthorID;references:ID"`
    	}
    
    	UserCondition struct {
    		Page         int      `json:"page"`
    		PageSize     int      `json:"page_ize"`
    		Username     string   `json:"username"`
    		Age          uint     `json:"age"`
    		OrderBy      []string `json:"order_by"`
    		ArticleTitle string   `json:"article_title"`
    	}
    )
    
    func main() {
    	dbSetting, err := gormPool.APP.DBSetting.New("db.yaml") // 读取配置文件
    	if err != nil {
    		panic(err) // 读取配置文件失败,程序无法继续运行
    	}
    	mysqlPool := gormPool.APP.MySQLPool.Once(dbSetting) // 创建 orm 连接池
    	db := mysqlPool.GetConn()
    
    	var (
    		users     []UserModel
    		condition = UserCondition{Username: "admin", Age: 18, Page: 1, PageSize: 100}
    	)
    
    	gormPool.APP.Finder.New(db.Model(UserModel{})).
    		WhenFunc(condition.ArticleTitle != "", func(db *gorm.DB) {
    			db.Preload("Articles").
    				Joins("articles", "articles.author_id = users.id").
    				Where("articles.title = ?", condition.ArticleTitle)
    		}). // 如果带有级联属性则使用 WhenFunc 来构建复杂的 SQL 条件
    		When(condition.Age > 20, "age > ?", condition.Age). // 通过条件判断是否要增加对应 SQL 的条件
    		WhenIn(condition.Username != "", "username", condition.Username). // 通过条件判断是否要增加对应 SQL 的条件 → IN 查询(更多查询: WhenNotIn、WhenBetween、WhenNotBetween、WhenLike、WhenLikeRight、WhenFunc)
    		TryPagination(condition.Page, condition.PageSize). // 尝试使用分页(当 page 和 pageSize 都大于 0 时,会尝试进行分页。结果也由简单的列表改为分页格式列表)
    		TryOrder(condition.OrderBy...). // 尝试进行排序
    		Find(&users) // 构建查询条件并执行查询
    }
    
  4. 高级用法:FinderCondition

    package main
    
    import (
    	`github.com/aid297/aid/gormPool`
    	`gorm.io/gorm`
    )
    
    type (
    	UserModel struct {
    		ID       uint            `gorm:"type:bigint unsigned;primaryKey;autoIncrement"`
    		Username string          `gorm:"type:varchar(64);not null;unique;default:''"`
    		Password string          `gorm:"type:varchar(255);not null;default:''"`
    		Age      uint            `gorm:"type:bigint unsigned;not null;default:0"`
    		Articles []*ArticleModel `gorm:"foreignKey:AuthorID;references:ID"`
    	}
    
    	ArticleModel struct {
    		Title    string     `gorm:"type:varchar(255);not null;unique;default:''"`
    		AuthorID int        `gorm:"type:bigint unsigned;not null;default:0"`
    		Author   *UserModel `gorm:"foreignKey:AuthorID;references:ID"`
    	}
    
    	UserRequest struct {
    		finderCondition *gormPool.FinderCondition
    	}
    )
    
    func main() {
    	var (
    		err       error
    		dbSetting *gormPool.DBSetting
    		mysqlPool *gormPool.MySQLPool
    		db        *gorm.DB
    		users     []UserModel
    		request   = &UserRequest{finderCondition: &gormPool.FinderCondition{}}
    	)
    	if dbSetting, err = gormPool.APP.DBSetting.New("db.yaml"); err != nil { // 读取配置文件
    		panic(err) // 读取配置文件失败,程序无法继续运行
    	}
    	mysqlPool = gormPool.APP.MySQLPool.Once(dbSetting) // 创建 orm 连接池
    	db = mysqlPool.GetConn()
    
    	if err = gormPool.APP.Finder.
    		New(db.Model(UserModel{})).
    		FindOnlyCondition(request.finderCondition, &users).
    		GetDB().
    		Error; err != nil {
    		panic(err) // 异常处理
    	}
    
    	// 参数格式:
    	// {
    	//    "page": 1,
    	//    "pageSize": 10,
    	//    "condition": {
    	//        "queries": [
    	//            {
    	//                "option": "and",
    	//                "conditions": [
    	//                    {
    	//                        "key": "env_kind",
    	//                        "operator": "=",
    	//                        "values": [
    	//                            "coderepo"
    	//                        ]
    	//                    },
    	//                    {
    	//                        "key": "project_uuid",
    	//                        "operator": "=",
    	//                        "values": [
    	//                            "1f0afe0f-b4fa-62c6-bebd-14361e47a020"
    	//                        ]
    	//                    },
    	//                    {
    	//                        "key": "operator_uuid",
    	//                        "operator": "!=",
    	//                        "values": [
    	//                            ""
    	//                        ]
    	//                    }
    	//                ]
    	//            }
    	//        ],
    	//        "orders": [
    	//            "id desc"
    	//        ]
    	//    }
    	// }
    }
    

Documentation

Index

Constants

This section is empty.

Variables

View Source
var APP struct {
	MySQLPool     MySQLPool
	PGPool        PGPool
	SQLServerPool SQLServerPool
	DBSetting     DBSetting
	Finder        Finder
}

Functions

func DefaultModel

func DefaultModel[model Modeler](db *gorm.DB, attrs ...ModelAttributer) *gorm.DB

Types

type ArSQLConnection added in v1.53.3

type ArSQLConnection struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     uint16 `yaml:"port"`
}

type ArSQLSetting added in v1.53.3

type ArSQLSetting struct {
	Database string                      `yaml:"database"`
	Rws      bool                        `yaml:"rws"`
	Main     *MySQLConnection            `yaml:"main"`
	Sources  map[string]*ArSQLConnection `yaml:"sources"`
	Replicas map[string]*ArSQLConnection `yaml:"replicas"`
}

type AttrDistinct

type AttrDistinct struct {
	// contains filtered or unexported fields
}

func Distinct

func Distinct(args ...any) *AttrDistinct

func (*AttrDistinct) Register

func (my *AttrDistinct) Register(model Modeler, db *gorm.DB) *gorm.DB

type AttrJoins

type AttrJoins struct {
	// contains filtered or unexported fields
}

func Joins

func Joins(join string, args ...any) *AttrJoins

func (*AttrJoins) Register

func (my *AttrJoins) Register(model Modeler, db *gorm.DB) *gorm.DB

type AttrPreload

type AttrPreload struct {
	// contains filtered or unexported fields
}

func Preload

func Preload(preloads ...string) *AttrPreload

func (*AttrPreload) Register

func (my *AttrPreload) Register(model Modeler, db *gorm.DB) *gorm.DB

type AttrSelect

type AttrSelect struct {
	// contains filtered or unexported fields
}

func Select

func Select(query any, args ...any) *AttrSelect

func (*AttrSelect) Register

func (my *AttrSelect) Register(model Modeler, db *gorm.DB) *gorm.DB

type AttrTable

type AttrTable struct {
	// contains filtered or unexported fields
}

func Table

func Table(table string) *AttrTable

func (*AttrTable) Register

func (my *AttrTable) Register(model Modeler, db *gorm.DB) *gorm.DB

type Common

type Common struct {
	Driver             string `yaml:"driver"`
	MaxOpenConnections int    `yaml:"max-open-connections"`
	MaxIdleConnections int    `yaml:"max-idle-connections"`
	MaxLifetime        int    `yaml:"max-lifetime"`
	MaxIdleTime        int    `yaml:"max-idle-time"`
}

type Condition

type Condition struct {
	Key      string `json:"key"`      // SQL字段名称,如果有别名则需要带有别名
	Operator string `json:"operator"` // 操作符:=、>、<、!=、<=、>=、<>、in、not in、between、not between、like、like%、%like、raw、join
	Values   []any  `json:"values"`   // 查询条件值
}

Condition 查询

type DBSetting added in v1.53.3

type DBSetting struct {
	Common    *Common           `yaml:"common,omitempty"`
	MySQL     *MySQLSetting     `yaml:"mysql,omitempty"`
	Postgres  *PGSetting        `yaml:"postgres,omitempty"`
	SQLServer *SQLServerSetting `yaml:"sql-server,omitempty"`
	ArSQL     *ArSQLSetting     `yaml:"ar-sql,omitempty"`
}

func (*DBSetting) ExampleYaml added in v1.53.3

func (*DBSetting) ExampleYaml() string

func (*DBSetting) New added in v1.53.3

func (*DBSetting) New(path string) (dbSetting *DBSetting, err error)

New 初始化:数据库配置

type Dsn

type Dsn struct {
	Name    string
	Content string
}

type Finder

type Finder struct {
	// contains filtered or unexported fields
}

Finder 查询帮助器

func DefaultFinder

func DefaultFinder[model Modeler](db *gorm.DB, attrs ...ModelAttributer) *Finder

func (*Finder) Ex

func (my *Finder) Ex(functions ...func(db *gorm.DB)) *Finder

Ex 额外操作

func (*Finder) Find

func (my *Finder) Find(ret any, preloads ...string) *Finder

Find 查询数据

func (*Finder) FindOnlyCondition

func (my *Finder) FindOnlyCondition(finderCondition *FinderCondition, ret any) *Finder

FindOnlyCondition 自动填充查询条件并查询:使用FinderCondition

func (*Finder) FindUseCondition

func (my *Finder) FindUseCondition(finderCondition *FinderCondition, page, size int, ret any) *Finder

FindUseCondition 自动填充查询条件并查询:使用FinderCondition

func (*Finder) FindUseMap

func (my *Finder) FindUseMap(queries map[string][]any, preloads []string, orders []string, page, size int, ret any) *Finder

FindUseMap 自动填充查询条件并查询:使用map[string][]any

func (*Finder) GetDB

func (my *Finder) GetDB() *gorm.DB

GetDB 获取 gorm.DB 对象

func (*Finder) GetTotal

func (my *Finder) GetTotal() int64

GetTotal 获取总数

func (*Finder) New

func (*Finder) New(db *gorm.DB) *Finder

New 实例化:查询帮助器

func (*Finder) QueryUseCondition

func (my *Finder) QueryUseCondition(finderCondition *FinderCondition) *Finder

QueryUseCondition 从请求体中获取查询条件

func (*Finder) QueryUseMap

func (my *Finder) QueryUseMap(queries map[string][]any) *Finder

QueryUseMap 从map中解析参数并查询

func (*Finder) SetTotal

func (my *Finder) SetTotal(total int64) *Finder

SetTotal 设置总数

func (*Finder) Transaction

func (my *Finder) Transaction(functions ...func(db *gorm.DB)) error

Transaction 执行一组数据库事务操作 参数 funcs 为需要在事务中执行的函数切片,每个函数接收一个 *gorm.DB 参数 如果任一函数执行出错,将回滚整个事务并返回错误 所有函数执行成功后提交事务 返回 error,nil 表示事务执行成功,非 nil 表示事务执行失败

func (*Finder) TryOrder

func (my *Finder) TryOrder(orders ...string) *Finder

TryOrder 尝试排序

func (*Finder) TryPagination

func (my *Finder) TryPagination(page, size int) *Finder

TryPagination 尝试分页

func (*Finder) TryPreload

func (my *Finder) TryPreload(preloads ...string) *Finder

TryPreload 尝试深度查询

func (*Finder) TryQuery

func (my *Finder) TryQuery(mode string, fieldName string, values ...any)

TryQuery 尝试查询

func (*Finder) When

func (my *Finder) When(condition bool, query any, args ...any) *Finder

When 当条件满足时执行:where

func (*Finder) WhenBetween

func (my *Finder) WhenBetween(condition bool, query any, args ...any) *Finder

WhenBetween 当条件满足时执行:where between

func (*Finder) WhenFunc

func (my *Finder) WhenFunc(condition bool, fn func(db *gorm.DB)) *Finder

WhenFunc 当条件满足时执行:通过回调执行

func (*Finder) WhenIn

func (my *Finder) WhenIn(condition bool, query any, args any) *Finder

WhenIn 当条件满足时执行:where in

func (*Finder) WhenInPtr

func (my *Finder) WhenInPtr(condition bool, query any, args any) *Finder

WhenInPtr 当条件满足时执行:where in args 为指针类型

func (*Finder) WhenLike

func (my *Finder) WhenLike(condition bool, query, arg any) *Finder

WhenLike 当条件满足时执行:like %?%

func (*Finder) WhenLikeLeft

func (my *Finder) WhenLikeLeft(condition bool, query, arg any) *Finder

WhenLikeLeft 当条件满足时执行:like %?

func (*Finder) WhenLikeRight

func (my *Finder) WhenLikeRight(condition bool, query, arg any) *Finder

WhenLikeRight 当条件满足时执行:like ?%

func (*Finder) WhenNotBetween

func (my *Finder) WhenNotBetween(condition bool, query any, args ...any) *Finder

WhenNotBetween 当条件满足时执行:where not between

func (*Finder) WhenNotIn

func (my *Finder) WhenNotIn(condition bool, query any, args any) *Finder

WhenNotIn 当条件满足时执行:where not in

func (*Finder) WhenNotInPtr

func (my *Finder) WhenNotInPtr(condition bool, query any, args any) *Finder

WhenNotInPtr 当条件满足时执行:where in args 为指针类型

type FinderCondition

type FinderCondition struct {
	Table    *string  `json:"table,omitempty"`
	Queries  []Query  `json:"queries,omitempty"`  // 查询条件
	Orders   []string `json:"orders,omitempty"`   // 排序
	Preloads []string `json:"preloads,omitempty"` // 预加载
	Page     int      `json:"page,omitempty"`     // 页码
	Limit    int      `json:"limit,omitempty"`    // 页容量
}

FinderCondition 查询条件

type GORMPool added in v1.53.3

type GORMPool interface {
	GetConn() *gorm.DB

	Close() error
	// contains filtered or unexported methods
}

func OncePostgresPool

func OncePostgresPool(dbSetting *DBSetting) GORMPool

OncePostgresPool 单例化:postgres链接池

func OnceSqlServerPool

func OnceSqlServerPool(dbSetting *DBSetting) GORMPool

OnceSqlServerPool 单例化:sql server连接池

type ModelAttributer

type ModelAttributer interface {
	Register(model Modeler, db *gorm.DB) *gorm.DB
}

type Modeler

type Modeler interface{ TableName() string }

Modeler 接口:模型

type MySQLConnection added in v1.53.3

type MySQLConnection struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     uint16 `yaml:"port"`
}

type MySQLPool added in v1.53.3

type MySQLPool struct {
	// contains filtered or unexported fields
}
var (
	MySqlDsnFormat = "%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local"
	MySqlPoolApp   MySQLPool
)

func OnceMySqlPool

func OnceMySqlPool(dbSetting *DBSetting) *MySQLPool

OnceMySqlPool 单例化:mysql链接池

func (*MySQLPool) Close added in v1.53.3

func (*MySQLPool) Close() error

Close 关闭数据库链接

func (*MySQLPool) GetConn added in v1.53.3

func (*MySQLPool) GetConn() *gorm.DB

GetConn 获取主数据库链接

func (*MySQLPool) Once added in v1.53.3

func (*MySQLPool) Once(dbSetting *DBSetting) *MySQLPool

type MySQLSetting added in v1.53.3

type MySQLSetting struct {
	Database  string                      `yaml:"database"`
	Charset   string                      `yaml:"charset"`
	Collation string                      `yaml:"collation"`
	Rws       bool                        `yaml:"rws"`
	Main      *MySQLConnection            `yaml:"main"`
	Sources   map[string]*MySQLConnection `yaml:"sources"`
	Replicas  map[string]*MySQLConnection `yaml:"replicas"`
}

type PGConnection added in v1.53.3

type PGConnection struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     uint16 `yaml:"port"`
	Database string `yaml:"database"`
	TimeZone string `yaml:"timezone"`
	SSLMode  string `yaml:"ssl-mode"`
}

type PGPool added in v1.53.3

type PGPool struct {
	// contains filtered or unexported fields
}
var (
	PostgresDsnFormat = "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s"
	PostgresPoolApp   PGPool
)

func (*PGPool) Close added in v1.53.3

func (my *PGPool) Close() error

Close 关闭数据库链接

func (*PGPool) GetConn added in v1.53.3

func (my *PGPool) GetConn() *gorm.DB

GetConn 获取主数据库链接

func (*PGPool) Once added in v1.53.3

func (*PGPool) Once(dbSetting *DBSetting) GORMPool

type PGSetting added in v1.53.3

type PGSetting struct {
	Main *PGConnection `yaml:"main"`
}

type Query added in v1.51.22

type Query struct {
	Option     *string     `json:"option,omitempty"`     // 操作:and、or、not
	Conditions []Condition `json:"conditions,omitempty"` // 条件
}

Query 查询

type SQLServerConnection added in v1.53.3

type SQLServerConnection struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     uint16 `yaml:"port"`
	Database string `yaml:"database"`
}

type SQLServerPool added in v1.53.3

type SQLServerPool struct {
	// contains filtered or unexported fields
}
var (
	SqlServerDsnFormat = "sqlserver://%s:%s@%s:?%d?database=%s"
	SqlServerPoolApp   SQLServerPool
)

func (*SQLServerPool) Close added in v1.53.3

func (my *SQLServerPool) Close() error

Close 关闭数据库链接

func (*SQLServerPool) GetConn added in v1.53.3

func (my *SQLServerPool) GetConn() *gorm.DB

GetConn 获取主数据库链接

func (*SQLServerPool) Once added in v1.53.3

func (*SQLServerPool) Once(dbSetting *DBSetting) GORMPool

type SQLServerSetting added in v1.53.3

type SQLServerSetting struct {
	Main *SQLServerConnection `yaml:"main"`
}

Jump to

Keyboard shortcuts

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