Help us shape the future of Go! Take the 2026 Go Developer Survey

define

package
v4.7.9 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	ErrEncryptionConfig = iota + 1000
	ErrEncryptionAlgorithm
	ErrKeySource
)

Variables

View Source
var CommonValidators = map[string]ValidationRule{
	"required": {
		Name: "required",
		Validate: func(value interface{}) error {
			if value == nil {
				return fmt.Errorf("field is required")
			}
			if str, ok := value.(string); ok && strings.TrimSpace(str) == "" {
				return fmt.Errorf("field is required")
			}
			return nil
		},
		Message: "field is required",
	},
	"email": {
		Name: "email",
		Validate: func(value interface{}) error {
			if str, ok := value.(string); ok {
				pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
				matched, _ := regexp.MatchString(pattern, str)
				if !matched {
					return fmt.Errorf("invalid email format")
				}
			}
			return nil
		},
		Message: "invalid email format",
	},
	"min": {
		Name: "min",
		Validate: func(value interface{}) error {
			v := reflect.ValueOf(value)
			min := v.Interface().(int)
			if min < 0 {
				return fmt.Errorf("value must be at least %d", min)
			}
			return nil
		},
		Message: "value is below minimum",
	},
	"max": {
		Name: "max",
		Validate: func(value interface{}) error {
			v := reflect.ValueOf(value)
			max := v.Interface().(int)
			if max < 0 {
				return fmt.Errorf("value must be at most %d", max)
			}
			return nil
		},
		Message: "value exceeds maximum",
	},
	"pattern": {
		Name: "pattern",
		Validate: func(value interface{}) error {
			if str, ok := value.(string); ok {
				pattern, _ := value.(string)
				matched, _ := regexp.MatchString(pattern, str)
				if !matched {
					return fmt.Errorf("value does not match pattern")
				}
			}
			return nil
		},
		Message: "value does not match pattern",
	},
}

CommonValidators provides commonly used validation rules

View Source
var Debug bool

Debug flag for enabling debug mode

View Source
var ErrEmptyTableName = errors.New("empty table name")

ErrEmptyTableName is returned when a table name is empty

View Source
var ErrManualRollback = errors.New("manual rollback")

ErrManualRollback is used to manually trigger a transaction rollback

Functions

func ClearCache added in v4.2.0

func ClearCache()

ClearCache clears the transfer cache

func ConvertRowToStruct added in v4.3.7

func ConvertRowToStruct(data map[string]interface{}, structValue reflect.Value) error

ConvertRowToStruct converts a single data row to a struct

func ConvertValue added in v4.2.4

func ConvertValue(value interface{}, targetType reflect.Type) (interface{}, error)

ConvertValue converts a value to the target type using the global type converter

func GetFieldMap added in v4.2.4

func GetFieldMap(obj interface{}) map[string]interface{}

GetFieldMap returns a map of field names to their values for a struct

func GetFieldToColMap added in v4.3.6

func GetFieldToColMap(i any, tableInfo *TableInfo) (map[string]string, map[string]string, error)

func IsErrorCode added in v4.2.5

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode checks if an error matches a specific error code

func RecoverHandler added in v4.2.5

func RecoverHandler(handler func(interface{}) error) func()

RecoverHandler provides a recovery function for panics

func RegisterFactory

func RegisterFactory(driver string, factory SQLFactory)

RegisterFactory registers a SQL factory for a specific driver

func StructToMap added in v4.2.0

func StructToMap(obj interface{}) (map[string]interface{}, error)

StructToMap converts a struct to a map[string]interface{} using gom tags Only non-zero values are included in the result

func StructToMapWithZero added in v4.4.1

func StructToMapWithZero(obj interface{}) (map[string]interface{}, error)

StructToMapWithZero converts a struct to a map[string]interface{}, including zero values

func UnregisterFactory

func UnregisterFactory(driver string)

UnregisterFactory removes a SQL factory for a specific driver

Types

type BatchOptions added in v4.1.4

type BatchOptions struct {
	// BatchSize is the size of each batch
	BatchSize int

	// Concurrency is the number of concurrent goroutines for batch processing
	// If set to 0, defaults to 1 (no concurrency)
	Concurrency int

	// Timeout is the maximum duration for the entire batch operation
	// If set to 0, no timeout is applied
	Timeout time.Duration

	// RetryCount is the number of times to retry a failed batch
	// If set to 0, no retries are attempted
	RetryCount int

	// RetryInterval is the duration to wait between retries
	// If set to 0, defaults to 1 second
	RetryInterval time.Duration
}

BatchOptions defines configuration options for batch operations

func DefaultBatchOptions added in v4.1.4

func DefaultBatchOptions() BatchOptions

DefaultBatchOptions returns the default batch operation options

