gom

package module
v4.7.4 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2025 License: Apache-2.0 Imports: 24 Imported by: 3

README

GOM - Go ORM Framework

GOM 是一个功能强大的 Go 语言 ORM 框架,提供了灵活的数据库操作和高级的类型转换功能。

发行注记

v4.6.4 (2025-03-25)
  • 修复 NULL 值处理机制,确保字符串类型字段能正确处理 NULL 值
  • 完善 Join 相关方法的实现和测试
  • 优化错误处理和上下文传递机制
v4.6.3 (2025-03-18)
  • 修复 BatchInsert 在上下文超时时的错误处理机制
  • 添加 Join(), LeftJoin(), RightJoin(), InnerJoin() 方法支持表连接查询
  • 新增 SetContext() 方法直接修改当前 Chain 实例的上下文
  • 优化事务处理和并发控制
  • 提升批处理操作的性能和稳定性
v4.6.1 (2025-03-10)
  • 完善了批量操作相关的示例代码
  • 增加了分组查询和聚合函数的使用示例
  • 补充了事务隔离级别和嵌套事务的示例
  • 优化了文档结构,提供更多实际应用场景的示例
v4.3.3 (2025-02-04)
  • 修复了主键字段识别问题
  • 优化了 Save 方法的自增字段处理
  • 改进了事务处理机制
  • 增强了类型转换系统的稳定性
  • 修复了批量操作中的并发问题

特性

  • 支持多种数据库(MySQL、PostgreSQL)
  • 链式操作 API
  • 自动类型转换
  • 自定义类型支持
  • 完整的事务支持
  • 详细的错误处理和日志记录

NULL 值处理

GOM 提供了多种处理数据库 NULL 值的方式:

方法 1:使用指针类型

将可能为 NULL 的字段定义为指针类型:

type User struct {
    ID       int64   `gom:"id"`
    Name     string  `gom:"name"`      // 非空字段
    ParentID *string `gom:"parent_id"` // 可能为 NULL 的字段
    Age      *int    `gom:"age"`       // 可能为 NULL 的字段
    Score    *float64 `gom:"score"`    // 可能为 NULL 的字段
}

使用指针类型时,NULL 值将被映射为 nil

if user.ParentID == nil {
    // 字段为 NULL
} else {
    parentID := *user.ParentID
    // 使用 parentID
}
方法 2:使用 sql.Null* 类型

使用标准库的 Null 类型:

type User struct {
    ID       int64           `gom:"id"`
    Name     string          `gom:"name"`       // 非空字段
    ParentID sql.NullString  `gom:"parent_id"`  // 可能为 NULL 的字段
    Age      sql.NullInt64   `gom:"age"`        // 可能为 NULL 的字段
    Score    sql.NullFloat64 `gom:"score"`      // 可能为 NULL 的字段
}

使用 sql.Null* 类型时,需要检查 Valid 字段:

if user.ParentID.Valid {
    // 字段不为 NULL
    parentID := user.ParentID.String
    // 使用 parentID
} else {
    // 字段为 NULL
}
方法 3:使用基本类型(适用于简单情况)

对于不关心 NULL 与空值区别的简单情况,可以直接使用基本类型:

type SimpleUser struct {
    ID       int64   `gom:"id"`
    Name     string  `gom:"name"`
    ParentID string  `gom:"parent_id"` // NULL 会被转为空字符串 ""
    Age      int     `gom:"age"`       // NULL 会被转为 0
    Score    float64 `gom:"score"`     // NULL 会被转为 0.0
}

⚠️ 注意:这种方法无法区分 NULL 和默认空值(如空字符串或 0),如果需要区分,请使用方法 1 或方法 2。

类型转换系统

基本类型支持
  • 整数类型:int, int8, int16, int32, int64
  • 无符号整数:uint, uint8, uint16, uint32, uint64
  • 浮点数:float32, float64
  • 布尔值:bool
  • 字符串:string
  • 字节数组:[]byte
  • 时间:time.Time
  • JSON 数组:支持 []string, []int
自定义类型
Status 枚举类型
type Status string

const (
    StatusActive   Status = "active"
    StatusInactive Status = "inactive"
    StatusPending  Status = "pending"
)
JSONMap 类型
type JSONMap struct {
    Data map[string]interface{}
}
IPAddress 类型
type IPAddress struct {
    Address string
}
类型转换接口

实现以下接口以支持自定义类型转换:

type TypeConverter interface {
    FromDB(value interface{}) error
    ToDB() (interface{}, error)
}
示例
  1. 基本查询操作:
type User struct {
    ID        int64     `gom:"id,@"`
    Name      string    `gom:"name"`
    Age       int       `gom:"age"`
    CreatedAt time.Time `gom:"created_at"`
    Status    Status    `gom:"status"`
    Balance   float64   `gom:"balance"`
}

// 插入单条数据
db.Chain().Table("users").Values(map[string]interface{}{
    "name":    "John",
    "age":     25,
    "status":  StatusActive,
    "balance": 1000.00,
}).Save()

// 批量插入数据
users := []User{
    {Name: "Alice", Age: 28, Status: StatusActive, Balance: 2000.00},
    {Name: "Bob", Age: 32, Status: StatusActive, Balance: 3000.00},
}
// 转换为 map 切片
userMaps := make([]map[string]interface{}, len(users))
for i, user := range users {
    userMaps[i] = map[string]interface{}{
        "name":    user.Name,
        "age":     user.Age,
        "status":  user.Status,
        "balance": user.Balance,
    }
}
// 执行批量插入,batchSize=100,enableConcurrent=true 表示启用并发插入
affected, err := db.Chain().Table("users").
    BatchValues(userMaps).
    BatchInsert(100, true)
