sqlbuilder

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

go-sqlbuilder

GitHub go.mod Go version GoDoc License

一个功能丰富、高性能的 Go 语言 GORM 仓储层封装库,提供类型安全的 CRUD 操作、复杂查询构建和便利方法。

✨ 特性

  • 🚀 仓储模式:泛型 BaseRepository 和 EnhancedRepository,类型安全的 CRUD 操作
  • 🔍 高级查询:FilterGroup 支持复杂的 AND/OR 条件组合和无限嵌套
  • 🎯 类型安全:完全的泛型支持,编译时类型检查
  • 📊 性能优化:批量操作、游标分页、原子字段更新
  • 🔐 错误处理:集成 go-toolbox/errorx 的结构化错误管理
  • 📝 审计追踪:内置审计字段(created_by, updated_by)
  • 🛠️ 便利方法:常用操作的快捷方法

📦 安装

go get github.com/kamalyes/go-sqlbuilder

🚀 快速开始

package main

import (
    "context"
    "log"
    
    sqlbuilder "github.com/kamalyes/go-sqlbuilder"
    "github.com/kamalyes/go-logger"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

type User struct {
    sqlbuilder.BaseModel
    Name   string `gorm:"type:varchar(100)"`
    Email  string `gorm:"type:varchar(100);uniqueIndex"`
    Age    int    `gorm:"type:int"`
    Status string `gorm:"type:varchar(20)"`
}

func main() {
    // 1. 连接数据库
    dsn := "user:password@tcp(127.0.0.1:3306)/testdb?charset=utf8mb4&parseTime=True"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Fatal(err)
    }
    
    // 2. 创建 Handler
    handler, err := sqlbuilder.NewGormHandler(db)
    if err != nil {
        log.Fatal(err)
    }
    
    // 3. 创建 Repository
    logger := logger.NewLogger(nil)
    repo := sqlbuilder.NewBaseRepository[User](handler, logger, "users")
    
    ctx := context.Background()
    
    // 4. 使用 Repository
    
    // 创建
    user := &User{Name: "张三", Email: "zhangsan@example.com", Age: 25}
    created, err := repo.Create(ctx, user)
    
    // 查询
    user, err = repo.Get(ctx, 1)
    
    // 更新
    user.Age = 26
    updated, err := repo.Update(ctx, user)
    
    // 删除
    err = repo.Delete(ctx, 1)
}

📚 核心功能

BaseRepository - 完整 CRUD

提供所有基础数据库操作:

repo := sqlbuilder.NewBaseRepository[User](handler, logger, "users")

// 创建操作
user, err := repo.Create(ctx, &User{Name: "Alice"})
err = repo.CreateBatch(ctx, users...)
created, isNew, err := repo.CreateIfNotExists(ctx, user, "email")

// 查询操作
user, err := repo.Get(ctx, 1)
users, err := repo.GetAll(ctx)
users, paging, err := repo.ListWithPagination(ctx, query, paging)

// 更新操作
user, err := repo.Update(ctx, user)
err = repo.UpdateFields(ctx, 1, map[string]interface{}{"age": 30})

// 删除操作
err = repo.Delete(ctx, 1)
err = repo.SoftDelete(ctx, 1, "deleted_at", time.Now())

// 统计操作
count, err := repo.Count(ctx)
exists, err := repo.Exists(ctx, filter)
EnhancedRepository - 便利方法

扩展方法提供更便捷的操作:

enhanced := sqlbuilder.NewEnhancedRepository[User](handler, logger, "users")

// 字段查询
users, err := enhanced.FindByField(ctx, "status", "active")

// 游标分页(大数据量性能更好)
users, cursor, err := enhanced.FindByFieldWithCursor(ctx, "status", "active", "", 20, "id", "ASC")

// 原子字段操作
err = enhanced.IncrementField(ctx, 1, "points", 10)      // 积分 +10
err = enhanced.DecrementField(ctx, 1, "stock", 5)        // 库存 -5
err = enhanced.ToggleField(ctx, 1, "is_active")          // 切换布尔值
FilterGroup - 复杂查询

支持任意复杂的 AND/OR 条件组合:

// 查询条件:(status = 'active' OR status = 'trial') AND age > 18
statusGroup := sqlbuilder.NewFilterGroup(sqlbuilder.OR).
    AddFilter(sqlbuilder.NewEqFilter("status", "active")).
    AddFilter(sqlbuilder.NewEqFilter("status", "trial"))

mainGroup := sqlbuilder.NewFilterGroup(sqlbuilder.AND).
    AddGroup(statusGroup).
    AddFilter(sqlbuilder.NewGtFilter("age", 18))

query := sqlbuilder.NewQuery().SetFilterGroup(mainGroup)
users, err := repo.List(ctx, query)
丰富的过滤器
// 比较操作
NewEqFilter("status", "active")              // =
NewGtFilter("age", 18)                       // >
NewBetweenFilter("price", 100, 1000)         // BETWEEN

// 范围操作
NewInFilter("id", []interface{}{1, 2, 3})    // IN
NewNotInFilter("status", []interface{}{"deleted", "banned"})

// 模糊查询
NewLikeFilter("name", "张")                  // LIKE '%张%'

// NULL 检查
NewIsNullFilter("deleted_at")                // IS NULL
NewIsNotNullFilter("verified_at")            // IS NOT NULL

// 时间范围
NewTodayFilter("created_at")                 // 今天
NewThisWeekFilter("created_at")              // 本周
NewLastMonthFilter("created_at")             // 上月

