repository

package
v0.19.4 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0, Apache-2.0 Imports: 25 Imported by: 2

Documentation

Overview

* @Author: kamalyes 501893067@qq.com * @Date: 2025-07-30 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-07-30 13:26:08 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\async_batch_writer.go * @Description: 通用异步批量写入器,适用于高频写入低频查询的场景(如 ClickHouse 日志表) * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 21:13:15 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-13 17:59:23 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\base.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2026-11-01 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-11-01 00:00:00 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\condition.go * @Description: 过滤条件编译的唯一入口 - 全库三条构建路径都委托到这里 * * 改造前本包有三份各自独立的算子 switch:ApplyFilter(gORM 链式)、 * buildFilterCondition(Query.Filters / FilterGroup 的字符串路径)和 * Query.buildFilterCondition(BuildWhereClause 的纯字符串路径) * 三份覆盖的算子集合并不相同,同一个过滤条件走不同入口会得到不同结果, * 缺失的算子被静默丢掉,查询无声地放宽 * * [EN] Single compilation entry point for filter conditions * There used to be three independent operator switches in this package, each * covering a different operator set, so one filter could compile differently * depending on the entry point and missing operators were silently dropped * * Copyright (c) 2026 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 08:15:15 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\filter.go * @Description: 过滤器和查询构建 - Filter、FilterGroup、Query等查询条件 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 22:55:38 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\helpers.go * @Description: 仓储辅助工具 - 软删除、查询辅助等功能 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 00:00:00 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\interfaces.go * @Description: 核心接口定义 - Repository、Transaction、Query 等 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-06-26 21:15:55 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\join.go * @Description: 通用 JOIN 查询封装 * * 用途:主表 JOIN 关联表补充字段(如 dict_entries JOIN dict_groups 取 group_type/group_name), * 且补充字段在主模型上为 gorm:"-"(非持久化,避免 AutoMigrate 建列) * * 配合 ListWithJoinScan 使用:扩展 struct 匿名内嵌主模型 + 带 column tag 的关联字段 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2026-07-03 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-07-03 01:06:56 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\json_query.go * @Description: JSON 数组包含查询辅助 - 方言感知的高效查询构建 * * 适用场景:JSON 数组列(如 sqltypes.Slice[int64] 存储的 channel_ids)包含某值的查询与计数 * - WHERE 查询:JsonArrayContainsExpr 返回 SQL 表达式 + 参数,用 OP_RAW 或直接 Where 拼接 * - SELECT 派生列:JsonArrayCountComputedField 返回 ComputedField,用于动态计算关联数 * * 性能建议: * - PostgreSQL/CockroachDB:对 JSON 列建 GIN/inverted index,@> 操作符可走索引 * - MySQL 8.0.17+:可对 JSON 列建 Multi-Valued Index * - SQLite:仅用于测试,EXISTS 子查询性能有限 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 22:50:00 * @FilePath: \go-toolbox\pkg\sqlbuilder\model.go * @Description: 基础模型定义 - BaseModel、AuditModel、UUIDModel 等 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-25 08:06:51 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\paging.go * @Description: 分页工具 - Pagination分页元数据和辅助方法 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 13:29:12 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\query.go * @Description: 类型定义 - Filter、Pagination、QueryCondition 等 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-11 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-11 02:00:15 * @FilePath: \go-toolbox\pkg\sqlbuilder\repository\scope.go * @Description: 类型定义 - Filter、Pagination、QueryCondition 等 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

Index

Constants

View Source
const (
	MaxWorkers       = 1000  // 最大工作协程数
	MaxTasksPerBatch = 10000 // 单批最大任务数
)

并发查询限制常量

View Source
const (
	// CursorSeparator 游标字段分隔符
	CursorSeparator = "|"
	// TimeFormat 默认时间格式
	TimeFormat = time.RFC3339Nano
)
View Source
const MaxFilterGroupDepth = 20

MaxFilterGroupDepth 过滤条件组最大嵌套深度,防止无限嵌套导致内存溢出

Variables

View Source
var (
	// ErrInvalidCursor 无效的游标
	ErrInvalidCursor = errors.New("invalid cursor format")
	// ErrEmptyCursor 空游标
	ErrEmptyCursor = errors.New("empty cursor")
	// ErrInvalidTimestamp 无效的时间戳
	ErrInvalidTimestamp = errors.New("invalid timestamp format")
)
View Source
var DefaultAsyncBatchWriterConfig = AsyncBatchWriterConfig{
	BatchSize:     200,
	FlushInterval: 800 * time.Millisecond,
	ChannelBuffer: 4096,
}

DefaultAsyncBatchWriterConfig 默认配置

Functions

func ApplyAndFilterGroup

func ApplyAndFilterGroup(db *gorm.DB, group *FilterGroup) *gorm.DB

ApplyAndFilterGroup 应用 AND 逻辑的过滤组

func ApplyDesensitize

func ApplyDesensitize(obj interface{})

ApplyDesensitize 对结构体指针应用脱敏 根据 desensitize tag 自动识别并脱敏字段 仅处理 string 和 *string 类型字段,跳过其他类型 支持嵌套结构体、指针、切片的递归处理

示例:

type UserModel struct {
    Name   string `desensitize:"name"`
    Email  string `desensitize:"email"`
    Phone  string `desensitize:"mobilePhone"`
    Avatar string // 无标签,不脱敏
}
ApplyDesensitize(&user) // user.Name/Email/Phone 被脱敏

func ApplyDesensitizeSlice

func ApplyDesensitizeSlice[T any](entities []*T)

ApplyDesensitizeSlice 批量对结构体指针切片应用脱敏

func ApplyFieldSelection

func ApplyFieldSelection(db *gorm.DB, selectFields, omitFields, modelFields []string, autoFields bool) *gorm.DB

ApplyFieldSelection 应用字段选择 selectFields: 要选择的字段列表 omitFields: 要排除的字段列表 modelFields: 模型的所有字段(用于自动字段模式) autoFields: 是否启用自动字段模式

func ApplyFilter

func ApplyFilter(dbQuery *gorm.DB, filter *Filter) *gorm.DB

ApplyFilter 应用单个过滤条件到 GORM 查询 条件编译统一走 buildConditionArgs,与 Query 的字符串构建路径共用同一套算子实现

[EN] ApplyFilter applies one filter to a GORM query Compilation goes through buildConditionArgs, shared with the string-building Query paths

func ApplyFilterGroup

func ApplyFilterGroup(db *gorm.DB, group *FilterGroup) *gorm.DB

ApplyFilterGroup 应用过滤条件组

func ApplyFilters

func ApplyFilters(db *gorm.DB, filters []*Filter) *gorm.DB

ApplyFilters 批量应用过滤器到查询

func ApplyJoins

func ApplyJoins(db *gorm.DB, query *Query, mainTable string) *gorm.DB

ApplyJoins 应用所有 JOIN 子句与补充字段 SELECT 拼接

mainTable 为主表名,用于 SELECT "mainTable.*" 限定,避免 JOIN 后字段歧义 mainTable 为空时只应用 JOIN 子句,不拼接 SELECT(count 场景) query 无 Joins 且无 ComputedFields 时直接返回原 db

SELECT 构建顺序:主表.* + 关联补充字段 + 计算字段 当计算字段 Alias 与主表物理列同名时,后出现的计算列会覆盖主表列值

func ApplyOrFilterGroup

func ApplyOrFilterGroup(db *gorm.DB, group *FilterGroup) *gorm.DB

ApplyOrFilterGroup 应用 OR 逻辑的过滤组

func ApplyOrdering

func ApplyOrdering(db *gorm.DB, orders []Order, defaultOrder string) *gorm.DB

ApplyOrdering 应用排序条件 orders: 排序条件列表 defaultOrder: 默认排序(当orders为空时使用),可为空字符串

func ApplyOrders

func ApplyOrders(db *gorm.DB, orders []Order) *gorm.DB

ApplyOrders 批量应用排序条件到查询

func ApplyPaginationOrLimit

func ApplyPaginationOrLimit(db *gorm.DB, query *Query) *gorm.DB

ApplyPaginationOrLimit 统一应用分页或限制条件 优先使用 query.Pagination,其次使用 LimitValue/OffsetValue

func ApplyPreloads

func ApplyPreloads(db *gorm.DB, preloads []string) *gorm.DB

ApplyPreloads 应用预加载关联

func ApplyQueryConditions

func ApplyQueryConditions[T any](repo *BaseRepository[T], db *gorm.DB, query *Query, preloads ...string) *gorm.DB

ApplyQueryConditions 统一应用所有查询条件(字段选择、预加载、过滤、分组、排序、分页等) 参数:

  • repo: BaseRepository 实例(用于获取默认配置)
  • db: GORM 数据库实例
  • query: 查询条件对象
  • preloads: 预加载关联(可选,为空则使用 repository 默认预加载)

func BuildSelectClause

func BuildSelectClause(tableName string, fields []string) string

BuildSelectClause 构建 SELECT 子句

func ConcurrentSimpleQuery

func ConcurrentSimpleQuery[T any](
	e *ConcurrentQueryExecutor,
	ctx context.Context,
	queries map[string]func(ctx context.Context) (T, error),
) (map[string]T, bool)

ConcurrentSimpleQuery 简化的并发查询接口(不需要创建 QueryTask) queries: map[任务名称]查询函数 返回: map[任务名称]查询结果, 是否有错误

func DeserializeJSON

func DeserializeJSON[T any](jsonStr string) (*T, error)

DeserializeJSON 将 JSON 字符串反序列化为结构体 用于从数据库 JSON 字段读取后的转换

func DistinctInto

func DistinctInto[V any, T any](repo *BaseRepository[T], ctx context.Context, field string, filters ...*Filter) ([]V, error)

DistinctInto 获取去重后的字段值到指定类型切片 V

用法:statuses, err := repository.DistinctInto[string](repo, ctx, "status", filters...)

func FilterFields

func FilterFields(allFields, selectFields, omitFields []string) []string

FilterFields 根据 select 和 omit 规则过滤字段列表

func GetDeleted

func GetDeleted[T any](ctx context.Context, db *gorm.DB, query *Query) ([]*T, error)

GetDeleted 获取已删除的记录(使用deleted_at字段)

func GetDesensitizeFields

func GetDesensitizeFields(model interface{}) map[string]string

GetDesensitizeFields 获取结构体中所有标记了 desensitize tag 的字段名 返回 map[fieldName]desensitizeType,用于调试或校验

func GetNonDeleted

func GetNonDeleted[T any](ctx context.Context, db *gorm.DB, query *Query) ([]*T, error)

GetNonDeleted 获取未删除的记录(使用deleted_at字段)

func GetNonPhysicalFields

func GetNonPhysicalFields(model interface{}) []string

GetNonPhysicalFields 获取模型中的非物理列字段名(gorm:"-:migration" 标记的字段)

这类字段在 AutoMigrate 时被忽略(数据库不建列),但 GORM 默认 SELECT 时仍会包含, 导致 "column xxx does not exist" 错误常见于由子查询动态计算的派生字段, 如 linked_tenant_count / linked_game_count 等

Get/GetByFilter/First 等基础查询方法会 Omit 这些字段,避免查询不存在的列; 需要填充派生值时通过 Query.AddComputedField 显式 SELECT

func GetSortableFields

func GetSortableFields(model interface{}) []string

GetSortableFields 返回模型中可排序的字段(排除 JSON/JSONB 类型字段,这类字段无法直接 ORDER BY) 适用于 BaseRepository.ApplySort 自动构建排序白名单,省去手写字段列表

func GetStructFields

func GetStructFields(model interface{}) []string

GetStructFields 获取结构体的所有数据库字段名(基于 gorm tag 或 json tag)

func GetTodayRange

func GetTodayRange() (startTime, endTime time.Time)

GetTodayRange 获取今天的时间范围:startTime 为今天墙上零点,endTime 为明天墙上零点(左闭右开)

[EN] GetTodayRange returns today's wall-clock midnight and tomorrow's, half-open

func IsTimeInTodayRange

func IsTimeInTodayRange(t *time.Time, todayStart, todayEnd time.Time) bool

IsTimeInTodayRange 判断时间是否在今天范围内

func IsToday

func IsToday(t *time.Time) bool

IsToday 判断时间是否为今天(支持 *time.Time)

func IsTodayFromProto

func IsTodayFromProto(t *timestamppb.Timestamp) bool

IsTodayFromProto 判断 protobuf Timestamp 是否为今天

func IsTodayRange

func IsTodayRange(startTime, endTime *time.Time) bool

IsTodayRange 判断时间范围是否包含今天

func JsonArrayContainsDB

func JsonArrayContainsDB(db *gorm.DB, column string, value interface{}) *gorm.DB

JsonArrayContainsDB 在 gorm.DB 上直接应用 JSON 数组包含过滤 适用于不想经过 Query/Filter 体系、直接链式调用 db.Where 的场景

func JsonArrayContainsExpr

func JsonArrayContainsExpr(dialect Dialect, column string, value interface{}) (sql string, args []interface{})

JsonArrayContainsExpr 构建 JSON 数组包含查询的 WHERE 表达式与参数(方言感知)

参数:

dialect  数据库方言(通过 DetectDialect(db) 获取)
column   JSON 数组列名(如 "channel_ids")
value    待检查是否包含的标量值(int64/string 等)

返回:

sql   可直接拼入 WHERE 的表达式(含 ? 占位符)
args  占位符参数(MySQL/PG/CRDB 为 JSON 编码的 '[value]',SQLite 为原始值)

用法:

sql, args := JsonArrayContainsExpr(dialect, "channel_ids", int64(1))
db.Where(sql, args...).Find(&items)

func JsonArrayContainsStr

func JsonArrayContainsStr(dialect Dialect, column string, value interface{}) string

JsonArrayContainsStr 便捷函数:构建 JSON 数组包含查询的完整 SQL 字符串(用于调试/日志输出) 将 ? 占位符替换为实际参数值,JSON 方言(MySQL/PG/CRDB)参数加单引号,SQLite/ClickHouse 参数为原始值

func JsonFieldEqualsExpr

func JsonFieldEqualsExpr(dialect Dialect, column, jsonKey string, value interface{}) (sql string, args []interface{})

JsonFieldEqualsExpr 构建 JSON 对象字段等值查询的 WHERE 表达式与参数(方言感知) 供 OP_JSON_FIELD_EQ 操作符在 ApplyFilter / buildFilterCondition 中内部调用

参数:

dialect  数据库方言(通过 DetectDialect(db) 获取)
column   JSON 对象列名(如 "package_config")
jsonKey  JSON 键名(如 "apk_package_prefix")
value    待比较的标量值(string/int 等)

返回:

sql   可直接拼入 WHERE 的表达式(含 ? 占位符)
args  占位符参数

func MustDeserializeJSON

func MustDeserializeJSON[T any](jsonStr string) *T

MustDeserializeJSON 反序列化结构体,失败返回 nil 用于不需要错误处理的场景

func MustSerializeJSON

func MustSerializeJSON[T any](data *T) string

MustSerializeJSON 序列化结构体,失败返回空字符串 用于不需要错误处理的场景

func PermanentlyDelete

func PermanentlyDelete[T any](ctx context.Context, db *gorm.DB, id interface{}) error

PermanentlyDelete 永久删除记录(从数据库中完全删除)

func PermanentlyDeleteBatch

func PermanentlyDeleteBatch[T any](ctx context.Context, db *gorm.DB, ids []interface{}) error

PermanentlyDeleteBatch 批量永久删除记录(从数据库中完全删除)

func PluckInto

func PluckInto[V any, T any](repo *BaseRepository[T], ctx context.Context, field string, filters ...*Filter) ([]V, error)

PluckInto 提取单个字段的值到指定类型切片 V,避免调用方对 []interface{} 做手动类型断言 直接 Pluck 进 []V,比 Pluck 更省一次内存拷贝,也规避部分驱动把字符串列扫描成 []byte 的问题

用法:hosts, err := repository.PluckInto[string](repo, ctx, "domain", filters...)

func RegisterDesensitizeType

func RegisterDesensitizeType(name string, desensitizer desensitize.Desensitizer)

RegisterDesensitizeType 注册自定义脱敏类型 扩展 go-toolbox 的注册器,方便在 go-toolbox/pkg/sqlbuilder 层统一注册

示例:

repository.RegisterDesensitizeType("myType", &desensitize.DefaultDesensitizer{desensitize.CustomExtension})

func RestoreDeleted

func RestoreDeleted[T any](ctx context.Context, db *gorm.DB, id interface{}) error

RestoreDeleted 恢复单个已删除记录(将deleted_at设为NULL)

func RestoreDeletedBatch

func RestoreDeletedBatch[T any](ctx context.Context, db *gorm.DB, ids []interface{}) error

RestoreDeletedBatch 批量恢复已删除记录(将deleted_at设为NULL)

func SerializeJSON

func SerializeJSON[T any](data *T) (string, error)

SerializeJSON 将结构体序列化为 JSON 字符串 用于保存到数据库 JSON 字段前的转换

func StructHasField

func StructHasField(model interface{}, field string) bool

StructHasField 检查结构体是否包含指定的数据库字段 字段匹配规则与 GetStructFields 一致:优先 gorm column tag,其次 json tag,最后蛇形字段名

Types

type AggregateField

type AggregateField struct {
	Function  string        // 聚合函数:SUM, COUNT, AVG, MAX, MIN
	Condition string        // CASE WHEN 条件
	ThenValue string        // THEN 子句的值(对于AVG/MAX/MIN是字段名,对于SUM/COUNT是1)
	Args      []interface{} // 条件参数
	Alias     string        // 结果别名
	ElseValue interface{}   // ELSE 值(默认 0)
}

AggregateField 聚合字段定义

type AggregateOperation

type AggregateOperation struct {
	Function  string        // COUNT, SUM, AVG, MAX, MIN
	Field     string        // 字段名(COUNT(*) 时为空)
	Alias     string        // 结果别名
	Distinct  bool          // 是否 DISTINCT
	Condition string        // 可选的 CASE WHEN 条件
	Args      []interface{} // 条件参数
}

AggregateOperation 聚合操作

type AsyncBatchWriter

type AsyncBatchWriter[T any] struct {
	// contains filtered or unexported fields
}

AsyncBatchWriter 通用异步批量写入器 通过内部 channel + goroutine 实现非阻塞写入,批量 flush 到数据库 适用于 ClickHouse 日志表等高频写入场景,调用方只需 Append 即可,无需等待 DB IO

func NewAsyncBatchWriter

func NewAsyncBatchWriter[T any](repo *BaseRepository[T], opts ...AsyncBatchWriterOption[T]) *AsyncBatchWriter[T]