if err != nil {
    log.Printf("批量插入失败: %v", err)
    return
}
log.Printf("成功插入 %d 条记录", affected)

// 基本查询
var user User
db.Chain().Table("users").Where("id = ?", 1).First().Into(&user)

// 条件查询示例
var users []User
db.Chain().Table("users").
    Eq("status", StatusActive).                    // 等于
    Ne("role", "guest").                          // 不等于
    Gt("age", 18).                                // 大于
    Ge("score", 60).                              // 大于等于
    Lt("login_attempts", 5).                      // 小于
    Le("balance", 1000).                          // 小于等于
    Like("name", "%John%").                       // LIKE
    NotLike("email", "%test%").                   // NOT LIKE
    In("department", []string{"IT", "HR"}).       // IN
    NotIn("status", []string{"deleted", "banned"}).// NOT IN
    IsNull("deleted_at").                         // IS NULL
    IsNotNull("updated_at").                      // IS NOT NULL
    Between("created_at", startTime, endTime).    // BETWEEN
    NotBetween("price", 100, 1000).              // NOT BETWEEN
    OrderBy("created_at DESC").
    Limit(10).
    Into(&users)

// 复杂条件组合示例
var complexUsers []User
db.Chain().Table("users").
    Eq("status", StatusActive).
    OrEq("role", "admin").                        // OR status = 'active' OR role = 'admin'
    AndGt("age", 18).                            // AND age > 18
    OrBetween("score", 60, 100).                 // OR score BETWEEN 60 AND 100
    OrIn("department", []string{"IT", "HR"}).    // OR department IN ('IT', 'HR')
    OrderBy("created_at DESC").
    Limit(10).
    Into(&complexUsers)

// 原生条件表达式
db.Chain().Table("users").
    Where("age > ? AND status = ?", 18, StatusActive).
    OrWhereRaw("experience >= 5 AND department IN ('IT', 'HR')").
    OrderBy("created_at DESC").
    Limit(10).
    Into(&users)

// 聚合函数
// 1. 计算总余额
var totalBalance float64
db.Chain().Table("users").
    Where("status = ?", StatusActive).
    Sum("balance").
    Into(&totalBalance)

// 2. 计算年龄段的用户数量
var userCount int64
db.Chain().Table("users").
    Where("age BETWEEN ? AND ?", 20, 30).
    Count().
    Into(&userCount)

// 3. 按状态分组统计平均余额
type StatusBalance struct {
    Status  Status   `gom:"status"`
    Average float64  `gom:"avg_balance"`
}
var statusBalances []StatusBalance
db.Chain().Table("users").
    Select("status, AVG(balance) as avg_balance").
    GroupBy("status").
    Into(&statusBalances)

// 4. 复杂分组和聚合查询示例
type DepartmentStats struct {
    Department string  `gom:"department"`
    AvgAge    float64 `gom:"avg_age"`
    MaxSalary float64 `gom:"max_salary"`
    MinSalary float64 `gom:"min_salary"`
    EmpCount  int64   `gom:"emp_count"`
}

var deptStats []DepartmentStats
db.Chain().Table("employees").
    Select(`
        department,
        AVG(age) as avg_age,
        MAX(salary) as max_salary,
        MIN(salary) as min_salary,
        COUNT(*) as emp_count
    `).
    GroupBy("department").
    Having("COUNT(*) > ?", 5).          // 只统计超过5人的部门
    OrderBy("avg_age DESC").
    Into(&deptStats)

// 5. 多表关联分组查询
type ProjectStats struct {
    ProjectID   int64   `gom:"project_id"`
    ProjectName string  `gom:"project_name"`
    TeamSize    int64   `gom:"team_size"`
    TotalCost   float64 `gom:"total_cost"`
    AvgProgress float64 `gom:"avg_progress"`
}

var projectStats []ProjectStats
db.Chain().Table("projects p").
    Select(`
        p.id as project_id,
        p.name as project_name,
        COUNT(DISTINCT t.user_id) as team_size,
        SUM(t.cost) as total_cost,
        AVG(t.progress) as avg_progress
    `).
    LeftJoin("tasks t ON t.project_id = p.id").
    GroupBy("p.id, p.name").
    Having("COUNT(DISTINCT t.user_id) >= ?", 3).  // 只统计团队成员至少3人的项目
    OrderBy("total_cost DESC").
    Into(&projectStats)

// 6. 时间维度的分组统计
type DailyStats struct {
    Date     time.Time `gom:"date"`
    NewUsers int64     `gom:"new_users"`
    Revenue  float64   `gom:"revenue"`
}

var dailyStats []DailyStats
db.Chain().Table("orders o").
    Select(`
        DATE(created_at) as date,
        COUNT(DISTINCT user_id) as new_users,
        SUM(amount) as revenue
    `).
    Join("users u ON u.id = o.user_id").
    Where("o.created_at >= ?", time.Now().AddDate(0, -1, 0)).  // 最近一个月的数据
    GroupBy("DATE(created_at)").
    Having("revenue > ?", 1000).                               // 只统计营收超过1000的日期
    OrderBy("date DESC").
    Into(&dailyStats)

// 7. 嵌套分组查询
type RegionSummary struct {
    Region       string  `gom:"region"`
    TotalStores  int64   `gom:"total_stores"`
    AvgEmployees float64 `gom:"avg_employees"`
    TotalSales   float64 `gom:"total_sales"`
}