func (*BatchOptions) Validate added in v4.1.4

func (o *BatchOptions) Validate() error

Validate validates the batch options and sets defaults if necessary

type ColumnInfo

type ColumnInfo struct {
	Name            string `json:"name"`              // 列名
	TypeName        string `json:"type_name"`         // 数据库类型名称
	DataType        string `json:"data_type"`         // 标准SQL数据类型
	Length          int64  `json:"length"`            // 长度
	Precision       int    `json:"precision"`         // 精度
	Scale           int    `json:"scale"`             // 小数位数
	IsNullable      bool   `json:"is_nullable"`       // 是否可空
	IsPrimaryKey    bool   `json:"is_primary_key"`    // 是否主键
	IsAutoIncrement bool   `json:"is_auto_increment"` // 是否自增
	DefaultValue    string `json:"default_value"`     // 默认值
	Comment         string `json:"comment"`           // 注释
}

ColumnInfo 列信息

type Condition

type Condition struct {
	Field      string
	Op         OpType
	Value      interface{} // For normal conditions: single value; for IN/BETWEEN: []interface{}; for raw expressions: []interface{} as args
	JoinType   JoinType
	SubConds   []*Condition // Sub-conditions for nested queries
	IsSubGroup bool         // Whether this is a sub-group of conditions
	IsRawExpr  bool         // Whether this is a raw SQL expression
}

Condition represents a WHERE condition

func Between added in v4.1.3

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

func Eq added in v4.1.3

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

Condition builder functions

func Ge added in v4.1.3

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

func Gt added in v4.1.3

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

func In added in v4.1.3

func In(field string, values ...interface{}) *Condition

In creates an IN condition with variadic parameters that may include arrays

func IsNotNull added in v4.1.3

func IsNotNull(field string) *Condition

func IsNull added in v4.1.3

func IsNull(field string) *Condition

func Le added in v4.1.3

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

func Like added in v4.1.3

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

func Lt added in v4.1.3

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

func Ne added in v4.1.3

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

func NewCondition added in v4.1.3

func NewCondition(field string, op OpType, value interface{}) *Condition

NewCondition creates a new condition

func NotBetween added in v4.1.3

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

func NotIn added in v4.1.3

func NotIn(field string, values ...interface{}) *Condition

NotIn creates a NOT IN condition with variadic parameters that may include arrays

func NotLike added in v4.1.3

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

func Raw added in v4.5.5

func Raw(expr string, args ...interface{}) *Condition

Raw creates a new raw SQL expression condition

func (*Condition) And added in v4.1.3

func (c *Condition) And(cond *Condition) *Condition

And adds a condition with AND join

func (*Condition) Or added in v4.1.3

func (c *Condition) Or(cond *Condition) *Condition

Or adds a condition with OR join

type Conditions added in v4.1.5

type Conditions []Condition

Conditions represents a slice of Condition

type ConnectionConfig added in v4.2.6

type ConnectionConfig struct {
	MaxOpenConns    int           // 最大打开连接数
	MaxIdleConns    int           // 最大空闲连接数
	ConnMaxLifetime time.Duration // 连接最大生命周期
	ConnMaxIdleTime time.Duration // 空闲连接最大生命周期
}

ConnectionConfig 数据库连接配置

type ConnectionPool added in v4.2.6

type ConnectionPool interface {
	GetConnection() (*sql.DB, error)
	ReturnConnection(*sql.DB)
	HealthCheck() error
	Close() error
}

ConnectionPool 连接池接口

type ConversionError added in v4.2.5

type ConversionError struct {
	Value   interface{}
	From    string
	To      string
	Message string
}

ConversionError represents an error that occurs during type conversion

func (*ConversionError) Error added in v4.2.5

func (e *ConversionError) Error() string

type DBError added in v4.5.0

type DBError struct {
	Code    int
	Op      string
	Message string
	Err     error
}

func (*DBError) Error added in v4.5.0

func (e *DBError) Error() string

type DBOptions added in v4.1.4

type DBOptions struct {
	// MaxOpenConns is the maximum number of open connections to the database
	// If MaxOpenConns <= 0, then there is no limit on the number of open connections
	MaxOpenConns int

	// MaxIdleConns is the maximum number of connections in the idle connection pool
	// If MaxIdleConns <= 0, no idle connections are retained
	MaxIdleConns int

	// ConnMaxLifetime is the maximum amount of time a connection may be reused
	// If ConnMaxLifetime <= 0, connections are not closed due to their age
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime is the maximum amount of time a connection may be idle
	// If ConnMaxIdleTime <= 0, connections are not closed due to idle time
	ConnMaxIdleTime time.Duration

	// Debug enables debug logging of SQL queries
	Debug bool
}

DBOptions defines database connection and pool configuration