NewAsyncBatchWriter 创建异步批量写入器

func (*AsyncBatchWriter[T]) Append

func (w *AsyncBatchWriter[T]) Append(ctx context.Context, item *T)

Append 非阻塞追加一条记录,ctx 用于 trace_id 透传到 flush 日志

func (*AsyncBatchWriter[T]) Stop

func (w *AsyncBatchWriter[T]) Stop()

Stop 停止写入器,等待所有待写入数据 flush 完成后返回

type AsyncBatchWriterConfig

type AsyncBatchWriterConfig struct {
	BatchSize     int           // 每批最大条数,达到即 flush
	FlushInterval time.Duration // 定时 flush 间隔
	ChannelBuffer int           // 输入通道缓冲大小
}

AsyncBatchWriterConfig 异步批量写入器配置

type AsyncBatchWriterOption

type AsyncBatchWriterOption[T any] func(*AsyncBatchWriter[T])

AsyncBatchWriterOption 配置选项

func WithAsyncBatchConfig

func WithAsyncBatchConfig[T any](config AsyncBatchWriterConfig) AsyncBatchWriterOption[T]

WithAsyncBatchConfig 设置批量写入配置

func WithAsyncBatchLogger

func WithAsyncBatchLogger[T any](log logger.ILogger) AsyncBatchWriterOption[T]

WithAsyncBatchLogger 设置日志记录器

type AuditModel

type AuditModel struct {
	BaseModel
	CreatedBy uint `json:"created_by,omitempty" gorm:"index;comment:创建人ID"`
	UpdatedBy uint `json:"updated_by,omitempty" gorm:"index;comment:更新人ID"`
}

AuditModel 审计模型(包含创建人和更新人信息) 适用于需要追踪操作人的业务场景

func (*AuditModel) GetCreatedBy

func (m *AuditModel) GetCreatedBy() uint

func (*AuditModel) GetUpdatedBy

func (m *AuditModel) GetUpdatedBy() uint

func (*AuditModel) SetCreatedBy

func (m *AuditModel) SetCreatedBy(userID uint)

func (*AuditModel) SetUpdatedBy

func (m *AuditModel) SetUpdatedBy(userID uint)

type AuditableModel

type AuditableModel interface {
	ModelInterface
	SetCreatedBy(userID uint)
	SetUpdatedBy(userID uint)
	GetCreatedBy() uint
	GetUpdatedBy() uint
}

AuditableModel 支持审计的模型接口

type BaseModel

type BaseModel struct {
	ID        uint           `json:"id" gorm:"primaryKey;autoIncrement;comment:自增主键"`
	Version   int            `json:"version" gorm:"default:1;comment:版本号"`
	CreatedAt time.Time      `json:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time      `json:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
	DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index;comment:删除时间"`
	Remark    string         `json:"remark,omitempty" gorm:"type:varchar(500);comment:备注"`
	Status    int8           `json:"status" gorm:"default:1;index;comment:状态(1:启用 0:禁用)"`
}

BaseModel 公共基础模型(带软删除、状态管理、版本控制)

func (*BaseModel) BeforeUpdate

func (m *BaseModel) BeforeUpdate(tx *gorm.DB) error

BeforeUpdate GORM更新前钩子

func (*BaseModel) Disable

func (m *BaseModel) Disable()

Disable 禁用

func (*BaseModel) Enable

func (m *BaseModel) Enable()

Enable 启用

func (*BaseModel) GetID

func (m *BaseModel) GetID() uint

GetID 获取主键ID

func (*BaseModel) GetVersion

func (m *BaseModel) GetVersion() int

GetVersion 获取版本号

func (*BaseModel) IsDeleted

func (m *BaseModel) IsDeleted() bool

IsDeleted 判断是否已删除

func (*BaseModel) IsEnabled

func (m *BaseModel) IsEnabled() bool

IsEnabled 判断是否启用

func (*BaseModel) IsNew

func (m *BaseModel) IsNew() bool

IsNew 判断是否为新记录

func (*BaseModel) SetCreatedAt

func (m *BaseModel) SetCreatedAt(t time.Time)

func (*BaseModel) SetRemark

func (m *BaseModel) SetRemark(remark string)

SetRemark 设置备注

func (*BaseModel) SetUpdatedAt

func (m *BaseModel) SetUpdatedAt(t time.Time)

type BaseRepository

type BaseRepository[T any] struct {
	// contains filtered or unexported fields
}

BaseRepository 基础仓储实现,包含通用的 CRUD 操作

func NewBaseRepository

func NewBaseRepository[T any](dbHandler db.Handler, logger logger.ILogger, table string, options ...RepositoryOption[T]) *BaseRepository[T]

NewBaseRepository 创建基础仓储

func (*BaseRepository[T]) ApplyQueryFilters

func (r *BaseRepository[T]) ApplyQueryFilters(db *gorm.DB, query *Query) *gorm.DB

ApplyQueryFilters 模型感知地应用查询过滤条件 BaseRepository 是泛型 [T],在方法内部通过 new(T) 自动获取模型类型, 调用 FilterGroupByModel 过滤掉 FilterGroup 中模型不存在的字段(保留 OP_RAW deny-all), 顶层 query.Filters(业务条件)原样应用,不修改入参 query

统一注入点:List/DeleteByQuery/UpdateByQuery/分页 等所有携带 *Query 的内部路径 均走本方法,从而让作用域注入的 region_code 等字段在不匹配的表上被自动剔除, 调用方零感知,无需传 model

func (*BaseRepository[T]) ApplySort

func (r *BaseRepository[T]) ApplySort(q *Query, sort Sorter, defaultField, defaultDirection string, excludeFields ...string) *Query

ApplySort 从 Sorter 自动应用安全排序,白名单取自模型可排序字段(排除 JSON 类型) 调用方无需手写白名单;如需排除特定字段(如 id/version),传入 excludeFields

参数:

  • q: 查询构建器
  • sort: 排序参数(可为 nil,回退默认排序)
  • defaultField: 默认排序字段(sort 为空或字段不在白名单时使用)
  • defaultDirection: 默认排序方向
  • excludeFields: 额外排除的字段(可选)

示例:

r.ApplySort(q, req.GetSort(), "sort", "DESC")
r.ApplySort(q, req.GetSort(), "sort", "DESC", "id", "version")

func (*BaseRepository[T]) BulkCreate

func (r *BaseRepository[T]) BulkCreate(ctx context.Context, entities []*T, batchSize ...int) error

BulkCreate 高性能批量创建

func (*BaseRepository[T]) ConcurrentQuery

func (r *BaseRepository[T]) ConcurrentQuery(
	ctx context.Context,
	queries map[string]func(ctx context.Context) (int64, error),
	opts ...ConcurrentQueryOption,
) (map[string]int64, bool)

ConcurrentQuery 简化的并发查询接口 直接传入查询函数的 map,返回结果的 map

func (*BaseRepository[T]) Count

func (r *BaseRepository[T]) Count(ctx context.Context, filters ...*Filter) (int64, error)

Count 计数

func (*BaseRepository[T]) CountByField

func (r *BaseRepository[T]) CountByField(ctx context.Context, field string) (map[interface{}]int64, error)

CountByField 按字段计数(GROUP BY)

func (*BaseRepository[T]) CountByFilterGroup

func (r *BaseRepository[T]) CountByFilterGroup(ctx context.Context, group *FilterGroup) (int64, error)

CountByFilterGroup 按 FilterGroup 计数 支持 OR 复合条件,与 Count(filters...) 对齐

func (*BaseRepository[T]) CountWhere

func (r *BaseRepository[T]) CountWhere(ctx context.Context, args ...interface{}) (int64, error)

CountWhere 简化的条件计数 示例: CountWhere(ctx, "status", "active")

func (*BaseRepository[T]) CountWhereOp

func (r *BaseRepository[T]) CountWhereOp(ctx context.Context, args ...interface{}) (int64, error)

CountWhereOp 带操作符的条件计数 示例: CountWhereOp(ctx, "age", constants.OP_GT, 18)

func (*BaseRepository[T]) Create

func (r *BaseRepository[T]) Create(ctx context.Context, entity *T) (*T, error)

Create 创建单个记录

func (*BaseRepository[T]) CreateBatch

func (r *BaseRepository[T]) CreateBatch(ctx context.Context, entities ...*T) error

CreateBatch 批量创建记录

func (*BaseRepository[T]) CreateIfNotExists

func (r *BaseRepository[T]) CreateIfNotExists(ctx context.Context, entity *T, uniqueFields ...string) (*T, bool, error)

CreateIfNotExists 如果不存在则创建

func (*BaseRepository[T]) CreateOrUpdate

func (r *BaseRepository[T]) CreateOrUpdate(ctx context.Context, entity *T, uniqueFields ...string) (*T, bool, error)

CreateOrUpdate 创建或更新记录

func (*BaseRepository[T]) DBHandler

func (r *BaseRepository[T]) DBHandler() db.Handler

DBHandler 获取数据库处理器

func (*BaseRepository[T]) Delete

func (r *BaseRepository[T]) Delete(ctx context.Context, id interface{}) error

Delete 删除单个记录

func (*BaseRepository[T]) DeleteBatch

func (r *BaseRepository[T]) DeleteBatch(ctx context.Context, ids ...interface{}) error

DeleteBatch 批量删除记录

func (*BaseRepository[T]) DeleteByFilterGroup

func (r *BaseRepository[T]) DeleteByFilterGroup(ctx context.Context, group *FilterGroup) error

DeleteByFilterGroup 按 FilterGroup 删除记录 支持 OR 复合条件,可将多组 AND 条件合并为单条 DELETE,N 次 IO 降为 1 次 典型场景:批量删除多条策略,每条策略由 (p_type=? AND v0=? AND ...) 精确匹配

示例:构造 OR 组删除 alice/bob 的所有策略

orGroup := NewFilterGroup(LOGIC_OR)
orGroup.AddGroup(NewFilterGroup(LOGIC_AND).AddFilter(NewEqFilter("v0","alice")).AddFilter(NewEqFilter("p_type","p")))
orGroup.AddGroup(NewFilterGroup(LOGIC_AND).AddFilter(NewEqFilter("v0","bob")).AddFilter(NewEqFilter("p_type","p")))
repo.DeleteByFilterGroup(ctx, orGroup)

func (*BaseRepository[T]) DeleteByFilterGroupWithCount

func (r *BaseRepository[T]) DeleteByFilterGroupWithCount(ctx context.Context, group *FilterGroup) (int64, error)

DeleteByFilterGroupWithCount 按 FilterGroup 删除记录并返回删除数量 先 COUNT 再 DELETE,避免全表扫描;语义与 DeleteByFiltersWithCount 对齐

func (*BaseRepository[T]) DeleteByFilters

func (r *BaseRepository[T]) DeleteByFilters(ctx context.Context, filters ...*Filter) error

DeleteByFilters 按过滤条件删除记录

func (*BaseRepository[T]) DeleteByFiltersWithCount

func (r *BaseRepository[T]) DeleteByFiltersWithCount(ctx context.Context, filters ...*Filter) (int64, error)

DeleteByFiltersWithCount 按过滤条件删除记录并返回删除数量 这是一个高效的方法,先COUNT再DELETE,避免查询所有记录

func (*BaseRepository[T]) DeleteByQuery

func (r *BaseRepository[T]) DeleteByQuery(ctx context.Context, query *Query) error

DeleteByQuery 按 Query 过滤条件删除记录

func (*BaseRepository[T]) DeleteWhere

func (r *BaseRepository[T]) DeleteWhere(ctx context.Context, args ...interface{}) error

DeleteWhere 简化的条件删除 示例: DeleteWhere(ctx, "status", "inactive")

func (*BaseRepository[T]) DeleteWhereOp

func (r *BaseRepository[T]) DeleteWhereOp(ctx context.Context, args ...interface{}) error

DeleteWhereOp 带操作符的条件删除 示例: DeleteWhereOp(ctx, "age", constants.OP_LT, 18)

func (*BaseRepository[T]) DeleteWhereOpWithCount

func (r *BaseRepository[T]) DeleteWhereOpWithCount(ctx context.Context, args ...interface{}) (int64, error)

DeleteWhereOpWithCount 带操作符的条件删除并返回删除数量 示例: DeleteWhereOpWithCount(ctx, "age", constants.OP_LT, 18)

func (*BaseRepository[T]) DisableAutoFields

func (r *BaseRepository[T]) DisableAutoFields()

DisableAutoFields 禁用自动字段模式

func (*BaseRepository[T]) DisableDesensitize

func (r *BaseRepository[T]) DisableDesensitize()

DisableDesensitize 禁用仓储级脱敏

func (*BaseRepository[T]) Distinct

func (r *BaseRepository[T]) Distinct(ctx context.Context, field string, filters ...*Filter) ([]interface{}, error)

Distinct 获取去重后的字段值列表

func (*BaseRepository[T]) EnableAutoFields

func (r *BaseRepository[T]) EnableAutoFields()

EnableAutoFields 启用自动字段模式

func (*BaseRepository[T]) EnableDesensitize

func (r *BaseRepository[T]) EnableDesensitize()

EnableDesensitize 启用仓储级脱敏

func (*BaseRepository[T]) ExecuteConcurrentQueries

func (r *BaseRepository[T]) ExecuteConcurrentQueries(
	ctx context.Context,
	tasks []ConcurrentQueryTask[int64],
	opts ...ConcurrentQueryOption,
) ([]ConcurrentQueryResult[int64], bool)

ExecuteConcurrentQueries 执行并发查询任务 这是一个便捷方法,直接在 repository 上执行并发查询

func (*BaseRepository[T]) Exists

func (r *BaseRepository[T]) Exists(ctx context.Context, filters ...*Filter) (bool, error)

Exists 检查记录是否存在

func (*BaseRepository[T]) ExistsByField

func (r *BaseRepository[T]) ExistsByField(ctx context.Context, field string, value interface{}, excludeField string, excludeValue interface{}) (bool, error)

ExistsByField 检查字段值是否已被占用(唯一性检查) excludeField 为空时不排除任何记录;非空时额外排除 excludeField = excludeValue 的记录(编辑场景排除自身)

r.ExistsByField(ctx, "code", req.Code, "id", req.Id)

func (*BaseRepository[T]) ExistsByFilterGroup

func (r *BaseRepository[T]) ExistsByFilterGroup(ctx context.Context, group *FilterGroup) (bool, error)

ExistsByFilterGroup 按 FilterGroup 检查记录是否存在 与 Exists(filters...) 对齐

func (*BaseRepository[T]) ExistsWhere

func (r *BaseRepository[T]) ExistsWhere(ctx context.Context, args ...interface{}) (bool, error)

ExistsWhere 简化的存在性检查 示例: ExistsWhere(ctx, "email", "user@example.com")

func (*BaseRepository[T]) Find

func (r *BaseRepository[T]) Find(ctx context.Context, options *FindOptions) ([]*T, error)

Find 通用查询方法,兼容旧的API调用方式

func (*BaseRepository[T]) FindOne

func (r *BaseRepository[T]) FindOne(ctx context.Context, filters ...*Filter) (*T, error)

FindOne 查找单条记录(不存在返回 nil)

func (*BaseRepository[T]) FindOneWhere

func (r *BaseRepository[T]) FindOneWhere(ctx context.Context, args ...interface{}) (*T, error)

FindOneWhere 简化的单条查询 示例: FindOneWhere(ctx, "email", "user@example.com")

func (*BaseRepository[T]) FindOneWhereOp

func (r *BaseRepository[T]) FindOneWhereOp(ctx context.Context, args ...interface{}) (*T, error)

FindOneWhereOp 带操作符的单条查询 示例: FindOneWhereOp(ctx, "age", constants.OP_GT, 18)

func (*BaseRepository[T]) FindWhere

func (r *BaseRepository[T]) FindWhere(ctx context.Context, args ...interface{}) ([]*T, error)

FindWhere 简化的条件查询(接受字段名和值) 示例: FindWhere(ctx, "status", "active", "age", 18)

func (*BaseRepository[T]) FindWhereOp

func (r *BaseRepository[T]) FindWhereOp(ctx context.Context, args ...interface{}) ([]*T, error)

FindWhereOp 带操作符的条件查询 示例: FindWhereOp(ctx, "age", constants.OP_GT, 18, "status", constants.OP_EQ, "active")

func (*BaseRepository[T]) First

func (r *BaseRepository[T]) First(ctx context.Context, filters ...*Filter) (*T, error)

First 获取第一条记录

func (*BaseRepository[T]) FirstWithQuery

func (r *BaseRepository[T]) FirstWithQuery(ctx context.Context, query *Query) (*T, error)

FirstWithQuery 根据 Query 查询第一条记录

func (*BaseRepository[T]) Get

func (r *BaseRepository[T]) Get(ctx context.Context, id interface{}) (*T, error)

Get 获取单个记录

func (*BaseRepository[T]) GetAll

func (r *BaseRepository[T]) GetAll(ctx context.Context) ([]*T, error)

GetAll 获取所有记录(不分页)

func (*BaseRepository[T]) GetByField

func (r *BaseRepository[T]) GetByField(ctx context.Context, field string, value interface{}) (*T, error)

GetByField 根据单个字段获取记录(等值匹配)

func (*BaseRepository[T]) GetByFields

func (r *BaseRepository[T]) GetByFields(ctx context.Context, fields map[string]interface{}) (*T, error)

GetByFields 根据多个字段获取记录

func (*BaseRepository[T]) GetByFilter

func (r *BaseRepository[T]) GetByFilter(ctx context.Context, filter *Filter) (*T, error)

GetByFilter 按单个过滤条件获取记录

func (*BaseRepository[T]) GetByFilters

func (r *BaseRepository[T]) GetByFilters(ctx context.Context, filters ...*Filter) (*T, error)

GetByFilters 按多个过滤条件获取记录

func (*BaseRepository[T]) GetDialect

func (r *BaseRepository[T]) GetDialect() Dialect

GetDialect 获取当前数据库方言(基于 db handler 自动检测,结果不做缓存)

func (*BaseRepository[T]) GetModelFields

func (r *BaseRepository[T]) GetModelFields() []string

GetModelFields 获取缓存的模型字段

func (*BaseRepository[T]) GetNonPhysicalFields

func (r *BaseRepository[T]) GetNonPhysicalFields() []string

GetNonPhysicalFields 获取缓存的非物理列字段名(gorm:"-:migration" 标记的字段)

func (*BaseRepository[T]) GetRandom

func (r *BaseRepository[T]) GetRandom(ctx context.Context, query *Query) (*T, error)