var regionSummary []RegionSummary
db.Chain().Table("stores s").
    Select(`
        region,
        COUNT(*) as total_stores,
        AVG(employee_count) as avg_employees,
        SUM(
            (SELECT SUM(amount) 
             FROM orders o 
             WHERE o.store_id = s.id 
             AND o.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY))
        ) as total_sales
    `).
    GroupBy("region").
    Having("total_sales > ?", 10000).
    OrderBy("total_sales DESC").
    Into(&regionSummary)

// 8. 分页查询示例
type PageInfo struct {
    PageNum     int         `json:"page_num"`
    PageSize    int         `json:"page_size"`
    Total       int64       `json:"total"`
    Pages       int         `json:"pages"`
    HasPrev     bool        `json:"has_prev"`
    HasNext     bool        `json:"has_next"`
    List        interface{} `json:"list"`
    IsFirstPage bool        `json:"is_first_page"`
    IsLastPage  bool        `json:"is_last_page"`
}

var userPage PageInfo
err := db.Chain().Table("users").
    Where("status = ?", StatusActive).
    OrderBy("created_at DESC").
    Page(1, 10).  // 第1页,每页10条
    Into(&userPage)

// 9. 批量更新示例
// 批量更新用户状态
userIDs := []int64{1, 2, 3, 4, 5}
updateData := make([]map[string]interface{}, len(userIDs))
for i, id := range userIDs {
    updateData[i] = map[string]interface{}{
        "id":     id,
        "status": StatusInactive,
        "updated_at": time.Now(),
    }
}
affected, err := db.Chain().Table("users").
    BatchValues(updateData).
    BatchUpdate(100)  // 每批100条
if err != nil {
    log.Printf("批量更新失败: %v", err)
    return
}
log.Printf("成功更新 %d 条记录", affected)

// 10. 软删除示例
type SoftDeleteModel struct {
    ID        int64      `gom:"id,@"`
    DeletedAt *time.Time `gom:"deleted_at"`  // 使用指针类型处理 NULL 值
}

// 软删除记录
err = db.Chain().Table("users").
    Where("id = ?", 1).
    Update(map[string]interface{}{
        "deleted_at": time.Now(),
    })

// 查询时自动排除已删除记录
var activeUsers []User
db.Chain().Table("users").
    Where("deleted_at IS NULL").
    OrderBy("created_at DESC").
    Into(&activeUsers)

// 11. 嵌套事务示例
func complexTransaction(db *gom.DB) error {
    return db.Transaction(func(tx *gom.DB) error {
        // 第一层事务
        if err := createOrder(tx); err != nil {
            return err
        }

        // 嵌套事务
        return tx.Transaction(func(tx2 *gom.DB) error {
            // 第二层事务
            if err := processPayment(tx2); err != nil {
                return err
            }
            return updateInventory(tx2)
        })
    })
}

// 12. 子查询和EXISTS条件示例
var activeProjects []Project
db.Chain().Table("projects p").
    Where("EXISTS (SELECT 1 FROM tasks t WHERE t.project_id = p.id AND t.status = ?)", "in_progress").
    AndWhere("(SELECT COUNT(*) FROM team_members tm WHERE tm.project_id = p.id) > ?", 3).
    OrderBy("p.priority DESC").
    Into(&activeProjects)

// 13. 批量删除示例
// 批量软删除过期用户
expiredUserIDs := []int64{1, 2, 3, 4, 5}
deleteData := make([]map[string]interface{}, len(expiredUserIDs))
for i, id := range expiredUserIDs {
    deleteData[i] = map[string]interface{}{
        "id": id,
    }
}
affected, err := db.Chain().Table("users").
    BatchValues(deleteData).
    BatchDelete(100)  // 每批100条
if err != nil {
    log.Printf("批量删除失败: %v", err)
    return
}
log.Printf("成功删除 %d 条记录", affected)

// 14. 使用表达式更新
err = db.Chain().Table("products").
    Where("id = ?", 1).
    Update(map[string]interface{}{
        "stock":      gom.Expr("stock - ?", 1),
        "sold_count": gom.Expr("sold_count + ?", 1),
        "updated_at": time.Now(),
    })

// 15. 事务隔离级别示例
err = db.Transaction(func(tx *gom.DB) error {
    opts := &gom.TransactionOptions{
        IsolationLevel: sql.LevelSerializable,
        Timeout:       time.Second * 30,
        ReadOnly:      false,
    }
    return tx.TransactionWithOptions(opts, func(tx2 *gom.DB) error {
        // 在可序列化隔离级别下执行操作
        return processHighPriorityTransaction(tx2)
    })
})
  1. 事务处理:
// 转账示例
func transfer(db *gom.DB, fromID, toID int64, amount float64) error {
    return db.Transaction(func(tx *gom.DB) error {
        // 检查余额
        var fromUser User
        if err := tx.Chain().Table("users").
            Where("id = ? AND balance >= ?", fromID, amount).
            First().
            Into(&fromUser); err != nil {
            return fmt.Errorf("insufficient balance or user not found: %w", err)
        }

        // 更新转出方余额
        if err := tx.Chain().Table("users").
            Where("id = ?", fromID).
            Update(map[string]interface{}{
                "balance": gom.Expr("balance - ?", amount),
            }); err != nil {
            return fmt.Errorf("failed to update sender balance: %w", err)
        }

        // 更新接收方余额
        if err := tx.Chain().Table("users").
            Where("id = ?", toID).
            Update(map[string]interface{}{
                "balance": gom.Expr("balance + ?", amount),
            }); err != nil {
            return fmt.Errorf("failed to update receiver balance: %w", err)
        }

        return nil
    })
}
  1. 复杂查询:
// 子查询示例
type UserStats struct {
    UserID      int64   `gom:"user_id"`
    TotalOrders int     `gom:"total_orders"`
    TotalSpent  float64 `gom:"total_spent"`
}