// 自定义 SQL
NewCustomFilter("YEAR(created_at) = ?", 2024)

📖 完整文档

我们提供了详细的模块化文档:

🏗️ 内置模型

BaseModel

包含基础字段的模型:

type User struct {
    sqlbuilder.BaseModel  // ID, CreatedAt, UpdatedAt, DeletedAt
    Name  string
    Email string
}
AuditModel

包含审计字段的模型:

type Article struct {
    sqlbuilder.AuditModel  // BaseModel + CreatedBy, UpdatedBy
    Title   string
    Content string
}

⚙️ 配置选项

repo := sqlbuilder.NewBaseRepository[User](
    handler,
    logger,
    "users",
    sqlbuilder.WithBatchSize[User](200),              // 批处理大小
    sqlbuilder.WithTimeout[User](60),                 // 超时时间
    sqlbuilder.WithDefaultPreloads[User]("Profile"),  // 默认预加载
    sqlbuilder.WithDefaultOrder[User]("id DESC"),     // 默认排序
)

🧪 测试

# 运行所有测试
go test ./... -v

# 测试覆盖率
go test ./... -cover
go test -coverprofile=coverage -covermode=atomic
go tool cover -func=coverage

# 运行特定测试
go test -v -run TestBaseRepository

📦 依赖

🤝 贡献

欢迎贡献!请随时提交 Pull Request。

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 开启 Pull Request

📄 许可证

本项目采用 MIT 许可证 - 详见 LICENSE 文件

👨‍💻 作者

Kamal Yang (@kamalyes)

🙏 致谢

  • GORM 团队提供的优秀 ORM
  • Go 社区的灵感和支持

Documentation

Overview

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-23 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 22:50:00 * @FilePath: \go-sqlbuilder\constants.go * @Description: 常量定义 - 操作符、分页、批处理等配置 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

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

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-23 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 22:50:00 * @FilePath: \go-sqlbuilder\handler.go * @Description: 数据库处理器 - Handler 接口和 GORM 实现 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

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

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

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-23 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 22:50:00 * @FilePath: \go-sqlbuilder\mapopt.go * @Description: Map类型扩展 - MapAny、MapString、StringSlice的数据库序列化和泛型操作 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

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

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-23 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 22:50:00 * @FilePath: \go-sqlbuilder\paging.go * @Description: 分页工具 - Pagination分页元数据和辅助方法 * * 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: 2025-11-23 22:39:16 * @FilePath: \go-sqlbuilder\repository.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

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

Index

Constants

View Source
const (
	OP_EQ          = OpEqual
	OP_NEQ         = OpNotEqual
	OP_GT          = OpGreaterThan
	OP_GTE         = OpGreaterThanOrEqual
	OP_LT          = OpLessThan
	OP_LTE         = OpLessThanOrEqual
	OP_LIKE        = OpLike
	OP_NOT_LIKE    = OpNotLike
	OP_IN          = OpIn
	OP_NOT_IN      = OpNotIn
	OP_BETWEEN     = OpBetween
	OP_IS_NULL     = OpIsNull
	OP_IS_NOT_NULL = OpIsNotNull
	OP_FIND_IN_SET = OpFindInSet
	LOGIC_AND      = LogicAnd
	LOGIC_OR       = LogicOr
)
View Source
const (
	// DefaultPage 默认页码
	DefaultPage = 1

	// DefaultPageSize 默认每页大小
	DefaultPageSize = 10
)
View Source
const (
	// SQL_EQUAL 等于条件模板
	SQL_EQUAL = "%s = ?"

	// SQL_NOT_EQUAL 不等于条件模板
	SQL_NOT_EQUAL = "%s != ?"

	// SQL_GREATER 大于条件模板
	SQL_GREATER = "%s > ?"

	// SQL_GREATER_EQUAL 大于等于条件模板
	SQL_GREATER_EQUAL = "%s >= ?"

	// SQL_LESS 小于条件模板
	SQL_LESS = "%s < ?"

	// SQL_LESS_EQUAL 小于等于条件模板
	SQL_LESS_EQUAL = "%s <= ?"

	// SQL_IN IN条件模板
	SQL_IN = "%s IN ?"

	// SQL_NOT_IN NOT IN条件模板
	SQL_NOT_IN = "%s NOT IN ?"

	// SQL_LIKE LIKE条件模板
	SQL_LIKE = "%s LIKE ?"

	// SQL_NOT_LIKE NOT LIKE条件模板
	SQL_NOT_LIKE = "%s NOT LIKE ?"

	// SQL_BETWEEN BETWEEN条件模板
	SQL_BETWEEN = "%s BETWEEN ? AND ?"

	// SQL_IS_NULL IS NULL条件模板
	SQL_IS_NULL = "%s IS NULL"

	// SQL_IS_NOT_NULL IS NOT NULL条件模板
	SQL_IS_NOT_NULL = "%s IS NOT NULL"

	// SQL_FIND_IN_SET FIND_IN_SET条件模板
	SQL_FIND_IN_SET = "FIND_IN_SET(?, %s)"

	// SQL_ORDER_BY 排序模板
	SQL_ORDER_BY = "%s %s"

	// SQL_INCREMENT 字段自增模板
	SQL_INCREMENT = "%s + ?"

	// SQL_DECREMENT 字段自减模板
	SQL_DECREMENT = "%s - ?"
)
View Source
const (
	// Asc 升序
	Asc = "ASC"

	// Desc 降序
	Desc = "DESC"

	// DefaultOrder 默认排序方向
	DefaultOrder = Asc
)
View Source
const (
	// DefaultBatchSize 默认批处理大小
	DefaultBatchSize = 100
)
View Source
const (
	// DefaultQueryTimeout 默认查询超时时间(秒)
	DefaultQueryTimeout = 30
)