GetRandom 随机获取一条记录(方言感知,一次 SQL 完成) query 可附加业务排序(如 usage_count ASC)与过滤条件,方言随机排序表达式会追加到 ORDER BY 末尾, 实现"按业务字段优先 + 随机打散"的选取(例如负载均衡场景下的最小计数随机) 无匹配记录时返回 gorm.ErrRecordNotFound

func (*BaseRepository[T]) GetSortableFields

func (r *BaseRepository[T]) GetSortableFields() []string

GetSortableFields 获取模型可排序字段(排除 JSON 类型),带缓存 用于 ApplySort 自动构建白名单,避免每个仓库手写字段列表

func (*BaseRepository[T]) GetWithPreloads

func (r *BaseRepository[T]) GetWithPreloads(ctx context.Context, id interface{}, preloads ...string) (*T, error)

GetWithPreloads 获取单个记录并指定预加载关联

func (*BaseRepository[T]) IsAutoFieldsEnabled

func (r *BaseRepository[T]) IsAutoFieldsEnabled() bool

IsAutoFieldsEnabled 检查是否启用自动字段模式

func (*BaseRepository[T]) IsDesensitizeEnabled

func (r *BaseRepository[T]) IsDesensitizeEnabled() bool

IsDesensitizeEnabled 检查仓储是否启用了脱敏

func (*BaseRepository[T]) JsonArrayCountComputedField

func (r *BaseRepository[T]) JsonArrayCountComputedField(table, jsonColumn, valueColumn, alias string) ComputedField

JsonArrayCountComputedField 构建 JSON 数组包含计数的 ComputedField(自动检测方言) 便捷封装,供 Repository 直接调用 AddComputedField

func (*BaseRepository[T]) Last

func (r *BaseRepository[T]) Last(ctx context.Context, filters ...*Filter) (*T, error)

Last 获取最后一条记录

func (*BaseRepository[T]) List

func (r *BaseRepository[T]) List(ctx context.Context, query *Query) ([]*T, error)

List 列表查询

func (*BaseRepository[T]) ListByIDs

func (r *BaseRepository[T]) ListByIDs(ctx context.Context, ids interface{}) ([]*T, error)

ListByIDs 根据主键 ID 列表查询(按 id 升序) ids 支持 []int64 / []string 等任意切片类型;空列表直接返回空结果,不发起 SQL

func (*BaseRepository[T]) ListWithPagination

func (r *BaseRepository[T]) ListWithPagination(ctx context.Context, query *Query, page ...*Pagination) ([]*T, *Pagination, error)

ListWithPagination 分页列表查询 page 可选,不传时优先使用 query.Pagination;若 query 也无分页,则使用默认值

func (*BaseRepository[T]) ListWithPagination32

func (r *BaseRepository[T]) ListWithPagination32(ctx context.Context, query *Query, page ...*Pagination32) ([]*T, *Pagination32, error)

ListWithPagination32 分页列表查询(int32 版本,用于一般场景)

func (*BaseRepository[T]) ListWithPagination64

func (r *BaseRepository[T]) ListWithPagination64(ctx context.Context, query *Query, page ...*Pagination64) ([]*T, *Pagination64, error)

ListWithPagination64 分页列表查询(int64 版本,用于需要大数值的场景)

func (*BaseRepository[T]) ListWithPreloads

func (r *BaseRepository[T]) ListWithPreloads(ctx context.Context, query *Query, preloads ...string) ([]*T, error)

ListWithPreloads 列表查询并指定预加载关联

func (*BaseRepository[T]) NewJsonArrayContainsFilter

func (r *BaseRepository[T]) NewJsonArrayContainsFilter(column string, value interface{}) (string, []interface{})

NewJsonArrayContainsFilter 构建 JSON 数组包含查询的 WHERE 表达式与参数(自动检测方言) 返回 sql 表达式与 args,调用方可用 db.Where(sql, args...) 拼接

func (*BaseRepository[T]) Paginate

func (r *BaseRepository[T]) Paginate(ctx context.Context, page, pageSize int, args ...interface{}) ([]*T, *Pagination, error)

Paginate 简化的分页查询(只需传页码和每页数量) 示例: Paginate(ctx, 1, 20, "status", "active")

func (*BaseRepository[T]) PaginateOp

func (r *BaseRepository[T]) PaginateOp(ctx context.Context, page, pageSize int, args ...interface{}) ([]*T, *Pagination, error)

PaginateOp 带操作符的分页查询 示例: PaginateOp(ctx, 1, 20, "age", constants.OP_GT, 18)

func (*BaseRepository[T]) Pluck

func (r *BaseRepository[T]) Pluck(ctx context.Context, field string, filters ...*Filter) ([]interface{}, error)

Pluck 提取单个字段的值列表

func (*BaseRepository[T]) Restore

func (r *BaseRepository[T]) Restore(ctx context.Context, id interface{}, field string, restoreValue interface{}) error

Restore 恢复软删除的记录 field: 软删除字段名,如 "deleted_at", "is_deleted" 等 restoreValue: 恢复时的值,如 nil, 0 等

func (*BaseRepository[T]) RestoreBatch

func (r *BaseRepository[T]) RestoreBatch(ctx context.Context, ids []interface{}, field string, restoreValue interface{}) error

RestoreBatch 批量恢复软删除的记录 field: 软删除字段名,如 "deleted_at", "is_deleted" 等 restoreValue: 恢复时的值,如 nil, 0 等

func (*BaseRepository[T]) Save

func (r *BaseRepository[T]) Save(ctx context.Context, entity *T) (*T, error)

Save 智能保存:自动判断是创建还是更新 如果实体有主键值则更新,否则创建

func (*BaseRepository[T]) SoftDelete

func (r *BaseRepository[T]) SoftDelete(ctx context.Context, id interface{}, field string, value interface{}) error

SoftDelete 软删除(需要指定删除标记字段和值) field: 软删除字段名,如 "deleted_at", "is_deleted" 等 value: 软删除标记值,如 time.Now(), 1 等

func (*BaseRepository[T]) SoftDeleteBatch

func (r *BaseRepository[T]) SoftDeleteBatch(ctx context.Context, ids []interface{}, field string, value interface{}) error

SoftDeleteBatch 批量软删除 field: 软删除字段名,如 "deleted_at", "is_deleted" 等 value: 软删除标记值,如 time.Now(), 1 等

func (*BaseRepository[T]) SoftDeleteByFilters

func (r *BaseRepository[T]) SoftDeleteByFilters(ctx context.Context, field string, value interface{}, filters ...*Filter) error

SoftDeleteByFilters 按过滤条件软删除 field: 软删除字段名,如 "deleted_at", "is_deleted" 等 value: 软删除标记值,如 time.Now(), 1 等

func (*BaseRepository[T]) Table

func (r *BaseRepository[T]) Table() string

Table 获取表名

func (*BaseRepository[T]) Transaction

func (r *BaseRepository[T]) Transaction(ctx context.Context, fn func(tx Transaction[T]) error) error

Transaction 事务支持

func (*BaseRepository[T]) TransactionWithRawDB

func (r *BaseRepository[T]) TransactionWithRawDB(ctx context.Context, fn func(tx *gorm.DB) error) error

TransactionWithRawDB 通用事务支持(可以操作任意模型)

func (*BaseRepository[T]) Update

func (r *BaseRepository[T]) Update(ctx context.Context, entity *T) (*T, error)

Update 更新单个记录

func (*BaseRepository[T]) UpdateBatch

func (r *BaseRepository[T]) UpdateBatch(ctx context.Context, entities ...*T) error

UpdateBatch 批量更新记录

func (*BaseRepository[T]) UpdateByFilters

func (r *BaseRepository[T]) UpdateByFilters(ctx context.Context, entity *T, filters ...*Filter) error

UpdateByFilters 按过滤条件更新记录

func (*BaseRepository[T]) UpdateFields

func (r *BaseRepository[T]) UpdateFields(ctx context.Context, id interface{}, fields map[string]interface{}) error

UpdateFields 更新指定字段

func (*BaseRepository[T]) UpdateFieldsByFilterGroup

func (r *BaseRepository[T]) UpdateFieldsByFilterGroup(ctx context.Context, fields map[string]interface{}, group *FilterGroup) error

UpdateFieldsByFilterGroup 按 FilterGroup 更新指定字段 支持 OR 复合条件,可将多组 AND 条件合并为单条 UPDATE,N 次 IO 降为 1 次 典型场景:批量更新多条策略,每条策略由 (p_type=? AND v0=? AND ...) 精确匹配定位 与 UpdateFieldsByFilters 对齐,区别仅在于过滤条件改为支持 OR 的 FilterGroup

func (*BaseRepository[T]) UpdateFieldsByFilters

func (r *BaseRepository[T]) UpdateFieldsByFilters(ctx context.Context, fields map[string]interface{}, filters ...*Filter) error

UpdateFieldsByFilters 按过滤条件更新指定字段

func (*BaseRepository[T]) UpdateFieldsByFiltersWithVersion

func (r *BaseRepository[T]) UpdateFieldsByFiltersWithVersion(ctx context.Context, fields map[string]interface{}, currentVersion int64, filters ...*Filter) (bool, error)

UpdateFieldsByFiltersWithVersion 按 Filter 定位并带乐观锁更新指定字段 与 UpdateFieldsWithOptimisticLock 对齐,区别在于定位条件由 id 列改为任意 Filter 组合, 适用于主键不是 id 列的模型(如 agent_line_id / config_id 业务主键) CAS: WHERE <filters> AND version = ? SET ... version = version + 1 返回是否更新成功(false = 版本冲突或记录不存在,由调用方映射乐观锁错误码)

func (*BaseRepository[T]) UpdateFieldsByQuery

func (r *BaseRepository[T]) UpdateFieldsByQuery(ctx context.Context, fields map[string]interface{}, query *Query) error

UpdateFieldsByQuery 按 Query 过滤条件更新指定字段

func (*BaseRepository[T]) UpdateFieldsWithOptimisticLock

func (r *BaseRepository[T]) UpdateFieldsWithOptimisticLock(ctx context.Context, id interface{}, currentVersion int64, fields map[string]interface{}) (bool, error)

UpdateFieldsWithOptimisticLock 乐观锁更新指定字段 WHERE id = ? AND version = ?,version 原子递增(不污染调用方传入的 fields,内部拷贝) 返回是否更新成功(false = 版本冲突或记录不存在,由调用方映射乐观锁错误码)

func (*BaseRepository[T]) UpdateWhere

func (r *BaseRepository[T]) UpdateWhere(ctx context.Context, updates map[string]interface{}, args ...interface{}) error

UpdateWhere 简化的条件更新 示例: UpdateWhere(ctx, map[string]interface{}{"status": "active"}, "id", 1)

func (*BaseRepository[T]) UpdateWhereOp

func (r *BaseRepository[T]) UpdateWhereOp(ctx context.Context, updates map[string]interface{}, args ...interface{}) error

UpdateWhereOp 带操作符的条件更新 示例: UpdateWhereOp(ctx, map[string]interface{}{"status": "active"}, "age", constants.OP_GT, 18)

type ClickHouseDialect

type ClickHouseDialect struct{}

ClickHouseDialect ClickHouse 方言

func (*ClickHouseDialect) FormatTimeGroup

func (d *ClickHouseDialect) FormatTimeGroup(field string, groupType TimeGroupType) string

func (*ClickHouseDialect) JsonArrayAppend

func (d *ClickHouseDialect) JsonArrayAppend(column, placeholder string) string

JsonArrayAppend ClickHouse: arrayPushBack(ClickHouse 推荐用 Array 类型而非 JSON)

func (*ClickHouseDialect) JsonArrayContains

func (d *ClickHouseDialect) JsonArrayContains(column, placeholder string) string

JsonArrayContains ClickHouse: 用 hasAny(CAST(column AS Array(String)), [?]) ClickHouse 推荐用 Array 类型而非 JSON,此处提供兼容实现

func (*ClickHouseDialect) JsonArrayCountSubQuery

func (d *ClickHouseDialect) JsonArrayCountSubQuery(table, jsonColumn, valueColumn string) string

JsonArrayCountSubQuery ClickHouse: 用 hasAny 计数

func (*ClickHouseDialect) JsonFieldExtract

func (d *ClickHouseDialect) JsonFieldExtract(column, jsonKey string) string

JsonFieldExtract ClickHouse: JSONExtractString(column, 'key')

func (*ClickHouseDialect) RandomOrderExpr

func (d *ClickHouseDialect) RandomOrderExpr() string

RandomOrderExpr ClickHouse: rand()

func (*ClickHouseDialect) UpsertColumnRef

func (d *ClickHouseDialect) UpsertColumnRef(column string) string

UpsertColumnRef ClickHouse: excluded.column ClickHouse 无标准 UPSERT 语法,此处提供兼容占位实现,与 SQLite/PostgreSQL 保持一致

type CockroachDBDialect

type CockroachDBDialect struct{}

CockroachDBDialect CockroachDB 方言(兼容PostgreSQL语法)

func (*CockroachDBDialect) FormatTimeGroup

func (d *CockroachDBDialect) FormatTimeGroup(field string, groupType TimeGroupType) string

func (*CockroachDBDialect) JsonArrayAppend

func (d *CockroachDBDialect) JsonArrayAppend(column, placeholder string) string

JsonArrayAppend CockroachDB: 兼容 PostgreSQL 的 COALESCE + || + ::jsonb

func (*CockroachDBDialect) JsonArrayContains

func (d *CockroachDBDialect) JsonArrayContains(column, placeholder string) string

JsonArrayContains CockroachDB: 兼容 PostgreSQL 的 @> 操作符,配合 inverted index 可高效查询

func (*CockroachDBDialect) JsonArrayCountSubQuery

func (d *CockroachDBDialect) JsonArrayCountSubQuery(table, jsonColumn, valueColumn string) string

JsonArrayCountSubQuery CockroachDB: 同 PostgreSQL,用 @> + CAST

func (*CockroachDBDialect) JsonFieldExtract

func (d *CockroachDBDialect) JsonFieldExtract(column, jsonKey string) string

JsonFieldExtract CockroachDB: 兼容 PostgreSQL 的 ->> 操作符

func (*CockroachDBDialect) RandomOrderExpr

func (d *CockroachDBDialect) RandomOrderExpr() string

RandomOrderExpr CockroachDB: RANDOM()

func (*CockroachDBDialect) UpsertColumnRef

func (d *CockroachDBDialect) UpsertColumnRef(column string) string

UpsertColumnRef CockroachDB: excluded.column(兼容 PostgreSQL 语法)

type ComparedColumn

type ComparedColumn struct {
	TableAlias  string
	ColumnName  string
	DBFieldName string
}

type ComparedValue

type ComparedValue struct {
	Value interface{}
	IsRaw bool
}

type ComputedField

type ComputedField struct {
	// Expr SQL 表达式,如 "(SELECT COUNT(*) FROM game_libraries WHERE brand_id = game_brands.id)"
	Expr string
	// Alias 结果列别名,如 "linked_game_count"
	// 需匹配主模型 struct 的 gorm column tag
	// 为空则直接用 Expr,不做 AS
	Alias string
}

ComputedField 计算字段:SELECT 中的派生表达式(如子查询聚合)

用于在查询时动态计算派生值,无需维护冗余列。 当 Alias 与主表物理列同名时,后出现的计算列会覆盖主表列的值(GORM 行为)。

用法:

q.AddComputedField("(SELECT COUNT(*) FROM game_libraries WHERE brand_id = game_brands.id)", "linked_game_count")

func JsonArrayCountComputedField

func JsonArrayCountComputedField(dialect Dialect, table, jsonColumn, valueColumn, alias string) ComputedField

JsonArrayCountComputedField 构建 JSON 数组包含计数的 ComputedField(用于 SELECT 派生列)

计算 table 表中 jsonColumn 包含 valueColumn 值的记录数,结果以 alias 命名 典型场景:payment_channels 列表动态计算 linked_method_count(payment_methods.channel_ids 包含该渠道 id 的数量)

参数:

dialect     数据库方言
table       被统计的表名(如 "payment_methods")
jsonColumn  被统计表的 JSON 数组列(如 "channel_ids")
valueColumn 外部主表的列引用(如 "payment_channels.id",须含表名前缀避免歧义)
alias       结果列别名(须匹配主模型 gorm column tag,如 "linked_method_count")

用法:

q.AddComputedField(JsonArrayCountComputedField(dialect, "payment_methods", "channel_ids", "payment_channels.id", "linked_method_count"))

type ConcurrentQueryBuilder

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

ConcurrentQueryBuilder 简单查询构建器:用于构建标准 COUNT/SUM 查询

func NewConcurrentQueryBuilder

func NewConcurrentQueryBuilder(db *gorm.DB, tableName, selectSQL string) *ConcurrentQueryBuilder

NewConcurrentQueryBuilder 创建简单查询构建器

func (*ConcurrentQueryBuilder) Build

func (b *ConcurrentQueryBuilder) Build() func(ctx context.Context) (int64, error)

Build 构建查询函数

func (*ConcurrentQueryBuilder) BuildWithTimeRange

func (b *ConcurrentQueryBuilder) BuildWithTimeRange(startTime, endTime time.Time) func(ctx context.Context) (int64, error)

BuildWithTimeRange 构建带时间范围的查询函数(快捷方法)

func (*ConcurrentQueryBuilder) Where

func (b *ConcurrentQueryBuilder) Where(condition string, args ...interface{}) *ConcurrentQueryBuilder

Where 添加 WHERE 条件

type ConcurrentQueryExecutor

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

ConcurrentQueryExecutor 并发查询执行器

func NewConcurrentQueryExecutor

func NewConcurrentQueryExecutor(db *gorm.DB) *ConcurrentQueryExecutor

NewConcurrentQueryExecutor 创建并发查询执行器

func (*ConcurrentQueryExecutor) WithLogger

WithLogger 设置日志记录器(链式调用)

func (*ConcurrentQueryExecutor) WithTimeout

WithTimeout 设置查询超时时间(链式调用)

func (*ConcurrentQueryExecutor) WithWorkers

func (e *ConcurrentQueryExecutor) WithWorkers(workers int) *ConcurrentQueryExecutor

WithWorkers 设置工作协程数(链式调用,自动限制在 1-MaxWorkers 范围内)

type ConcurrentQueryOption

type ConcurrentQueryOption func(*ConcurrentQueryExecutor)

ConcurrentQueryOption 并发查询配置选项

func WithQueryTimeout

func WithQueryTimeout(timeout time.Duration) ConcurrentQueryOption

WithQueryTimeout 设置查询超时时间