var highValueUsers []UserStats
db.Chain().Table("orders o").
    Select(`
        u.id as user_id,
        COUNT(*) as total_orders,
        SUM(o.amount) as total_spent
    `).
    Join("users u ON u.id = o.user_id").
    Where("u.status = ?", StatusActive).
    GroupBy("u.id").
    Having("total_spent > ?", 10000).
    OrderBy("total_spent DESC").
    Into(&highValueUsers)

// 动态条件查询
func buildUserQuery(name string, minAge int, status Status) *gom.Chain {
    chain := db.Chain().Table("users")
    
    if name != "" {
        chain = chain.Where("name LIKE ?", "%"+name+"%")
    }
    if minAge > 0 {
        chain = chain.Where("age >= ?", minAge)
    }
    if status != "" {
        chain = chain.Where("status = ?", status)
    }
    
    return chain
}

// 使用动态查询
var users []User
buildUserQuery("John", 25, StatusActive).
    OrderBy("created_at DESC").
    Into(&users)
  1. 自定义类型:
type CustomInt int

func (c *CustomInt) FromDB(value interface{}) error {
    switch v := value.(type) {
    case int64:
        *c = CustomInt(v)
    case string:
        if v == "zero" {
            *c = 0
        } else if v == "one" {
            *c = 1
        }
    }
    return nil
}

func (c *CustomInt) ToDB() (interface{}, error) {
    return int64(*c), nil
}
特性
  1. NULL 值处理
  • 所有基本类型都有合理的零值处理
  • 支持指针类型处理 NULL 值
  • 自定义类型可以定义自己的 NULL 值行为
  1. 特殊字符支持
  • 完整的 Unicode 支持
  • HTML 和 SQL 特殊字符处理
  • 支持换行符和制表符
  1. 错误处理
  • 详细的错误消息
  • 类型转换错误追踪
  • 验证错误处理
  1. 日志记录
  • 支持多个日志级别
  • 详细的操作日志
  • 可自定义日志处理器
最佳实践
  1. 类型安全
// 推荐:使用强类型
type UserStatus Status

// 不推荐:直接使用字符串
status string
  1. 错误处理
// 推荐:详细的错误处理
if err := result.Error; err != nil {
    log.Printf("Failed to save user: %v", err)
    return fmt.Errorf("save user: %w", err)
}

// 不推荐:忽略错误
result.Save()
  1. 验证
// 推荐:在 ToDB 方法中进行验证
func (ip *IPAddress) ToDB() (interface{}, error) {
    if err := ip.Validate(); err != nil {
        return nil, err
    }
    return ip.Address, nil
}

许可证

MIT License

贡献

欢迎提交 Issue 和 Pull Request!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExampleUsage added in v4.7.4

func ExampleUsage()

使用示例

Types

type AutoIncrementUser added in v4.7.4

type AutoIncrementUser struct {
	ID        int64     `gom:"id,@"` // @ 表示自增主键
	Name      string    `gom:"name"`
	Email     string    `gom:"email"`
	CreatedAt time.Time `gom:"created_at"`
}

自增主键示例

type AutoIncrementUser2 added in v4.7.4

type AutoIncrementUser2 struct {
	ID        int64     `gom:"id,auto"` // auto 也表示自增主键
	Name      string    `gom:"name"`
	Email     string    `gom:"email"`
	CreatedAt time.Time `gom:"created_at"`
}

或者使用 auto 标签

type Chain

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

Chain represents the base chain structure

func NewChain added in v4.2.4

func NewChain(db *DB, factory define.SQLFactory) *Chain

NewChain creates a new Chain instance with the given database and factory

func (*Chain) AddSensitiveField added in v4.1.5

func (c *Chain) AddSensitiveField(field string, options SensitiveOptions) *Chain

AddSensitiveField adds a sensitive field to the chain

func (*Chain) And added in v4.1.5

func (c *Chain) And(field string, op define.OpType, value interface{}) *Chain

And adds a condition with AND join

func (*Chain) AndGroup added in v4.1.5

func (c *Chain) AndGroup(conditions []*define.Condition) *Chain

AndGroup adds a group of conditions with AND join

func (*Chain) BatchDelete added in v4.1.5

func (c *Chain) BatchDelete(batchSize int) (int64, error)

BatchDelete performs batch delete operation with the given batch size

func (*Chain) BatchInsert added in v4.1.3

func (c *Chain) BatchInsert(batchSize int, enableConcurrent bool) (int64, error)

BatchInsert performs batch insert operation with the given batch size

func (*Chain) BatchInsert2 added in v4.7.3

func (c *Chain) BatchInsert2(models []interface{}, batchSize int, enableConcurrent bool) (int64, error)

BatchInsert2 performs batch insert operation with a slice of struct models

func (*Chain) BatchInsertModels added in v4.7.3

func (c *Chain) BatchInsertModels(models interface{}, batchSize int, enableConcurrent bool) (int64, error)

BatchInsertModels 是 BatchInsert2 的简化版本,更易于使用 示例: db.Chain().BatchInsertModels(users, 1000, true)

func (*Chain) BatchUpdate added in v4.1.5

func (c *Chain) BatchUpdate(batchSize int) (int64, error)

BatchUpdate performs batch update operation with the given batch size

func (*Chain) BatchValues

func (c *Chain) BatchValues(values []map[string]interface{}) *Chain

BatchValues sets batch insert values

func (*Chain) Begin

func (c *Chain) Begin() (*Chain, error)

Begin starts a new transaction

func (*Chain) BeginChain added in v4.1.5

func (c *Chain) BeginChain() (*Chain, error)