func DefaultDBOptions added in v4.1.4

func DefaultDBOptions() DBOptions

DefaultDBOptions returns the default database options

func (*DBOptions) Validate added in v4.1.4

func (o *DBOptions) Validate() error

Validate validates the database options and sets defaults if necessary

type DataRow added in v4.3.7

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

DataRow represents a single row of data from Result

func (*DataRow) GetBool added in v4.3.7

func (r *DataRow) GetBool(name string) (bool, error)

GetBool returns the bool value for the given column name

func (*DataRow) GetBoolOrDefault added in v4.4.1

func (r *DataRow) GetBoolOrDefault(name string, defaultValue bool) bool

GetBoolOrDefault returns the bool value for the given column name or default value if not found

func (*DataRow) GetBytes added in v4.4.1

func (r *DataRow) GetBytes(name string) ([]byte, error)

GetBytes returns the []byte value for the given column name

func (*DataRow) GetBytesOrDefault added in v4.4.1

func (r *DataRow) GetBytesOrDefault(name string, defaultValue []byte) []byte

GetBytesOrDefault returns the []byte value for the given column name or default value if not found

func (*DataRow) GetDataMap added in v4.3.7

func (r *DataRow) GetDataMap() map[string]any

GetDataMap returns the underlying map data

func (*DataRow) GetFloat64 added in v4.3.7

func (r *DataRow) GetFloat64(name string) (float64, error)

GetFloat64 returns the float64 value for the given column name

func (*DataRow) GetFloat64OrDefault added in v4.4.1

func (r *DataRow) GetFloat64OrDefault(name string, defaultValue float64) float64

GetFloat64OrDefault returns the float64 value for the given column name or default value if not found

func (*DataRow) GetInt added in v4.3.7

func (r *DataRow) GetInt(name string) (int, error)

GetInt returns the int value for the given column name

func (*DataRow) GetInt64 added in v4.3.7

func (r *DataRow) GetInt64(name string) (int64, error)

GetInt64 returns the int64 value for the given column name

func (*DataRow) GetInt64OrDefault added in v4.4.1

func (r *DataRow) GetInt64OrDefault(name string, defaultValue int64) int64

GetInt64OrDefault returns the int64 value for the given column name or default value if not found

func (*DataRow) GetIntOrDefault added in v4.4.1

func (r *DataRow) GetIntOrDefault(name string, defaultValue int) int

GetIntOrDefault returns the int value for the given column name or default value if not found

func (*DataRow) GetMap added in v4.4.1

func (r *DataRow) GetMap(name string) (map[string]interface{}, error)

GetMap returns the map[string]interface{} value for the given column name

func (*DataRow) GetMapOrDefault added in v4.4.1

func (r *DataRow) GetMapOrDefault(name string, defaultValue map[string]interface{}) map[string]interface{}

GetMapOrDefault returns the map[string]interface{} value for the given column name or default value if not found

func (*DataRow) GetNullBool added in v4.4.1

func (r *DataRow) GetNullBool(name string) (sql.NullBool, error)

GetNullBool returns the sql.NullBool value for the given column name

func (*DataRow) GetNullFloat64 added in v4.4.1

func (r *DataRow) GetNullFloat64(name string) (sql.NullFloat64, error)

GetNullFloat64 returns the sql.NullFloat64 value for the given column name

func (*DataRow) GetNullInt64 added in v4.4.1

func (r *DataRow) GetNullInt64(name string) (sql.NullInt64, error)

GetNullInt64 returns the sql.NullInt64 value for the given column name

func (*DataRow) GetNullString added in v4.4.1

func (r *DataRow) GetNullString(name string) (sql.NullString, error)

GetNullString returns the sql.NullString value for the given column name

func (*DataRow) GetNullTime added in v4.4.1

func (r *DataRow) GetNullTime(name string) (sql.NullTime, error)

GetNullTime returns the sql.NullTime value for the given column name

func (*DataRow) GetSlice added in v4.4.1

func (r *DataRow) GetSlice(name string) ([]interface{}, error)

GetSlice returns the []interface{} value for the given column name

func (*DataRow) GetSliceOrDefault added in v4.4.1

func (r *DataRow) GetSliceOrDefault(name string, defaultValue []interface{}) []interface{}

GetSliceOrDefault returns the []interface{} value for the given column name or default value if not found

func (*DataRow) GetString added in v4.3.7

func (r *DataRow) GetString(name string) (string, error)

GetString returns the string value for the given column name

func (*DataRow) GetStringOrDefault added in v4.4.1

func (r *DataRow) GetStringOrDefault(name string, defaultValue string) string

GetStringOrDefault returns the string value for the given column name or default value if not found

func (*DataRow) GetTime added in v4.3.7