func WithQueryWorkers

func WithQueryWorkers(workers int) ConcurrentQueryOption

WithQueryWorkers 设置工作协程数

type ConcurrentQueryResult

type ConcurrentQueryResult[T any] struct {
	Name  string // 任务名称
	Value T      // 查询结果值
	Error error  // 错误信息(如果有)
}

ConcurrentQueryResult 查询结果

func ExecuteConcurrentQueries

func ExecuteConcurrentQueries[T any](
	ctx context.Context,
	db *gorm.DB,
	log logger.ILogger,
	tasks []ConcurrentQueryTask[T],
	opts ...ConcurrentQueryOption,
) ([]ConcurrentQueryResult[T], bool)

ExecuteConcurrentQueries 全局便捷函数:执行并发查询

func ExecuteConcurrentQuery

func ExecuteConcurrentQuery[T any](e *ConcurrentQueryExecutor, ctx context.Context, tasks []ConcurrentQueryTask[T]) ([]ConcurrentQueryResult[T], bool)

ExecuteConcurrentQuery 执行并发查询任务(支持任务数限制) tasks: 查询任务列表 返回: 所有查询结果和是否有错误发生

type ConcurrentQueryTask

type ConcurrentQueryTask[T any] struct {
	Name      string                               // 任务名称(用于日志和错误追踪)
	Query     func(ctx context.Context) (T, error) // 查询执行函数
	OnSuccess func(T)                              // 成功回调(可选)
	OnError   func(error)                          // 错误回调(可选)
}

ConcurrentQueryTask 泛型查询任务定义 T: 查询结果的类型(支持任意类型:int64, float64, struct, []struct 等)

type Condition

type Condition struct {
	Field string
	Op    constants.Operator
	Value interface{}
}

Condition 查询条件结构

type ConditionalAggregateBuilder

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

ConditionalAggregateBuilder 条件聚合构建器 用于构建复杂的 SUM(CASE WHEN ...) 查询

func NewConditionalAggregateBuilder

func NewConditionalAggregateBuilder(db *gorm.DB, tableName string) *ConditionalAggregateBuilder

NewConditionalAggregateBuilder 创建条件聚合构建器

func (*ConditionalAggregateBuilder) AvgWhen

func (b *ConditionalAggregateBuilder) AvgWhen(condition, field string, alias string, args ...interface{}) *ConditionalAggregateBuilder

AvgWhen 添加 AVG(CASE WHEN condition THEN field ELSE NULL END)

func (*ConditionalAggregateBuilder) Build

func (b *ConditionalAggregateBuilder) Build() (*gorm.DB, []interface{})

Build 构建 SQL 查询

func (*ConditionalAggregateBuilder) CountWhen

func (b *ConditionalAggregateBuilder) CountWhen(condition string, alias string, args ...interface{}) *ConditionalAggregateBuilder

CountWhen 添加 COUNT(CASE WHEN condition THEN 1 ELSE NULL END)

func (*ConditionalAggregateBuilder) Execute

func (b *ConditionalAggregateBuilder) Execute(ctx context.Context) (map[string]interface{}, error)

Execute 执行查询并返回单行结果(map)

func (*ConditionalAggregateBuilder) ExecuteInto

func (b *ConditionalAggregateBuilder) ExecuteInto(ctx context.Context, dest interface{}) error

ExecuteInto 执行查询并扫描到结构体

func (*ConditionalAggregateBuilder) ExecuteList

func (b *ConditionalAggregateBuilder) ExecuteList(ctx context.Context) ([]map[string]interface{}, error)

ExecuteList 执行查询并返回多行结果(用于 GROUP BY)

func (*ConditionalAggregateBuilder) GroupBy

GroupBy 添加分组字段

func (*ConditionalAggregateBuilder) Having

func (b *ConditionalAggregateBuilder) Having(condition string, args ...interface{}) *ConditionalAggregateBuilder

Having 添加 HAVING 条件

func (*ConditionalAggregateBuilder) Limit

Limit 设置限制

func (*ConditionalAggregateBuilder) MaxWhen

func (b *ConditionalAggregateBuilder) MaxWhen(condition, field string, alias string, args ...interface{}) *ConditionalAggregateBuilder

MaxWhen 添加 MAX(CASE WHEN condition THEN field ELSE NULL END)

func (*ConditionalAggregateBuilder) MinWhen

func (b *ConditionalAggregateBuilder) MinWhen(condition, field string, alias string, args ...interface{}) *ConditionalAggregateBuilder

MinWhen 添加 MIN(CASE WHEN condition THEN field ELSE NULL END)

func (*ConditionalAggregateBuilder) OrderBy

OrderBy 设置排序

func (*ConditionalAggregateBuilder) SumWhen

func (b *ConditionalAggregateBuilder) SumWhen(condition string, alias string, args ...interface{}) *ConditionalAggregateBuilder

SumWhen 添加 SUM(CASE WHEN condition THEN 1 ELSE 0 END)

func (*ConditionalAggregateBuilder) WithTimeField

WithTimeField 设置时间字段

func (*ConditionalAggregateBuilder) WithTimeRange

func (b *ConditionalAggregateBuilder) WithTimeRange(start, end time.Time) *ConditionalAggregateBuilder

WithTimeRange 设置时间范围

type ContextFieldExtractor

type ContextFieldExtractor func(ctx context.Context, log logger.ILogger) logger.ILogger

ContextFieldExtractor context字段提取器函数类型 用于从context中提取需要记录到日志的字段

type Dialect

type Dialect interface {
	// FormatTimeGroup 格式化时间分组表达式
	FormatTimeGroup(field string, groupType TimeGroupType) string
	// JsonArrayContains 构建JSON数组包含查询的SQL表达式(WHERE 子句用)
	// placeholder 为参数占位符(如 "?"),返回的表达式应直接拼入WHERE,参数由调用方通过args传入
	//   MySQL:           JSON_CONTAINS(column, ?)
	//   PostgreSQL/CRDB: column @> ?::jsonb
	//   SQLite:          EXISTS(SELECT 1 FROM json_each(column) WHERE json_each.value = ?)
	JsonArrayContains(column, placeholder string) string
	// JsonArrayCountSubQuery 构建JSON数组包含计数子查询(用于 ComputedField / SELECT 派生列)
	// 计算 table 表中 jsonColumn 包含 valueColumn 值的记录数
	//   MySQL:           (SELECT COUNT(*) FROM table WHERE JSON_CONTAINS(jsonColumn, CAST(valueColumn AS JSON)))
	//   PostgreSQL/CRDB: (SELECT COUNT(*) FROM table WHERE jsonColumn @> CAST('[' || valueColumn::text || ']' AS JSONB))
	//   SQLite:          (SELECT COUNT(*) FROM table t2 WHERE EXISTS(SELECT 1 FROM json_each(t2.jsonColumn) WHERE json_each.value = table.valueColumn))
	JsonArrayCountSubQuery(table, jsonColumn, valueColumn string) string
	// JsonFieldExtract 构建JSON对象字段提取的SQL表达式(返回无引号字符串)
	// 用于从JSON列中提取指定键的值,可用于 WHERE 等值/LIKE 等比较
	//   MySQL:           JSON_UNQUOTE(JSON_EXTRACT(column, '$.key'))
	//   PostgreSQL/CRDB: column->>'key'
	//   SQLite:          json_extract(column, '$.key')
	JsonFieldExtract(column, jsonKey string) string
	// RandomOrderExpr 返回用于 ORDER BY 的随机排序表达式(无方向,直接拼入 ORDER BY)
	//   MySQL:           RAND()
	//   PostgreSQL/CRDB: RANDOM()
	//   SQLite:          RANDOM()
	//   ClickHouse:      rand()
	RandomOrderExpr() string
	// UpsertColumnRef 返回 UPSERT 场景下引用"待插入行"中指定列值的 SQL 表达式
	// 用于 INSERT ... ON CONFLICT/ON DUPLICATE KEY UPDATE 的赋值子句,引用新插入行的列值
	//   MySQL:           VALUES(column)
	//   SQLite:          excluded.column
	//   PostgreSQL/CRDB: excluded.column
	//   ClickHouse:      excluded.column(ClickHouse 无标准 UPSERT,此为兼容占位)
	UpsertColumnRef(column string) string
	// JsonArrayAppend 构建向 JSON 数组列追加元素的 SQL 表达式(UPDATE SET 赋值用)
	// column 为 JSON 数组列名,placeholder 为待追加 JSON 元素的参数占位符(如 "?")
	// 当列为 NULL 时初始化为空数组再追加
	//   MySQL:           JSON_ARRAY_APPEND(IFNULL(column, JSON_ARRAY()), '$', CAST(placeholder AS JSON))
	//   SQLite:          json_insert(IFNULL(column, json_array()), '$[#]', json(placeholder))
	//   PostgreSQL/CRDB: COALESCE(column::jsonb, '[]'::jsonb) || placeholder::jsonb
	//   ClickHouse:      arrayPushBack(CAST(column AS Array(String)), toString(placeholder))
	JsonArrayAppend(column, placeholder string) string
}

Dialect 数据库方言接口

func DetectDialect

func DetectDialect(db *gorm.DB) Dialect

DetectDialect 自动检测数据库方言

type EnhancedRepository

type EnhancedRepository[T any] struct {
	*BaseRepository[T]
	// contains filtered or unexported fields
}

EnhancedRepository 增强版仓储实现

func NewEnhancedRepository

func NewEnhancedRepository[T any](dbHandler db.Handler, logger gologger.ILogger, tableName string) *EnhancedRepository[T]

NewEnhancedRepository 创建增强版仓储实例

func NewEnhancedRepositoryWithDB

func NewEnhancedRepositoryWithDB[T any](gormDB *gorm.DB, logger gologger.ILogger, tableName string) *EnhancedRepository[T]

NewEnhancedRepositoryWithDB 使用GORM DB直接创建增强版仓储

func (*EnhancedRepository[T]) BatchUpdateByField

func (r *EnhancedRepository[T]) BatchUpdateByField(ctx context.Context, field string, values []interface{}, updates map[string]interface{}) error

BatchUpdateByField 根据字段批量更新

func (*EnhancedRepository[T]) CountByField

func (r *EnhancedRepository[T]) CountByField(ctx context.Context, field string, value interface{}) (int64, error)

CountByField 根据字段统计数量

func (*EnhancedRepository[T]) CreateIfNotExists

func (r *EnhancedRepository[T]) CreateIfNotExists(ctx context.Context, entity *T, checkField string) (*T, bool, error)

CreateIfNotExists 如果不存在则创建

func (*EnhancedRepository[T]) DecrementField

func (r *EnhancedRepository[T]) DecrementField(ctx context.Context, whereField string, whereValue interface{}, decrementField string, step int64) error

DecrementField 字段自减

func (*EnhancedRepository[T]) DeleteByField

func (r *EnhancedRepository[T]) DeleteByField(ctx context.Context, field string, value interface{}) error

DeleteByField 根据字段删除记录

func (*EnhancedRepository[T]) ExistsBy

func (r *EnhancedRepository[T]) ExistsBy(ctx context.Context, field string, value interface{}) (bool, error)

ExistsBy 检查记录是否存在

func (*EnhancedRepository[T]) FindByField

func (r *EnhancedRepository[T]) FindByField(ctx context.Context, field string, value interface{}) ([]*T, error)

FindByField 根据单个字段查找记录

func (*EnhancedRepository[T]) FindByFieldWithCursor

func (r *EnhancedRepository[T]) FindByFieldWithCursor(ctx context.Context, field string, value interface{}, cursorField string, lastCursor interface{}, limit int) ([]*T, bool, error)

FindByFieldWithCursor 根据字段查找记录(游标分页)

func (*EnhancedRepository[T]) FindByFieldWithPagination

func (r *EnhancedRepository[T]) FindByFieldWithPagination(ctx context.Context, field string, value interface{}, limit, offset int) ([]*T, int64, error)

FindByFieldWithPagination 根据字段查找记录(带分页)

func (*EnhancedRepository[T]) FindByFields

func (r *EnhancedRepository[T]) FindByFields(ctx context.Context, conditions map[string]interface{}) ([]*T, error)

FindByFields 根据多个字段查找记录

func (*EnhancedRepository[T]) FindByTimeRange

func (r *EnhancedRepository[T]) FindByTimeRange(ctx context.Context, timeField string, startTime, endTime interface{}) ([]*T, error)

FindByTimeRange 根据时间范围查找

func (*EnhancedRepository[T]) FindInField

func (r *EnhancedRepository[T]) FindInField(ctx context.Context, field string, values []interface{}) ([]*T, error)

FindInField 根据字段的IN查询

func (*EnhancedRepository[T]) FindOneByField

func (r *EnhancedRepository[T]) FindOneByField(ctx context.Context, field string, value interface{}) (*T, error)

FindOneByField 根据单个字段查找单条记录

func (*EnhancedRepository[T]) FindWithOrder

func (r *EnhancedRepository[T]) FindWithOrder(ctx context.Context, whereField string, whereValue interface{}, orderField string, orderDirection string) ([]*T, error)

FindWithOrder 根据条件查找并排序

func (*EnhancedRepository[T]) GetDistinctValues

func (r *EnhancedRepository[T]) GetDistinctValues(ctx context.Context, field string) ([]interface{}, error)

GetDistinctValues 获取字段的不同值

func (*EnhancedRepository[T]) IncrementField

func (r *EnhancedRepository[T]) IncrementField(ctx context.Context, whereField string, whereValue interface{}, incrementField string, step int64) error

IncrementField 字段自增

func (*EnhancedRepository[T]) UpdateByField

func (r *EnhancedRepository[T]) UpdateByField(ctx context.Context, field string, value interface{}, updates map[string]interface{}) error

UpdateByField 根据字段更新记录

func (*EnhancedRepository[T]) UpdateSingleField

func (r *EnhancedRepository[T]) UpdateSingleField(ctx context.Context, whereField string, whereValue interface{}, updateField string, updateValue interface{}) error

UpdateSingleField 更新单个字段

type Filter

type Filter struct {
	Field    string             // 字段名
	Operator constants.Operator // 操作符
	Value    interface{}        // 值(可以是普通值或 *SubQuery)
}

Filter 过滤条件

func NewBetweenFilter

func NewBetweenFilter(field string, min, max interface{}) *Filter

NewBetweenFilter 创建 BETWEEN 过滤条件

func NewContainsFilter

func NewContainsFilter(field string, value string) *Filter

NewContainsFilter 创建包含子串过滤条件,两侧各加一个通配符 与 NewLikeFilter 的差别在算子:NewLikeFilter 直接用 OP_LIKE, 本函数用 OP_CONTAINS,由条件编译阶段统一补通配符,调用方传原文即可

[EN] NewContainsFilter builds a substring match with a wildcard on both sides It differs from NewLikeFilter in the operator: OP_CONTAINS lets the condition compiler add the wildcards, so the caller passes the raw text

func NewEndsWithFilter

func NewEndsWithFilter(field string, value string) *Filter

NewEndsWithFilter 创建后缀匹配过滤条件

func NewEqFilter

func NewEqFilter(field string, value interface{}) *Filter

NewEqFilter 创建等于过滤条件

func NewFilter

func NewFilter(field string, operator constants.Operator, value interface{}) *Filter

NewFilter 创建通用过滤条件(支持任意操作符)

func NewFindInSetFilter

func NewFindInSetFilter(field string, value interface{}) *Filter

NewFindInSetFilter 创建 FIND_IN_SET 过滤条件(MySQL特定)

func NewGtFilter

func NewGtFilter(field string, value interface{}) *Filter

NewGtFilter 创建大于过滤条件

func NewGteFilter

func NewGteFilter(field string, value interface{}) *Filter

NewGteFilter 创建大于等于过滤条件

func NewILikeFilter

func NewILikeFilter(field string, value string) *Filter

NewILikeFilter 创建大小写不敏感 LIKE 过滤条件 跨数据库实现:LOWER(field) LIKE LOWER(?),兼容 PostgreSQL/MySQL/SQLite 等

func NewInFilter

func NewInFilter(field string, values ...interface{}) *Filter

NewInFilter 创建 IN 过滤条件 支持两种传参方式:

  1. 多个标量参数:NewInFilter("id", 1, 2, 3)
  2. 单个切片参数:NewInFilter("id", []int64{1, 2, 3})(自动展开,避免生成 IN ((...)) 双重括号)

func NewInFilterSlice

func NewInFilterSlice(field string, values []interface{}) *Filter

NewInFilterSlice 创建 IN 过滤条件(使用切片参数)

func NewInSubQueryFilter

func NewInSubQueryFilter(field, subSQL string, args ...interface{}) *Filter

NewInSubQueryFilter 创建 IN 子查询过滤条件:field IN (subSQL) subSQL 为子查询 SQL(含 ? 占位符),args 为子查询参数 示例: NewInSubQueryFilter("group_id", "SELECT id FROM dict_groups WHERE type IN (?)", types)

func NewIsNotNullFilter

func NewIsNotNullFilter(field string) *Filter

NewIsNotNullFilter 创建 IS NOT NULL 过滤条件

func NewIsNullFilter

func NewIsNullFilter(field string) *Filter

NewIsNullFilter 创建 IS NULL 过滤条件

func NewJsonArrayContainsFilter

func NewJsonArrayContainsFilter(field string, value interface{}) *Filter

NewJsonArrayContainsFilter 创建 JSON 数组包含过滤条件(方言感知) 用于查询 JSON 数组列是否包含指定值,SQL 表达式由各方言在 ApplyFilter 时生成:

MySQL:           JSON_CONTAINS(field, ?)
PostgreSQL/CRDB: field @> ?::jsonb
SQLite:          EXISTS(SELECT 1 FROM json_each(field) WHERE json_each.value = ?)

value 为待检查的标量值(int64/string 等),参数序列化由方言自动处理

func NewJsonFieldEqFilter

func NewJsonFieldEqFilter(column, jsonKey string, value interface{}) *Filter

NewJsonFieldEqFilter 创建 JSON 对象字段等值过滤条件(方言感知) 用于从 JSON 列中提取指定键的值并做等值比较,Field 编码为 "column:jsonKey" SQL 表达式由各方言在 ApplyFilter 时生成:

MySQL:           JSON_UNQUOTE(JSON_EXTRACT(column, '$.jsonKey')) = ?
PostgreSQL/CRDB: column->>'jsonKey' = ?
SQLite:          json_extract(column, '$.jsonKey') = ?

用法:NewJsonFieldEqFilter("app_params", "app_name", "MyApp")

func NewJsonbLikeFilter