BeginChain starts a new transaction and returns a Chain

func (*Chain) BeginNested added in v4.1.5

func (c *Chain) BeginNested() (*Chain, error)

BeginNested starts a new nested transaction

func (*Chain) Between added in v4.1.3

func (c *Chain) Between(field string, start, end interface{}) *Chain

Between adds a BETWEEN condition

func (*Chain) BuildSelect added in v4.2.4

func (c *Chain) BuildSelect() *define.SqlProto

BuildSelect builds a SELECT query

func (*Chain) Commit

func (c *Chain) Commit() error

Commit commits the current transaction

func (*Chain) CommitNested added in v4.1.5

func (c *Chain) CommitNested() error

CommitNested commits the current nested transaction

func (*Chain) Count added in v4.1.3

func (c *Chain) Count() (int64, error)

Count returns the count of records matching the current conditions

func (*Chain) Count2 added in v4.1.3

func (c *Chain) Count2(field string) (int64, error)

Count2 returns the count of records for a specific field

func (*Chain) CreateTable

func (c *Chain) CreateTable(model interface{}) error

CreateTable creates a table based on the model struct

func (*Chain) Delete

func (c *Chain) Delete(models ...interface{}) *define.Result

Delete deletes records based on the current conditions

func (*Chain) Eq added in v4.1.3

func (c *Chain) Eq(field string, value interface{}) *Chain

Eq adds an equals condition

func (*Chain) Exec added in v4.1.9

func (c *Chain) Exec() *define.Result

Exec 执行原始 SQL 语句

func (*Chain) Fields

func (c *Chain) Fields(fields ...string) *Chain

Fields sets the fields to select

func (*Chain) First

func (c *Chain) First(dest ...interface{}) *define.Result

First returns the first result

func (*Chain) From

func (c *Chain) From(model interface{}) *Chain

From sets the model for the chain operation

func (*Chain) Ge added in v4.1.3

func (c *Chain) Ge(field string, value interface{}) *Chain

Ge adds a greater than or equal condition

func (*Chain) GetLastQueryStats added in v4.1.5

func (c *Chain) GetLastQueryStats() *QueryStats

GetLastQueryStats returns the statistics of the last executed query

func (*Chain) GetTransactionLevel added in v4.1.5

func (c *Chain) GetTransactionLevel() int

GetTransactionLevel returns the current transaction nesting level

func (*Chain) GroupBy added in v4.1.3

func (c *Chain) GroupBy(fields ...string) *Chain

GroupBy adds GROUP BY clause to the query

func (*Chain) Gt added in v4.1.3

func (c *Chain) Gt(field string, value interface{}) *Chain

Gt adds a greater than condition

func (*Chain) Having added in v4.1.3

func (c *Chain) Having(condition interface{}, args ...interface{}) *Chain

Having adds HAVING clause to the query

func (*Chain) In added in v4.1.3

func (c *Chain) In(field string, value interface{}) *Chain

In adds an IN condition

func (*Chain) InnerJoin added in v4.6.1

func (c *Chain) InnerJoin(joinExpr string) *Chain

InnerJoin adds an INNER JOIN clause to the query

func (*Chain) Insert added in v4.4.1

func (c *Chain) Insert(model interface{}) *define.Result

Insert inserts a new record into the database

func (*Chain) Into

func (c *Chain) Into(dest interface{}) error

Into scans the result into a struct or slice of structs

func (*Chain) IsInTransaction

func (c *Chain) IsInTransaction() bool

IsInTransaction returns whether the chain is currently in a transaction

func (*Chain) IsNotNull added in v4.1.3

func (c *Chain) IsNotNull(field string) *Chain

IsNotNull adds an IS NOT NULL condition

func (*Chain) IsNull added in v4.1.3

func (c *Chain) IsNull(field string) *Chain

IsNull adds an IS NULL condition

func (*Chain) Join added in v4.6.1

func (c *Chain) Join(joinExpr string) *Chain

Join adds a JOIN clause to the query

func (*Chain) Le added in v4.1.3

func (c *Chain) Le(field string, value interface{}) *Chain

Le adds a less than or equal condition

func (*Chain) LeftJoin added in v4.6.1

func (c *Chain) LeftJoin(joinExpr string) *Chain

LeftJoin adds a LEFT JOIN clause to the query

func (*Chain) Like added in v4.1.3

func (c *Chain) Like(field string, value interface{}) *Chain

Like adds a LIKE condition

func (*Chain) Limit

func (c *Chain) Limit(count int) *Chain

Limit sets the limit count

func (*Chain) List

func (c *Chain) List(dest ...interface{}) *define.Result

List executes a SELECT query and returns all results

func (*Chain) Lt added in v4.1.3

func (c *Chain) Lt(field string, value interface{}) *Chain

Lt adds a less than condition

func (*Chain) Ne added in v4.1.3

func (c *Chain) Ne(field string, value interface{}) *Chain

Ne adds a not equals condition

func (*Chain) NewCondition added in v4.1.3

func (c *Chain) NewCondition() *define.Condition

NewCondition creates a new condition with AND join type

func (*Chain) NotBetween added in v4.1.3

func (c *Chain) NotBetween(field string, start, end interface{}) *Chain

NotBetween adds a NOT BETWEEN condition

func (*Chain) NotIn added in v4.1.3

func (c *Chain) NotIn(field string, value interface{}) *Chain

NotIn adds a NOT IN condition

func (*Chain) NotLike added in v4.1.3

func (c *Chain) NotLike(field string, value interface{}) *Chain

NotLike adds a NOT LIKE condition

func (*Chain) Offset

func (c *Chain) Offset(count int) *Chain

Offset sets the offset count