Variables

This section is empty.

Functions

func GetDeleted added in v0.2.0

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

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

func GetNonDeleted added in v0.2.0

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

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

func PermanentlyDelete added in v0.2.0

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

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

func PermanentlyDeleteBatch added in v0.2.0

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

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

func RestoreDeleted added in v0.2.0

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

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

func RestoreDeletedBatch added in v0.2.0

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

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

Types

type AuditModel added in v0.2.0

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 added in v0.2.0

func (m *AuditModel) GetCreatedBy() uint

func (*AuditModel) GetUpdatedBy added in v0.2.0

func (m *AuditModel) GetUpdatedBy() uint

func (*AuditModel) SetCreatedBy added in v0.2.0

func (m *AuditModel) SetCreatedBy(userID uint)

func (*AuditModel) SetUpdatedBy added in v0.2.0

func (m *AuditModel) SetUpdatedBy(userID uint)

type AuditableModel added in v0.2.0

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

AuditableModel 支持审计的模型接口

type BaseModel added in v0.2.0

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 added in v0.2.0

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

BeforeUpdate GORM更新前钩子

func (*BaseModel) Disable added in v0.2.0

func (m *BaseModel) Disable()

Disable 禁用

func (*BaseModel) Enable added in v0.2.0

func (m *BaseModel) Enable()

Enable 启用

func (*BaseModel) GetID added in v0.2.0

func (m *BaseModel) GetID() uint

GetID 获取主键ID

func (*BaseModel) GetVersion added in v0.2.0

func (m *BaseModel) GetVersion() int

GetVersion 获取版本号

func (*BaseModel) IsDeleted added in v0.2.0

func (m *BaseModel) IsDeleted() bool

IsDeleted 判断是否已删除

func (*BaseModel) IsEnabled added in v0.2.0

func (m *BaseModel) IsEnabled() bool

IsEnabled 判断是否启用

func (*BaseModel) IsNew added in v0.2.0

func (m *BaseModel) IsNew() bool

IsNew 判断是否为新记录

func (*BaseModel) SetCreatedAt added in v0.2.0

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

func (*BaseModel) SetRemark added in v0.2.0

func (m *BaseModel) SetRemark(remark string)

SetRemark 设置备注

func (*BaseModel) SetUpdatedAt added in v0.2.0

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

type BaseRepository added in v0.2.0

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

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

func NewBaseRepository added in v0.2.0

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

NewBaseRepository 创建基础仓储

func (*BaseRepository[T]) BulkCreate added in v0.2.0

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

BulkCreate 高性能批量创建

func (*BaseRepository[T]) Count added in v0.2.0

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

Count 计数

func (*BaseRepository[T]) CountByField added in v0.2.0

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

CountByField 按字段计数(GROUP BY)

func (*BaseRepository[T]) Create added in v0.2.0

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

Create 创建单个记录

func (*BaseRepository[T]) CreateBatch added in v0.2.0

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

CreateBatch 批量创建记录

func (*BaseRepository[T]) CreateIfNotExists added in v0.2.0

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

CreateIfNotExists 如果不存在则创建

func (*BaseRepository[T]) CreateOrUpdate added in v0.2.0

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

CreateOrUpdate 创建或更新记录

func (*BaseRepository[T]) DBHandler added in v0.2.0

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

DBHandler 获取数据库处理器

func (*BaseRepository[T]) Delete added in v0.2.0

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

Delete 删除单个记录

func (*BaseRepository[T]) DeleteBatch added in v0.2.0

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

DeleteBatch 批量删除记录

func (*BaseRepository[T]) DeleteByFilters added in v0.2.0

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

DeleteByFilters 按过滤条件删除记录

func (*BaseRepository[T]) Distinct added in v0.2.0

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

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

func (*BaseRepository[T]) Exists added in v0.2.0

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

Exists 检查记录是否存在

func (*BaseRepository[T]) Find added in v0.2.0

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

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

func (*BaseRepository[T]) FindOne added in v0.2.0

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

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

func (*BaseRepository[T]) First added in v0.2.0

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

First 获取第一条记录

func (*BaseRepository[T]) Get added in v0.2.0

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

Get 获取单个记录

func (*BaseRepository[T]) GetAll added in v0.2.0

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

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

func (*BaseRepository[T]) GetByFields added in v0.2.0

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

GetByFields 根据多个字段获取记录

func (*BaseRepository[T]) GetByFilter added in v0.2.0

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

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

func (*BaseRepository[T]) GetByFilters added in v0.2.0

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

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

func (*BaseRepository[T]) GetWithPreloads added in v0.2.0

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

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

func (*BaseRepository[T]) Last added in v0.2.0

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

Last 获取最后一条记录

func (*BaseRepository[T]) List added in v0.2.0

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

List 列表查询

func (*BaseRepository[T]) ListWithPagination added in v0.2.0

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

ListWithPagination 分页列表查询

func (*BaseRepository[T]) ListWithPreloads added in v0.2.0

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

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

func (*BaseRepository[T]) Pluck added in v0.2.0

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

Pluck 提取单个字段的值列表

func (*BaseRepository[T]) Restore added in v0.2.0

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 added in v0.2.0

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]) SoftDelete added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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

Table 获取表名

