sqlbuilder

package module
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

README

go-sqlbuilder

GitHub go.mod Go version GoDoc License

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

📖 特性 & 文档导航

特性 说明 文档
🚀 仓储模式 泛型 BaseRepository 和 EnhancedRepository,类型安全的 CRUD 📘 快速开始
🔍 高级查询 FilterGroup 支持复杂 AND/OR 条件组合和无限嵌套 📙 高级查询
🎯 类型安全 完全的泛型支持,编译时类型检查 📗 Repository 基础
自动字段选择 基于 struct tags 自动生成查询字段,避免 SELECT * ⚡ 自动字段选择
🔗 链式查询 便捷方法支持链式调用构建查询条件 🔥 便捷查询示例
📊 性能优化 批量操作、游标分页、原子字段更新、字段缓存 📓 EnhancedRepository
🔐 错误处理 集成 go-toolbox/errorx 的结构化错误管理 📒 错误处理
📝 审计追踪 内置审计字段(created_by, updated_by) 📔 模型定义
🗄️ 数据库迁移 自动迁移、索引创建、表注释 🗄️ 数据库迁移器
🔄 上下文支持 超时控制、日志追踪、请求隔离 🔄 Context 使用指南
🎛️ 复杂条件 FilterGroup 支持无限嵌套的条件组合 📕 FilterGroup 指南
🚄 并发统计 多表并发查询、时间分组统计、条件聚合 🚄 并发统计查询

📦 安装

go get github.com/kamalyes/go-sqlbuilder

🚀 快速开始

package main

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

type User struct {
    repository.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"
    gormDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Fatal(err)
    }
    
    // 2. 创建 Handler
    handler, err := db.NewGormHandler(gormDB)
    if err != nil {
        log.Fatal(err)
    }
    
    // 3. 创建 Repository
    logger := logger.NewLogger(nil)
    repo := repository.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 := repository.NewBaseRepository[User](handler, logger, "users",
    repository.WithAutoFields[User](),  // 🔥 自动字段选择
)

// 创建
user, err := repo.Create(ctx, &User{Name: "Alice"})
err = repo.CreateBatch(ctx, users...)

// 查询
user, err := repo.Get(ctx, 1)
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())
🔗 链式查询构建
query := repository.NewQuery().
    AddEqual("status", 1).
    AddLike("name", "test").
    AddBetween("age", 18, 65).
    AddOrderDesc("created_at").
    Page(1, 20)

users, err := repo.List(ctx, query)
传统方式 便捷方法
AddFilter(NewEqFilter(...)) AddEqual("field", value)
AddFilter(NewLikeFilter(...)) AddLike("field", "test")
AddOrder("field", "DESC") AddOrderDesc("field")
⚡ EnhancedRepository - 便利方法
enhanced := repository.NewEnhancedRepository[User](handler, logger, "users")

users, err := enhanced.FindByField(ctx, "status", "active")
err = enhanced.IncrementField(ctx, 1, "points", 10)  // 原子 +10
err = enhanced.ToggleField(ctx, 1, "is_active")      // 切换布尔
🎛️ FilterGroup - 复杂查询
// (status = 'active' OR status = 'trial') AND age > 18
statusGroup := repository.NewFilterGroup(constants.AND_OR).
    AddFilter(repository.NewEqFilter("status", "active")).
    AddFilter(repository.NewEqFilter("status", "trial"))

mainGroup := repository.NewFilterGroup(constants.AND_AND).
    AddGroup(statusGroup).
    AddFilter(repository.NewGtFilter("age", 18))

query := repository.NewQuery().SetFilterGroup(mainGroup)

🏗️ 内置模型

// BaseModel - ID, CreatedAt, UpdatedAt, DeletedAt
type User struct {
    repository.BaseModel
    Name string
}

// AuditModel - BaseModel + CreatedBy, UpdatedBy
type Article struct {
    repository.AuditModel
    Title string
}

⚙️ 配置选项

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

🧪 测试

go test ./... -v                    # 运行所有测试
go test ./... -cover                # 测试覆盖率
go test -v -run TestBaseRepository  # 运行特定测试

📦 依赖

🤝 贡献

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

📋 Git Commit Emoji 规范

点击展开 Emoji 规范表
Emoji 类型 说明
feat 新功能
🐛 fix 修复 bug
📝 docs 文档更新
♻️ refactor 代码重构
perf 性能优化
test 测试相关
🔧 chore 配置/构建
🚀 deploy 部署发布
🔒 security 安全修复
🔥 remove 删除代码
🗃️ db 数据库相关

示例: git commit -m "✨ feat(db): 新增 Migrator 迁移器"

📄 许可证

MIT License - 详见 LICENSE

👨‍💻 作者

Kamal Yang (@kamalyes)

Documentation

Overview

* @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-sqlbuilder\mapopt.go * @Description: Map类型扩展 - MapAny、MapString、StringSlice的数据库序列化和泛型操作 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

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

type StringSlice []string

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

func ParseStringSlice added in v0.3.3

func ParseStringSlice(input []string) StringSlice

ParseStringSlice 从混合格式解析字符串切片 支持数组或分隔字符串 (分号;换行符\n)

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) FromDelimitedString added in v0.3.3

func (s *StringSlice) FromDelimitedString(input string, delimiters ...string) StringSlice

FromDelimitedString 从分隔符字符串创建 StringSlice 支持多种分隔符: 分号(;)、换行符(\n)、逗号(,) 自动去除空白字符和空字符串

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)

Directories

Path Synopsis
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-23 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-26 21:55:50 * @FilePath: \go-sqlbuilder\constants\operators.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-26 21:55:50 * @FilePath: \go-sqlbuilder\constants\operators.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 13:05:48 * @FilePath: \go-sqlbuilder\db\handler.go * @Description: 数据库处理器 - Handler 接口和 GORM 实现 * * 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:05:48 * @FilePath: \go-sqlbuilder\db\handler.go * @Description: 数据库处理器 - Handler 接口和 GORM 实现 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-13 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-13 10:26:53 * @FilePath: \go-sqlbuilder\errors\checker.go * @Description: 数据库错误检测工具函数 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-13 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-13 10:26:53 * @FilePath: \go-sqlbuilder\errors\checker.go * @Description: 数据库错误检测工具函数 * * 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-12-04 09:15:32 * @FilePath: \go-sqlbuilder\repository\base.go * @Description: * * 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-12-04 09:15:32 * @FilePath: \go-sqlbuilder\repository\base.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

Jump to

Keyboard shortcuts

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