func (*Chain) One

func (c *Chain) One(dest ...interface{}) *define.Result

One returns exactly one result

func (*Chain) Or added in v4.1.3

func (c *Chain) Or(field string, op define.OpType, value interface{}) *Chain

Or adds a condition with OR join

func (*Chain) OrBetween added in v4.1.3

func (c *Chain) OrBetween(field string, start, end interface{}) *Chain

OrBetween adds an OR BETWEEN condition

func (*Chain) OrCond added in v4.1.5

func (c *Chain) OrCond(cond *define.Condition) *Chain

OrCond adds a condition with OR join type

func (*Chain) OrEq added in v4.1.3

func (c *Chain) OrEq(field string, value interface{}) *Chain

OrEq adds an OR equals condition

func (*Chain) OrGe added in v4.1.3

func (c *Chain) OrGe(field string, value interface{}) *Chain

OrGe adds an OR greater than or equal condition

func (*Chain) OrGroup added in v4.1.5

func (c *Chain) OrGroup(conditions []*define.Condition) *Chain

OrGroup adds a group of conditions with OR join

func (*Chain) OrGt added in v4.1.3

func (c *Chain) OrGt(field string, value interface{}) *Chain

OrGt adds an OR greater than condition

func (*Chain) OrIn added in v4.1.3

func (c *Chain) OrIn(field string, value interface{}) *Chain

OrIn adds an OR IN condition

func (*Chain) OrIsNotNull added in v4.1.3

func (c *Chain) OrIsNotNull(field string) *Chain

OrIsNotNull adds an OR IS NOT NULL condition

func (*Chain) OrIsNull added in v4.1.3

func (c *Chain) OrIsNull(field string) *Chain

OrIsNull adds an OR IS NULL condition

func (*Chain) OrLe added in v4.1.3

func (c *Chain) OrLe(field string, value interface{}) *Chain

OrLe adds an OR less than or equal condition

func (*Chain) OrLike added in v4.1.3

func (c *Chain) OrLike(field string, value interface{}) *Chain

OrLike adds an OR LIKE condition

func (*Chain) OrLt added in v4.1.3

func (c *Chain) OrLt(field string, value interface{}) *Chain

OrLt adds an OR less than condition

func (*Chain) OrNe added in v4.1.3

func (c *Chain) OrNe(field string, value interface{}) *Chain

OrNe adds an OR not equals condition

func (*Chain) OrNotBetween added in v4.1.3

func (c *Chain) OrNotBetween(field string, start, end interface{}) *Chain

OrNotBetween adds an OR NOT BETWEEN condition

func (*Chain) OrNotIn added in v4.1.3

func (c *Chain) OrNotIn(field string, value interface{}) *Chain

OrNotIn adds an OR NOT IN condition

func (*Chain) OrNotLike added in v4.1.3

func (c *Chain) OrNotLike(field string, value interface{}) *Chain

OrNotLike adds an OR NOT LIKE condition

func (*Chain) OrWhere added in v4.1.5

func (c *Chain) OrWhere(field string, op define.OpType, value interface{}) *Chain

OrWhere adds a condition with OR join

func (*Chain) OrWhereGroup added in v4.1.3

func (c *Chain) OrWhereGroup() *define.Condition

OrWhereGroup starts a new condition group with OR join type

func (*Chain) OrWhereRaw added in v4.5.5

func (c *Chain) OrWhereRaw(expr string, args ...interface{}) *Chain

OrWhereRaw adds a raw SQL expression as an OR WHERE condition

func (*Chain) OrderBy

func (c *Chain) OrderBy(field string) *Chain

OrderBy adds an ascending order by clause

func (*Chain) OrderByDesc

func (c *Chain) OrderByDesc(field string) *Chain

OrderByDesc adds a descending order by clause

func (*Chain) Page

func (c *Chain) Page(pageNum, pageSize int) *Chain

Page sets the page number and page size for pagination

func (*Chain) PageInfo added in v4.1.3

func (c *Chain) PageInfo(models ...interface{}) (*PageInfo, error)

PageInfo executes a paginated query and returns pagination information

func (*Chain) Query added in v4.7.2

func (c *Chain) Query() *define.Result

Query 执行原始 SQL 查询并返回结果集

func (*Chain) Raw added in v4.1.9

func (c *Chain) Raw(query string, args ...interface{}) *Chain

Raw 执行原始 SQL 查询

func (*Chain) RawExecute

func (c *Chain) RawExecute(sql string, args ...interface{}) define.Result

RawExecute executes a raw SQL query

func (*Chain) RawQuery

func (c *Chain) RawQuery(sqlStr string, args ...interface{}) *define.Result

RawQuery executes a raw SQL query

func (*Chain) ReleaseSavepoint

func (c *Chain) ReleaseSavepoint(name string) error

ReleaseSavepoint releases the specified savepoint

func (*Chain) RightJoin added in v4.6.1

func (c *Chain) RightJoin(joinExpr string) *Chain

RightJoin adds a RIGHT JOIN clause to the query

func (*Chain) Rollback

func (c *Chain) Rollback() error

Rollback rolls back the current transaction

func (*Chain) RollbackNested added in v4.1.5

func (c *Chain) RollbackNested() error

RollbackNested rolls back to the last savepoint

func (*Chain) RollbackTo

func (c *Chain) RollbackTo(name string) error

RollbackTo rolls back to the specified savepoint

func (*Chain) Savepoint

func (c *Chain) Savepoint(name string) error

Savepoint creates a savepoint with the given name

func (*Chain) Set

func (c *Chain) Set(field string, value interface{}) *Chain

Set sets update fields

func (*Chain) SetContext added in v4.6.4