func (*BaseRepository[T]) Transaction added in v0.2.0

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

Transaction 事务支持

func (*BaseRepository[T]) Update added in v0.2.0

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

Update 更新单个记录

func (*BaseRepository[T]) UpdateBatch added in v0.2.0

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

UpdateBatch 批量更新记录

func (*BaseRepository[T]) UpdateByFilters added in v0.2.0

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

UpdateByFilters 按过滤条件更新记录

func (*BaseRepository[T]) UpdateFields added in v0.2.0

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

UpdateFields 更新指定字段

func (*BaseRepository[T]) UpdateFieldsByFilters added in v0.2.0

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

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

type ComparedColumn added in v0.2.0

type ComparedColumn struct {
	TableAlias  string
	ColumnName  string
	DBFieldName string
}

type ComparedValue added in v0.2.0

type ComparedValue struct {
	Value interface{}
	IsRaw bool
}

type Condition added in v0.2.0

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

Condition 查询条件结构

type ContextFieldExtractor added in v0.2.0

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

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

type EnhancedRepository added in v0.2.0

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

EnhancedRepository 增强版仓储实现

func NewEnhancedRepository added in v0.2.0

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

NewEnhancedRepository 创建增强版仓储实例

func NewEnhancedRepositoryWithDB added in v0.2.0

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

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

func (*EnhancedRepository[T]) BatchUpdateByField added in v0.2.0

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

BatchUpdateByField 根据字段批量更新

func (*EnhancedRepository[T]) CountByField added in v0.2.0

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

CountByField 根据字段统计数量

func (*EnhancedRepository[T]) CreateIfNotExists added in v0.2.0

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

CreateIfNotExists 如果不存在则创建

func (*EnhancedRepository[T]) DecrementField added in v0.2.0

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

DecrementField 字段自减

func (*EnhancedRepository[T]) DeleteByField added in v0.2.0

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

DeleteByField 根据字段删除记录

func (*EnhancedRepository[T]) ExistsBy added in v0.2.0

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

ExistsBy 检查记录是否存在

func (*EnhancedRepository[T]) FindByField added in v0.2.0

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

FindByField 根据单个字段查找记录

func (*EnhancedRepository[T]) FindByFieldWithCursor added in v0.2.0

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 added in v0.2.0

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

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

func (*EnhancedRepository[T]) FindByFields added in v0.2.0

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

FindByFields 根据多个字段查找记录

func (*EnhancedRepository[T]) FindByTimeRange added in v0.2.0

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

FindByTimeRange 根据时间范围查找

func (*EnhancedRepository[T]) FindInField added in v0.2.0

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

FindInField 根据字段的IN查询

func (*EnhancedRepository[T]) FindOneByField added in v0.2.0

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

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

func (*EnhancedRepository[T]) FindWithOrder added in v0.2.0

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

FindWithOrder 根据条件查找并排序

func (*EnhancedRepository[T]) GetDistinctValues added in v0.2.0

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

GetDistinctValues 获取字段的不同值

func (*EnhancedRepository[T]) IncrementField added in v0.2.0

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

IncrementField 字段自增

func (*EnhancedRepository[T]) UpdateByField added in v0.2.0

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

UpdateByField 根据字段更新记录

func (*EnhancedRepository[T]) UpdateSingleField added in v0.2.0

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

UpdateSingleField 更新单个字段

type ErrorCode added in v0.2.0

type ErrorCode = errorx.ErrorType

ErrorCode 错误代码类型(复用 errorx.ErrorType)

const (
	ErrorCodeNotFound     ErrorCode = 1001 // 记录不存在
	ErrorCodeAlreadyExist ErrorCode = 1002 // 记录已存在
	ErrorCodeInvalidInput ErrorCode = 1003 // 输入参数无效
	ErrorCodeUnauthorized ErrorCode = 1004 // 未授权
	ErrorCodeForbidden    ErrorCode = 1005 // 禁止访问
	ErrorCodeConflict     ErrorCode = 1006 // 操作冲突
)

通用业务错误 (1000-1999)

const (
	ErrorCodeDBError           ErrorCode = 2001 // 数据库操作失败
	ErrorCodeDBDuplicate       ErrorCode = 2002 // 数据库记录重复
	ErrorCodeDBConstraint      ErrorCode = 2003 // 数据库约束冲突
	ErrorCodeDBDeadlock        ErrorCode = 2004 // 数据库死锁
	ErrorCodeNoDatabaseConn    ErrorCode = 2005 // 无数据库连接
	ErrorCodeDBFailedUpdate    ErrorCode = 2006 // 数据库更新失败
	ErrorCodeDBFailedInsert    ErrorCode = 2007 // 数据库插入失败
	ErrorCodeDBFailedDelete    ErrorCode = 2008 // 数据库删除失败
	ErrorCodeNestedTransaction ErrorCode = 2009 // 嵌套事务错误
)

数据库错误 (2000-2999)

const (
	ErrorCodeCacheError              ErrorCode = 3001 // 缓存操作失败
	ErrorCodeCacheMiss               ErrorCode = 3002 // 缓存未命中
	ErrorCodeCacheStoreNotFound      ErrorCode = 3003 // 缓存存储未找到
	ErrorCodeCacheKeyNotFound        ErrorCode = 3004 // 缓存键不存在
	ErrorCodeCacheExpired            ErrorCode = 3005 // 缓存已过期
	ErrorCodeCacheStoreNotConfigured ErrorCode = 3006 // 缓存存储未配置
	ErrorCodeCacheInvalidData        ErrorCode = 3007 // 缓存数据无效
)