func (r *DataRow) GetTime(name string) (time.Time, error)

GetTime returns the time.Time value for the given column name

func (*DataRow) GetTimeOrDefault added in v4.4.1

func (r *DataRow) GetTimeOrDefault(name string, defaultValue time.Time) time.Time

GetTimeOrDefault returns the time.Time value for the given column name or default value if not found

type EnhancedError added in v4.2.5

type EnhancedError struct {
	Code     ErrorCode
	Message  string
	Severity ErrorSeverity
	Context  ErrorContext
	Cause    error
}

EnhancedError represents a detailed error with context

func NewError added in v4.2.5

func NewError(code ErrorCode, message string, severity ErrorSeverity, cause error) *EnhancedError

NewError creates a new enhanced error

func (*EnhancedError) Error added in v4.2.5

func (e *EnhancedError) Error() string

func (*EnhancedError) WithData added in v4.2.5

func (e *EnhancedError) WithData(key string, value interface{}) *EnhancedError

WithData adds contextual data to the error

type ErrorCode added in v4.2.5

type ErrorCode string

ErrorCode represents specific error types

const (
	// Database error codes
	ErrDatabaseConnection ErrorCode = "DB_CONNECTION_ERROR"
	ErrDatabaseQuery      ErrorCode = "DB_QUERY_ERROR"
	ErrDatabaseExec       ErrorCode = "DB_EXEC_ERROR"
	ErrDatabaseTx         ErrorCode = "DB_TRANSACTION_ERROR"

	// Validation error codes
	ErrValidation       ErrorCode = "VALIDATION_ERROR"
	ErrInvalidInput     ErrorCode = "INVALID_INPUT"
	ErrInvalidType      ErrorCode = "INVALID_TYPE"
	ErrRequired         ErrorCode = "REQUIRED_FIELD"
	ErrInvalidFormat    ErrorCode = "INVALID_FORMAT"
	ErrUniqueConstraint ErrorCode = "UNIQUE_CONSTRAINT"

	// Security error codes
	ErrEncryption    ErrorCode = "ENCRYPTION_ERROR"
	ErrDecryption    ErrorCode = "DECRYPTION_ERROR"
	ErrUnauthorized  ErrorCode = "UNAUTHORIZED"
	ErrKeyManagement ErrorCode = "KEY_MANAGEMENT_ERROR"

	// Configuration error codes
	ErrConfiguration ErrorCode = "CONFIGURATION_ERROR"
	ErrEnvironment   ErrorCode = "ENVIRONMENT_ERROR"

	// System error codes
	ErrInternal ErrorCode = "INTERNAL_ERROR"
	ErrTimeout  ErrorCode = "TIMEOUT_ERROR"
	ErrIO       ErrorCode = "IO_ERROR"
)

type ErrorContext added in v4.2.5

type ErrorContext struct {
	Timestamp time.Time
	Stack     []StackTrace
	Data      map[string]interface{}
}

ErrorContext contains contextual information about an error

func GetErrorContext added in v4.2.5

func GetErrorContext(err error) *ErrorContext

GetErrorContext retrieves the context from an error if available

type ErrorHandler added in v4.2.5

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

ErrorHandler handles and processes errors

func NewErrorHandler added in v4.2.5

func NewErrorHandler() *ErrorHandler

NewErrorHandler creates a new error handler

func (*ErrorHandler) Handle added in v4.2.5

func (h *ErrorHandler) Handle(err error) error

Handle processes an error using registered handlers

func (*ErrorHandler) RegisterHandler added in v4.2.5

func (h *ErrorHandler) RegisterHandler(code ErrorCode, handler func(*EnhancedError) error)

RegisterHandler registers a handler for a specific error code

type ErrorLogger added in v4.2.5

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

ErrorLogger provides error logging functionality

func NewErrorLogger added in v4.2.5

func NewErrorLogger(minSeverity ErrorSeverity, logFunc func(error)) *ErrorLogger

NewErrorLogger creates a new error logger

func (*ErrorLogger) Log added in v4.2.5

func (l *ErrorLogger) Log(err error)

Log logs an error if it meets the minimum severity level

type ErrorRetrier added in v4.2.5

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

ErrorRetrier provides retry functionality for operations that may fail

func NewErrorRetrier added in v4.2.5

func NewErrorRetrier(maxAttempts int, backoff time.Duration) *ErrorRetrier

NewErrorRetrier creates a new error retrier

func (*ErrorRetrier) Retry added in v4.2.5

func (r *ErrorRetrier) Retry(operation func() error) error

Retry attempts an operation with retries

type ErrorSeverity added in v4.2.5

type ErrorSeverity int

ErrorSeverity represents the severity level of an error

const (
	SeverityDebug ErrorSeverity = iota
	SeverityInfo
	SeverityWarning
	SeverityError
	SeverityCritical
)