func NewJsonbLikeFilter(field string, value string) *Filter

NewJsonbLikeFilter 创建 jsonb 字段文本搜索过滤条件(PostgreSQL: field::text LIKE ?) 用于对 jsonb 类型字段进行模糊搜索,自动将字段转为 text 后匹配

func NewLikeFilter

func NewLikeFilter(field string, value string) *Filter

NewLikeFilter 创建 LIKE 过滤条件

func NewLtFilter

func NewLtFilter(field string, value interface{}) *Filter

NewLtFilter 创建小于过滤条件

func NewLteFilter

func NewLteFilter(field string, value interface{}) *Filter

NewLteFilter 创建小于等于过滤条件

func NewNeqFilter

func NewNeqFilter(field string, value interface{}) *Filter

NewNeqFilter 创建不等于过滤条件

func NewNotBetweenFilter

func NewNotBetweenFilter(field string, min, max interface{}) *Filter

NewNotBetweenFilter 创建 NOT BETWEEN 过滤条件 [EN] NewNotBetweenFilter builds a NOT BETWEEN condition

func NewNotILikeFilter

func NewNotILikeFilter(field string, value string) *Filter

NewNotILikeFilter 创建大小写不敏感 NOT LIKE 过滤条件

func NewNotInFilter

func NewNotInFilter(field string, values ...interface{}) *Filter

NewNotInFilter 创建 NOT IN 过滤条件 支持两种传参方式:

  1. 多个标量参数:NewNotInFilter("id", 1, 2, 3)
  2. 单个切片参数:NewNotInFilter("id", []int64{1, 2, 3})(自动展开,避免生成 NOT IN ((...)) 双重括号)

func NewNotInFilterSlice

func NewNotInFilterSlice(field string, values []interface{}) *Filter

NewNotInFilterSlice 创建 NOT IN 过滤条件(使用切片参数)

func NewNotInSubQueryFilter

func NewNotInSubQueryFilter(field, subSQL string, args ...interface{}) *Filter

NewNotInSubQueryFilter 创建 NOT IN 子查询过滤条件:field NOT IN (subSQL) subSQL 为子查询 SQL(含 ? 占位符),args 为子查询参数 示例: NewNotInSubQueryFilter("group_id", "SELECT id FROM dict_groups WHERE type IN (?)", types)

func NewNotLikeFilter

func NewNotLikeFilter(field string, value string) *Filter

NewNotLikeFilter 创建 NOT LIKE 过滤条件

func NewRegexpFilter

func NewRegexpFilter(field string, pattern string) *Filter

NewRegexpFilter 创建正则匹配过滤条件(仅MySQL/PostgreSQL)

func NewStartsWithFilter

func NewStartsWithFilter(field string, value string) *Filter

NewStartsWithFilter 创建前缀匹配过滤条件

type FilterGroup

type FilterGroup struct {
	Filters []*Filter          // 过滤条件列表
	Groups  []*FilterGroup     // 嵌套条件组
	LogicOp constants.Operator // 逻辑操作符:AND/OR
}

FilterGroup 过滤条件组,支持逻辑操作

func FilterGroupByModel

func FilterGroupByModel(group *FilterGroup, model interface{}) *FilterGroup

FilterGroupByModel 模型感知地过滤 FilterGroup,移除模型中不存在的字段 用于在执行层(BaseRepository,已知泛型 T)自动剔除作用域注入但目标表不存在的列 (如 customer_service_modules 没有 region_code),避免 "column xxx does not exist" 错误

处理策略:

  • 普通 Filter:字段不存在则丢弃
  • OP_RAW 条件(如 deny-all "1 = 0"):保留
  • 子 FilterGroup:递归过滤;过滤后为空则丢弃

func NewFilterGroup

func NewFilterGroup(logicOp constants.Operator) *FilterGroup

NewFilterGroup 创建新的过滤条件组

func NewKeywordFilterGroup

func NewKeywordFilterGroup(keyword string, likeFields, iLikeFields []string) *FilterGroup

NewKeywordFilterGroup 创建关键字多字段 OR 模糊匹配过滤组

用于实现"一个关键字在多个字段中任一匹配"的搜索场景,逻辑为:

(field1 LIKE ? OR field2 ILIKE ? OR ...)

likeFields 使用 LIKE (大小写敏感)匹配,适用于 ID 等固定格式字段 iLikeFields 使用 ILIKE (大小写不敏感)匹配,适用于名称、编码等文本字段 当 keyword 为空或所有字段列表均为空时返回 nil

用法:

keywordGroup := NewKeywordFilterGroup(keyword, []string{"id"}, []string{"name", "code"})
q.WithFilterGroup(keywordGroup)

func (*FilterGroup) AddBetweenFilterIfNotEmpty

func (fg *FilterGroup) AddBetweenFilterIfNotEmpty(field string, min, max interface{}) *FilterGroup

AddBetweenFilterIfNotEmpty 当最小值和最大值都不为空时添加 BETWEEN 过滤条件

func (*FilterGroup) AddEndsWithFilterIfNotEmpty

func (fg *FilterGroup) AddEndsWithFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddEndsWithFilterIfNotEmpty 当值不为空时添加后缀匹配过滤条件 value 支持 string 和 *string 类型

func (*FilterGroup) AddEqFilterIfNotEmpty

func (fg *FilterGroup) AddEqFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddEqFilterIfNotEmpty 当值不为空时添加等于过滤条件

func (*FilterGroup) AddFilter

func (fg *FilterGroup) AddFilter(filter *Filter) *FilterGroup

AddFilter 向条件组添加过滤条件

func (*FilterGroup) AddFilterIf

func (fg *FilterGroup) AddFilterIf(condition bool, filter *Filter) *FilterGroup

AddFilterIf 当条件为真时添加过滤条件

func (*FilterGroup) AddFilterIfNotEmpty

func (fg *FilterGroup) AddFilterIfNotEmpty(field string, operator constants.Operator, value interface{}) *FilterGroup

AddFilterIfNotEmpty 当值不为空时添加过滤条件 支持指针自动解引用,string, slice, map 等类型的空值判断

func (*FilterGroup) AddFilterIfValueNotEmpty

func (fg *FilterGroup) AddFilterIfValueNotEmpty(filter *Filter) *FilterGroup

AddFilterIfValueNotEmpty 当 filter 的 Value 不为空时添加过滤条件

func (*FilterGroup) AddFilters

func (fg *FilterGroup) AddFilters(filters ...*Filter) *FilterGroup

AddFilters 向条件组批量添加过滤条件

func (*FilterGroup) AddFindInSetFilterIfNotEmpty

func (fg *FilterGroup) AddFindInSetFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddFindInSetFilterIfNotEmpty 当值不为空时添加 FIND_IN_SET 过滤条件(MySQL特定)

func (*FilterGroup) AddGroup

func (fg *FilterGroup) AddGroup(group *FilterGroup) *FilterGroup

AddGroup 向条件组添加嵌套条件组(检查嵌套深度限制)

func (*FilterGroup) AddGroupIf

func (fg *FilterGroup) AddGroupIf(condition bool, group *FilterGroup) *FilterGroup

AddGroupIf 当条件为真时添加嵌套条件组

func (*FilterGroup) AddGroupIfNotEmpty

func (fg *FilterGroup) AddGroupIfNotEmpty(group *FilterGroup) *FilterGroup

AddGroupIfNotEmpty 当嵌套条件组不为空时添加

func (*FilterGroup) AddGtFilterIfNotEmpty

func (fg *FilterGroup) AddGtFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddGtFilterIfNotEmpty 当值不为空时添加大于过滤条件

func (*FilterGroup) AddGteFilterIfNotEmpty

func (fg *FilterGroup) AddGteFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddGteFilterIfNotEmpty 当值不为空时添加大于等于过滤条件

func (*FilterGroup) AddILikeFilterIfNotEmpty

func (fg *FilterGroup) AddILikeFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddILikeFilterIfNotEmpty 当值不为空时添加大小写不敏感 LIKE 过滤条件 跨数据库实现:LOWER(field) LIKE LOWER(?),value 支持 string 和 *string 类型

func (*FilterGroup) AddInFilterIfNotEmpty

func (fg *FilterGroup) AddInFilterIfNotEmpty(field string, values interface{}) *FilterGroup

AddInFilterIfNotEmpty 当切片不为空时添加 IN 过滤条件 values 支持任意切片类型([]string、[]int 等)以及对应指针类型

func (*FilterGroup) AddJsonArrayContainsFilterIfNotEmpty

func (fg *FilterGroup) AddJsonArrayContainsFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddJsonArrayContainsFilterIfNotEmpty 当值不为空时添加 JSON 数组包含过滤条件(方言感知) 用于查询 JSON 数组列是否包含指定值,SQL 表达式由各方言在执行时生成 value 支持 int64/string 等标量类型及对应指针类型

func (*FilterGroup) AddJsonFieldEqFilterIfNotEmpty

func (fg *FilterGroup) AddJsonFieldEqFilterIfNotEmpty(column, jsonKey string, value interface{}) *FilterGroup

AddJsonFieldEqFilterIfNotEmpty 当值不为空时添加 JSON 对象字段等值过滤条件(方言感知) 用于从 JSON 列中提取指定键的值并做等值比较 value 支持 string 等标量类型及对应指针类型

func (*FilterGroup) AddLikeFilterIfNotEmpty

func (fg *FilterGroup) AddLikeFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddLikeFilterIfNotEmpty 当值不为空时添加 LIKE 过滤条件 value 支持 string 和 *string 类型

func (*FilterGroup) AddLtFilterIfNotEmpty

func (fg *FilterGroup) AddLtFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddLtFilterIfNotEmpty 当值不为空时添加小于过滤条件

func (*FilterGroup) AddLteFilterIfNotEmpty

func (fg *FilterGroup) AddLteFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddLteFilterIfNotEmpty 当值不为空时添加小于等于过滤条件

func (*FilterGroup) AddNeqFilterIfNotEmpty

func (fg *FilterGroup) AddNeqFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddNeqFilterIfNotEmpty 当值不为空时添加不等于过滤条件

func (*FilterGroup) AddNotILikeFilterIfNotEmpty

func (fg *FilterGroup) AddNotILikeFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddNotILikeFilterIfNotEmpty 当值不为空时添加大小写不敏感 NOT LIKE 过滤条件

func (*FilterGroup) AddNotInFilterIfNotEmpty

func (fg *FilterGroup) AddNotInFilterIfNotEmpty(field string, values interface{}) *FilterGroup

AddNotInFilterIfNotEmpty 当切片不为空时添加 NOT IN 过滤条件 values 支持任意切片类型([]string、[]int 等)以及对应指针类型

func (*FilterGroup) AddNotLikeFilterIfNotEmpty

func (fg *FilterGroup) AddNotLikeFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddNotLikeFilterIfNotEmpty 当值不为空时添加 NOT LIKE 过滤条件 value 支持 string 和 *string 类型

func (*FilterGroup) AddRegexpFilterIfNotEmpty

func (fg *FilterGroup) AddRegexpFilterIfNotEmpty(field string, pattern interface{}) *FilterGroup

AddRegexpFilterIfNotEmpty 当值不为空时添加正则匹配过滤条件(仅MySQL/PostgreSQL) pattern 支持 string 和 *string 类型

func (*FilterGroup) AddStartsWithFilterIfNotEmpty

func (fg *FilterGroup) AddStartsWithFilterIfNotEmpty(field string, value interface{}) *FilterGroup

AddStartsWithFilterIfNotEmpty 当值不为空时添加前缀匹配过滤条件 value 支持 string 和 *string 类型

func (*FilterGroup) Clear

func (fg *FilterGroup) Clear() *FilterGroup

Clear 清空所有过滤条件和条件组

func (*FilterGroup) Clone

func (fg *FilterGroup) Clone() *FilterGroup

Clone 克隆条件组(深拷贝,检查嵌套深度)

func (*FilterGroup) Count

func (fg *FilterGroup) Count() int

Count 返回条件总数(包括嵌套组)

func (*FilterGroup) IsEmpty

func (fg *FilterGroup) IsEmpty() bool

IsEmpty 检查条件组是否为空

type FindOptions

type FindOptions struct {
	Conditions []Condition
	Orders     []OrderBy
	Limit      int
	Offset     int
}

FindOptions 兼容旧API的查询选项结构

type FullFeaturedModel

FullFeaturedModel 全功能模型接口(组合所有特性)

type JoinField

type JoinField struct {
	// Expr 字段表达式,如 "g.type"
	Expr string
	// Alias 结果列别名,如 "group_type"(需匹配目标扩展 struct 的 gorm column tag)
	// 为空则直接用 Expr,不做 AS
	Alias string
}

JoinField JOIN 关联表要 SELECT 的补充字段

type JoinSpec

type JoinSpec struct {
	// JoinType JOIN 类型,使用 constants.JOIN_LEFT / constants.JOIN_INNER 等
	JoinType string
	// Table 关联表名
	Table string
	// Alias 关联表别名(如 "g"),为空则用 Table
	Alias string
	// On ON 条件,可含 ? 占位符(如 "g.id = e.group_id" 或 "g.type IN ?")
	On string
	// Args ON 条件参数(对应 On 中的 ?)
	Args []interface{}
	// SelectFields 从关联表 SELECT 的补充字段
	SelectFields []JoinField
}

JoinSpec 一次 JOIN 的描述

type LightModel