缓存错误 (3000-3999)

const (
	ErrorCodeResourceNotFound      ErrorCode = 4001 // 资源不存在
	ErrorCodeBuilderNotInitialized ErrorCode = 4002 // Builder未初始化
	ErrorCodeInvalidTableName      ErrorCode = 4003 // 表名无效
	ErrorCodeInvalidFieldName      ErrorCode = 4004 // 字段名无效
	ErrorCodeInvalidSQLQuery       ErrorCode = 4005 // SQL查询无效
	ErrorCodeAdapterNotSupported   ErrorCode = 4006 // 适配器不支持
)

SQL构建器错误 (4000-4999)

const (
	ErrorCodeInvalidOperator    ErrorCode = 4101 // 无效的操作符
	ErrorCodeInvalidFilterValue ErrorCode = 4102 // 过滤值无效
	ErrorCodePageNumberInvalid  ErrorCode = 4103 // 页码无效
	ErrorCodePageSizeInvalid    ErrorCode = 4104 // 页大小无效
	ErrorCodeTimeRangeInvalid   ErrorCode = 4105 // 时间范围无效
	ErrorCodeEmptyFilterParam   ErrorCode = 4106 // 过滤参数为空
)

查询错误 (复用4000区间扩展)

const (
	ErrorCodeInternal        ErrorCode = 9001 // 内部服务错误
	ErrorCodeTimeout         ErrorCode = 9002 // 请求超时
	ErrorCodeTooManyRequests ErrorCode = 9003 // 请求过于频繁(限流)
	ErrorCodeUnsupported     ErrorCode = 9004 // 不支持的操作
	ErrorCodeUnknown         ErrorCode = 9005 // 未知错误
	ErrorCodeOperationFailed ErrorCode = 9006 // 操作失败
)

系统级错误 (9000-9999)

const (
	ErrorCodeSuccess ErrorCode = 0 // 成功
)

基础通用错误 (0-999)

type Filter

type Filter struct {
	Field    string      // 字段名
	Operator Operator    // 操作符
	Value    interface{} // 值
}

Filter 过滤条件

func NewBetweenFilter added in v0.2.0

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

NewBetweenFilter 创建 BETWEEN 过滤条件

func NewContainsFilter added in v0.2.0

func NewContainsFilter(field string, value string) *Filter

NewContainsFilter 创建包含匹配过滤条件(与 NewLikeFilter 相同)

func NewEndsWithFilter added in v0.2.0

func NewEndsWithFilter(field string, value string) *Filter

NewEndsWithFilter 创建后缀匹配过滤条件

func NewEqFilter added in v0.2.0

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

NewEqFilter 创建等于过滤条件

func NewFindInSetFilter added in v0.2.0

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

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

func NewGtFilter added in v0.2.0

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

NewGtFilter 创建大于过滤条件

func NewGteFilter added in v0.2.0

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

NewGteFilter 创建大于等于过滤条件

func NewInFilter added in v0.2.0

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

NewInFilter 创建 IN 过滤条件

func NewIsNotNullFilter added in v0.2.0

func NewIsNotNullFilter(field string) *Filter

NewIsNotNullFilter 创建 IS NOT NULL 过滤条件

func NewIsNullFilter added in v0.2.0

func NewIsNullFilter(field string) *Filter

NewIsNullFilter 创建 IS NULL 过滤条件

func NewLikeFilter added in v0.2.0

func NewLikeFilter(field string, value string) *Filter

NewLikeFilter 创建 LIKE 过滤条件

func NewLtFilter added in v0.2.0

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

NewLtFilter 创建小于过滤条件

func NewLteFilter added in v0.2.0

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

NewLteFilter 创建小于等于过滤条件

func NewNeqFilter added in v0.2.0

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

NewNeqFilter 创建不等于过滤条件

func NewNotInFilter added in v0.2.0

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

NewNotInFilter 创建 NOT IN 过滤条件

func NewNotLikeFilter added in v0.2.0

func NewNotLikeFilter(field string, value string) *Filter

NewNotLikeFilter 创建 NOT LIKE 过滤条件

func NewStartsWithFilter added in v0.2.0

func NewStartsWithFilter(field string, value string) *Filter

NewStartsWithFilter 创建前缀匹配过滤条件

type FilterGroup

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

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

func NewFilterGroup added in v0.2.0

func NewFilterGroup(logicOp Operator) *FilterGroup

NewFilterGroup 创建新的过滤条件组

func (*FilterGroup) AddFilter added in v0.2.0

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

AddFilter 向条件组添加过滤条件

func (*FilterGroup) AddFilters added in v0.2.0

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

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

func (*FilterGroup) AddGroup added in v0.2.0

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

AddGroup 向条件组添加嵌套条件组

func (*FilterGroup) Count added in v0.2.0

func (fg *FilterGroup) Count() int

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

func (*FilterGroup) IsEmpty added in v0.2.0

func (fg *FilterGroup) IsEmpty() bool

IsEmpty 检查条件组是否为空

type FindOptions

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

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

type FullFeaturedModel added in v0.2.0

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

type GormHandler added in v0.2.0

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

GormHandler 标准 GORM 处理器实现

func (*GormHandler) GetDB added in v0.2.0

func (h *GormHandler) GetDB() *gorm.DB

DB 返回底层 GORM 实例

func (*GormHandler) IsConnected added in v0.2.0

func (h *GormHandler) IsConnected() bool

