orm

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 17 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRecordNotFound = gorm.ErrRecordNotFound
	ErrDuplicatedKey  = gorm.ErrDuplicatedKey
)
View Source
var EnabledAutoMigrate bool

Deprecated: 请使用 GetEnabledAutoMigrate / SetEnabledAutoMigrate

Functions

func CountWithContext added in v1.3.16

func CountWithContext[T any](ctx context.Context, db *gorm.DB, opts ...QueryOption) (int64, error)

CountWithContext 通用计数查询

func Delete deprecated

func Delete(db *gorm.DB, model any, opts ...QueryOption) error

Deprecated: 请使用 Store 内部直接 db.Clauses(clause.Returning{}).Delete(model)

func DeleteWithContext deprecated

func DeleteWithContext(ctx context.Context, db *gorm.DB, model any, opts ...QueryOption) error

Deprecated: 请使用 Store 内部直接 db.Clauses(clause.Returning{}).Delete(model)

func Find deprecated

func Find[T any](db *gorm.DB, out *[]*T, p Pager, opts ...QueryOption) (int64, error)

Deprecated: 请使用 ListWithContext

func FindWithContext deprecated

func FindWithContext[T any](ctx context.Context, db *gorm.DB, out *[]*T, p Pager, opts ...QueryOption) (int64, error)

Deprecated: 请使用 ListWithContext

func First deprecated

func First(db *gorm.DB, out any, opts ...QueryOption) error

Deprecated: 请使用 Store 内部直接 db.WithContext(ctx).Take(model)

func FirstWithContext

func FirstWithContext(ctx context.Context, db *gorm.DB, out any, opts ...QueryOption) error

FirstWithContext 按条件查询单条记录(内部使用 Take 避免额外排序)

func GenerateRandomString

func GenerateRandomString(length int) string

func GetEnabledAutoMigrate added in v1.3.1

func GetEnabledAutoMigrate() bool

func GormDB added in v1.7.10

func GormDB(tx Tx) *gorm.DB

GormDB 从 Tx 中提取底层 *gorm.DB,仅供 Store 层实现使用。

func IsDuplicatedKey

func IsDuplicatedKey(err error) bool

func IsErrRecordNotFound

func IsErrRecordNotFound(err error) bool

func JSONUnmarshal added in v1.2.12

func JSONUnmarshal(input, obj any) error

JSONUnmarshal 将 input 反序列化到 obj 上

func List deprecated added in v1.7.0

func List[T any](db *gorm.DB, out *[]*T, p Pager, opts ...QueryOption) (int64, error)

Deprecated: 请在 Store 内直接实现分页查询逻辑

func ListWithContext deprecated added in v1.7.0

func ListWithContext[T any](ctx context.Context, db *gorm.DB, out *[]*T, p Pager, opts ...QueryOption) (int64, error)

Deprecated: 请在 Store 内直接实现分页查询逻辑

func New

func New(dialector gorm.Dialector, cfg Config, opts ...GormOption) (*gorm.DB, error)

New ... 默认采用 slog.Default() 记录日志,如果日志是 debug 级别会输出所有 sql warn 级别用于记录慢 sql

func ParseTimeToLayout

func ParseTimeToLayout(value string) string

ParseTimeToLayout 解析字符串对应的 layout 仅支持 年-月-日 或 年/月/日 等这种格式

func SetEnabledAutoMigrate added in v1.3.1

func SetEnabledAutoMigrate(v bool)

func Transaction added in v1.7.10

func Transaction(db *gorm.DB, fn func(Tx) error) error

Transaction 便捷方法:开启事务,执行 fn,自动 Commit/Rollback。

func Update deprecated

func Update[T any](db *gorm.DB, model *T, changeFn func(*T), opts ...QueryOption) error

Deprecated: changeFn 应返回 error,请使用 Store 内部 Transaction + Take + Save

func UpdateWithContext deprecated

func UpdateWithContext[T any](ctx context.Context, db *gorm.DB, model *T, changeFn func(*T), opts ...QueryOption) error

Deprecated: changeFn 应返回 error,请使用 UpdateWithContext2

func UpdateWithContext2 added in v1.3.0

func UpdateWithContext2[T any](ctx context.Context, db *gorm.DB, model *T, changeFn func(*T) error, opts ...QueryOption) error