type LightModel struct {
	ID        uint      `json:"id" gorm:"primaryKey;autoIncrement;comment:自增主键"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
	Status    int8      `json:"status" gorm:"default:1;index;comment:状态(1:启用 0:禁用)"`
}

LightModel 轻量级模型(仅包含基本字段,无软删除、无版本控制)

func (*LightModel) Disable

func (m *LightModel) Disable()

func (*LightModel) Enable

func (m *LightModel) Enable()

func (*LightModel) GetID

func (m *LightModel) GetID() uint

func (*LightModel) IsEnabled

func (m *LightModel) IsEnabled() bool

func (*LightModel) IsNew

func (m *LightModel) IsNew() bool

type ModelInterface

type ModelInterface interface {
	IsNew() bool
}

ModelInterface 模型通用接口

type MultiTableStatsBuilder

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

MultiTableStatsBuilder 多表统计构建器 专门用于并发查询多个表的统计数据(如仪表盘)

func NewMultiTableStatsBuilder

func NewMultiTableStatsBuilder(ctx context.Context, db *gorm.DB, log logger.ILogger) *MultiTableStatsBuilder

NewMultiTableStatsBuilder 创建多表统计构建器

func (*MultiTableStatsBuilder) AddCondition

func (b *MultiTableStatsBuilder) AddCondition(tableName, condition string, args ...interface{}) *MultiTableStatsBuilder

AddCondition 为特定表添加额外条件

func (*MultiTableStatsBuilder) Avg

func (b *MultiTableStatsBuilder) Avg(tableName, field, alias string) *MultiTableStatsBuilder

Avg 添加 AVG(field) 查询

func (*MultiTableStatsBuilder) Count

func (b *MultiTableStatsBuilder) Count(tableName, alias string) *MultiTableStatsBuilder

Count 添加 COUNT(*) 查询

func (*MultiTableStatsBuilder) CountDistinct

func (b *MultiTableStatsBuilder) CountDistinct(tableName, field, alias string) *MultiTableStatsBuilder

CountDistinct 添加 COUNT(DISTINCT field) 查询

func (*MultiTableStatsBuilder) Execute

func (b *MultiTableStatsBuilder) Execute() (map[string]int64, error)

Execute 执行所有查询并返回结果

func (*MultiTableStatsBuilder) ExecuteWithDetails

func (b *MultiTableStatsBuilder) ExecuteWithDetails() ([]ConcurrentQueryResult[int64], bool, error)

ExecuteWithDetails 执行并返回详细结果(包含错误信息)

func (*MultiTableStatsBuilder) Max

func (b *MultiTableStatsBuilder) Max(tableName, field, alias string) *MultiTableStatsBuilder

Max 添加 MAX(field) 查询

func (*MultiTableStatsBuilder) Min

func (b *MultiTableStatsBuilder) Min(tableName, field, alias string) *MultiTableStatsBuilder

Min 添加 MIN(field) 查询

func (*MultiTableStatsBuilder) Sum

func (b *MultiTableStatsBuilder) Sum(tableName, field, alias string) *MultiTableStatsBuilder

Sum 添加 SUM(field) 查询

func (*MultiTableStatsBuilder) WithTimeField

func (b *MultiTableStatsBuilder) WithTimeField(field string) *MultiTableStatsBuilder

WithTimeField 设置时间字段名

func (*MultiTableStatsBuilder) WithTimeRange

func (b *MultiTableStatsBuilder) WithTimeRange(start, end time.Time) *MultiTableStatsBuilder

WithTimeRange 设置时间范围(应用到所有表)

func (*MultiTableStatsBuilder) WithTimeout

WithTimeout 设置查询超时

func (*MultiTableStatsBuilder) WithWorkers

func (b *MultiTableStatsBuilder) WithWorkers(workers int) *MultiTableStatsBuilder

WithWorkers 设置并发工作数

type MySQLDialect

type MySQLDialect struct{}

MySQLDialect MySQL 方言

func (*MySQLDialect) FormatTimeGroup

func (d *MySQLDialect) FormatTimeGroup(field string, groupType TimeGroupType) string

func (*MySQLDialect) JsonArrayAppend

func (d *MySQLDialect) JsonArrayAppend(column, placeholder string) string

JsonArrayAppend MySQL: JSON_ARRAY_APPEND + IFNULL + JSON_ARRAY + CAST AS JSON

func (*MySQLDialect) JsonArrayContains

func (d *MySQLDialect) JsonArrayContains(column, placeholder string) string

JsonArrayContains MySQL: JSON_CONTAINS(column, ?),参数为 JSON 编码的 '[value]'

func (*MySQLDialect) JsonArrayCountSubQuery

func (d *MySQLDialect) JsonArrayCountSubQuery(table, jsonColumn, valueColumn string) string

JsonArrayCountSubQuery MySQL: 用 JSON_CONTAINS + CAST 利用 json 列索引

func (*MySQLDialect) JsonFieldExtract

func (d *MySQLDialect) JsonFieldExtract(column, jsonKey string) string

JsonFieldExtract MySQL: JSON_UNQUOTE(JSON_EXTRACT(column, '$.key'))

func (*MySQLDialect) RandomOrderExpr

func (d *MySQLDialect) RandomOrderExpr() string

RandomOrderExpr MySQL: RAND()

func (*MySQLDialect) UpsertColumnRef

func (d *MySQLDialect) UpsertColumnRef(column string) string

UpsertColumnRef MySQL: VALUES(column) MySQL 专有的 VALUES() 函数,在 ON DUPLICATE KEY UPDATE 中引用待插入行的列值

type NormalizeFunc

type NormalizeFunc func(value string) string

NormalizeFunc 归一化函数类型

type Order

type Order struct {
	Field     string
	Direction string // "ASC" or "DESC"
}

Order 排序条件

type OrderBy

type OrderBy struct {
	Field     string
	Direction string
}

OrderBy 排序条件结构

type Pagination

type Pagination = PaginationT[int]

Pagination 默认分页类型

type Pagination32

type Pagination32 = PaginationT[int32]

Pagination32 int32 版本的分页类型(用于一般场景)

type Pagination64

type Pagination64 = PaginationT[int64]

Pagination64 int64 版本的分页类型(用于需要大数值的场景)

type PaginationResult32

type PaginationResult32 = Pagination32

PaginationResult32 分页结果类型别名(int32版本,与Pagination32一致)

type PaginationResult64

type PaginationResult64 = Pagination64

PaginationResult64 分页结果类型别名(int64版本,与Pagination64一致)

type PaginationT

type PaginationT[T types.Integer] struct {
	Page     T     `json:"page"`      // 当前页码(从1开始)
	PageSize T     `json:"page_size"` // 每页记录数
	Total    int64 `json:"total"`     // 总记录数(固定 int64 以支持大数据量)
}

PaginationT 泛型分页元数据

func ListWithPaginationT

func ListWithPaginationT[T any, P types.Integer](r *BaseRepository[T], ctx context.Context, query *Query, page ...*PaginationT[P]) ([]*T, *PaginationT[P], error)

ListWithPagination 分页列表查询(泛型版本,支持任意整数类型的分页参数) page 可选,不传时优先使用 query.Pagination;若 query 也为 nil 或无分页,则使用默认值 优先级:显式传入的 page > query.Pagination > 默认值

当 query 配置了 JoinScanDest + JoinExtract(参见 Query.WithJoinScan)时, 走 JOIN 扩展 struct 路径:Find 到 *[]E 再用 extract 提取 []*T 返回 否则走默认路径:Find 到 []*T

func (*PaginationT[T]) GetLimit

func (p *PaginationT[T]) GetLimit() int

GetLimit 获取查询限制数(自动应用默认值和最大值限制)

func (*PaginationT[T]) GetOffset

func (p *PaginationT[T]) GetOffset() int

GetOffset 计算数据库偏移量

func (*PaginationT[T]) GetTotalPages

func (p *PaginationT[T]) GetTotalPages() T

GetTotalPages 计算总页数

func (*PaginationT[T]) HasNextPage

func (p *PaginationT[T]) HasNextPage() bool

HasNextPage 是否有下一页

func (*PaginationT[T]) HasPrevPage

func (p *PaginationT[T]) HasPrevPage() bool

HasPrevPage 是否有上一页

func (*PaginationT[T]) ToInt

func (p *PaginationT[T]) ToInt() *Pagination

ToInt 转换为 Pagination (int 类型)

func (*PaginationT[T]) ToInt32

func (p *PaginationT[T]) ToInt32() *Pagination32

ToInt32 转换为 Pagination32 (int32 类型)

func (*PaginationT[T]) ToInt64

func (p *PaginationT[T]) ToInt64() *Pagination64

ToInt64 转换为 Pagination64 (int64 类型)

type PostgreSQLDialect

type PostgreSQLDialect struct{}

PostgreSQLDialect PostgreSQL 方言

func (*PostgreSQLDialect) FormatTimeGroup

func (d *PostgreSQLDialect) FormatTimeGroup(field string, groupType TimeGroupType) string

func (*PostgreSQLDialect) JsonArrayAppend

func (d *PostgreSQLDialect) JsonArrayAppend(column, placeholder string) string

JsonArrayAppend PostgreSQL: COALESCE + || + ::jsonb PostgreSQL 用 jsonb 的 || 操作符将元素追加到数组末尾

func (*PostgreSQLDialect) JsonArrayContains

func (d *PostgreSQLDialect) JsonArrayContains(column, placeholder string) string

JsonArrayContains PostgreSQL: column @> ?::jsonb,参数为 JSON 编码的 '[value]' 配合 GIN 索引(CREATE INDEX USING GIN (column))可获得最佳查询性能

func (*PostgreSQLDialect) JsonArrayCountSubQuery

func (d *PostgreSQLDialect) JsonArrayCountSubQuery(table, jsonColumn, valueColumn string) string

JsonArrayCountSubQuery PostgreSQL: 用 @> 操作符 + CAST 利用 GIN 索引

func (*PostgreSQLDialect) JsonFieldExtract

func (d *PostgreSQLDialect) JsonFieldExtract(column, jsonKey string) string

JsonFieldExtract PostgreSQL: column->>'key'(返回 text 类型)

func (*PostgreSQLDialect) RandomOrderExpr

func (d *PostgreSQLDialect) RandomOrderExpr() string

RandomOrderExpr PostgreSQL: RANDOM()

func (*PostgreSQLDialect) UpsertColumnRef

func (d *PostgreSQLDialect) UpsertColumnRef(column string) string

UpsertColumnRef PostgreSQL: excluded.column PostgreSQL 的 ON CONFLICT ... DO UPDATE 用 excluded.column 引用待插入行的列值

type Query

type Query struct {
	Filters        []*Filter       // 简单过滤条件
	FilterGroup    *FilterGroup    // 复合过滤条件组
	Orders         []Order         // 排序条件
	Pagination     *Pagination     // 分页信息
	LimitValue     *int            // 限制数量
	OffsetValue    *int            // 偏移量
	Distinct       bool            // 是否去重
	GroupBy        []string        // 分组字段
	Having         []*Filter       // HAVING 条件
	SelectFields   []string        // 要查询的字段列表(为空则查询所有字段)
	OmitFields     []string        // 要排除的字段列表
	Joins          []JoinSpec      // JOIN 关联(主表 JOIN 关联表补充字段)
	ComputedFields []ComputedField // 计算字段(派生表达式 SELECT,如子查询聚合,可覆盖主表同名列)

	// JoinScanDest 设置后 ListWithPagination* 会将结果 Find 到此扩展 struct 切片(*[]E),
	// 而非默认的 []*T用于 JOIN 关联表补充字段的场景,配合 Joins 与 JoinExtract 使用
	// 扩展 struct 约定:匿名内嵌主模型 T 作为首字段(gorm 展开扫描主表所有列),
	// 关联字段用 gorm column tag 匹配 JoinField.Alias
	JoinScanDest interface{} // 类型必须为 *[]E
	// JoinExtract 提取回调:func(E) *TJoinScanDest 设置后必填
	// ListWithPagination* 完成 Find 后会用反射逐行调用此回调,组装出 []*T 返回
	JoinExtract interface{} // 类型必须为 func(E) *T

	// Desensitize 是否对本次查询结果进行脱敏(基于 model 的 desensitize tag)
	// 为 true 时,查询返回的 model 会自动扫描 desensitize tag 并脱敏对应字段
	// 也可通过 WithDesensitize[T]() 仓储选项全局启用
	Desensitize bool
	// contains filtered or unexported fields
}

Query 查询条件

func NewQuery

func NewQuery() *Query

NewQuery 创建查询条件,初始化所有切片字段

func (*Query) AddBetween

func (q *Query) AddBetween(field string, start, end interface{}) *Query

AddBetween 添加BETWEEN条件

func (*Query) AddBetweenFilterIfNotEmpty

func (q *Query) AddBetweenFilterIfNotEmpty(field string, min, max interface{}) *Query

AddBetweenFilterIfNotEmpty 添加 BETWEEN 过滤条件(仅当最小值和最大值都不为空时)

func (*Query) AddComputedField

func (q *Query) AddComputedField(expr, alias string) *Query

AddComputedField 添加计算字段(SELECT 中的派生表达式,如子查询聚合)

用于查询时动态计算派生值,避免维护冗余列计算字段会追加到 SELECT 末尾, 当 alias 与主表物理列同名时,后出现的计算列会覆盖主表列值

用法:

q.AddComputedField("(SELECT COUNT(*) FROM game_libraries WHERE brand_id = game_brands.id)", "linked_game_count")

注意:表达式中的主表别名需与 ListWithPaginationT 使用的表名一致(默认为主模型 TableName)

func (*Query) AddComputedFields

func (q *Query) AddComputedFields(fields ...ComputedField) *Query

AddComputedFields 批量添加计算字段

func (*Query) AddCursorFilter

func (q *Query) AddCursorFilter(field string, cursor interface{}, isPrev bool) *Query

AddCursorFilter 游标分页方向过滤(仅当 cursor 不为空时生效) isPrev=true 时使用 <(向前翻页),否则使用 >(向后翻页)

func (*Query) AddEndsWith

func (q *Query) AddEndsWith(field, suffix string) *Query

AddEndsWith 添加后缀匹配条件

func (*Query) AddEndsWithFilterIfNotEmpty

func (q *Query) AddEndsWithFilterIfNotEmpty(field string, value interface{}) *Query

AddEndsWithFilterIfNotEmpty 添加后缀匹配过滤条件(仅当值不为空时) value 支持 string 和 *string 类型

func (*Query) AddEqOrInFilter

func (q *Query) AddEqOrInFilter(field string, values interface{}) *Query

AddEqOrInFilter 单值用 =,多值自动转 IN(仅当切片不为空时生效) 适用于"按单个或多个 ID 过滤"的常见场景,避免手动判断长度 values 支持任意切片类型([]string、[]int 等)以及对应指针类型 示例: query.AddEqOrInFilter("session_id", sessionIDs)

func (*Query) AddEqual

func (q *Query) AddEqual(field string, value interface{}) *Query

AddEqual 添加等于条件

func (*Query) AddFilter

func (q *Query) AddFilter(filter *Filter) *Query

AddFilter 添加过滤条件

func (*Query) AddFilterIfNotEmpty

func (q *Query) AddFilterIfNotEmpty(field string, value interface{}) *Query

AddFilterIfNotEmpty 添加过滤条件(仅当值不为空时) 支持泛型自动处理不同类型的值,包括指针自动解引用 规则: nil/nil指针 -> 跳过, 布尔/数字(含零值) -> 有效, 空字符串/空切片 -> 跳过, 非空切片 -> IN

func (*Query) AddFilters

func (q *Query) AddFilters(filters ...*Filter) *Query

AddFilters 批量添加过滤条件

func (*Query) AddFindInSetFilterIfNotEmpty

func (q *Query) AddFindInSetFilterIfNotEmpty(field string, value interface{}) *Query

AddFindInSetFilterIfNotEmpty 添加 FIND_IN_SET 过滤条件(仅当值不为空时,MySQL特定)

func (*Query) AddGreaterEqual

func (q *Query) AddGreaterEqual(field string, value interface{}) *Query

AddGreaterEqual 添加大于等于条件

func (*Query) AddGreaterThan

func (q *Query) AddGreaterThan(field string, value interface{}) *Query

AddGreaterThan 添加大于条件

func (*Query) AddGroupBy

func (q *Query) AddGroupBy(fields ...string) *Query

AddGroupBy 添加分组字段

func (*Query) AddGtFilterIfNotEmpty

func (q *Query) AddGtFilterIfNotEmpty(field string, value interface{}) *Query

AddGtFilterIfNotEmpty 添加大于过滤条件(仅当值不为空时)

func (*Query) AddGteFilterIfNotEmpty

func (q *Query) AddGteFilterIfNotEmpty(field string, value interface{}) *Query

AddGteFilterIfNotEmpty 添加大于等于过滤条件(仅当值不为空时)

func (*Query) AddHaving

func (q *Query) AddHaving(filter *Filter) *Query

AddHaving 添加HAVING条件

func (*Query) AddILikeFilterIfNotEmpty

func (q *Query) AddILikeFilterIfNotEmpty(field string, keyword interface{}) *Query

AddILikeFilterIfNotEmpty 添加大小写不敏感 LIKE 过滤条件(仅当关键词不为空时) 跨数据库实现:LOWER(field) LIKE LOWER(?),keyword 支持 string 和 *string 类型

func (*Query) AddIn

func (q *Query) AddIn(field string, values ...interface{}) *Query

AddIn 添加IN条件

func (*Query) AddInFilterIfNotEmpty

func (q *Query) AddInFilterIfNotEmpty(field string, values interface{}) *Query

AddInFilterIfNotEmpty 添加 IN 过滤条件(仅当切片不为空时) values 支持任意切片类型([]string、[]int 等)以及对应指针类型

func (*Query) AddInSubQueryFilterIfNotEmpty

func (q *Query) AddInSubQueryFilterIfNotEmpty(field, subSQL string, args ...interface{}) *Query

AddInSubQueryFilterIfNotEmpty 添加 IN 子查询过滤条件(仅当首个参数非空时) 用于 "field IN (SELECT id FROM xxx WHERE col IN (?))" 场景,替代手动 query.AddFilter(NewFilter(field, OP_IN, NewSubQuery(sql, args))) args 传单个切片(如 []string、[]enumspb.Xxx)时由 gorm 展开匹配 IN (?),nil/空切片时跳过 args 传多个参数时按 subSQL 中 ? 占位符顺序逐个绑定,数量需与占位符一致

func (*Query) AddIsNotNull

func (q *Query) AddIsNotNull(field string) *Query

AddIsNotNull 添加IS NOT NULL条件

func (*Query) AddIsNull

func (q *Query) AddIsNull(field string) *Query

AddIsNull 添加IS NULL条件

func (*Query) AddJoin

func (q *Query) AddJoin(joinType, table, alias, on string, args ...interface{}) *Query

AddJoin 添加 JOIN 关联(不含补充字段,仅用于过滤场景) joinType 使用 constants.JOIN_LEFT / constants.JOIN_INNER 等

func (*Query) AddJoinWithSelect

func (q *Query) AddJoinWithSelect(joinType, table, alias, on string, selectFields []JoinField, args ...interface{}) *Query

AddJoinWithSelect 添加 JOIN 关联并指定关联表补充 SELECT 字段 selectFields 中 JoinField.Alias 需匹配目标扩展 struct 的 gorm column tag

func (*Query) AddJsonArrayContainsFilterIfNotEmpty

func (q *Query) AddJsonArrayContainsFilterIfNotEmpty(field string, value interface{}) *Query

AddJsonArrayContainsFilterIfNotEmpty 添加 JSON 数组包含过滤条件(仅当值不为空时,方言感知) 用于查询 JSON 数组列(如 sqltypes.Slice[int64] 存储的 channel_ids)是否包含指定值 SQL 表达式由各方言在执行时自动生成(MySQL: JSON_CONTAINS / PG&CRDB: @>::jsonb / SQLite: json_each) value 支持 int64/string 等标量类型及对应指针类型

func (*Query) AddJsonbLikeFilterIfNotEmpty

func (q *Query) AddJsonbLikeFilterIfNotEmpty(field string, keyword interface{}) *Query

AddJsonbLikeFilterIfNotEmpty 添加 jsonb 字段文本搜索过滤条件(仅当关键词不为空时) 用于对 PostgreSQL jsonb 类型字段进行模糊搜索,自动将字段转为 text 后匹配 keyword 支持 string 和 *wrapperspb.StringValue 等类型

func (*Query) AddLessEqual

func (q *Query) AddLessEqual(field string, value interface{}) *Query

AddLessEqual 添加小于等于条件

func (*Query) AddLessThan

func (q *Query) AddLessThan(field string, value interface{}) *Query

AddLessThan 添加小于条件

func (*Query) AddLike

func (q *Query) AddLike(field, keyword string) *Query

AddLike 添加LIKE条件(包含匹配)

func (*Query) AddLikeFilterIfNotEmpty

func (q *Query) AddLikeFilterIfNotEmpty(field string, keyword interface{}) *Query

AddLikeFilterIfNotEmpty 添加 LIKE 过滤条件(仅当关键词不为空时) keyword 支持 string 和 *string 类型

func (*Query) AddLtFilterIfNotEmpty

func (q *Query) AddLtFilterIfNotEmpty(field string, value interface{}) *Query

AddLtFilterIfNotEmpty 添加小于过滤条件(仅当值不为空时)

func (*Query) AddLteFilterIfNotEmpty

func (q *Query) AddLteFilterIfNotEmpty(field string, value interface{}) *Query

AddLteFilterIfNotEmpty 添加小于等于过滤条件(仅当值不为空时)

func (*Query) AddNeqFilterIfNotEmpty

func (q *Query) AddNeqFilterIfNotEmpty(field string, value interface{}) *Query

AddNeqFilterIfNotEmpty 添加不等于过滤条件(仅当值不为空时)

func (*Query) AddNotEqual

func (q *Query) AddNotEqual(field string, value interface{}) *Query

AddNotEqual 添加不等于条件

func (*Query) AddNotILikeFilterIfNotEmpty

func (q *Query) AddNotILikeFilterIfNotEmpty(field string, value interface{}) *Query

AddNotILikeFilterIfNotEmpty 添加大小写不敏感 NOT LIKE 过滤条件(仅当值不为空时) 跨数据库实现:LOWER(field) NOT LIKE LOWER(?),value 支持 string 和 *string 类型

func (*Query) AddNotIn

func (q *Query) AddNotIn(field string, values ...interface{}) *Query

AddNotIn 添加NOT IN条件

func (*Query) AddNotInFilterIfNotEmpty

func (q *Query) AddNotInFilterIfNotEmpty(field string, values interface{}) *Query

AddNotInFilterIfNotEmpty 添加 NOT IN 过滤条件(仅当切片不为空时) values 支持任意切片类型([]string、[]int 等)以及对应指针类型

func (*Query) AddNotInSubQueryFilterIfNotEmpty

func (q *Query) AddNotInSubQueryFilterIfNotEmpty(field, subSQL string, args ...interface{}) *Query

AddNotInSubQueryFilterIfNotEmpty 添加 NOT IN 子查询过滤条件(仅当首个参数非空时) 用于 "field NOT IN (SELECT id FROM xxx WHERE col IN (?))" 场景 args 传单个切片;nil/空切片时跳过;多参数用法同 AddInSubQueryFilterIfNotEmpty

func (*Query) AddNotLikeFilterIfNotEmpty

func (q *Query) AddNotLikeFilterIfNotEmpty(field string, value interface{}) *Query

AddNotLikeFilterIfNotEmpty 添加 NOT LIKE 过滤条件(仅当值不为空时) value 支持 string 和 *string 类型

func (*Query) AddOrder

func (q *Query) AddOrder(field, direction string) *Query

AddOrder 添加排序条件

func (*Query) AddOrderAsc

func (q *Query) AddOrderAsc(field string) *Query

AddOrderAsc 添加升序排序

func (*Query) AddOrderDesc

func (q *Query) AddOrderDesc(field string) *Query

AddOrderDesc 添加降序排序

func (*Query) AddRawFilter

func (q *Query) AddRawFilter(rawCondition string) *Query

AddRawFilter 添加原始 SQL 过滤条件(用于复杂条件,如子查询、函数等) 注意:此方法直接将条件添加到 SQL 中,使用时需确保 SQL 注入安全 示例: query.AddRawFilter("to_agent_id IS NOT NULL AND to_agent_id != ”")

func (*Query) AddRawOrder

func (q *Query) AddRawOrder(orderExpr string) *Query

AddRawOrder 添加原始SQL排序表达式(用于复杂排序,如多字段排序、函数排序等) 注意:此方法直接将排序表达式添加到SQL中,使用时需确保SQL注入安全

func (*Query) AddSafeOrder

func (q *Query) AddSafeOrder(sortBy, sortOrder, defaultField, defaultDirection string, allowedFields ...[]string) *Query

AddSafeOrder 安全地添加排序条件 参数:

  • sortBy: 排序字段(可选,为空时使用defaultField)
  • sortOrder: 排序方向(可选,仅支持"ASC"/"DESC",为空时使用defaultDirection)
  • defaultField: 默认排序字段
  • defaultDirection: 默认排序方向
  • allowedFields: 允许的字段白名单(可选,为空则不限制)

示例:

query.AddSafeOrder(filter.SortBy, filter.SortOrder, "created_at", "DESC", []string{"created_at", "updated_at", "id"})

func (*Query) AddSafeOrderBool

func (q *Query) AddSafeOrderBool(sortBy string, ascending bool, defaultField, defaultDirection string, allowedFields ...[]string) *Query

AddSafeOrderBool 安全添加排序条件(ascending 布尔版本) 将 ascending bool 转为排序方向:true→ASC, false→DESC,其余行为与 AddSafeOrder 一致 适用于 protobuf SortRequest{field, ascending} 场景,省去手动方向转换与 if/else 分支

参数:

  • sortBy: 排序字段(可选,为空或不在白名单时使用默认)
  • ascending: 是否升序(true=ASC, false=DESC)
  • defaultField: 默认排序字段
  • defaultDirection: 默认排序方向
  • allowedFields: 允许的字段白名单(可选,为空则不限制)

示例:

q.AddSafeOrderBool(req.GetSort().GetField(), req.GetSort().GetAscending(), "sort", "DESC", []string{"name", "sort", "created_at"})

func (*Query) AddSafeOrderFromSort

func (q *Query) AddSafeOrderFromSort(sort Sorter, defaultField, defaultDirection string, allowedFields ...[]string) *Query

AddSafeOrderFromSort 直接从 Sorter 接口构建安全排序(最简形式) 自动提取 field + ascending,sort 为 nil 或字段为空/不在白名单时回退默认排序 适用于 protobuf req.GetSort() 场景,省去手动拆解字段与方向

参数:

  • sort: 排序参数(可为 nil,protobuf getter 对 nil 接收者返回零值,安全)
  • defaultField: 默认排序字段
  • defaultDirection: 默认排序方向
  • allowedFields: 允许的字段白名单(可选,为空则不限制)

示例:

q.AddSafeOrderFromSort(req.GetSort(), "sort", "DESC", []string{"name", "sort", "created_at"})

func (*Query) AddStartsWith

func (q *Query) AddStartsWith(field, prefix string) *Query

AddStartsWith 添加前缀匹配条件

func (*Query) AddStartsWithFilterIfNotEmpty

func (q *Query) AddStartsWithFilterIfNotEmpty(field string, value interface{}) *Query

AddStartsWithFilterIfNotEmpty 添加前缀匹配过滤条件(仅当值不为空时) value 支持 string 和 *string 类型

func (*Query) AddThisMonth

func (q *Query) AddThisMonth(field string) *Query

AddThisMonth 添加本月条件

func (*Query) AddThisWeek

func (q *Query) AddThisWeek(field string) *Query

AddThisWeek 添加本周条件

func (*Query) AddThisYear

func (q *Query) AddThisYear(field string) *Query

AddThisYear 添加今年条件

func (*Query) AddTimeAfter

func (q *Query) AddTimeAfter(field string, t time.Time) *Query

AddTimeAfter 添加时间晚于条件

func (*Query) AddTimeBefore

func (q *Query) AddTimeBefore(field string, t time.Time) *Query

AddTimeBefore 添加时间早于条件

func (*Query) AddTimeBetween

func (q *Query) AddTimeBetween(field string, start, end time.Time) *Query

AddTimeBetween 添加时间范围条件

func (*Query) AddTimeRangeFilter

func (q *Query) AddTimeRangeFilter(field string, startTime, endTime interface{}) *Query

AddTimeRangeFilter 添加时间范围过滤条件 自动过滤掉nil和零值时间,避免生成无效的SQL条件

func (*Query) AddToday

func (q *Query) AddToday(field string) *Query

AddToday 添加今天的条件(日期部分匹配) 区间上界沿用 todayRangeAt 的日历日推进,夏令时切换日不会偏一小时

[EN] AddToday reuses todayRangeAt's calendar-day advance, so the upper bound does not slip by an hour on a DST transition day

func (*Query) BuildWhereClause

func (q *Query) BuildWhereClause() (string, []interface{})

BuildWhereClause 构建WHERE子句和参数 返回值: whereClause (SQL条件字符串), args (参数数组) 示例: "agent_id = ? AND work_status = ? AND start_time >= ?", []interface{}{"user123", 2, time.Now()}

func (*Query) Clone

func (q *Query) Clone() *Query

Clone 深拷贝查询对象,创建一个新的独立副本

func (*Query) GetAllFilters

func (q *Query) GetAllFilters() []*Filter

GetAllFilters 获取所有过滤条件(扁平化)

func (*Query) GetPagination

func (q *Query) GetPagination() *Pagination

GetPagination 获取分页对象(如果不存在则创建默认分页)

func (*Query) HasFilters

func (q *Query) HasFilters() bool

HasFilters 检查是否有过滤条件

func (*Query) HasGroupBy

func (q *Query) HasGroupBy() bool

HasGroupBy 检查是否设置了分组

func (*Query) HasHaving

func (q *Query) HasHaving() bool

HasHaving 检查是否设置了HAVING条件

func (*Query) HasOmitFields

func (q *Query) HasOmitFields() bool

HasOmitFields 检查是否指定了排除字段

func (*Query) HasOrders

func (q *Query) HasOrders() bool

HasOrders 检查是否设置了排序

func (*Query) HasPagination

func (q *Query) HasPagination() bool

HasPagination 检查是否设置了分页

func (*Query) HasSelectFields

func (q *Query) HasSelectFields() bool

HasSelectFields 检查是否指定了查询字段

func (*Query) IsLimited

func (q *Query) IsLimited() bool

IsLimited 检查是否设置了查询限制数量

func (*Query) IsOffset

func (q *Query) IsOffset() bool

IsOffset 检查是否设置了查询偏移量

func (*Query) Limit

func (q *Query) Limit(limit int) *Query

Limit 设置查询限制数量

func (*Query) Offset

func (q *Query) Offset(offset int) *Query

Offset 设置查询偏移量

func (*Query) Omit

func (q *Query) Omit(fields ...string) *Query

Omit 排除不需要查询的字段 示例: query.Omit("password", "secret")

func (*Query) OmitLargeFields

func (q *Query) OmitLargeFields() *Query

OmitLargeFields 排除大字段的便捷方法 默认排除: content, description, detail, data, payload, body

func (*Query) OmitSensitive

func (q *Query) OmitSensitive() *Query

OmitSensitive 排除敏感字段的便捷方法 默认排除: password, secret, token, api_key

func (*Query) ResetFilters

func (q *Query) ResetFilters() *Query

ResetFilters 重置所有过滤条件(包括简单过滤器和复合过滤组)

func (*Query) ResetOrders

func (q *Query) ResetOrders() *Query

ResetOrders 重置所有排序条件

func (*Query) ResetPagination

func (q *Query) ResetPagination() *Query

ResetPagination 重置分页设置

func (*Query) Select

func (q *Query) Select(fields ...string) *Query

Select 指定要查询的字段 示例: query.Select("id", "name", "email")

func (*Query) SetDialect

func (q *Query) SetDialect(dialect Dialect)

SetDialect 设置数据库方言(供 OP_JSON_CONTAINS 等方言感知操作符使用,通常由 BaseRepository 自动注入)

func (*Query) SetPage

func (q *Query) SetPage(page interface{}) *Query

SetPage 设置当前页码

func (*Query) SetPageSize

func (q *Query) SetPageSize(pageSize interface{}) *Query

SetPageSize 设置每页记录数

func (*Query) SetPagination

func (q *Query) SetPagination(page, pageSize interface{}) *Query

SetPagination 设置分页参数(页码和每页大小)

func (*Query) WithDesensitize

func (q *Query) WithDesensitize() *Query

WithDesensitize 启用本次查询的脱敏(基于 model 的 desensitize tag 自动识别) 仅对当前 Query 生效,不影响其他查询

示例:

query := NewQuery().WithDesensitize()
items, _, err := repo.ListWithPagination32(ctx, query, paging)
// items 中标记了 desensitize tag 的字段已自动脱敏

func (*Query) WithDistinct

func (q *Query) WithDistinct() *Query

WithDistinct 设置去重查询

func (*Query) WithFilterGroup

func (q *Query) WithFilterGroup(group *FilterGroup) *Query

WithFilterGroup 设置复合过滤条件组

func (*Query) WithFilters

func (q *Query) WithFilters(builders ...QueryFilterBuilder) *Query

WithFilters 追加一组业务过滤构造函数

func (*Query) WithJoinScan

func (q *Query) WithJoinScan(scanDest interface{}, extract interface{}) *Query

WithJoinScan 配置 JOIN 后扫描到扩展 struct 切片,再通过 extract 回调提取 []*T 适用场景:主表 JOIN 关联表补充字段(如 dict_entries JOIN dict_groups 取 group_type/group_name),且补充字段在主模型上为 gorm:"-"(非持久化, 避免 AutoMigrate 建列)

扩展 struct 约定:

  • 匿名内嵌主模型 T 作为首字段(gorm 展开扫描主表所有列)
  • 关联字段用 gorm column tag 匹配 JoinField.Alias(如 `gorm:"column:group_type"`)

用法:

type dictEntryWithGroup struct {
    models.DictEntryModel
    GroupType enumspb.DictGroupType `gorm:"column:group_type"`
    GroupName string                 `gorm:"column:group_name"`
}
var rows []dictEntryWithGroup
query.WithJoinScan(&rows, func(r dictEntryWithGroup) *models.DictEntryModel {
    r.DictEntryModel.GroupType = r.GroupType
    r.DictEntryModel.GroupName = r.GroupName
    return &r.DictEntryModel
})
entries, paging, err := repo.ListWithPagination32(ctx, query)

注意:

  • JOIN 后字段可能歧义,调用方需在 Filter/Order 中用表别名限定(如 "e.created_at"、"g.type")
  • count 复用 JOIN+WHERE;若关联为一对多可能使 total 翻倍,调用方需自行保证一对一或改用子查询

func (*Query) WithKeywordFilter

func (q *Query) WithKeywordFilter(keyword string, likeFields, iLikeFields []string) *Query

WithKeywordFilter 添加关键字多字段 OR 模糊匹配过滤组(链式)

内部调用 NewKeywordFilterGroup 构建过滤组并通过 WithFilterGroup 应用到查询, 实现"一个关键字在多个字段中任一匹配"的搜索场景。

使用示例:

q := NewQuery().
    AddSafeOrder("", "", "created_at", "DESC").
    AddFilterIfNotEmpty("status", 1).
    WithKeywordFilter(keyword,
        []string{"tenant_id"},           // LIKE 匹配(大小写敏感),适用于 ID 等固定格式字段
        []string{"name", "code"})        // ILIKE 匹配(大小写不敏感),适用于名称、编码等文本字段

likeFields 使用 LIKE 匹配,适用于 ID 等固定格式字段 iLikeFields 使用 ILIKE 匹配,适用于名称、编码等文本字段 当 keyword 为空或所有字段列表均为空时不添加任何过滤,直接返回原 query

func (*Query) WithPaging

func (q *Query) WithPaging(page, pageSize interface{}) *Query

WithPaging 设置分页条件

func (*Query) WithScope

func (q *Query) WithScope(hook ScopeHook) *Query

WithScope 为查询添加作用域钩子

func (*Query) WithScopeFilters

func (q *Query) WithScopeFilters(hook ScopeHook, builders ...QueryFilterBuilder) *Query

WithScopeFilters 先应用作用域,再追加业务过滤条件 当业务搜索字段包含 tenant_id/region_code/platform_id 等作用域字段时, 使用该方法可以保证搜索条件只会收窄权限范围,而不会被 ScopeHook 清理掉

type QueryCondition

type QueryCondition struct {
	Filters    []Filter
	Orders     []OrderBy
	Pagination *Pagination
}

type QueryFilterBuilder

type QueryFilterBuilder func(query *Query)

QueryFilterBuilder 在已有 Query 上追加业务过滤条件

type RemarkableModel

type RemarkableModel interface {
	ModelInterface
	SetRemark(remark string)
}

RemarkableModel 支持备注的模型接口

type Repository

type Repository[T any] interface {
	// 创建
	Create(ctx context.Context, entity *T) (*T, error)
	CreateBatch(ctx context.Context, entities ...*T) error

	// 读取
	Get(ctx context.Context, id interface{}) (*T, error)
	GetByFilter(ctx context.Context, filter *Filter) (*T, error)
	GetByFilters(ctx context.Context, filters ...*Filter) (*T, error)
	GetAll(ctx context.Context) ([]*T, error)
	First(ctx context.Context, filters ...*Filter) (*T, error)
	Last(ctx context.Context, filters ...*Filter) (*T, error)
	FindOne(ctx context.Context, filters ...*Filter) (*T, error)
	FirstWithQuery(ctx context.Context, query *Query) (*T, error)
	List(ctx context.Context, query *Query) ([]*T, error)
	ListWithPagination(ctx context.Context, query *Query, page ...*Pagination) ([]*T, *Pagination, error)

	// 更新
	Update(ctx context.Context, entity *T) (*T, error)
	UpdateBatch(ctx context.Context, entities ...*T) error
	UpdateByFilters(ctx context.Context, entity *T, filters ...*Filter) error
	UpdateFields(ctx context.Context, id interface{}, fields map[string]interface{}) error
	UpdateFieldsByFilters(ctx context.Context, fields map[string]interface{}, filters ...*Filter) error
	UpdateFieldsByQuery(ctx context.Context, fields map[string]interface{}, query *Query) error

	// 删除
	Delete(ctx context.Context, id interface{}) error
	DeleteBatch(ctx context.Context, ids ...interface{}) error
	DeleteByFilters(ctx context.Context, filters ...*Filter) error
	DeleteByQuery(ctx context.Context, query *Query) error
	SoftDelete(ctx context.Context, id interface{}, field string, value interface{}) error
	SoftDeleteBatch(ctx context.Context, ids []interface{}, field string, value interface{}) error
	SoftDeleteByFilters(ctx context.Context, field string, value interface{}, filters ...*Filter) error
	Restore(ctx context.Context, id interface{}, field string, restoreValue interface{}) error
	RestoreBatch(ctx context.Context, ids []interface{}, field string, restoreValue interface{}) error

	// 事务
	Transaction(ctx context.Context, fn func(tx Transaction[T]) error) error
	TransactionWithRawDB(ctx context.Context, fn func(tx *gorm.DB) error) error

	// 工具方法
	Count(ctx context.Context, filters ...*Filter) (int64, error)
	Exists(ctx context.Context, filters ...*Filter) (bool, error)
	CountByField(ctx context.Context, field string) (map[interface{}]int64, error)
	Pluck(ctx context.Context, field string, filters ...*Filter) ([]interface{}, error)
	Distinct(ctx context.Context, field string, filters ...*Filter) ([]interface{}, error)

	// 并发查询
	ExecuteConcurrentQueries(ctx context.Context, tasks []ConcurrentQueryTask[int64], opts ...ConcurrentQueryOption) ([]ConcurrentQueryResult[int64], bool)
	ConcurrentQuery(ctx context.Context, queries map[string]func(ctx context.Context) (int64, error), opts ...ConcurrentQueryOption) (map[string]int64, bool)
}

Repository 通用仓储接口

type RepositoryFactory

type RepositoryFactory[T any] interface {
	// 创建仓储
	CreateRepository(table string) Repository[T]

	// 关闭工厂
	Close() error
}

RepositoryFactory 仓储工厂接口

type RepositoryOption

type RepositoryOption[T any] func(*BaseRepository[T])

RepositoryOption 仓储配置选项

func WithAutoFields

func WithAutoFields[T any]() RepositoryOption[T]

WithAutoFields 启用自动字段模式(根据model自动提取字段)

func WithBatchSize

func WithBatchSize[T any](size int) RepositoryOption[T]

WithBatchSize 设置批处理大小

func WithDefaultOrder

func WithDefaultOrder[T any](order string) RepositoryOption[T]

WithDefaultOrder 设置默认排序

func WithDefaultPreloads

func WithDefaultPreloads[T any](preloads ...string) RepositoryOption[T]

WithDefaultPreloads 设置默认预加载关联

func WithDesensitize

func WithDesensitize[T any]() RepositoryOption[T]

WithDesensitize 启用查询结果自动脱敏 启用后,所有查询方法返回的 model 会自动扫描 desensitize tag 并脱敏对应字段 仅对标记了 `desensitize:"类型"` 的 string/*string 字段生效

用法:

repo := NewBaseRepository[UserModel](db, logger, "users",
    WithAutoFields[UserModel](),
    WithDesensitize[UserModel](),
)
// 查询结果中 Email/Phone 等字段自动脱敏
user, err := repo.Get(ctx, 1) // user.Email → "z***@example.com"

func WithLogger

func WithLogger[T any](log logger.ILogger) RepositoryOption[T]

WithLogger 设置日志记录器

func WithNormalize

func WithNormalize[T any]() RepositoryOption[T]

WithNormalize 启用 JSON 字段归一化 默认使用 serializer.NormalizeJSONText 进行归一化

func WithNormalizeConfig

func WithNormalizeConfig[T any](enabled bool, fn NormalizeFunc, defaultValue string) RepositoryOption[T]

WithNormalizeConfig 统一配置归一化选项

func WithNormalizeDefaultValue

func WithNormalizeDefaultValue[T any](defaultValue string) RepositoryOption[T]

WithNormalizeDefaultValue 设置 JSON 字段默认值 当字段为空时使用此默认值

func WithNormalizeFunc

func WithNormalizeFunc[T any](fn NormalizeFunc) RepositoryOption[T]

WithNormalizeFunc 设置自定义归一化函数

func WithReadOnly

func WithReadOnly[T any]() RepositoryOption[T]

WithReadOnly 设置为只读模式

func WithTimeout

func WithTimeout[T any](seconds int) RepositoryOption[T]

WithTimeout 设置查询超时时间

type RepositoryWithSoftDelete

type RepositoryWithSoftDelete[T any] struct {
	*BaseRepository[T]
}

RepositoryWithSoftDelete 带软删除功能的仓储

func NewRepositoryWithSoftDelete

func NewRepositoryWithSoftDelete[T any](repo *BaseRepository[T]) *RepositoryWithSoftDelete[T]

NewRepositoryWithSoftDelete 创建带软删除功能的仓储

func (*RepositoryWithSoftDelete[T]) ListDeleted

func (r *RepositoryWithSoftDelete[T]) ListDeleted(ctx context.Context, query *Query) ([]*T, error)

ListDeleted 查询已删除的记录(deleted_at 字段)

func (*RepositoryWithSoftDelete[T]) ListDeletedByIsDeleted

func (r *RepositoryWithSoftDelete[T]) ListDeletedByIsDeleted(ctx context.Context, query *Query) ([]*T, error)

ListDeletedByIsDeleted 查询已删除的记录(is_deleted 字段)

func (*RepositoryWithSoftDelete[T]) ListNotDeleted

func (r *RepositoryWithSoftDelete[T]) ListNotDeleted(ctx context.Context, query *Query) ([]*T, error)

ListNotDeleted 查询未删除的记录(deleted_at 字段)

func (*RepositoryWithSoftDelete[T]) ListNotDeletedByIsDeleted

func (r *RepositoryWithSoftDelete[T]) ListNotDeletedByIsDeleted(ctx context.Context, query *Query) ([]*T, error)

ListNotDeletedByIsDeleted 查询未删除的记录(is_deleted 字段)

func (*RepositoryWithSoftDelete[T]) RestoreBatchWithDeletedAt

func (r *RepositoryWithSoftDelete[T]) RestoreBatchWithDeletedAt(ctx context.Context, ids []interface{}) error

RestoreBatchWithDeletedAt 使用 deleted_at 字段批量恢复

func (*RepositoryWithSoftDelete[T]) RestoreBatchWithIsDeleted

func (r *RepositoryWithSoftDelete[T]) RestoreBatchWithIsDeleted(ctx context.Context, ids []interface{}) error

RestoreBatchWithIsDeleted 使用 is_deleted 字段批量恢复

func (*RepositoryWithSoftDelete[T]) RestoreWithDeletedAt

func (r *RepositoryWithSoftDelete[T]) RestoreWithDeletedAt(ctx context.Context, id interface{}) error

RestoreWithDeletedAt 使用 deleted_at 字段恢复

func (*RepositoryWithSoftDelete[T]) RestoreWithIsDeleted

func (r *RepositoryWithSoftDelete[T]) RestoreWithIsDeleted(ctx context.Context, id interface{}) error

RestoreWithIsDeleted 使用 is_deleted 字段恢复

func (*RepositoryWithSoftDelete[T]) SoftDeleteBatchWithDeletedAt

func (r *RepositoryWithSoftDelete[T]) SoftDeleteBatchWithDeletedAt(ctx context.Context, ids []interface{}) error

SoftDeleteBatchWithDeletedAt 使用 deleted_at 字段批量软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteBatchWithIsDeleted

func (r *RepositoryWithSoftDelete[T]) SoftDeleteBatchWithIsDeleted(ctx context.Context, ids []interface{}) error

SoftDeleteBatchWithIsDeleted 使用 is_deleted 字段批量软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteByFiltersWithDeletedAt

func (r *RepositoryWithSoftDelete[T]) SoftDeleteByFiltersWithDeletedAt(ctx context.Context, filters ...*Filter) error

SoftDeleteByFiltersWithDeletedAt 使用 deleted_at 字段按条件软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteByFiltersWithIsDeleted

func (r *RepositoryWithSoftDelete[T]) SoftDeleteByFiltersWithIsDeleted(ctx context.Context, filters ...*Filter) error

SoftDeleteByFiltersWithIsDeleted 使用 is_deleted 字段按条件软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteWithDeletedAt

func (r *RepositoryWithSoftDelete[T]) SoftDeleteWithDeletedAt(ctx context.Context, id interface{}) error

SoftDeleteWithDeletedAt 使用 deleted_at 字段软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteWithIsDeleted

func (r *RepositoryWithSoftDelete[T]) SoftDeleteWithIsDeleted(ctx context.Context, id interface{}) error

SoftDeleteWithIsDeleted 使用 is_deleted 字段软删除

type SQLiteDialect

type SQLiteDialect struct{}

SQLiteDialect SQLite 方言

func (*SQLiteDialect) FormatTimeGroup

func (d *SQLiteDialect) FormatTimeGroup(field string, groupType TimeGroupType) string

func (*SQLiteDialect) JsonArrayAppend

func (d *SQLiteDialect) JsonArrayAppend(column, placeholder string) string

JsonArrayAppend SQLite: json_insert + IFNULL + json_array + json() SQLite 无 JSON_ARRAY_APPEND,用 json_insert 配合 '$[#]'(数组长度占位)实现尾部追加

func (*SQLiteDialect) JsonArrayContains

func (d *SQLiteDialect) JsonArrayContains(column, placeholder string) string

JsonArrayContains SQLite: 用 json_each 表值函数 + EXISTS,参数为原始标量值 SQLite 无原生 JSON_CONTAINS,EXISTS 子查询可利用 json_each 的虚拟表

func (*SQLiteDialect) JsonArrayCountSubQuery

func (d *SQLiteDialect) JsonArrayCountSubQuery(table, jsonColumn, valueColumn string) string

JsonArrayCountSubQuery SQLite: EXISTS 子查询计数(性能较低,仅用于测试/兼容) valueColumn 应为外部主表的完整列引用(如 "payment_channels.id")

func (*SQLiteDialect) JsonFieldExtract

func (d *SQLiteDialect) JsonFieldExtract(column, jsonKey string) string

JsonFieldExtract SQLite: json_extract(column, '$.key')

func (*SQLiteDialect) RandomOrderExpr

func (d *SQLiteDialect) RandomOrderExpr() string

RandomOrderExpr SQLite: RANDOM()

func (*SQLiteDialect) UpsertColumnRef

func (d *SQLiteDialect) UpsertColumnRef(column string) string

UpsertColumnRef SQLite: excluded.column SQLite 的 ON CONFLICT ... DO UPDATE 用 excluded.column 引用待插入行的列值

type ScopeHook

type ScopeHook interface {
	ApplyScope(query *Query) *Query
}

ScopeHook 作用域钩子接口

type SimpleModel

type SimpleModel struct {
	ID        uint      `json:"id" gorm:"primaryKey;autoIncrement;comment:自增主键"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
}