IsConnected 检查数据库连接是否有效

type Handler added in v0.2.0

type Handler interface {
	// GetDB 返回 GORM 数据库实例
	GetDB() *gorm.DB

	// IsConnected 检查数据库连接是否有效
	IsConnected() bool
}

Handler 数据库处理器接口 所有 Repository 都基于这个接口工作,提供统一的数据库访问抽象

func MustNewGormHandler added in v0.2.0

func MustNewGormHandler(db *gorm.DB) Handler

MustNewGormHandler 创建 GORM 处理器(panic 版本) 仅在确定 db 不为 nil 时使用,通常用于初始化阶段

func NewGormHandler added in v0.2.0

func NewGormHandler(db *gorm.DB) (Handler, error)

NewGormHandler 创建 GORM 处理器 返回 Handler 接口和可能的错误

type JSONType added in v0.1.7

type JSONType[T any] struct {
	Data T
}

泛型 JSON 类型,支持任意可序列化类型

func (*JSONType[T]) Get added in v0.1.7

func (j *JSONType[T]) Get() T

Get 获取数据

func (*JSONType[T]) Scan added in v0.1.7

func (j *JSONType[T]) Scan(value interface{}) error

func (*JSONType[T]) Set added in v0.1.7

func (j *JSONType[T]) Set(data T)

Set 设置数据

func (JSONType[T]) Value added in v0.1.7

func (j JSONType[T]) Value() (driver.Value, error)

type LightModel added in v0.2.0

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 added in v0.2.0

func (m *LightModel) Disable()

func (*LightModel) Enable added in v0.2.0

func (m *LightModel) Enable()

func (*LightModel) GetID added in v0.2.0

func (m *LightModel) GetID() uint

func (*LightModel) IsEnabled added in v0.2.0

func (m *LightModel) IsEnabled() bool

func (*LightModel) IsNew added in v0.2.0

func (m *LightModel) IsNew() bool

type MapAny

type MapAny map[string]any

MapAny 任意类型的 Map,支持数据库 JSON 序列化

func (MapAny) Clone added in v0.1.7

func (m MapAny) Clone() MapAny

Clone 克隆一个新的 Map

func (MapAny) Delete added in v0.1.7

func (m MapAny) Delete(key string) MapAny

Delete 删除指定 key

func (MapAny) Get added in v0.1.7

func (m MapAny) Get(key string, defaultValue ...any) any

Get 获取指定 key 的值,支持默认值

func (MapAny) GetBool added in v0.1.7

func (m MapAny) GetBool(key string, defaultValue ...bool) bool

GetBool 获取布尔值

func (MapAny) GetInt added in v0.1.7

func (m MapAny) GetInt(key string, defaultValue ...int) int

GetInt 获取整数值

func (MapAny) GetString added in v0.1.7

func (m MapAny) GetString(key string, defaultValue ...string) string

GetString 获取字符串值

func (MapAny) Has added in v0.1.7

func (m MapAny) Has(key string) bool

Has 检查 key 是否存在

func (MapAny) Keys added in v0.1.7

func (m MapAny) Keys() []string

Keys 获取所有 key

func (MapAny) Merge added in v0.1.7

func (m MapAny) Merge(other MapAny) MapAny

Merge 合并另一个 Map

func (*MapAny) Scan

func (m *MapAny) Scan(value interface{}) error

func (MapAny) Set added in v0.1.7

func (m MapAny) Set(key string, value any) MapAny

Set 设置值

func (MapAny) Value

func (m MapAny) Value() (driver.Value, error)

func (MapAny) Values added in v0.1.7

func (m MapAny) Values() []any

Values 获取所有 value

type MapString

type MapString map[string]string

MapString 字符串类型的 Map,支持数据库 JSON 序列化

func (MapString) Clone added in v0.1.7

func (m MapString) Clone() MapString

Clone 克隆一个新的 Map

func (MapString) Delete added in v0.1.7

func (m MapString) Delete(key string) MapString

Delete 删除指定 key

func (MapString) Get added in v0.1.7

func (m MapString) Get(key string, defaultValue ...string) string

Get 获取指定 key 的值,支持默认值

func (MapString) Has added in v0.1.7

func (m MapString) Has(key string) bool

Has 检查 key 是否存在

func (MapString) Keys added in v0.1.7

func (m MapString) Keys() []string

Keys 获取所有 key

func (MapString) Merge added in v0.1.7

func (m MapString) Merge(other MapString) MapString

Merge 合并另一个 Map

func (*MapString) Scan

func (m *MapString) Scan(value interface{}) error

func (MapString) Set added in v0.1.7

func (m MapString) Set(key, value string) MapString

Set 设置值

func (MapString) ToMapAny added in v0.1.7

func (m MapString) ToMapAny() MapAny

ToMapAny 转换为 MapAny

func (MapString) Value

func (m MapString) Value() (driver.Value, error)

func (MapString) Values added in v0.1.7

func (m MapString) Values() []string

Values 获取所有 value

type ModelInterface

type ModelInterface interface {
	IsNew() bool
}

ModelInterface 模型通用接口

type Operator added in v0.2.0

type Operator string

Operator 操作符类型(统一定义,避免重复)