type ExecuteType added in v4.5.0

type ExecuteType string
const (
	Query ExecuteType = "query"
	Exec  ExecuteType = "exec"
)

type FieldInfo added in v4.2.0

type FieldInfo struct {
	Index      int          // Field index in struct
	Name       string       // Field name in struct
	Column     string       // Column name in database
	Type       reflect.Type // Field type
	IsAuto     bool         // Is auto-increment field
	IsPrimary  bool         // Is primary key
	HasDefault bool         // Has default value
}

FieldInfo stores the mapping information for a single field

type ITableModel

type ITableModel interface {
	// TableName returns the custom table name
	TableName() string
	// CreateSql returns the custom CREATE TABLE SQL statement
	CreateSql() string
}

ITableModel defines the interface for custom table models

type ITypeConverter added in v4.2.5

type ITypeConverter interface {
	Convert(value interface{}, targetType reflect.Type) (interface{}, error)
}

ITypeConverter defines the interface for type conversion

func NewTypeConverter added in v4.2.5

func NewTypeConverter() ITypeConverter

NewTypeConverter creates a new ITypeConverter instance

type IsolationLevel added in v4.1.5

type IsolationLevel sql.IsolationLevel

IsolationLevel represents the transaction isolation level

const (
	// LevelDefault is the default isolation level for the database
	LevelDefault IsolationLevel = IsolationLevel(sql.LevelDefault)
	// LevelReadUncommitted is the read uncommitted isolation level
	LevelReadUncommitted IsolationLevel = IsolationLevel(sql.LevelReadUncommitted)
	// LevelReadCommitted is the read committed isolation level
	LevelReadCommitted IsolationLevel = IsolationLevel(sql.LevelReadCommitted)
	// LevelWriteCommitted is the write committed isolation level
	LevelWriteCommitted IsolationLevel = IsolationLevel(sql.LevelWriteCommitted)
	// LevelRepeatableRead is the repeatable read isolation level
	LevelRepeatableRead IsolationLevel = IsolationLevel(sql.LevelRepeatableRead)
	// LevelSnapshot is the snapshot isolation level
	LevelSnapshot IsolationLevel = IsolationLevel(sql.LevelSnapshot)
	// LevelSerializable is the serializable isolation level
	LevelSerializable IsolationLevel = IsolationLevel(sql.LevelSerializable)
	// LevelLinearizable is the linearizable isolation level
	LevelLinearizable IsolationLevel = IsolationLevel(sql.LevelLinearizable)
)

type JoinType added in v4.1.3

type JoinType int

JoinType represents the type of JOIN operation

const (
	// JoinAnd represents AND join
	JoinAnd JoinType = iota
	// JoinOr represents OR join
	JoinOr
)

type LockType added in v4.1.5

type LockType int

LockType represents the type of row locking

const (
	// LockNone represents no locking
	LockNone LockType = iota
	// LockForUpdate represents FOR UPDATE lock
	LockForUpdate
	// LockForShare represents FOR SHARE lock
	LockForShare
)

type MockSQLFactory added in v4.2.4

type MockSQLFactory struct{}

MockSQLFactory is a mock implementation of SQLFactory for testing

func (*MockSQLFactory) BuildBatchInsert added in v4.2.4

func (f *MockSQLFactory) BuildBatchInsert(table string, values []map[string]interface{}) *SqlProto

func (*MockSQLFactory) BuildCreateTable added in v4.2.4

func (f *MockSQLFactory) BuildCreateTable(table string, modelType reflect.Type) *SqlProto

func (*MockSQLFactory) BuildDelete added in v4.2.4

func (f *MockSQLFactory) BuildDelete(table string, conditions []*Condition) *SqlProto

func (*MockSQLFactory) BuildInsert added in v4.2.4

func (f *MockSQLFactory) BuildInsert(table string, fields map[string]interface{}, fieldOrder []string) *SqlProto

func (*MockSQLFactory) BuildOrderBy added in v4.2.4

func (f *MockSQLFactory) BuildOrderBy(orders []OrderBy) string

func (*MockSQLFactory) BuildRawQuery added in v4.2.4

func (f *MockSQLFactory) BuildRawQuery(query string, args []interface{}) (*SQLQuery, error)

func (*MockSQLFactory) BuildSelect added in v4.2.4

func (f *MockSQLFactory) BuildSelect(table string, fields []string, conditions []*Condition, orderBy string, limit, offset int) *SqlProto

func (*MockSQLFactory) BuildUpdate added in v4.2.4

func (f *MockSQLFactory) BuildUpdate(table string, fields map[string]interface{}, fieldOrder []string, conditions []*Condition) *SqlProto

func (*MockSQLFactory) Connect added in v4.2.4