SimpleModel 简化模型(不带软删除)

func (*SimpleModel) GetID

func (m *SimpleModel) GetID() uint

func (*SimpleModel) IsNew

func (m *SimpleModel) IsNew() bool

type SoftDeletableModel

type SoftDeletableModel interface {
	ModelInterface
	IsDeleted() bool
}

SoftDeletableModel 支持软删除的模型接口

type SoftDeleteHelper

type SoftDeleteHelper[T any] interface {
	// 使用 deleted_at 字段的软删除
	SoftDeleteWithDeletedAt(ctx context.Context, id interface{}) error
	SoftDeleteBatchWithDeletedAt(ctx context.Context, ids []interface{}) error
	SoftDeleteByFiltersWithDeletedAt(ctx context.Context, filters ...*Filter) error
	RestoreWithDeletedAt(ctx context.Context, id interface{}) error
	RestoreBatchWithDeletedAt(ctx context.Context, ids []interface{}) error

	// 使用 is_deleted 字段的软删除
	SoftDeleteWithIsDeleted(ctx context.Context, id interface{}) error
	SoftDeleteBatchWithIsDeleted(ctx context.Context, ids []interface{}) error
	SoftDeleteByFiltersWithIsDeleted(ctx context.Context, filters ...*Filter) error
	RestoreWithIsDeleted(ctx context.Context, id interface{}) error
	RestoreBatchWithIsDeleted(ctx context.Context, ids []interface{}) error
}