const (
	OpEqual              Operator = "="  // 等于
	OpNotEqual           Operator = "!=" // 不等于
	OpGreaterThan        Operator = ">"  // 大于
	OpGreaterThanOrEqual Operator = ">=" // 大于等于
	OpLessThan           Operator = "<"  // 小于
	OpLessThanOrEqual    Operator = "<=" // 小于等于
)
const (
	OpLike    Operator = "LIKE"     // 模糊匹配
	OpNotLike Operator = "NOT LIKE" // 不匹配
)
const (
	OpIn      Operator = "IN"      // 包含
	OpNotIn   Operator = "NOT IN"  // 不包含
	OpBetween Operator = "BETWEEN" // 范围
)
const (
	OpIsNull    Operator = "IS NULL"     // 为空
	OpIsNotNull Operator = "IS NOT NULL" // 不为空
)
const (
	OpFindInSet Operator = "FIND_IN_SET" // MySQL FIND_IN_SET
	OpRegex     Operator = "REGEXP"      // 正则匹配
	OpNotRegex  Operator = "NOT REGEXP"  // 正则不匹配
)
const (
	LogicAnd Operator = "AND" // 逻辑与
	LogicOr  Operator = "OR"  // 逻辑或
	LogicNot Operator = "NOT" // 逻辑非
)

type Order added in v0.2.0

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

Order 排序条件

type OrderBy

type OrderBy struct {
	Field     string
	Direction string
}

OrderBy 排序条件结构

type Pagination added in v0.2.0

type Pagination struct {
	Page     int32 `json:"page"`      // 当前页码(从1开始)
	PageSize int32 `json:"page_size"` // 每页记录数
	Offset   int32 `json:"offset"`    // 数据库偏移量
	Limit    int32 `json:"limit"`     // 查询限制数
	Total    int64 `json:"total"`     // 总记录数
}

Pagination 分页元数据

func (*Pagination) GetLimit added in v0.2.0

func (p *Pagination) GetLimit() int

GetLimit 获取查询限制数

func (*Pagination) GetOffset added in v0.2.0

func (p *Pagination) GetOffset() int

GetOffset 计算数据库偏移量

func (*Pagination) GetTotalPages added in v0.2.0

func (p *Pagination) GetTotalPages() int64

GetTotalPages 计算总页数

func (*Pagination) HasNextPage added in v0.2.0

func (p *Pagination) HasNextPage() bool

HasNextPage 是否有下一页

func (*Pagination) HasPrevPage added in v0.2.0

func (p *Pagination) HasPrevPage() bool

HasPrevPage 是否有上一页

type Query added in v0.2.0

type Query struct {
	Filters     []*Filter    // 简单过滤条件
	FilterGroup *FilterGroup // 复合过滤条件组
	Orders      []Order      // 排序条件
	Pagination  *Pagination  // 分页信息
	LimitValue  *int         // 限制数量
	OffsetValue *int         // 偏移量
	Distinct    bool         // 是否去重
	GroupBy     []string     // 分组字段
	Having      []*Filter    // HAVING 条件
}

Query 查询条件

func NewQuery added in v0.2.0

func NewQuery() *Query

NewQuery 创建查询条件

func (*Query) AddFilter added in v0.2.0

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

AddFilter 添加过滤条件

func (*Query) AddFilters added in v0.2.0

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

AddFilters 批量添加过滤条件

func (*Query) AddGroupBy added in v0.2.0

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

AddGroupBy 添加分组字段

func (*Query) AddHaving added in v0.2.0

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

AddHaving 添加HAVING条件

func (*Query) AddOrder added in v0.2.0

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

AddOrder 添加排序条件

func (*Query) GetAllFilters added in v0.2.0

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

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

func (*Query) HasFilters added in v0.2.0

func (q *Query) HasFilters() bool

HasFilters 检查是否有过滤条件

func (*Query) Limit added in v0.2.0

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

Limit 设置查询限制数量

func (*Query) Offset added in v0.2.0

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

Offset 设置查询偏移量

func (*Query) WithDistinct added in v0.2.0

func (q *Query) WithDistinct(distinct bool) *Query

WithDistinct 设置去重查询

func (*Query) WithFilterGroup added in v0.2.0

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

WithFilterGroup 设置复合过滤条件组

func (*Query) WithPaging added in v0.2.0

func (q *Query) WithPaging(page, pageSize int) *Query

WithPaging 设置分页条件

type QueryCondition added in v0.2.0

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

type RemarkableModel added in v0.2.0

type RemarkableModel interface {
	ModelInterface
	SetRemark(remark string)
}

RemarkableModel 支持备注的模型接口

type Repository added in v0.2.0

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)
	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

	// 删除
	Delete(ctx context.Context, id interface{}) error
	DeleteBatch(ctx context.Context, ids ...interface{}) error
	DeleteByFilters(ctx context.Context, filters ...*Filter) 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

	// 工具方法
	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)
}

Repository 通用仓储接口

type RepositoryFactory added in v0.2.0

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

	// 关闭工厂
	Close() error
}

RepositoryFactory 仓储工厂接口

type RepositoryOption added in v0.2.0

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

RepositoryOption 仓储配置选项

func WithBatchSize added in v0.2.0

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

WithBatchSize 设置批处理大小

func WithDefaultOrder added in v0.2.0

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

WithDefaultOrder 设置默认排序

func WithDefaultPreloads added in v0.2.0

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

WithDefaultPreloads 设置默认预加载关联

func WithLogger added in v0.2.0

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

WithLogger 设置日志记录器

func WithReadOnly added in v0.2.0

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

WithReadOnly 设置为只读模式

func WithTimeout added in v0.2.0

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

WithTimeout 设置查询超时时间

type RepositoryWithSoftDelete added in v0.2.0

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

RepositoryWithSoftDelete 带软删除功能的仓储

