Documentation
¶
Index ¶
- Constants
- Variables
- func Camel2UnderScore(name string) string
- func EnsureIsSliceOrArray(obj interface{}) reflect.Value
- func EscapeMysqlString(sql string) string
- func Expr(expression string, args ...interface{}) clause.Expr
- func ExprIf(clientType, expr string, ok, nok interface{}) clause.Expr
- func ExprInc(clientType, field string) clause.Expr
- func ExprIncBy(clientType, field string, cnt int64) clause.Expr
- func FormatSql(sql string, values ...interface{}) string
- func IsUniqueIndexConflictErr(err error) bool
- func NewLogger() *logger
- func QuoteFieldName(name string, clientType string) string
- func SetDefaultLogger(l Logger)
- func UniqueSlice(s interface{}) interface{}
- func UpdateCase[M string | *Cond](caseMap map[M]any, def ...interface{}) clause.Expr
- func UpdateCaseOneField(field string, caseMap map[any]any, def ...interface{}) clause.Expr
- type BsonSerializer
- type ChunkResult
- type Client
- func (p *Client) AutoMigrate(table interface{}) (err error)
- func (p *Client) AutoMigrates(dst ...interface{}) (err error)
- func (p *Client) Close() error
- func (p *Client) Database() *gorm.DB
- func (p *Client) DriverType() string
- func (p *Client) ExpectBegin() *ExpectedBegin
- func (p *Client) ExpectClose() *ExpectedClose
- func (p *Client) ExpectCommit() *ExpectedCommit
- func (p *Client) ExpectExec(sql string) *ExpectedExec
- func (p *Client) ExpectQuery(sql string) *ExpectedQuery
- func (p *Client) ExpectRollback() *ExpectedRollback
- func (p *Client) ExpectationsWereMet() error
- func (p *Client) MockDB() *MockDB
- func (p *Client) NewScoop() *Scoop
- func (p *Client) Ping() error
- func (p *Client) SqlDB() (*sql.DB, error)
- type Cond
- func Between(column string, min, max interface{}) *Cond
- func LeftLike(column string, value string) *Cond
- func Like(column string, value string) *Cond
- func NotBetween(column string, min, max interface{}) *Cond
- func NotLeftLike(column string, value string) *Cond
- func NotLike(column string, value string) *Cond
- func NotRightLike(column string, value string) *Cond
- func Or(args ...interface{}) *Cond
- func OrWhere(args ...interface{}) *Cond
- func RightLike(column string, value string) *Cond
- func Where(args ...interface{}) *Cond
- func (p *Cond) Between(column string, min, max interface{}) *Cond
- func (p *Cond) GoString() string
- func (p *Cond) LeftLike(column string, value string) *Cond
- func (p *Cond) Like(column string, value string) *Cond
- func (p *Cond) NotBetween(column string, min, max interface{}) *Cond
- func (p *Cond) NotLeftLike(column string, value string) *Cond
- func (p *Cond) NotLike(column string, value string) *Cond
- func (p *Cond) NotRightLike(column string, value string) *Cond
- func (p *Cond) Or(args ...interface{}) *Cond
- func (p *Cond) OrWhere(args ...interface{}) *Cond
- func (p *Cond) Reset() *Cond
- func (p *Cond) RightLike(column string, value string) *Cond
- func (p *Cond) String() string
- func (p *Cond) ToString() string
- func (p *Cond) Where(args ...interface{}) *Cond
- type Config
- type CreateIfNotExistsResult
- type CreateInBatchesResult
- type CreateNotExistResult
- type CreateOrUpdateResult
- type CreateResult
- type DeleteResult
- type ExpectedBegin
- type ExpectedClose
- type ExpectedCommit
- type ExpectedExec
- type ExpectedQuery
- type ExpectedRollback
- type FindResult
- type FirstOrCreateResult
- type FirstResult
- type IniSerializer
- type JsonSerializer
- type Logger
- type MockDB
- type Model
- func (p *Model[M]) IsDuplicatedKeyError(err error) bool
- func (p *Model[M]) IsNotFound(err error) bool
- func (p *Model[M]) NewScoop(tx ...*Scoop) *ModelScoop[M]
- func (p *Model[M]) SetDuplicatedKeyError(err error) *Model[M]
- func (p *Model[M]) SetNotFound(err error) *Model[M]
- func (p *Model[M]) TableName() string
- type ModelScoop
- func (p *ModelScoop[M]) Asc(fields ...string) *ModelScoop[M]
- func (p *ModelScoop[M]) Between(column string, min, max interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) Chunk(size uint64, fc func(tx *Scoop, out []*M, offset uint64) error) *ChunkResult
- func (p *ModelScoop[M]) Create(m *M) error
- func (p *ModelScoop[M]) CreateIfNotExists(m *M) *CreateIfNotExistsResult
- func (p *ModelScoop[M]) CreateInBatches(values []*M, batchSize int) *CreateInBatchesResult
- func (p *ModelScoop[M]) CreateNotExist(m *M) *CreateNotExistResult[M]
- func (p *ModelScoop[M]) CreateOrUpdate(values map[string]interface{}, m *M) *CreateOrUpdateResult[M]
- func (p *ModelScoop[M]) Desc(fields ...string) *ModelScoop[M]
- func (p *ModelScoop[M]) Equal(column string, value interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) Find() ([]*M, error)
- func (p *ModelScoop[M]) FindByPage(opt *core.ListOption) (page *core.Paginate, values []*M, err error)
- func (p *ModelScoop[M]) First() (*M, error)
- func (p *ModelScoop[M]) FirstOrCreate(m *M) *FirstOrCreateResult[M]
- func (p *ModelScoop[M]) Group(fields ...string) *ModelScoop[M]
- func (p *ModelScoop[M]) Ignore(b ...bool) *ModelScoop[M]
- func (p *ModelScoop[M]) In(column string, values interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) LeftLike(column string, value string) *ModelScoop[M]
- func (p *ModelScoop[M]) Like(column string, value string) *ModelScoop[M]
- func (p *ModelScoop[M]) Limit(limit uint64) *ModelScoop[M]
- func (p *ModelScoop[M]) NotBetween(column string, min, max interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) NotEqual(column string, value interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) NotIn(column string, values interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) NotLeftLike(column string, value string) *ModelScoop[M]
- func (p *ModelScoop[M]) NotLike(column string, value string) *ModelScoop[M]
- func (p *ModelScoop[M]) NotRightLike(column string, value string) *ModelScoop[M]
- func (p *ModelScoop[M]) Offset(offset uint64) *ModelScoop[M]
- func (p *ModelScoop[M]) Or(args ...interface{}) *ModelScoop[M]
- func (p *ModelScoop[M]) Order(fields ...string) *ModelScoop[M]
- func (p *ModelScoop[M]) RightLike(column string, value string) *ModelScoop[M]
- func (p *ModelScoop[M]) Scan(dest interface{}) *ScanResult
- func (p *ModelScoop[M]) Select(fields ...string) *ModelScoop[M]
- func (p *ModelScoop[M]) Unscoped(b ...bool) *ModelScoop[M]
- func (p *ModelScoop[M]) UpdateOrCreate(values map[string]interface{}, m *M) *UpdateOrCreateResult[M]
- func (p *ModelScoop[M]) Where(args ...interface{}) *ModelScoop[M]
- type ProtojsonSerializer
- type SQLOperationType
- type ScanResult
- type Scoop
- func (p *Scoop) AutoMigrate(dst ...interface{}) error
- func (p *Scoop) Begin() *Scoop
- func (p *Scoop) Between(column string, min, max interface{}) *Scoop
- func (p *Scoop) Chunk(dest interface{}, size uint64, fc func(tx *Scoop, offset uint64) error) *ChunkResult
- func (p *Scoop) Commit() *Scoop
- func (p *Scoop) CommitOrRollback(tx *Scoop, logic func(tx *Scoop) error) error
- func (p *Scoop) Count() (uint64, error)
- func (p *Scoop) Create(value interface{}) *CreateResult
- func (p *Scoop) CreateInBatches(value interface{}, batchSize int) *CreateInBatchesResult
- func (p *Scoop) CrossJoin(table string) *Scoop
- func (p *Scoop) Delete() *DeleteResult
- func (p *Scoop) Equal(column string, value interface{}) *Scoop
- func (p *Scoop) Exist() (bool, error)
- func (p *Scoop) Find(out interface{}) *FindResult
- func (p *Scoop) FindByPage(opt *core.ListOption, values any) (*core.Paginate, error)
- func (p *Scoop) First(out interface{}) *FirstResult
- func (p *Scoop) FullJoin(table, condition string) *Scoop
- func (p *Scoop) Group(fields ...string) *Scoop
- func (p *Scoop) Having(args ...interface{}) *Scoop
- func (p *Scoop) Ignore(b ...bool) *Scoop
- func (p *Scoop) In(column string, values interface{}) *Scoop
- func (p *Scoop) InnerJoin(table, condition string) *Scoop
- func (p *Scoop) IsDuplicatedKeyError(err error) bool
- func (p *Scoop) IsNotFound(err error) bool
- func (p *Scoop) Join(joinType, table, condition string) *Scoop
- func (p *Scoop) LeftJoin(table, condition string) *Scoop
- func (p *Scoop) LeftLike(column string, value string) *Scoop
- func (p *Scoop) Like(column string, value string) *Scoop
- func (p *Scoop) Limit(limit uint64) *Scoop
- func (p *Scoop) Model(m any) *Scoop
- func (p *Scoop) NotBetween(column string, min, max interface{}) *Scoop
- func (p *Scoop) NotEqual(column string, value interface{}) *Scoop
- func (p *Scoop) NotIn(column string, values interface{}) *Scoop
- func (p *Scoop) NotLeftLike(column string, value string) *Scoop
- func (p *Scoop) NotLike(column string, value string) *Scoop
- func (p *Scoop) NotRightLike(column string, value string) *Scoop
- func (p *Scoop) Offset(offset uint64) *Scoop
- func (p *Scoop) Order(fields ...string) *Scoop
- func (p *Scoop) RightJoin(table, condition string) *Scoop
- func (p *Scoop) RightLike(column string, value string) *Scoop
- func (p *Scoop) Rollback() *Scoop
- func (p *Scoop) Scan(dest interface{}) *ScanResult
- func (p *Scoop) Select(fields ...string) *Scoop
- func (p *Scoop) Table(m string) *Scoop
- func (p *Scoop) ToSQL(operation SQLOperationType, value ...interface{}) string
- func (p *Scoop) Unscoped(b ...bool) *Scoop
- func (p *Scoop) Updates(m interface{}, args ...interface{}) *UpdateResult
- func (p *Scoop) Where(args ...interface{}) *Scoop
- type Tabler
- type TestProfile
- type TestUser
- type TomlSerializer
- type UpdateOrCreateResult
- type UpdateResult
- type YamlSerializer
Constants ¶
const ( Sqlite = "sqlite" MySQL = "mysql" Postgres = "postgres" ClickHouse = "clickhouse" TiDB = "tidb" GaussDB = "gaussdb" )
Variables ¶
var ErrBatchesStop = errors.New("batches stop")
Functions ¶
func Camel2UnderScore ¶
func EnsureIsSliceOrArray ¶
func EscapeMysqlString ¶
func QuoteFieldName ¶
QuoteFieldName 智能引用字段名,自动处理保留关键字和特殊字符 - 已引用的字段名保持不变(向后兼容) - 保留关键字自动添加引号(防止 SQL 语法错误) - 包含特殊字符的字段名自动添加引号 - 使用缓存优化性能 导出函数供测试使用
func SetDefaultLogger ¶
func SetDefaultLogger(l Logger)
func UniqueSlice ¶
func UniqueSlice(s interface{}) interface{}
UniqueSlice removes duplicate elements from a slice while preserving order. It uses a map for O(n) time complexity but requires elements to be comparable.
Performance characteristics:
- Time: O(n) where n is the slice length
- Space: O(n) for the map storage
- Returns original slice unchanged if length < 2
- Note: Uses reflection, so has overhead. Consider type-specific implementations for performance-critical paths.
Example:
input := []int{1, 2, 2, 3, 1, 4}
output := UniqueSlice(input).([]int) // []int{1, 2, 3, 4}
func UpdateCase ¶
CASE WHEN (`a` = 1) THEN "1" WHEN (`b` = 2) THEN 2 ELSE 10 END
Types ¶
type BsonSerializer ¶
type BsonSerializer struct {
}
BsonSerializer BSON 序列化器
type ChunkResult ¶
type ChunkResult struct {
Error error
}
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) AutoMigrate ¶
func (*Client) AutoMigrates ¶
func (*Client) DriverType ¶
func (*Client) ExpectBegin ¶
func (p *Client) ExpectBegin() *ExpectedBegin
ExpectBegin sets up an expectation for a transaction begin operation
func (*Client) ExpectClose ¶
func (p *Client) ExpectClose() *ExpectedClose
ExpectClose sets up an expectation for a database close operation
func (*Client) ExpectCommit ¶
func (p *Client) ExpectCommit() *ExpectedCommit
ExpectCommit sets up an expectation for a transaction commit operation
func (*Client) ExpectExec ¶
func (p *Client) ExpectExec(sql string) *ExpectedExec
ExpectExec sets up an expectation for an exec operation Returns the ExpectedExec for further configuration (WillReturnResult, etc.)
func (*Client) ExpectQuery ¶
func (p *Client) ExpectQuery(sql string) *ExpectedQuery
ExpectQuery sets up an expectation for a query operation Returns the ExpectedQuery for further configuration (WillReturnRows, etc.)
func (*Client) ExpectRollback ¶
func (p *Client) ExpectRollback() *ExpectedRollback
ExpectRollback sets up an expectation for a transaction rollback operation
func (*Client) ExpectationsWereMet ¶
ExpectationsWereMet checks if all mock expectations were met This should be called at the end of each test to ensure all expectations were satisfied
type Cond ¶
type Cond struct {
// contains filtered or unexported fields
}
func NotBetween ¶
NotBetween creates a new Cond with NOT BETWEEN condition
func NotLeftLike ¶
NotLeftLike creates a new Cond with NOT LEFT LIKE condition
func NotRightLike ¶
NotRightLike creates a new Cond with NOT RIGHT LIKE condition
func OrWhere ¶
func OrWhere(args ...interface{}) *Cond
OrWhere creates a new Cond with OR conditions
func (*Cond) NotBetween ¶
type Config ¶
type Config struct {
// Database type, support sqlite, sqlite-cgo, mysql, postgres, clickhouse, tidb, gaussdb, default sqlite
// sqlite: sqlite|sqlite3 (pure Go, no CGO, no encryption support)
// sqlite-cgo: sqlite-cgo (with CGO, supports encryption via SQLCipher)
// mysql: mysql
// postgres: postgres|pg|postgresql|pgsql
// clickhouse: clickhouse|ch
// tidb: tidb (MySQL-compatible)
// gaussdb: gaussdb (PostgreSQL-compatible)
Type string `yaml:"type,omitempty" json:"type,omitempty" env:"DATABASE_TYPE"`
// Database debug, default false
Debug bool `yaml:"debug,omitempty" json:"debug,omitempty" env:"DATABASE_DEBUG"`
// Mock mode, if true, use mock database for testing, default false
Mock bool `yaml:"mock,omitempty" json:"mock,omitempty" env:"DATABASE_MOCK"`
// Database address
// sqlite: full filepath, default exec path
// mysql: database address, default 127.0.0.1
// postgres: database address, default 127.0.0.1
// clickhouse: database address, default 127.0.0.1
// tidb: database address, default 127.0.0.1
// gaussdb: database address, default 127.0.0.1
Address string `yaml:"address,omitempty" json:"address,omitempty" env:"DATABASE_ADDRESS"`
// Database port
// sqlite: empty
// mysql: database port, default 3306
// postgres: database port, default 5432
// clickhouse: database port, default 9000 (native) or 8123 (http)
// tidb: database port, default 4000
// gaussdb: database port, default 5432
Port int `yaml:"port,omitempty" json:"port,omitempty" env:"DATABASE_PORT"`
// Database name
// sqlite: database file name, default ice.db
// mysql: database name, default ice
// postgres: database name, default ice
// clickhouse: database name, default default
// tidb: database name, default ice
// gaussdb: database name, default ice
Name string `yaml:"name,omitempty" json:"name,omitempty" env:"DATABASE_NAME"`
// Database username
// sqlite: empty
// mysql: database username
// postgres: database username
// sqlserver: database username
Username string `yaml:"username,omitempty" json:"username,omitempty" env:"DATABASE_USERNAME"`
// Database password
// sqlite: not supported (use sqlite-cgo for encryption)
// sqlite-cgo: SQLCipher encryption key
// mysql: database password
// postgres: database password
// sqlserver: database password
Password string `yaml:"password,omitempty" json:"password,omitempty" env:"DATABASE_PASSWORD"`
MaxIdleConns int `yaml:"max_idle_conns,omitempty" json:"max_idle_conns,omitempty" env:"DATABASE_MAX_IDLE_CONNS"` // 最大空闲连接数,-1 表示不限制
MaxOpenConns int `yaml:"max_open_conns,omitempty" json:"max_open_conns,omitempty" env:"DATABASE_MAX_OPEN_CONNS"` // 最大连接数,-1 表示不限制
// ConnMaxLifetime is the maximum connection lifetime.
// Default: 1 hour (avoid long-lived connection issues)
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime,omitempty" json:"conn_max_lifetime,omitempty" env:"DATABASE_CONN_MAX_LIFETIME"`
// ConnMaxIdleTime is the maximum idle time for connections.
// Default: 10 minutes (release idle connections promptly)
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time,omitempty" json:"conn_max_idle_time,omitempty" env:"DATABASE_CONN_MAX_IDLE_TIME"`
// ConnectTimeout is the MySQL/TiDB connection timeout.
// Default: 5 seconds
ConnectTimeout time.Duration `yaml:"connect_timeout,omitempty" json:"connect_timeout,omitempty" env:"DATABASE_CONNECT_TIMEOUT"`
// ReadTimeout is the MySQL/TiDB read timeout.
// Default: 30 seconds
ReadTimeout time.Duration `yaml:"read_timeout,omitempty" json:"read_timeout,omitempty" env:"DATABASE_READ_TIMEOUT"`
// WriteTimeout is the MySQL/TiDB write timeout.
// Default: 30 seconds
WriteTimeout time.Duration `yaml:"write_timeout,omitempty" json:"write_timeout,omitempty" env:"DATABASE_WRITE_TIMEOUT"`
Extras map[string]string `yaml:"extras,omitempty" json:"extras,omitempty" env:"DATABASE_EXTRAS"`
Logger Logger `json:"-" yaml:"-"`
}
type CreateIfNotExistsResult ¶
type CreateInBatchesResult ¶
type CreateNotExistResult ¶
type CreateOrUpdateResult ¶
type CreateResult ¶
type DeleteResult ¶
type ExpectedBegin ¶
type ExpectedBegin struct {
// contains filtered or unexported fields
}
ExpectedBegin wraps sqlmock.ExpectedBegin
func (*ExpectedBegin) WillReturnError ¶
func (e *ExpectedBegin) WillReturnError(err error) *ExpectedBegin
type ExpectedClose ¶
type ExpectedClose struct {
// contains filtered or unexported fields
}
ExpectedClose wraps sqlmock.ExpectedClose
func (*ExpectedClose) WillReturnError ¶
func (e *ExpectedClose) WillReturnError(err error) *ExpectedClose
type ExpectedCommit ¶
type ExpectedCommit struct {
// contains filtered or unexported fields
}
ExpectedCommit wraps sqlmock.ExpectedCommit
func (*ExpectedCommit) WillReturnError ¶
func (e *ExpectedCommit) WillReturnError(err error) *ExpectedCommit
type ExpectedExec ¶
type ExpectedExec struct {
// contains filtered or unexported fields
}
ExpectedExec wraps sqlmock.ExpectedExec
func (*ExpectedExec) WillReturnError ¶
func (e *ExpectedExec) WillReturnError(err error) *ExpectedExec
func (*ExpectedExec) WillReturnResult ¶
func (e *ExpectedExec) WillReturnResult(result sql.Result) *ExpectedExec
func (*ExpectedExec) WithArgs ¶
func (e *ExpectedExec) WithArgs(args ...interface{}) *ExpectedExec
type ExpectedQuery ¶
type ExpectedQuery struct {
// contains filtered or unexported fields
}
ExpectedQuery wraps sqlmock.ExpectedQuery
func (*ExpectedQuery) WillReturnError ¶
func (e *ExpectedQuery) WillReturnError(err error) *ExpectedQuery
func (*ExpectedQuery) WillReturnRows ¶
func (e *ExpectedQuery) WillReturnRows(rows *sqlmock.Rows) *ExpectedQuery
func (*ExpectedQuery) WithArgs ¶
func (e *ExpectedQuery) WithArgs(args ...interface{}) *ExpectedQuery
type ExpectedRollback ¶
type ExpectedRollback struct {
// contains filtered or unexported fields
}
ExpectedRollback wraps sqlmock.ExpectedRollback
func (*ExpectedRollback) WillReturnError ¶
func (e *ExpectedRollback) WillReturnError(err error) *ExpectedRollback
type FindResult ¶
type FirstOrCreateResult ¶
type FirstResult ¶
type FirstResult struct {
Error error
}
type IniSerializer ¶
type IniSerializer struct {
}
IniSerializer INI 序列化器
type Logger ¶
type Logger interface {
gormLog.Interface
Log(skip int, begin time.Time, fc func() (sql string, rowsAffected int64), err error)
}
func GetDefaultLogger ¶
func GetDefaultLogger() Logger
type MockDB ¶
MockDB represents a mock database connection with sqlmock
func (*MockDB) ExpectationsWereMet ¶
ExpectationsWereMet checks if all expectations were met
type Model ¶
type Model[M any] struct { // contains filtered or unexported fields }
func (*Model[M]) IsDuplicatedKeyError ¶
func (*Model[M]) IsNotFound ¶
func (*Model[M]) NewScoop ¶
func (p *Model[M]) NewScoop(tx ...*Scoop) *ModelScoop[M]
func (*Model[M]) SetDuplicatedKeyError ¶
func (*Model[M]) SetNotFound ¶
type ModelScoop ¶
func NewModelScoop ¶
func NewModelScoop[M any](db *gorm.DB, clientType string) *ModelScoop[M]
func (*ModelScoop[M]) Asc ¶
func (p *ModelScoop[M]) Asc(fields ...string) *ModelScoop[M]
func (*ModelScoop[M]) Between ¶
func (p *ModelScoop[M]) Between(column string, min, max interface{}) *ModelScoop[M]
func (*ModelScoop[M]) Chunk ¶
func (p *ModelScoop[M]) Chunk(size uint64, fc func(tx *Scoop, out []*M, offset uint64) error) *ChunkResult
func (*ModelScoop[M]) Create ¶
func (p *ModelScoop[M]) Create(m *M) error
func (*ModelScoop[M]) CreateIfNotExists ¶
func (p *ModelScoop[M]) CreateIfNotExists(m *M) *CreateIfNotExistsResult
func (*ModelScoop[M]) CreateInBatches ¶
func (p *ModelScoop[M]) CreateInBatches(values []*M, batchSize int) *CreateInBatchesResult
func (*ModelScoop[M]) CreateNotExist ¶
func (p *ModelScoop[M]) CreateNotExist(m *M) *CreateNotExistResult[M]
CreateNotExist is an alias for FirstOrCreate for backward compatibility. It performs the same operation: finds a record, returns it if found, creates it if not. Deprecated: Use FirstOrCreate instead, which provides the same functionality.
func (*ModelScoop[M]) CreateOrUpdate ¶
func (p *ModelScoop[M]) CreateOrUpdate(values map[string]interface{}, m *M) *CreateOrUpdateResult[M]
func (*ModelScoop[M]) Desc ¶
func (p *ModelScoop[M]) Desc(fields ...string) *ModelScoop[M]
func (*ModelScoop[M]) Equal ¶
func (p *ModelScoop[M]) Equal(column string, value interface{}) *ModelScoop[M]
func (*ModelScoop[M]) Find ¶
func (p *ModelScoop[M]) Find() ([]*M, error)
func (*ModelScoop[M]) FindByPage ¶
func (p *ModelScoop[M]) FindByPage(opt *core.ListOption) (page *core.Paginate, values []*M, err error)
func (*ModelScoop[M]) First ¶
func (p *ModelScoop[M]) First() (*M, error)
func (*ModelScoop[M]) FirstOrCreate ¶
func (p *ModelScoop[M]) FirstOrCreate(m *M) *FirstOrCreateResult[M]
func (*ModelScoop[M]) Group ¶
func (p *ModelScoop[M]) Group(fields ...string) *ModelScoop[M]
func (*ModelScoop[M]) Ignore ¶
func (p *ModelScoop[M]) Ignore(b ...bool) *ModelScoop[M]
func (*ModelScoop[M]) In ¶
func (p *ModelScoop[M]) In(column string, values interface{}) *ModelScoop[M]
func (*ModelScoop[M]) LeftLike ¶
func (p *ModelScoop[M]) LeftLike(column string, value string) *ModelScoop[M]
func (*ModelScoop[M]) Like ¶
func (p *ModelScoop[M]) Like(column string, value string) *ModelScoop[M]
func (*ModelScoop[M]) Limit ¶
func (p *ModelScoop[M]) Limit(limit uint64) *ModelScoop[M]
func (*ModelScoop[M]) NotBetween ¶
func (p *ModelScoop[M]) NotBetween(column string, min, max interface{}) *ModelScoop[M]
func (*ModelScoop[M]) NotEqual ¶
func (p *ModelScoop[M]) NotEqual(column string, value interface{}) *ModelScoop[M]
func (*ModelScoop[M]) NotIn ¶
func (p *ModelScoop[M]) NotIn(column string, values interface{}) *ModelScoop[M]
func (*ModelScoop[M]) NotLeftLike ¶
func (p *ModelScoop[M]) NotLeftLike(column string, value string) *ModelScoop[M]
func (*ModelScoop[M]) NotLike ¶
func (p *ModelScoop[M]) NotLike(column string, value string) *ModelScoop[M]
func (*ModelScoop[M]) NotRightLike ¶
func (p *ModelScoop[M]) NotRightLike(column string, value string) *ModelScoop[M]
func (*ModelScoop[M]) Offset ¶
func (p *ModelScoop[M]) Offset(offset uint64) *ModelScoop[M]
func (*ModelScoop[M]) Or ¶
func (p *ModelScoop[M]) Or(args ...interface{}) *ModelScoop[M]
func (*ModelScoop[M]) Order ¶
func (p *ModelScoop[M]) Order(fields ...string) *ModelScoop[M]
func (*ModelScoop[M]) RightLike ¶
func (p *ModelScoop[M]) RightLike(column string, value string) *ModelScoop[M]
func (*ModelScoop[M]) Scan ¶
func (p *ModelScoop[M]) Scan(dest interface{}) *ScanResult
Scan executes the query and scans the result into dest. The dest parameter can be:
- A pointer to a basic type (int, string, etc.) for single value queries
- A pointer to a slice for multiple values
- A pointer to M or []*M for model queries
Returns ScanResult containing any error that occurred.
Example:
var count int64
result := scoop.Select("COUNT(*)").Where("age > ?", 18).Scan(&count)
var ids []uint64
result := scoop.Select("id").Where("status = ?", "active").Scan(&ids)
func (*ModelScoop[M]) Select ¶
func (p *ModelScoop[M]) Select(fields ...string) *ModelScoop[M]
func (*ModelScoop[M]) Unscoped ¶
func (p *ModelScoop[M]) Unscoped(b ...bool) *ModelScoop[M]
func (*ModelScoop[M]) UpdateOrCreate ¶
func (p *ModelScoop[M]) UpdateOrCreate(values map[string]interface{}, m *M) *UpdateOrCreateResult[M]
UpdateOrCreate is an alias for CreateOrUpdate for backward compatibility. It performs the same operation: finds a record, updates it if found, creates it if not. Deprecated: Use CreateOrUpdate instead, which provides more detailed status information.
func (*ModelScoop[M]) Where ¶
func (p *ModelScoop[M]) Where(args ...interface{}) *ModelScoop[M]
type ProtojsonSerializer ¶
type ProtojsonSerializer struct {
}
ProtojsonSerializer Protobuf JSON 序列化器,使用 protojson 处理 protobuf 消息(包括 oneof 字段)
type SQLOperationType ¶
type SQLOperationType string
SQLOperationType represents the type of SQL operation
const ( SQLOperationSelect SQLOperationType = "SELECT" SQLOperationInsert SQLOperationType = "INSERT" SQLOperationUpdate SQLOperationType = "UPDATE" SQLOperationDelete SQLOperationType = "DELETE" )
type ScanResult ¶
type Scoop ¶
type Scoop struct {
// contains filtered or unexported fields
}
func (*Scoop) AutoMigrate ¶
func (*Scoop) CommitOrRollback ¶
func (*Scoop) Count ¶
Count returns the number of rows matching the query conditions. Respects WHERE clauses and soft delete (DeletedAt) filtering. Returns the count and any error that occurred.
Example:
count, err := scoop.Table("users").Where("age > ?", 18).Count()
func (*Scoop) Create ¶
func (p *Scoop) Create(value interface{}) *CreateResult
Create inserts a single record into the database using raw SQL. The value parameter must be a pointer to a struct. Auto-increment primary keys and timestamp fields are handled automatically. Supports soft delete by inserting 0 for nil DeletedAt fields. Returns CreateResult with LastInsertId and RowsAffected.
Example:
user := &User{Name: "John", Age: 30}
result := scoop.Table("users").Create(user)
func (*Scoop) CreateInBatches ¶
func (p *Scoop) CreateInBatches(value interface{}, batchSize int) *CreateInBatchesResult
CreateInBatches inserts multiple records in batches using raw SQL. The value parameter must be a slice of structs or pointers to structs. Records are inserted in batches of the specified batchSize to optimize performance. Auto-increment primary keys and timestamp fields are handled automatically. Returns CreateInBatchesResult with total RowsAffected across all batches.
Example:
users := []User{{Name: "Alice"}, {Name: "Bob"}, {Name: "Charlie"}}
result := scoop.Table("users").CreateInBatches(users, 100)
func (*Scoop) CrossJoin ¶
CrossJoin adds a CROSS JOIN clause to the query Example: CrossJoin("orders")
func (*Scoop) Delete ¶
func (p *Scoop) Delete() *DeleteResult
Delete performs a soft or hard delete on matching rows. If the table has a DeletedAt field, performs soft delete by setting timestamp. Otherwise performs hard delete by removing rows from the database. Use Unscoped() to force hard delete even with DeletedAt field. Returns DeleteResult with RowsAffected count.
Example:
// Soft delete
result := scoop.Table("users").Where("id = ?", 1).Delete()
// Hard delete
result := scoop.Table("users").Unscoped().Where("id = ?", 1).Delete()
func (*Scoop) Find ¶
func (p *Scoop) Find(out interface{}) *FindResult
Find executes a SELECT query and scans all matching rows into out. The out parameter must be a pointer to a slice of structs. Returns FindResult containing any error that occurred.
Example:
var users []User
result := scoop.Where("age > ?", 18).Find(&users)
func (*Scoop) FindByPage ¶
func (*Scoop) First ¶
func (p *Scoop) First(out interface{}) *FirstResult
First executes a SELECT query with LIMIT 1 and scans the first row into out. The out parameter must be a pointer to a struct. Returns FirstResult with Error set to ErrRecordNotFound if no row is found.
Example:
var user User
result := scoop.Table("users").Where("id = ?", 1).First(&user)
func (*Scoop) FullJoin ¶
FullJoin adds a FULL OUTER JOIN clause to the query Example: FullJoin("orders", "users.id = orders.user_id")
func (*Scoop) Having ¶
Having adds a HAVING clause to the query (used with GROUP BY) Example: Having("COUNT(*) > ?", 5)
func (*Scoop) InnerJoin ¶
InnerJoin adds an INNER JOIN clause to the query Example: InnerJoin("orders", "users.id = orders.user_id")
func (*Scoop) IsDuplicatedKeyError ¶
func (*Scoop) IsNotFound ¶
func (*Scoop) Join ¶
Join adds a JOIN clause to the query Example: Join("INNER", "orders", "users.id = orders.user_id")
func (*Scoop) LeftJoin ¶
LeftJoin adds a LEFT JOIN clause to the query Example: LeftJoin("orders", "users.id = orders.user_id")
func (*Scoop) NotBetween ¶
func (*Scoop) RightJoin ¶
RightJoin adds a RIGHT JOIN clause to the query Example: RightJoin("orders", "users.id = orders.user_id")
func (*Scoop) Scan ¶
func (p *Scoop) Scan(dest interface{}) *ScanResult
Scan executes the query and scans the result into dest. The dest parameter can be:
- A pointer to a basic type (int, string, etc.) for single value queries
- A pointer to a slice for multiple values
- A pointer to a struct for single row queries
- A pointer to a slice of structs for multiple rows
Returns ScanResult containing any error that occurred.
Example:
var count int64
result := scoop.Table("users").Select("COUNT(*)").Where("age > ?", 18).Scan(&count)
var names []string
result := scoop.Table("users").Select("name").Where("age > ?", 18).Scan(&names)
func (*Scoop) ToSQL ¶
func (p *Scoop) ToSQL(operation SQLOperationType, value ...interface{}) string
ToSQL returns the generated SQL query string for debugging/testing purposes operation: the type of SQL operation (SELECT, INSERT, UPDATE, DELETE) value: optional value parameter (required for INSERT and UPDATE operations) This method is primarily for testing and should not be used in production code
func (*Scoop) Updates ¶
func (p *Scoop) Updates(m interface{}, args ...interface{}) *UpdateResult
Updates performs an UPDATE operation on matching rows. The parameters can be:
- map[string]interface{}: key-value pairs for update (order not preserved)
- struct: non-zero fields are updated (order not preserved)
- variadic args: key, value, key, value, ... pairs (order preserved)
- argument count must be even
- keys at even positions must be strings
- values at odd positions can be any type
Only non-zero fields are updated for structs. Use clause.Expr for SQL expressions. Automatically updates UpdatedAt field if present. Returns UpdateResult with RowsAffected count.
Example:
// Using map (order not preserved)
result := scoop.Table("users").Where("id = ?", 1).Updates(map[string]interface{}{"age": 25, "name": "John"})
// Using struct (order not preserved)
result := scoop.Table("users").Where("id = ?", 1).Updates(&User{Age: 25})
// Using variadic args (order preserved)
result := scoop.Table("users").Where("id = ?", 1).Updates("name", "John", "age", 25)
type TestProfile ¶
type TestProfile struct {
Id int64 `gorm:"primaryKey;autoIncrement"`
UserId int64 `gorm:"index"`
Bio string `gorm:"type:text"`
Website string `gorm:"size:255"`
}
TestProfile model for testing relationships
func (TestProfile) TableName ¶
func (TestProfile) TableName() string
TableName returns the table name for TestProfile
type TestUser ¶
type TestUser struct {
Id int64 `gorm:"primaryKey;autoIncrement"`
Name string `gorm:"size:100;not null"`
Email string `gorm:"size:100;unique"`
Age int `gorm:"default:0"`
CreatedAt int64 `gorm:"autoCreateTime"`
UpdatedAt int64 `gorm:"autoUpdateTime"`
DeletedAt int64 `gorm:"index;default:0"`
}
TestUser model for testing database operations This model is used by both db and db_test packages
type TomlSerializer ¶
type TomlSerializer struct {
}
TomlSerializer TOML 序列化器
type UpdateOrCreateResult ¶
type UpdateResult ¶
type YamlSerializer ¶
type YamlSerializer struct {
}
YamlSerializer YAML 序列化器
Source Files
¶
- client.go
- client_init.go
- client_migration.go
- cond.go
- config.go
- expr.go
- field_utils.go
- log.go
- mock.go
- model.go
- model_scoop.go
- model_scoop_condition.go
- model_scoop_create.go
- model_scoop_query.go
- model_scoop_update.go
- reserved_keywords.go
- scoop.go
- scoop_condition.go
- scoop_create.go
- scoop_create_batch.go
- scoop_delete.go
- scoop_gorm.go
- scoop_insert.go
- scoop_query.go
- scoop_sql.go
- scoop_transaction.go
- scoop_update.go
- serializer.go
- sqlite_cgo.go
- statement_cache.go
- sub_cond.go
- test_models.go
- update.go
- utils.go