SoftDeleteHelper 软删除辅助接口

type Sorter

type Sorter interface {
	GetField() string
	GetAscending() bool
}

Sorter 排序参数接口,由调用方传入 protobuf Sorting/SortRequest 等消息对象 实现 GetField() string 和 GetAscending() bool 即可,go-toolbox/pkg/sqlbuilder 不依赖任何业务 proto

type StatusModel

type StatusModel interface {
	ModelInterface
	Enable()
	Disable()
	IsEnabled() bool
}

StatusModel 支持状态管理的模型接口

type SubQuery

type SubQuery struct {
	SQL  string        // 子查询 SQL
	Args []interface{} // 子查询参数
}

SubQuery 子查询结构

func NewSubQuery

func NewSubQuery(sql string, args ...interface{}) *SubQuery

NewSubQuery 创建子查询

type TimeEntityCursor

type TimeEntityCursor struct {
	Timestamp string // 时间戳(RFC3339Nano格式)
	EntityID  string // 实体ID(如用户ID、工单ID等)
}

TimeEntityCursor 时间戳+实体ID游标(用于复合排序分页)

func NewTimeEntityCursor

func NewTimeEntityCursor(timestamp *time.Time, entityID string) *TimeEntityCursor

NewTimeEntityCursor 从时间戳和实体ID创建游标

func NewTimeEntityCursorFromTime

func NewTimeEntityCursorFromTime(t time.Time, entityID string, format ...string) *TimeEntityCursor

NewTimeEntityCursorFromTime 从时间对象和实体ID创建游标(支持自定义时间格式)

func ParseTimeEntityCursor

func ParseTimeEntityCursor(cursorStr string) *TimeEntityCursor

ParseTimeEntityCursor 从字符串解析时间戳+实体ID游标

func ParseTimeEntityCursorFromJSON

func ParseTimeEntityCursorFromJSON(jsonStr string) (*TimeEntityCursor, error)

ParseTimeEntityCursorFromJSON 从JSON字符串解析游标

func (*TimeEntityCursor) Clone

func (c *TimeEntityCursor) Clone() *TimeEntityCursor

Clone 深拷贝游标

func (*TimeEntityCursor) Compare

func (c *TimeEntityCursor) Compare(other *TimeEntityCursor) (int, error)

Compare 比较两个游标的先后顺序 返回值: -1(c<other), 0(c==other), 1(c>other)

func (*TimeEntityCursor) Equal

func (c *TimeEntityCursor) Equal(other *TimeEntityCursor) bool

Equal 判断两个游标是否相等

func (*TimeEntityCursor) GetTime

func (c *TimeEntityCursor) GetTime() (*time.Time, error)

GetTime 获取解析后的时间对象

func (*TimeEntityCursor) IsEmpty

func (c *TimeEntityCursor) IsEmpty() bool

IsEmpty 判断游标是否为空

func (*TimeEntityCursor) IsValid

func (c *TimeEntityCursor) IsValid() error

IsValid 验证游标是否有效(两个字段都有值且时间戳格式正确)

func (*TimeEntityCursor) String

func (c *TimeEntityCursor) String() string

String 返回游标的字符串表示(格式:时间戳|实体ID)

func (*TimeEntityCursor) ToBase64

func (c *TimeEntityCursor) ToBase64() string

ToBase64 返回Base64编码的游标字符串(更安全的传输)

func (*TimeEntityCursor) ToJSON

func (c *TimeEntityCursor) ToJSON() (string, error)

ToJSON 序列化为JSON

type TimeEntityCursorBuilder

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

TimeEntityCursorBuilder 游标构建器

func NewCursorBuilder

func NewCursorBuilder() *TimeEntityCursorBuilder

NewCursorBuilder 创建游标构建器

func (*TimeEntityCursorBuilder) Build

Build 构建游标

func (*TimeEntityCursorBuilder) MustBuild

func (b *TimeEntityCursorBuilder) MustBuild() *TimeEntityCursor

MustBuild 构建游标(如果验证失败则panic)

func (*TimeEntityCursorBuilder) WithEntityID

func (b *TimeEntityCursorBuilder) WithEntityID(entityID string) *TimeEntityCursorBuilder

WithEntityID 设置实体ID

func (*TimeEntityCursorBuilder) WithTime

WithTime 设置时间对象

func (*TimeEntityCursorBuilder) WithTimestamp

func (b *TimeEntityCursorBuilder) WithTimestamp(timestamp string) *TimeEntityCursorBuilder

WithTimestamp 设置时间戳字符串

type TimeGroupBuilder

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

TimeGroupBuilder 时间分组聚合构建器

func NewTimeGroupBuilder

func NewTimeGroupBuilder(db *gorm.DB, tableName string, groupType TimeGroupType) *TimeGroupBuilder

NewTimeGroupBuilder 创建时间分组构建器

func (*TimeGroupBuilder) AddGroupBy

func (b *TimeGroupBuilder) AddGroupBy(fields ...string) *TimeGroupBuilder

AddGroupBy 添加额外的分组字段

func (*TimeGroupBuilder) Avg

func (b *TimeGroupBuilder) Avg(field, alias string) *TimeGroupBuilder

Avg 添加 AVG 聚合

func (*TimeGroupBuilder) Build

func (b *TimeGroupBuilder) Build() (*gorm.DB, []interface{})

Build 构建 SQL 查询

func (*TimeGroupBuilder) Count

func (b *TimeGroupBuilder) Count(alias string) *TimeGroupBuilder

Count 添加 COUNT 聚合

func (*TimeGroupBuilder) CountDistinct

func (b *TimeGroupBuilder) CountDistinct(field, alias string) *TimeGroupBuilder

CountDistinct 添加 COUNT DISTINCT 聚合

func (*TimeGroupBuilder) CountWhen

func (b *TimeGroupBuilder) CountWhen(condition, alias string, args ...interface{}) *TimeGroupBuilder

CountWhen 添加条件计数

func (*TimeGroupBuilder) Execute

func (b *TimeGroupBuilder) Execute(ctx context.Context) ([]map[string]interface{}, error)

Execute 执行查询并返回结果

func (*TimeGroupBuilder) ExecuteInto

func (b *TimeGroupBuilder) ExecuteInto(ctx context.Context, dest interface{}) error

ExecuteInto 执行查询并扫描到结构体切片

func (*TimeGroupBuilder) Having

func (b *TimeGroupBuilder) Having(condition string, args ...interface{}) *TimeGroupBuilder

Having 添加 HAVING 条件

func (*TimeGroupBuilder) Limit

func (b *TimeGroupBuilder) Limit(limit int) *TimeGroupBuilder

Limit 设置限制

func (*TimeGroupBuilder) Max

func (b *TimeGroupBuilder) Max(field, alias string) *TimeGroupBuilder

Max 添加 MAX 聚合

func (*TimeGroupBuilder) Min

func (b *TimeGroupBuilder) Min(field, alias string) *TimeGroupBuilder

Min 添加 MIN 聚合

func (*TimeGroupBuilder) OrderBy

func (b *TimeGroupBuilder) OrderBy(order string) *TimeGroupBuilder

OrderBy 设置排序

func (*TimeGroupBuilder) Sum

func (b *TimeGroupBuilder) Sum(field, alias string) *TimeGroupBuilder

Sum 添加 SUM 聚合

func (*TimeGroupBuilder) SumWhen

func (b *TimeGroupBuilder) SumWhen(condition, alias string, args ...interface{}) *TimeGroupBuilder

SumWhen 添加条件求和

func (*TimeGroupBuilder) Where

func (b *TimeGroupBuilder) Where(condition string, args ...interface{}) *TimeGroupBuilder

Where 添加 WHERE 条件

func (*TimeGroupBuilder) WithTimeField

func (b *TimeGroupBuilder) WithTimeField(field string) *TimeGroupBuilder

WithTimeField 设置时间字段

func (*TimeGroupBuilder) WithTimeRange

func (b *TimeGroupBuilder) WithTimeRange(start, end time.Time) *TimeGroupBuilder

WithTimeRange 设置时间范围

type TimeGroupType

type TimeGroupType string

TimeGroupType 时间分组类型

const (
	GroupByHour  TimeGroupType = "hour"  // 按小时分组
	GroupByDay   TimeGroupType = "day"   // 按天分组
	GroupByWeek  TimeGroupType = "week"  // 按周分组
	GroupByMonth TimeGroupType = "month" // 按月分组
	GroupByYear  TimeGroupType = "year"  // 按年分组
)

type TimestampModel

type TimestampModel struct {
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
}

TimestampModel 仅包含时间戳的模型

type Transaction

type Transaction[T any] interface {
	// 执行事务内的操作
	Create(ctx context.Context, entity *T) error
	CreateBatch(ctx context.Context, entities ...*T) error
	Update(ctx context.Context, entity *T) error
	UpdateBatch(ctx context.Context, entities ...*T) error
	Delete(ctx context.Context, entity *T) error
	DeleteBatch(ctx context.Context, entities ...*T) error
}

Transaction 事务接口

type UUIDModel

type UUIDModel struct {
	ID        string         `json:"id" gorm:"primaryKey;type:char(36);comment:UUID主键"`
	Version   int            `json:"version" gorm:"default:1;comment:版本号"`
	CreatedAt time.Time      `json:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time      `json:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
	DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index;comment:删除时间"`
}

UUIDModel UUID作为主键的模型

func (*UUIDModel) BeforeUpdate

func (m *UUIDModel) BeforeUpdate(tx *gorm.DB) error

func (*UUIDModel) GetID

func (m *UUIDModel) GetID() string

func (*UUIDModel) GetVersion

func (m *UUIDModel) GetVersion() int

func (*UUIDModel) IsDeleted

func (m *UUIDModel) IsDeleted() bool

func (*UUIDModel) IsNew

func (m *UUIDModel) IsNew() bool

type VersionedModel

type VersionedModel interface {
	ModelInterface
	GetVersion() int
}

VersionedModel 支持版本控制的模型接口

Jump to

Keyboard shortcuts

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