func (c *Chain) SetContext(ctx context.Context) *Chain

SetContext 设置当前链对象的上下文 注意: 这将修改当前对象,而不是创建新对象

func (*Chain) SetEncryptionConfig added in v4.4.1

func (c *Chain) SetEncryptionConfig(config *EncryptionConfig) *Chain

SetEncryptionConfig sets the encryption configuration for the chain

func (*Chain) SetIsolationLevel

func (c *Chain) SetIsolationLevel(level sql.IsolationLevel) *Chain

SetIsolationLevel sets the isolation level for the next transaction

func (*Chain) Sets added in v4.2.4

func (c *Chain) Sets(fields map[string]interface{}) *Chain

Sets allows batch setting of field values

func (*Chain) Sum added in v4.1.3

func (c *Chain) Sum(field string) (float64, error)

Sum calculates the sum of a specific field

func (*Chain) Table

func (c *Chain) Table(table string) *Chain

Table sets the table name for the chain

func (*Chain) Transaction

func (c *Chain) Transaction(fn func(tx *Chain) error) error

Transaction executes a function within a transaction

func (*Chain) TransactionWithOptions added in v4.1.5

func (c *Chain) TransactionWithOptions(opts define.TransactionOptions, fn func(tx *Chain) error) error

TransactionWithOptions starts a new transaction with options

func (*Chain) Update

func (c *Chain) Update(models ...interface{}) *define.Result

Update updates records based on the current conditions

func (*Chain) Values

func (c *Chain) Values(fields map[string]interface{}) *Chain

Values sets insert fields

func (*Chain) Where

func (c *Chain) Where(field string, op define.OpType, value interface{}) *Chain

Where adds a WHERE condition to the chain

func (*Chain) Where2 added in v4.1.3

func (c *Chain) Where2(cond *define.Condition) *Chain

Where2 adds a condition directly

func (*Chain) WhereGroup added in v4.1.3

func (c *Chain) WhereGroup() *define.Condition

WhereGroup starts a new condition group with AND join type

func (*Chain) WhereRaw added in v4.5.5

func (c *Chain) WhereRaw(expr string, args ...interface{}) *Chain

WhereRaw adds a raw SQL expression as a WHERE condition

func (*Chain) WithContext added in v4.5.0

func (c *Chain) WithContext(ctx context.Context) *Chain

type DB

type DB struct {
	sync.RWMutex
	DB        *sql.DB
	Factory   define.SQLFactory
	RoutineID int64
	// contains filtered or unexported fields
}

DB represents the database connection

func MustOpen

func MustOpen(driverName, dsn string, opts *define.DBOptions) *DB

MustOpen creates a new DB connection with options and panics on error

func Open

func Open(driverName, dsn string, opts *define.DBOptions) (*DB, error)

Open creates a new DB connection with options

func OpenWithDefaults added in v4.1.4

func OpenWithDefaults(driverName, dsn string) (*DB, error)

OpenWithDefaults creates a new DB connection with default options

func (*DB) Begin added in v4.1.4

func (db *DB) Begin() (*sql.Tx, error)

Begin starts a new transaction

func (*DB) BeginChain added in v4.1.5

func (db *DB) BeginChain() (*Chain, error)

BeginChain starts a new transaction and returns a Chain

func (*DB) Chain

func (db *DB) Chain() *Chain

Chain starts a new chain

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection

func (*DB) GenerateStruct

func (db *DB) GenerateStruct(tableName, outputDir, packageName string) error

GenerateStruct 生成单个表的结构体代码

func (*DB) GenerateStructs

func (db *DB) GenerateStructs(opts GenerateOptions) error

GenerateStructs 批量生成表的结构体代码

func (*DB) GetDB added in v4.1.5

func (db *DB) GetDB() *sql.DB

GetDB returns the underlying sql.DB object

func (*DB) GetMetrics added in v4.1.5

func (db *DB) GetMetrics() DBMetrics

GetMetrics returns the current database metrics

func (*DB) GetOptions added in v4.1.4

func (db *DB) GetOptions() define.DBOptions

GetOptions returns the current database options

func (*DB) GetTableInfo

func (db *DB) GetTableInfo(tableName string) (*define.TableInfo, error)

GetTableInfo 获取表信息

func (*DB) GetTableName added in v4.1.3

func (db *DB) GetTableName(model interface{}) (string, error)

GetTableName returns the table name for a model

func (*DB) GetTableStruct added in v4.2.8

func (db *DB) GetTableStruct(i any, table string) (*define.TableStruct, error)

func (*DB) GetTableStruct2 added in v4.2.8

func (db *DB) GetTableStruct2(i any) (*define.TableStruct, error)

func (*DB) GetTables

func (db *DB) GetTables(pattern string) ([]string, error)

GetTables returns a list of table names in the database

func (*DB) SetMaxOpenConns added in v4.5.0

func (db *DB) SetMaxOpenConns(n int)

func (*DB) Stats added in v4.5.0

func (db *DB) Stats() sql.DBStats

func (*DB) UpdateOptions added in v4.1.4

func (db *DB) UpdateOptions(opts define.DBOptions) error

UpdateOptions updates the database connection pool settings

type DBError added in v4.1.3

type DBError struct {
	Type    DBErrorType
	Op      string
	Err     error
	Details string
	Query   string // Optional, for debugging (only set in debug mode)
}

DBError represents a database operation error with enhanced context

func (*DBError) Error added in v4.1.3

func (e *DBError) Error() string

type DBErrorType added in v4.1.5

type DBErrorType int

DBErrorType represents specific types of database errors

const (
	ErrConnection DBErrorType = iota
	ErrQuery
	ErrTransaction
	ErrValidation
	ErrConfiguration
)