func (f *MockSQLFactory) Connect(dsn string) (*sql.DB, error)

func (*MockSQLFactory) GetTableInfo added in v4.2.4

func (f *MockSQLFactory) GetTableInfo(db *sql.DB, tableName string) (*TableInfo, error)

func (*MockSQLFactory) GetTables added in v4.2.4

func (f *MockSQLFactory) GetTables(db *sql.DB, pattern string) ([]string, error)

func (*MockSQLFactory) GetType added in v4.2.4

func (f *MockSQLFactory) GetType() string

type NullRawBytes added in v4.6.7

type NullRawBytes struct {
	RawBytes []byte
	Valid    bool // Valid is true if RawBytes is not NULL
}

NullRawBytes represents a sql.RawBytes that may be null. NullRawBytes implements the Scanner interface so it can be used as a scan destination like sql.NullString.

func (*NullRawBytes) Scan added in v4.6.7

func (n *NullRawBytes) Scan(value interface{}) error

Scan implements the Scanner interface.

func (NullRawBytes) Value added in v4.6.7

func (n NullRawBytes) Value() (interface{}, error)

Value implements the driver.Valuer interface.

type OpType added in v4.1.3

type OpType int

OpType represents the type of operation

const (
	// OpEq represents equals operation
	OpEq OpType = iota
	// OpNe represents not equals operation
	OpNe
	// OpGt represents greater than operation
	OpGt
	// OpGe represents greater than or equals operation
	OpGe
	// OpLt represents less than operation
	OpLt
	// OpLe represents less than or equals operation
	OpLe
	// OpLike represents LIKE operation
	OpLike
	// OpNotLike represents NOT LIKE operation
	OpNotLike
	// OpIn represents IN operation
	OpIn
	// OpNotIn represents NOT IN operation
	OpNotIn
	// OpIsNull represents IS NULL operation
	OpIsNull
	// OpIsNotNull represents IS NOT NULL operation
	OpIsNotNull
	// OpBetween represents BETWEEN operation
	OpBetween
	// OpNotBetween represents NOT BETWEEN operation
	OpNotBetween
	// OpCustom represents custom operation
	OpCustom
)

type OrderBy added in v4.1.3

type OrderBy struct {
	Field string
	Type  OrderType
}

OrderBy represents an order by clause

type OrderType added in v4.1.3

type OrderType int

OrderType represents the type of ordering

const (
	OrderAsc  OrderType = iota // Ascending order
	OrderDesc                  // Descending order
)

func (OrderType) String added in v4.2.4

func (o OrderType) String() string

String returns the string representation of OrderType

type ReplicationConfig added in v4.2.6

type ReplicationConfig struct {
	Master *ConnectionConfig
	Slaves []*ConnectionConfig
}

ReplicationConfig 主从配置

type Result

type Result struct {
	ID       int64            `json:"id"`
	Affected int64            `json:"affected"`
	Error    error            `json:"error"`
	Data     []map[string]any `json:"data"`
	Columns  []string         `json:"columns"`
}

Result implements sql.Result interface and includes query result functionality

func (*Result) Empty added in v4.1.6

func (r *Result) Empty() bool

Empty returns true if the result is empty

func (*Result) First added in v4.1.6

func (r *Result) First() *Result

First returns the first result or error if no results

func (*Result) FromJSON added in v4.1.7

func (r *Result) FromJSON(jsonStr string) error

FromJSON parses JSON string into the result

func (*Result) GetFirstRow added in v4.3.7

func (r *Result) GetFirstRow() (*DataRow, error)

GetFirstRow returns the first DataRow from the result

func (*Result) GetRow added in v4.3.7

func (r *Result) GetRow(index int) (*DataRow, error)

GetRow returns a DataRow for the specified index

func (*Result) Into added in v4.1.6

func (r *Result) Into(dest interface{}) error

Into converts the result data into the specified struct slice or struct pointer

func (*Result) IntoMap added in v4.1.7

func (r *Result) IntoMap() (map[string]interface{}, error)

IntoMap scans a single result row into a map

func (*Result) IntoMaps added in v4.1.7

func (r *Result) IntoMaps() ([]map[string]interface{}, error)

IntoMaps returns all result rows as a slice of maps

func (*Result) LastInsertId

func (r *Result) LastInsertId() (int64, error)

LastInsertId returns the last inserted ID

func (*Result) RowsAffected

func (r *Result) RowsAffected() (int64, error)

RowsAffected returns the number of rows affected

func (*Result) Scan added in v4.2.4

func (r *Result) Scan(rows *sql.Rows) error

Scan implements the sql.Scanner interface

func (*Result) Size added in v4.1.6

func (r *Result) Size() int

Size returns the number of rows in the result

func (*Result) ToJSON added in v4.1.7

