gom

package module
v4.3.7 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: Apache-2.0 Imports: 23 Imported by: 1

README

GOM - Go ORM Framework

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

发行注记

v4.3.3 (2025-02-04)
  • 修复了主键字段识别问题
  • 优化了 Save 方法的自增字段处理
  • 改进了事务处理机制
  • 增强了类型转换系统的稳定性
  • 修复了批量操作中的并发问题

特性

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

类型转换系统

基本类型支持
  • 整数类型: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"`
    CreatedAt time.Time `gom:"created_at"`
    Status    Status    `gom:"status"`
}

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

// 查询数据
var user User
db.Chain().Table("users").Where("id = ?", 1).First().Into(&user)
  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

This section is empty.

Types

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) (int64, error)

BatchInsert performs batch insert operation with the given batch size

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() (string, []interface{}, error)

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 executes a DELETE query

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

func (c *Chain) Save(fieldsOrModel ...interface{}) *define.Result

Save saves (inserts or updates) records with the given fields or model

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) 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) 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(fieldsOrModel ...interface{}) *define.Result

Update updates records with the given fields or model

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 with custom operator

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

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) GetColumns added in v4.2.8

func (db DB) GetColumns(table string) ([]define.Column, error)

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

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

Jump to

Keyboard shortcuts

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