type DBMetrics added in v4.1.5

type DBMetrics struct {
	OpenConnections   int64         // Current number of open connections
	InUseConnections  int64         // Current number of connections in use
	IdleConnections   int64         // Current number of idle connections
	WaitCount         int64         // Total number of connections waited for
	WaitDuration      time.Duration // Total time waited for connections
	MaxIdleTimeClosed int64         // Number of connections closed due to max idle time
}

DBMetrics tracks database connection pool statistics

type EncryptionAlgorithm added in v4.1.5

type EncryptionAlgorithm string

EncryptionAlgorithm defines the encryption algorithm to use

const (
	// AES256 uses AES-256 encryption
	AES256 EncryptionAlgorithm = "AES256"
	// AES192 uses AES-192 encryption
	AES192 EncryptionAlgorithm = "AES192"
	// AES128 uses AES-128 encryption
	AES128 EncryptionAlgorithm = "AES128"
)

type EncryptionConfig added in v4.1.5

type EncryptionConfig struct {
	Algorithm       EncryptionAlgorithm `json:"algorithm"`
	KeyRotation     time.Duration       `json:"key_rotation"`
	KeySource       KeySource           `json:"key_source"`
	KeySourceConfig map[string]string   `json:"key_source_config"`
}

EncryptionConfig represents configuration for data encryption

type GenerateOptions

type GenerateOptions struct {
	OutputDir   string // 输出目录
	PackageName string // 包名
	Pattern     string // 表名匹配模式
}

GenerateOptions 代码生成选项

type KeySource added in v4.1.5

type KeySource string

KeySource defines where encryption keys are sourced from

const (
	// KeySourceEnv sources keys from environment variables
	KeySourceEnv KeySource = "env"
	// KeySourceFile sources keys from files
	KeySourceFile KeySource = "file"
	// KeySourceVault sources keys from a key vault
	KeySourceVault KeySource = "vault"
)

type ManualKeyUser added in v4.7.4

type ManualKeyUser struct {
	ID        int64     `gom:"id,!"` // ! 表示普通主键(非自增)
	Name      string    `gom:"name"`
	Email     string    `gom:"email"`
	CreatedAt time.Time `gom:"created_at"`
}

普通主键示例(非自增)

type ManualKeyUser2 added in v4.7.4

type ManualKeyUser2 struct {
	ID        int64     `gom:"id,pk"` // pk 也表示普通主键(非自增)
	Name      string    `gom:"name"`
	Email     string    `gom:"email"`
	CreatedAt time.Time `gom:"created_at"`
}

或者使用 pk 标签

type PageInfo added in v4.1.3

type PageInfo struct {
	PageNum     int         `json:"pageNum"`     // 当前页码
	PageSize    int         `json:"pageSize"`    // 每页大小
	Total       int64       `json:"total"`       // 总记录数
	Pages       int         `json:"pages"`       // 总页数
	HasPrev     bool        `json:"hasPrev"`     // 是否有上一页
	HasNext     bool        `json:"hasNext"`     // 是否有下一页
	List        interface{} `json:"list"`        // 当前页数据
	IsFirstPage bool        `json:"isFirstPage"` // 是否是第一页
	IsLastPage  bool        `json:"isLastPage"`  // 是否是最后页
}

PageInfo represents pagination information

type QueryStats added in v4.1.5

type QueryStats struct {
	SQL          string
	Duration     time.Duration
	RowsAffected int64
	StartTime    time.Time
	Args         []interface{}
}

QueryStats tracks statistics for a single query execution

type SensitiveOptions added in v4.1.5

type SensitiveOptions struct {
	Type       SensitiveType
	Encryption *security.EncryptionConfig
	Mask       string
}

SensitiveOptions represents options for sensitive data handling

type SensitiveType added in v4.1.5

type SensitiveType int

SensitiveType defines the type of sensitive data

const (
	// SensitiveNone indicates no sensitivity
	SensitiveNone SensitiveType = iota
	// SensitivePhone for phone numbers
	SensitivePhone
	// SensitiveEmail for email addresses
	SensitiveEmail
	// SensitiveIDCard for ID card numbers
	SensitiveIDCard
	// SensitiveBankCard for bank card numbers
	SensitiveBankCard
	// SensitiveAddress for addresses
	SensitiveAddress
	// SensitiveEncrypted for encrypted data
	SensitiveEncrypted
	// SensitiveMasked for masked data
	SensitiveMasked
)

type TransactionOptions added in v4.1.5

type TransactionOptions struct {
	Timeout         time.Duration
	IsolationLevel  sql.IsolationLevel
	PropagationMode TransactionPropagation
	ReadOnly        bool
}

TransactionOptions represents options for transaction

type TransactionPropagation added in v4.1.5

type TransactionPropagation int

TransactionPropagation defines transaction propagation behavior

const (
	// PropagationRequired starts a new transaction if none exists
	PropagationRequired TransactionPropagation = iota
	// PropagationRequiresNew always starts a new transaction
	PropagationRequiresNew
	// PropagationNested starts a nested transaction if possible
	PropagationNested
	// PropagationSupports uses existing transaction if available
	PropagationSupports
	// PropagationNotSupported suspends current transaction if exists
	PropagationNotSupported
	// PropagationNever throws exception if transaction exists
	PropagationNever
	// PropagationMandatory throws exception if no transaction exists
	PropagationMandatory
)

Directories

Path Synopsis
Code generated by gom at 2025-01-06 17:53:08.
Code generated by gom at 2025-01-06 17:53:08.
factory
cmd/gomen command

Jump to

Keyboard shortcuts

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