gormPools

package
v2.9.2 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

GORMPool 使用说明

  1. 初始化

    package main
    
    import `github.com/aid297/aid/v2/gormPools`
    
    func main() {
    	dbSetting, err := gormPools.APP.DBSetting.New("db.yaml") // 读取配置文件
    	if err != nil {
    		panic(err) // 读取配置文件失败,程序无法继续运行
    	}
    	mysqlPool := gormPools.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/v2/gormPools`
    	`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 := gormPools.APP.DBSetting.New("db.yaml") // 读取配置文件
    	if err != nil {
    		panic(err) // 读取配置文件失败,程序无法继续运行
    	}
    	mysqlPool := gormPools.APP.MySQLPool.Once(dbSetting) // 创建 orm 连接池
    	db := mysqlPool.GetConn()
    
    	var (
    		users     []UserModel
    		condition = UserCondition{Username: "admin", Age: 18, Page: 1, PageSize: 100}
    	)
    
    	gormPools.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/v2/gormPools`
    	`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 *gormPools.FinderCondition
    	}
    )
    
    func main() {
    	var (
    		err       error
    		dbSetting *gormPools.DBSetting
    		mysqlPool *gormPools.MySQLPool
    		db        *gorm.DB
    		users     []UserModel
    		request   = &UserRequest{finderCondition: &gormPools.FinderCondition{}}
    	)
    	if dbSetting, err = gormPools.APP.DBSetting.New("db.yaml"); err != nil { // 读取配置文件
    		panic(err) // 读取配置文件失败,程序无法继续运行
    	}
    	mysqlPool = gormPools.APP.MySQLPool.Once(dbSetting) // 创建 orm 连接池
    	db = mysqlPool.GetConn()
    
    	if err = gormPools.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 {
	DBSetting DBSetting
}

Functions

func Exist

func Exist(tx *gorm.DB, query any, args ...any) (exist bool, err error)

func SaveOrCreate

func SaveOrCreate(tx *gorm.DB, data Modeler, query any, args ...any) (err error)

func ToModel

func ToModel[model Modeler](db *gorm.DB, attrs ...ModelAttr) *gorm.DB

func UpdateColumnsOrCreate

func UpdateColumnsOrCreate(tx *gorm.DB, data Modeler, updates any, query any, args ...any) (err error)

func UpdatesOrCreate

func UpdatesOrCreate(tx *gorm.DB, data Modeler, updates any, query any, args ...any) (err error)

Types

type ArSQLEndpoint

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

type ArSQLSetting

type ArSQLSetting struct {
	Database string                    `yaml:"database"`
	Rws      bool                      `yaml:"rws"`
	Main     *MySQLEndpoint            `yaml:"main"`
	Sources  map[string]*ArSQLEndpoint `yaml:"sources"`
	Replicas map[string]*ArSQLEndpoint `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(preload string, args ...any) AttrPreload

func (AttrPreload) Register

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

type AttrPreloadMap

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

func PreloadMap

func PreloadMap(preloadMap map[string][]any) AttrPreloadMap

func (AttrPreloadMap) Register

func (my AttrPreloadMap) 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

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

func (*DBSetting) ExampleYaml

func (*DBSetting) ExampleYaml() string

func (*DBSetting) New

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

New 初始化:数据库配置

type DSN

type DSN struct {
	Name    string
	Content string
}

type Finder

type Finder interface {
	GetDB() *gorm.DB
	Find(ret any, preloads ...string) Finder
	Ex(functions ...func(db *gorm.DB)) Finder
	TryPagination(page, size int) Finder
	TryOrder(orders ...string) Finder
	TryPreload(preloads ...string) Finder
	TryQuery(mode string, fieldName string, values ...any)
	SetTotal(total int64) Finder
	GetTotal() int64
	When(condition bool, query any, args ...any) Finder
	WhenIn(condition bool, query any, args any) Finder
	WhenInPtr(condition bool, query any, args any) Finder
	WhenNotIn(condition bool, query any, args any) Finder
	WhenNotInPtr(condition bool, query any, args any) Finder
	WhenBetween(condition bool, query any, args ...any) Finder
	WhenNotBetween(condition bool, query any, args ...any) Finder
	WhenLike(condition bool, query, arg any) Finder
	WhenLikeLeft(condition bool, query, arg any) Finder
	WhenLikeRight(condition bool, query, arg any) Finder
	WhenFunc(condition bool, fn func(db *gorm.DB)) Finder
	Transaction(functions ...func(db *gorm.DB)) error
	QueryUseMap(queries map[string][]any) Finder
	QueryUseCondition(finderCondition *FinderCondition) Finder
	FindUseMap(queries map[string][]any, preloads []string, orders []string, page, size int, ret any) Finder
	FindUseCondition(finderCondition *FinderCondition, page, size int, ret any) Finder
	FindOnlyCondition(finderCondition *FinderCondition, ret any) Finder
	// contains filtered or unexported methods
}

func NewFinder

func NewFinder(db *gorm.DB) Finder

func ToFinder

func ToFinder[model Modeler](db *gorm.DB, attrs ...ModelAttr) Finder

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 FinderImpl

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

FinderImpl 查询帮助器

func (*FinderImpl) Ex

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

Ex 额外操作

func (*FinderImpl) Find

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

Find 查询数据

func (*FinderImpl) FindOnlyCondition

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

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

func (*FinderImpl) FindUseCondition

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

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

func (*FinderImpl) FindUseMap

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

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

func (*FinderImpl) GetDB

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

GetDB 获取 gorm.DB 对象

func (*FinderImpl) GetTotal

func (my *FinderImpl) GetTotal() int64

GetTotal 获取总数

func (*FinderImpl) QueryUseCondition

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

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

func (*FinderImpl) QueryUseMap

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

QueryUseMap 从map中解析参数并查询

func (*FinderImpl) SetTotal

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

SetTotal 设置总数

func (*FinderImpl) Transaction

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

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

func (*FinderImpl) TryOrder

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

TryOrder 尝试排序

func (*FinderImpl) TryPagination

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

TryPagination 尝试分页

func (*FinderImpl) TryPreload

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

TryPreload 尝试深度查询

func (*FinderImpl) TryQuery

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

TryQuery 尝试查询

func (*FinderImpl) When

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

When 当条件满足时执行:where

func (*FinderImpl) WhenBetween

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

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

func (*FinderImpl) WhenFunc

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

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

func (*FinderImpl) WhenIn

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

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

func (*FinderImpl) WhenInPtr

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

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

func (*FinderImpl) WhenLike

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

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

func (*FinderImpl) WhenLikeLeft

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

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

func (*FinderImpl) WhenLikeRight

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

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

func (*FinderImpl) WhenNotBetween

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

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

func (*FinderImpl) WhenNotIn

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

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

func (*FinderImpl) WhenNotInPtr

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

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

type GORMPool

type GORMPool interface {
	GetConn() *gorm.DB

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

type MSSQLEndpoint

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

type MSSQLSetting

type MSSQLSetting struct {
	Main *MSSQLEndpoint `yaml:"main"`
}

type ModelAttr

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

type Modeler

type Modeler interface {
	TableName() string
}

Modeler 接口:模型

type MySQLBasic

type MySQLBasic struct {
	ID        int64          `gorm:"column:id;type:bigint unsigned;primaryKey" json:"id"`
	CreatedAt time.Time      `gorm:"column:created_at;type:datetime;not null;default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time      `gorm:"column:updated_at;type:datetime;not null;default:current_timestamp;autoUpdateTime:true" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime;not null" json:"deleted_at"`
	UUID      string         `gorm:"column:uuid;type:char(36);not null;unique" json:"uuid"`
}

type MySQLEndpoint

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

type MySQLSetting

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

type PGEndpoint

type PGEndpoint 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 PGSetting

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

type Query

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

Query 查询

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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