func (r *Result) ToJSON() (string, error)

ToJSON converts the result to JSON string

type RetryConfig added in v4.2.6

type RetryConfig struct {
	MaxRetries int           // 最大重试次数
	RetryDelay time.Duration // 重试延迟
	MaxDelay   time.Duration // 最大延迟
}

RetryConfig 重试配置

type SQLFactory

type SQLFactory interface {
	// Connect creates a new database connection
	Connect(dsn string) (*sql.DB, error)

	// GetType returns the database type (e.g., "mysql", "postgres")
	GetType() string

	// BuildSelect builds a SELECT query
	BuildSelect(table string, fields []string, conditions []*Condition, orderBy string, limit, offset int) *SqlProto

	// BuildUpdate builds an UPDATE query
	BuildUpdate(table string, fields map[string]interface{}, fieldOrder []string, conditions []*Condition) *SqlProto

	// BuildInsert builds an INSERT query
	BuildInsert(table string, fields map[string]interface{}, fieldOrder []string) *SqlProto

	// BuildBatchInsert builds a batch INSERT query
	BuildBatchInsert(table string, values []map[string]interface{}) *SqlProto

	// BuildDelete builds a DELETE query
	BuildDelete(table string, conditions []*Condition) *SqlProto

	// BuildCreateTable builds a CREATE TABLE query
	BuildCreateTable(table string, modelType reflect.Type) *SqlProto

	// GetTableInfo 获取表信息
	GetTableInfo(db *sql.DB, tableName string) (*TableInfo, error)

	// GetTables 获取符合模式的所有表
	// pattern: 表名匹配模式,支持 * 通配符
	// 对于 PostgreSQL,pattern 可以是 schema.table 格式
	GetTables(db *sql.DB, pattern string) ([]string, error)

	// BuildOrderBy builds the ORDER BY clause
	BuildOrderBy(orders []OrderBy) string
}

SQLFactory defines the interface for SQL query builders

func GetFactory

func GetFactory(driver string) (SQLFactory, error)

GetFactory returns the SQL factory for a specific driver

type SQLQuery added in v4.2.4

type SQLQuery struct {
	Query string
	Args  []interface{}
}

SQLQuery represents a SQL query with its arguments

type ScannerInfo added in v4.2.0

type ScannerInfo struct {
	Index   int                           // Field index in struct
	Scanner interface{}                   // Pre-allocated scanner
	Convert func(interface{}) interface{} // Value converter function
}

ScannerInfo stores information for scanning database columns

type SqlProto added in v4.5.0

type SqlProto struct {
	SqlType ExecuteType
	Sql     string
	Args    []any
	Error   error
}

type StackTrace added in v4.2.5

type StackTrace struct {
	File     string
	Line     int
	Function string
}

StackTrace represents a stack trace

type TableInfo

type TableInfo struct {
	TableName    string       `json:"table_name"`    // 表名
	TableComment string       `json:"table_comment"` // 表注释
	PrimaryKeys  []string     `json:"primary_keys"`  // 主键列表
	Columns      []ColumnInfo `json:"columns"`       // 列信息
	HasDecimal   bool         `json:"has_decimal"`   // 是否包含 Decimal 类型
	HasUUID      bool         `json:"has_uuid"`      // 是否包含 UUID 类型
	HasIP        bool         `json:"has_ip"`        // 是否包含 IP 类型
	HasTime      bool         `json:"has_time"`      // 是否包含时间类型
}

TableInfo 表信息

type TableStruct added in v4.3.6

type TableStruct struct {
	TableInfo     TableInfo         `json:"table_info"`
	FieldToColMap map[string]string `json:"field_to_col_map"`
	ColToFieldMap map[string]string `json:"col_to_field_map"`
}

type Transaction added in v4.1.5

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

Transaction represents a database transaction

func NewTransaction added in v4.1.5

func NewTransaction(db interface{}, tx interface{}, driver string) *Transaction

NewTransaction creates a new transaction

func (*Transaction) GetDB added in v4.1.5

func (t *Transaction) GetDB() interface{}

GetDB returns the database instance

func (*Transaction) GetDriver added in v4.1.5

func (t *Transaction) GetDriver() string

GetDriver returns the database driver name

func (*Transaction) GetTx added in v4.1.5

func (t *Transaction) GetTx() interface{}

GetTx returns the transaction instance

type TransactionFunc added in v4.1.5

type TransactionFunc func(tx *Transaction) Result

TransactionFunc represents a function that executes within a transaction

type TransactionOptions added in v4.1.5

type TransactionOptions struct {
	Timeout         time.Duration
	IsolationLevel  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
)

type Transfer added in v4.2.0

