db

package
v0.0.0-...-43a48ce Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: AGPL-3.0 Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Sqlite     = "sqlite"
	MySQL      = "mysql"
	Postgres   = "postgres"
	ClickHouse = "clickhouse"
	TiDB       = "tidb"
	GaussDB    = "gaussdb"
)

Variables

View Source
var ErrBatchesStop = errors.New("batches stop")

Functions

func Camel2UnderScore

func Camel2UnderScore(name string) string

func EnsureIsSliceOrArray

func EnsureIsSliceOrArray(obj interface{}) reflect.Value

func EscapeMysqlString

func EscapeMysqlString(sql string) string

func Expr

func Expr(expression string, args ...interface{}) clause.Expr

func ExprIf

func ExprIf(clientType, expr string, ok, nok interface{}) clause.Expr

func ExprInc

func ExprInc(clientType, field string) clause.Expr

func ExprIncBy

func ExprIncBy(clientType, field string, cnt int64) clause.Expr

func FormatSql

func FormatSql(sql string, values ...interface{}) string

func IsUniqueIndexConflictErr

func IsUniqueIndexConflictErr(err error) bool

func NewLogger

func NewLogger() *logger

func QuoteFieldName

func QuoteFieldName(name string, clientType string) string

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

func UpdateCase[M string | *Cond](caseMap map[M]any, def ...interface{}) clause.Expr

CASE WHEN (`a` = 1) THEN "1" WHEN (`b` = 2) THEN 2 ELSE 10 END

func UpdateCaseOneField

func UpdateCaseOneField(field string, caseMap map[any]any, def ...interface{}) clause.Expr

CASE `a` WHEN 1 THEN "1" WHEN 2 THEN 2 ELSE 10 END

Types

type BsonSerializer

type BsonSerializer struct {
}

BsonSerializer BSON 序列化器

func (*BsonSerializer) Scan