UpdateWithContext2 事务内悲观锁更新(SELECT FOR UPDATE + Save),changeFn 可返回 error 中止事务

func UpdateWithSession deprecated

func UpdateWithSession[T any](tx *gorm.DB, model *T, fn func(*T) error, opts ...QueryOption) error

Deprecated: 请使用 WithTx 模式替代 Session

Types

type Config

type Config struct {
	MaxIdleConns    int
	MaxOpenConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
	SlowThreshold   time.Duration
}

type DeletedAt

type DeletedAt = gorm.DeletedAt

type DeletedModel

type DeletedModel struct {
	Model
	DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"-"`
}

DeletedModel 删除模型

func (*DeletedModel) BeforeCreate

func (d *DeletedModel) BeforeCreate(*gorm.DB) error

func (*DeletedModel) BeforeUpdate

func (d *DeletedModel) BeforeUpdate(*gorm.DB) error

type Engine deprecated

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

Deprecated: 请使用 godddx 生成的 Store 实现

func NewEngine deprecated

func NewEngine(db *gorm.DB) Engine

Deprecated: 请使用 godddx 生成的 Store 实现

func (Engine) DeleteOne deprecated

func (e Engine) DeleteOne(model Tabler, opts ...Option) error

Deprecated: 请使用 godddx 生成的 Store 实现

func (Engine) Find deprecated

func (e Engine) Find(model Tabler, bean any, opts ...Option) (total int64, err error)

Deprecated: 请使用 godddx 生成的 Store 实现

func (Engine) FirstOrCreate deprecated

func (e Engine) FirstOrCreate(b any) (bool, error)

Deprecated: 请使用 godddx 生成的 Store 实现

func (Engine) InsertOne deprecated

func (e Engine) InsertOne(model Tabler) error

Deprecated: 请使用 godddx 生成的 Store 实现

func (Engine) NextSeq deprecated

func (e Engine) NextSeq(model Tabler) (nextID int, err error)

Deprecated: 请使用 godddx 生成的 Store 实现

func (Engine) UpdateOne deprecated

func (e Engine) UpdateOne(model Tabler, id int, data map[string]any) error

Deprecated: 请使用 godddx 生成的 Store 实现

type GormOption added in v1.5.0

type GormOption func(*gorm.Config)

func WithGormLogger added in v1.5.0

func WithGormLogger(l *slog.Logger, slow time.Duration) GormOption

WithGormLogger 如果需要自定义 logger 的创建,仅供参考

type JSONValueScanner added in v1.4.0

type JSONValueScanner interface {
	sql.Scanner
	driver.Valuer
}

JSONValueScanner 数据库类型定义为 json 的结构体应当实现此接口

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(l *slog.Logger, slow time.Duration) *Logger

NewLogger 封装日志 如果需要记录全部日志,开启 slog 的 debug 日志级别即可 建议 logLevel 用

func (*Logger) Error added in v1.5.0

func (l *Logger) Error(ctx context.Context, msg string, args ...any)

Error implements logger.Interface. Subtle: this method shadows the method (*Logger).Error of Logger.Logger.

func (*Logger) Info added in v1.5.0

func (l *Logger) Info(ctx context.Context, msg string, args ...any)

Info implements logger.Interface. Subtle: this method shadows the method (*Logger).Info of Logger.Logger.

func (*Logger) LogMode added in v1.5.0

func (l *Logger) LogMode(level logger.LogLevel) logger.Interface

LogMode implements logger.Interface.

func (*Logger) SetLevel added in v1.5.0

func (l *Logger) SetLevel(level slog.Level)

func (*Logger) Trace added in v1.5.0

func (l *Logger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

Trace implements logger.Interface.

func (*Logger) Warn added in v1.5.0

func (l *Logger) Warn(ctx context.Context, msg string, args ...any)

Warn implements logger.Interface. Subtle: this method shadows the method (*Logger).Warn of Logger.Logger.

type Map added in v1.5.2

type Map map[string]any

Map 因值是 any 类型,封装一些快速提取的函数

func (Map) Delete added in v1.5.2

func (i Map) Delete(key string) Map

Delete 删除指定 key

func (Map) Get added in v1.5.2

func (i Map) Get(key string) any

Get 获取指定 key 的值

func (Map) GetBool added in v1.5.2

func (i Map) GetBool(key string) bool

GetBool 获取指定 key 的布尔值

func (Map) GetInt added in v1.5.2

func (i Map) GetInt(key string) int

GetInt 获取指定 key 的整数值

func (Map) GetString added in v1.5.2

func (i Map) GetString(key string) string

GetString 获取指定 key 的字符串值

func (Map) Has added in v1.5.2

func (i Map) Has(key string) bool

Has 判断是否存在指定 key

func (Map) Merge added in v1.5.2

func (i Map) Merge(other Map) Map

Merge 合并另一个 Map,相同 key 会被覆盖

func (*Map) Scan added in v1.5.2

func (i *Map) Scan(input any) error

func (Map) Set added in v1.5.2

func (i Map) Set(key string, value any) Map

Set 设置指定 key 的值

func (*Map) UnmarshalJSON added in v1.5.2

func (i *Map) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (Map) Value added in v1.5.2

func (i Map) Value() (driver.Value, error)

type Model

type Model struct {
	ID        int  `gorm:"primaryKey;" json:"id"`
	CreatedAt Time `gorm:"notNull;default:CURRENT_TIMESTAMP;index;comment:创建时间" json:"created_at"`
	UpdatedAt Time `gorm:"notNull;default:CURRENT_TIMESTAMP;comment:更新时间" json:"updated_at"`
}

Model int id 模型 sqlite 不支持 default:now(),支持 CURRENT_TIMESTAMP

func (*Model) BeforeCreate

func (d *Model) BeforeCreate(*gorm.DB) error

func (*Model) BeforeUpdate

func (d *Model) BeforeUpdate(*gorm.DB) error

type ModelWithStrID

type ModelWithStrID struct {
	ID        string `gorm:"primaryKey;" json:"id"`
	CreatedAt Time   `gorm:"notNull;default:CURRENT_TIMESTAMP;index;comment:创建时间" json:"created_at"`
	UpdatedAt Time   `gorm:"notNull;default:CURRENT_TIMESTAMP;comment:更新时间" json:"updated_at"`
}

ModelWithStrID string id 模型

func NewModelWithStrID

func NewModelWithStrID(id string) ModelWithStrID

NewModelWithStrID 新建模型

func (*ModelWithStrID) BeforeCreate

func (d *ModelWithStrID) BeforeCreate(*gorm.DB) error

func (*ModelWithStrID) BeforeUpdate

func (d *ModelWithStrID) BeforeUpdate(*gorm.DB) error

type Option deprecated

type Option func(*gorm.DB)

Deprecated: 请使用 QueryOption func(*gorm.DB) *gorm.DB(返回新 DB 实例的正确链式语义)

func WithCreatedAt deprecated

func WithCreatedAt(startAt, endAt int64) Option

Deprecated: 请在 Store 内直接编写时间范围查询

func WithID deprecated

func WithID(id int) Option

Deprecated: 请使用 Store 直接 db.Where("id=?", id)

func WithLimit deprecated

func WithLimit(limit, offset int) Option

Deprecated: 请使用 Pager 接口

type Pager deprecated

type Pager interface {
	Limit() int
	Offset() int
}

Deprecated: 请在 Store 内直接实现分页查询逻辑

type Query

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

Query 链式查询条件构建器

func NewQuery

func NewQuery(l int) *Query

NewQuery 创建查询条件构建器

func (*Query) Encode

func (q *Query) Encode() []QueryOption

func (*Query) OrderBy

func (q *Query) OrderBy(value any) *Query

func (*Query) Select added in v1.7.6

func (q *Query) Select(columns any) *Query

func (*Query) Where

func (q *Query) Where(query any, args ...any) *Query

type QueryOption

type QueryOption func(*gorm.DB) *gorm.DB

QueryOption 查询选项函数

func OrderBy deprecated

func OrderBy(value any) QueryOption

Deprecated: 请使用 Query.OrderBy

func Select deprecated added in v1.7.6

func Select(columns any) QueryOption

Deprecated: 请使用 Query.Select

func Unscoped deprecated added in v1.5.4

func Unscoped() QueryOption

Deprecated: 请在 Store 直接调用 db.Unscoped()

func Where

func Where(query any, args ...any) QueryOption

Where 查询条件

type Scaner deprecated

type Scaner = sql.Scanner

Deprecated: 请使用 JSONValueScanner

type StructMap added in v1.7.5

type StructMap[T any] struct {
	Data T // 泛型数据
	Map    // 原始数据
}

StructMap 其目的是将已知的参数作为结构体调用,未知的参数不动 例如 s.Data.Username Example: type User = StructMap[UserInfo]

func (StructMap[T]) MarshalJSON added in v1.7.5

func (s StructMap[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*StructMap[T]) Scan added in v1.7.5

func (i *StructMap[T]) Scan(input any) error

func (*StructMap[T]) UnmarshalJSON added in v1.7.5

func (s *StructMap[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (StructMap[T]) Value added in v1.7.5

func (i StructMap[T]) Value() (driver.Value, error)

type Tabler

type Tabler interface {
	TableName() string
}

Tabler 模型需要用指针接收器实现接口

type Time

type Time struct {
	time.Time
}

func Now

func Now() Time

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

func (*Time) Scan

func (t *Time) Scan(input any) error

Scan implements scaner

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (Time) Value

func (t Time) Value() (driver.Value, error)

type Tx added in v1.7.10

type Tx interface {
	Commit() error
	Rollback() error
}

Tx 事务句柄,用于跨域事务协调。 Core 层只感知 Commit/Rollback 语义,不接触 gorm。

func Begin added in v1.7.10

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

Begin 开启一个事务,返回 Tx 句柄。

type Type deprecated

type Type[T any] struct {
	// contains filtered or unexported fields
}

Deprecated: 请使用 godddx 生成的 Store 实现

func NewType deprecated added in v1.3.0

func NewType[T any](db *gorm.DB) Type[T]

Deprecated: 请使用 godddx 生成的 Store 实现

func (Type[T]) Add deprecated

func (t Type[T]) Add(ctx context.Context, model *T) error

Deprecated: 请使用 Store.Create

func (Type[T]) Create deprecated added in v1.7.0

func (t Type[T]) Create(ctx context.Context, model *T) error

Deprecated: 请使用 Store.Create

func (Type[T]) Del deprecated

func (t Type[T]) Del(ctx context.Context, model *T, opts ...QueryOption) error

Deprecated: 请使用 Store.Delete

func (Type[T]) Delete deprecated added in v1.7.0

func (t Type[T]) Delete(ctx context.Context, model *T, opts ...QueryOption) error

Deprecated: 请使用 Store.Delete

func (Type[T]) Edit deprecated

func (t Type[T]) Edit(ctx context.Context, model *T, changeFn func(*T) error, opts ...QueryOption) error

Deprecated: 请使用 Store.Update

func (Type[T]) Find deprecated

func (t Type[T]) Find(ctx context.Context, out *[]*T, p Pager, opts ...QueryOption) (int64, error)

Deprecated: 请使用 Store.List

func (Type[T]) Get deprecated

func (t Type[T]) Get(ctx context.Context, out *T, opts ...QueryOption) error

Deprecated: 请使用 Store.GetByID

func (Type[T]) List deprecated added in v1.7.0

func (t Type[T]) List(ctx context.Context, out *[]*T, p Pager, opts ...QueryOption) (int64, error)

Deprecated: 请使用 Store.List

func (Type[T]) Update deprecated added in v1.7.0

func (t Type[T]) Update(ctx context.Context, model *T, changeFn func(*T) error, opts ...QueryOption) error

Deprecated: 请使用 Store.Update

type Universal deprecated

type Universal[T any] interface {
	Get(context.Context, *T, ...QueryOption) error
	Edit(context.Context, *T, func(*T) error, ...QueryOption) error
	Del(context.Context, *T, ...QueryOption) error
	Add(context.Context, *T) error
	Find(context.Context, *[]*T, Pager, ...QueryOption) (int64, error)
	Delete(context.Context, *T, ...QueryOption) error
	Create(context.Context, *T) error
	List(context.Context, *[]*T, Pager, ...QueryOption) (int64, error)
	Update(context.Context, *T, func(*T) error, ...QueryOption) error
}

Deprecated: 请使用 godddx 生成代码,而非内嵌此接口

type UniversalSession deprecated

type UniversalSession[T any] interface {
	Session(ctx context.Context, changeFns ...func(*gorm.DB) error) error
	EditWithSession(tx *gorm.DB, model *T, changeFn func(*T) error, opts ...QueryOption) error
}

Deprecated: 请使用 WithTx 模式

Jump to

Keyboard shortcuts

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