type Transfer struct {
	TableName  string                // Table name
	Fields     map[string]*FieldInfo // Map of column name to field info
	FieldOrder []string              // Order of fields for consistent operations
	PrimaryKey *FieldInfo            // Primary key field info
	// contains filtered or unexported fields
}

Transfer caches the mapping between struct and database table

func GetTransfer added in v4.2.0

func GetTransfer(model interface{}) *Transfer

GetTransfer gets or creates a Transfer for the given struct type

func (*Transfer) CreateScanners added in v4.2.0

func (t *Transfer) CreateScanners(columns []string) []interface{}

CreateScanners creates a list of scanners for the given columns

func (*Transfer) First added in v4.2.4

func (t *Transfer) First(rows *sql.Rows) (interface{}, error)

First scans a single row into a model instance

func (*Transfer) GetFieldNames added in v4.2.0

func (t *Transfer) GetFieldNames() []string

GetFieldNames returns all field names in order

func (*Transfer) GetFieldTag added in v4.4.1

func (t *Transfer) GetFieldTag(fieldName string) string

GetFieldTag returns the gom tag for a given field name

func (*Transfer) GetPrimaryKeyValue added in v4.2.0

func (t *Transfer) GetPrimaryKeyValue(model interface{}) (interface{}, error)

GetPrimaryKeyValue gets the primary key value from the model

func (*Transfer) GetTableName added in v4.2.0

func (t *Transfer) GetTableName() string

GetTableName returns the cached table name

func (*Transfer) Result added in v4.2.4

func (t *Transfer) Result(rows *sql.Rows) (interface{}, error)

Result scans the rows into a slice of model instances

func (*Transfer) ScanAll added in v4.2.0

func (t *Transfer) ScanAll(rows *sql.Rows) (interface{}, error)

ScanAll scans all rows into a slice of struct instances

func (*Transfer) ScanRow added in v4.2.0

func (t *Transfer) ScanRow(rows *sql.Rows) (interface{}, error)

ScanRow scans a database row into a new instance of the model

func (*Transfer) ScanRows added in v4.2.4

func (t *Transfer) ScanRows(rows *sql.Rows) (interface{}, error)

ScanRows scans multiple rows into a slice of model instances

func (*Transfer) SetModel added in v4.2.0

func (t *Transfer) SetModel(model interface{})

SetModel sets the model type for scanning

func (*Transfer) ToMap added in v4.2.0

func (t *Transfer) ToMap(model interface{}, isUpdate ...bool) map[string]interface{}

ToMap converts a struct to map using cached field information

type TypeConverter added in v4.2.2

type TypeConverter interface {
	// FromDB converts a value from database format to Go type
	FromDB(value interface{}) error
	// ToDB converts a Go type to database format
	ToDB() (interface{}, error)
}

TypeConverter is the interface that wraps the basic type conversion methods

type ValidationContext added in v4.2.5

type ValidationContext struct {
	FieldName string
	Value     interface{}
	Parent    interface{}
	Rules     []ValidationRule
}

ValidationContext provides context for validation

type ValidationError added in v4.2.5

type ValidationError struct {
	Field   string
	Rule    string
	Message string
}

ValidationError represents a validation error

func (*ValidationError) Error added in v4.2.5

func (e *ValidationError) Error() string

type ValidationManager added in v4.2.5

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

ValidationManager handles validation rules and execution

func NewValidationManager added in v4.2.5

func NewValidationManager() *ValidationManager

NewValidationManager creates a new validation manager

func (*ValidationManager) AddCustomRule added in v4.2.5

func (vm *ValidationManager) AddCustomRule(field string, validate func(value interface{}) error, message string)

AddCustomRule adds a custom validation rule

func (*ValidationManager) AddRule added in v4.2.5

func (vm *ValidationManager) AddRule(field string, rule ValidationRule)

AddRule adds a validation rule for a field

func (*ValidationManager) CrossFieldValidation added in v4.2.5

func (vm *ValidationManager) CrossFieldValidation(s interface{}, rules map[string]func(fields map[string]interface{}) error) []error

CrossFieldValidation validates fields that depend on each other

func (*ValidationManager) ValidateField added in v4.2.5

func (vm *ValidationManager) ValidateField(field string, value interface{}) error

ValidateField validates a single field

func (*ValidationManager) ValidateStruct added in v4.2.5

func (vm *ValidationManager) ValidateStruct(s interface{}) []error

ValidateStruct validates a struct using reflection

type ValidationRule added in v4.2.5

type ValidationRule struct {
	Name       string
	Validate   func(value interface{}) error
	Message    string
	Parameters map[string]interface{}
}

ValidationRule defines a validation rule

type Validator added in v4.2.5

type Validator interface {
	Validate(ctx *ValidationContext) error
}

Validator defines the validation interface

Jump to

Keyboard shortcuts

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