func (p *BsonSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

func (*BsonSerializer) Value

func (p *BsonSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

type ChunkResult

type ChunkResult struct {
	Error error
}

type Client

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

func New

func New(c *Config, tables ...interface{}) (*Client, error)

func (*Client) AutoMigrate

func (p *Client) AutoMigrate(table interface{}) (err error)

func (*Client) AutoMigrates

func (p *Client) AutoMigrates(dst ...interface{}) (err error)

func (*Client) Close

func (p *Client) Close() error

func (*Client) Database

func (p *Client) Database() *gorm.DB

func (*Client) DriverType

func (p *Client) DriverType() string

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

func (p *Client) ExpectationsWereMet() error

ExpectationsWereMet checks if all mock expectations were met This should be called at the end of each test to ensure all expectations were satisfied

func (*Client) MockDB

func (p *Client) MockDB() *MockDB

MockDB returns the underlying MockDB for mock configuration This provides direct access to the MockDB for advanced mock configurations

func (*Client) NewScoop

func (p *Client) NewScoop() *Scoop

func (*Client) Ping

func (p *Client) Ping() error

func (*Client) SqlDB

func (p *Client) SqlDB() (*sql.DB, error)

type Cond

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

func Between

func Between(column string, min, max interface{}) *Cond

Between creates a new Cond with BETWEEN condition

func LeftLike

func LeftLike(column string, value string) *Cond

LeftLike creates a new Cond with LEFT LIKE condition (value%)

func Like

func Like(column string, value string) *Cond

Like creates a new Cond with LIKE condition

func NotBetween

func NotBetween(column string, min, max interface{}) *Cond

NotBetween creates a new Cond with NOT BETWEEN condition

func NotLeftLike

func NotLeftLike(column string, value string) *Cond

NotLeftLike creates a new Cond with NOT LEFT LIKE condition

func NotLike

func NotLike(column string, value string) *Cond

NotLike creates a new Cond with NOT LIKE condition

func NotRightLike

func NotRightLike(column string, value string) *Cond

NotRightLike creates a new Cond with NOT RIGHT LIKE condition

func Or

func Or(args ...interface{}) *Cond

Or is an alias for OrWhere

func OrWhere

func OrWhere(args ...interface{}) *Cond

OrWhere creates a new Cond with OR conditions

func RightLike

func RightLike(column string, value string) *Cond

RightLike creates a new Cond with RIGHT LIKE condition (%value)

func Where

func Where(args ...interface{}) *Cond

Where creates a new Cond with AND conditions

func (*Cond) Between

func (p *Cond) Between(column string, min, max interface{}) *Cond

func (*Cond) GoString

func (p *Cond) GoString() string

func (*Cond) LeftLike

func (p *Cond) LeftLike(column string, value string) *Cond

func (*Cond) Like

func (p *Cond) Like(column string, value string) *Cond

func (*Cond) NotBetween

func (p *Cond) NotBetween(column string, min, max interface{}) *Cond

func (*Cond) NotLeftLike

func (p *Cond) NotLeftLike(column string, value string) *Cond

func (*Cond) NotLike

func (p *Cond) NotLike(column string, value string) *Cond

func (*Cond) NotRightLike

func (p *Cond) NotRightLike(column string, value string) *Cond

func (*Cond) Or

func (p *Cond) Or(args ...interface{}) *Cond

func (*Cond) OrWhere

func (p *Cond) OrWhere(args ...interface{}) *Cond

func (*Cond) Reset

func (p *Cond) Reset() *Cond

Reset clears all conditions and resets the Cond to its initial state. This includes clearing conditions, resetting OR/AND mode, top-level flag, table prefix, and skip flag. Use this when you want to reuse a Cond object.

func (*Cond) RightLike

func (p *Cond) RightLike(column string, value string) *Cond

func (*Cond) String

func (p *Cond) String() string

func (*Cond) ToString

func (p *Cond) ToString() string

func (*Cond) Where

func (p *Cond) Where(args ...interface{}) *Cond

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:"-"`
}

func (*Config) DSN

func (c *Config) DSN() string

type CreateIfNotExistsResult

type CreateIfNotExistsResult struct {
	IsCreated bool
	Error     error
}

type CreateInBatchesResult

type CreateInBatchesResult struct {
	RowsAffected int64
	Error        error
}

type CreateNotExistResult

type CreateNotExistResult[M any] struct {
	IsCreated bool
	Error     error

	Object *M
}

type CreateOrUpdateResult

type CreateOrUpdateResult[M any] struct {
	Error  error
	Object *M

	Created bool
	Updated bool
}

type CreateResult

type CreateResult struct {
	RowsAffected int64
	Error        error
}

type DeleteResult

type DeleteResult struct {
	RowsAffected int64
	Error        error
}

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 FindResult struct {
	RowsAffected int64
	Error        error
}

type FirstOrCreateResult

type FirstOrCreateResult[M any] struct {
	IsCreated bool
	Error     error

	Object *M
}

type FirstResult

type FirstResult struct {
	Error error
}

type IniSerializer

type IniSerializer struct {
}

IniSerializer INI 序列化器

func (*IniSerializer) Scan

func (p *IniSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

func (*IniSerializer) Value

func (p *IniSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

type JsonSerializer

type JsonSerializer struct {
}

func (*JsonSerializer) Scan

func (p *JsonSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

func (*JsonSerializer) Value

func (p *JsonSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

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

type MockDB struct {
	DB    *gorm.DB
	Mock  sqlmock.Sqlmock
	SqlDB *sql.DB
}

MockDB represents a mock database connection with sqlmock

func (*MockDB) Close

func (m *MockDB) Close() error

Close closes the mock database connection

func (*MockDB) ExpectationsWereMet

func (m *MockDB) ExpectationsWereMet() error

ExpectationsWereMet checks if all expectations were met

type Model

type Model[M any] struct {
	// contains filtered or unexported fields
}

func NewModel

func NewModel[M any](db *Client) *Model[M]

func (*Model[M]) IsDuplicatedKeyError

func (p *Model[M]) IsDuplicatedKeyError(err error) bool

func (*Model[M]) IsNotFound

func (p *Model[M]) IsNotFound(err error) bool

func (*Model[M]) NewScoop

func (p *Model[M]) NewScoop(tx ...*Scoop) *ModelScoop[M]

func (*Model[M]) SetDuplicatedKeyError

func (p *Model[M]) SetDuplicatedKeyError(err error) *Model[M]

func (*Model[M]) SetNotFound

func (p *Model[M]) SetNotFound(err error) *Model[M]

func (*Model[M]) TableName

func (p *Model[M]) TableName() string

type ModelScoop

type ModelScoop[M any] struct {
	Scoop
	// contains filtered or unexported fields
}

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 字段)

func (*ProtojsonSerializer) Scan

func (p *ProtojsonSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

func (*ProtojsonSerializer) Value

func (p *ProtojsonSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

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 ScanResult struct {
	RowsAffected int64
	Error        error
}

type Scoop

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

func NewScoop

func NewScoop(db *gorm.DB, clientType string) *Scoop

func (*Scoop) AutoMigrate

func (p *Scoop) AutoMigrate(dst ...interface{}) error

func (*Scoop) Begin

func (p *Scoop) Begin() *Scoop

func (*Scoop) Between

func (p *Scoop) Between(column string, min, max interface{}) *Scoop

func (*Scoop) Chunk

func (p *Scoop) Chunk(dest interface{}, size uint64, fc func(tx *Scoop, offset uint64) error) *ChunkResult

func (*Scoop) Commit

func (p *Scoop) Commit() *Scoop

func (*Scoop) CommitOrRollback

func (p *Scoop) CommitOrRollback(tx *Scoop, logic func(tx *Scoop) error) error

func (*Scoop) Count

func (p *Scoop) Count() (uint64, error)

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

func (p *Scoop) CrossJoin(table string) *Scoop

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

func (p *Scoop) Equal(column string, value interface{}) *Scoop

func (*Scoop) Exist

func (p *Scoop) Exist() (bool, error)

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 (p *Scoop) FindByPage(opt *core.ListOption, values any) (*core.Paginate, error)

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

func (p *Scoop) FullJoin(table, condition string) *Scoop

FullJoin adds a FULL OUTER JOIN clause to the query Example: FullJoin("orders", "users.id = orders.user_id")

func (*Scoop) Group

func (p *Scoop) Group(fields ...string) *Scoop

func (*Scoop) Having

func (p *Scoop) Having(args ...interface{}) *Scoop

Having adds a HAVING clause to the query (used with GROUP BY) Example: Having("COUNT(*) > ?", 5)

func (*Scoop) Ignore

func (p *Scoop) Ignore(b ...bool) *Scoop

func (*Scoop) In

func (p *Scoop) In(column string, values interface{}) *Scoop

func (*Scoop) InnerJoin

func (p *Scoop) InnerJoin(table, condition string) *Scoop

InnerJoin adds an INNER JOIN clause to the query Example: InnerJoin("orders", "users.id = orders.user_id")

func (*Scoop) IsDuplicatedKeyError

func (p *Scoop) IsDuplicatedKeyError(err error) bool

func (*Scoop) IsNotFound

func (p *Scoop) IsNotFound(err error) bool

func (*Scoop) Join

func (p *Scoop) Join(joinType, table, condition string) *Scoop

Join adds a JOIN clause to the query Example: Join("INNER", "orders", "users.id = orders.user_id")

func (*Scoop) LeftJoin

func (p *Scoop) LeftJoin(table, condition string) *Scoop

LeftJoin adds a LEFT JOIN clause to the query Example: LeftJoin("orders", "users.id = orders.user_id")

func (*Scoop) LeftLike

func (p *Scoop) LeftLike(column string, value string) *Scoop

func (*Scoop) Like

func (p *Scoop) Like(column string, value string) *Scoop

func (*Scoop) Limit

func (p *Scoop) Limit(limit uint64) *Scoop

func (*Scoop) Model

func (p *Scoop) Model(m any) *Scoop

func (*Scoop) NotBetween

func (p *Scoop) NotBetween(column string, min, max interface{}) *Scoop

func (*Scoop) NotEqual

func (p *Scoop) NotEqual(column string, value interface{}) *Scoop

func (*Scoop) NotIn

func (p *Scoop) NotIn(column string, values interface{}) *Scoop

func (*Scoop) NotLeftLike

func (p *Scoop) NotLeftLike(column string, value string) *Scoop

func (*Scoop) NotLike

func (p *Scoop) NotLike(column string, value string) *Scoop

func (*Scoop) NotRightLike

func (p *Scoop) NotRightLike(column string, value string) *Scoop

func (*Scoop) Offset

func (p *Scoop) Offset(offset uint64) *Scoop

func (*Scoop) Order

func (p *Scoop) Order(fields ...string) *Scoop

func (*Scoop) RightJoin

func (p *Scoop) RightJoin(table, condition string) *Scoop

RightJoin adds a RIGHT JOIN clause to the query Example: RightJoin("orders", "users.id = orders.user_id")

func (*Scoop) RightLike

func (p *Scoop) RightLike(column string, value string) *Scoop

func (*Scoop) Rollback

func (p *Scoop) Rollback() *Scoop

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

func (p *Scoop) Select(fields ...string) *Scoop

func (*Scoop) Table

func (p *Scoop) Table(m string) *Scoop

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

func (p *Scoop) Unscoped(b ...bool) *Scoop

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)

func (*Scoop) Where

func (p *Scoop) Where(args ...interface{}) *Scoop

type Tabler

type Tabler interface {
	TableName() string
}

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

func (TestUser) TableName

func (TestUser) TableName() string

TableName returns the table name for TestUser

type TomlSerializer

type TomlSerializer struct {
}

TomlSerializer TOML 序列化器

func (*TomlSerializer) Scan

func (p *TomlSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

func (*TomlSerializer) Value

func (p *TomlSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

type UpdateOrCreateResult

type UpdateOrCreateResult[M any] struct {
	IsCreated bool
	Error     error

	Object *M
}

type UpdateResult

type UpdateResult struct {
	RowsAffected int64
	Error        error
}

type YamlSerializer

type YamlSerializer struct {
}

YamlSerializer YAML 序列化器

func (*YamlSerializer) Scan

func (p *YamlSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

func (*YamlSerializer) Value

func (p *YamlSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

Jump to

Keyboard shortcuts

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