func NewRepositoryWithSoftDelete added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) ListDeleted added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) ListDeletedByIsDeleted added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) ListNotDeleted added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) ListNotDeletedByIsDeleted added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) RestoreBatchWithDeletedAt added in v0.2.0

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

RestoreBatchWithDeletedAt 使用 deleted_at 字段批量恢复

func (*RepositoryWithSoftDelete[T]) RestoreBatchWithIsDeleted added in v0.2.0

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

RestoreBatchWithIsDeleted 使用 is_deleted 字段批量恢复

func (*RepositoryWithSoftDelete[T]) RestoreWithDeletedAt added in v0.2.0

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

RestoreWithDeletedAt 使用 deleted_at 字段恢复

func (*RepositoryWithSoftDelete[T]) RestoreWithIsDeleted added in v0.2.0

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

RestoreWithIsDeleted 使用 is_deleted 字段恢复

func (*RepositoryWithSoftDelete[T]) SoftDeleteBatchWithDeletedAt added in v0.2.0

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

SoftDeleteBatchWithDeletedAt 使用 deleted_at 字段批量软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteBatchWithIsDeleted added in v0.2.0

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

SoftDeleteBatchWithIsDeleted 使用 is_deleted 字段批量软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteByFiltersWithDeletedAt added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) SoftDeleteByFiltersWithIsDeleted added in v0.2.0

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

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

func (*RepositoryWithSoftDelete[T]) SoftDeleteWithDeletedAt added in v0.2.0

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

SoftDeleteWithDeletedAt 使用 deleted_at 字段软删除

func (*RepositoryWithSoftDelete[T]) SoftDeleteWithIsDeleted added in v0.2.0

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

SoftDeleteWithIsDeleted 使用 is_deleted 字段软删除

type SimpleModel added in v0.2.0

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 added in v0.2.0

func (m *SimpleModel) GetID() uint

func (*SimpleModel) IsNew added in v0.2.0

func (m *SimpleModel) IsNew() bool

type Slice added in v0.1.7

type Slice[T any] []T

泛型切片类型

func Map added in v0.1.7

func Map[T any, R any](s Slice[T], fn func(T) R) Slice[R]

Map 映射转换

func (*Slice[T]) Append added in v0.1.7

func (s *Slice[T]) Append(items ...T) Slice[T]

Append 追加元素

func (Slice[T]) Clone added in v0.1.7

func (s Slice[T]) Clone() Slice[T]

Clone 克隆切片

func (Slice[T]) Filter added in v0.1.7

func (s Slice[T]) Filter(fn func(T) bool) Slice[T]

Filter 过滤元素

func (Slice[T]) Len added in v0.1.7

func (s Slice[T]) Len() int

Len 获取长度

func (*Slice[T]) Scan added in v0.1.7

func (s *Slice[T]) Scan(value interface{}) error

func (Slice[T]) Value added in v0.1.7

func (s Slice[T]) Value() (driver.Value, error)

type SoftDeletableModel added in v0.2.0

type SoftDeletableModel interface {
	ModelInterface
	IsDeleted() bool
}

SoftDeletableModel 支持软删除的模型接口

type SoftDeleteHelper added in v0.2.0

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 StatusModel added in v0.2.0

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

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

type StringSlice

type StringSlice []string

StringSlice 字符串切片,支持数据库 JSON 序列化

func (*StringSlice) Append added in v0.1.7

func (s *StringSlice) Append(items ...string) StringSlice

Append 追加元素

func (StringSlice) Clone added in v0.1.7

func (s StringSlice) Clone() StringSlice

Clone 克隆一个新的切片

func (StringSlice) Contains added in v0.1.7

func (s StringSlice) Contains(item string) bool

Contains 检查是否包含指定元素

func (StringSlice) Filter added in v0.1.7

func (s StringSlice) Filter(fn func(string) bool) StringSlice

Filter 过滤元素

func (StringSlice) IndexOf added in v0.1.7

func (s StringSlice) IndexOf(item string) int

IndexOf 查找元素索引,未找到返回 -1

func (StringSlice) Join added in v0.1.7

func (s StringSlice) Join(sep string) string

Join 连接为字符串

func (StringSlice) Map added in v0.1.7

func (s StringSlice) Map(fn func(string) string) StringSlice

Map 映射转换

func (*StringSlice) Remove added in v0.1.7

func (s *StringSlice) Remove(item string) StringSlice

Remove 移除指定元素(第一个匹配的)

func (*StringSlice) RemoveAt added in v0.1.7

func (s *StringSlice) RemoveAt(index int) StringSlice

RemoveAt 移除指定索引的元素

func (*StringSlice) Scan

func (s *StringSlice) Scan(value interface{}) error

func (StringSlice) Unique added in v0.1.7

func (s StringSlice) Unique() StringSlice

Unique 去重

func (StringSlice) Value

func (s StringSlice) Value() (driver.Value, error)

type TimestampModel added in v0.2.0

type TimestampModel struct {
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
}

TimestampModel 仅包含时间戳的模型

type Transaction added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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

func (*UUIDModel) GetID added in v0.2.0

func (m *UUIDModel) GetID() string

func (*UUIDModel) GetVersion added in v0.2.1

func (m *UUIDModel) GetVersion() int

func (*UUIDModel) IsDeleted added in v0.2.1

func (m *UUIDModel) IsDeleted() bool

func (*UUIDModel) IsNew added in v0.2.0

func (m *UUIDModel) IsNew() bool

type VersionedModel added in v0.2.0

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