orm

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 17 Imported by: 0

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 EnabledAutoMigrate 是否开启自动迁移 每次表迁移耗时,提供此全局变量,程序可根据需要是否迁移

Functions

func CountWithContext

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

func Delete

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

func DeleteWithContext

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

func Find deprecated

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

Deprecated: 请使用 List

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

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

func FirstWithContext

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

func GenerateRandomString

func GenerateRandomString(length int) string

func GetEnabledAutoMigrate

func GetEnabledAutoMigrate() bool

func IsDuplicatedKey

func IsDuplicatedKey(err error) bool

func IsErrRecordNotFound

func IsErrRecordNotFound(err error) bool

func JSONUnmarshal

func JSONUnmarshal(input, obj any) error

JSONUnmarshal 将 input 反序列化到 obj 上

func List

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

func ListWithContext

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

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

func SetEnabledAutoMigrate(v bool)

func Update

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

func UpdateWithContext

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

func UpdateWithContext2

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

func UpdateWithSession

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

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

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

func NewEngine

func NewEngine(db *gorm.DB) Engine

func (Engine) DeleteOne

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

func (Engine) Find

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

func (Engine) FirstOrCreate

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

FirstOrCreate true:创建;false:查询

func (Engine) InsertOne

func (e Engine) InsertOne(model Tabler) error

func (Engine) NextSeq

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

NextSeq 获取序列下一个值

func (Engine) UpdateOne

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

type GormOption

type GormOption func(*gorm.Config)

func WithGormLogger

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

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

type JSONValueScanner

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

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

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

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

LogMode implements logger.Interface.

func (*Logger) SetLevel

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

func (*Logger) Trace

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

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

type Map map[string]any

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

func (Map) Delete

func (i Map) Delete(key string) Map

Delete 删除指定 key

func (Map) Get

func (i Map) Get(key string) any

Get 获取指定 key 的值

func (Map) GetBool

func (i Map) GetBool(key string) bool

GetBool 获取指定 key 的布尔值

func (Map) GetInt

func (i Map) GetInt(key string) int

GetInt 获取指定 key 的整数值

func (Map) GetString

func (i Map) GetString(key string) string

GetString 获取指定 key 的字符串值

func (Map) Has

func (i Map) Has(key string) bool

Has 判断是否存在指定 key

func (Map) Merge

func (i Map) Merge(other Map) Map

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

func (*Map) Scan

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

func (Map) Set

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

Set 设置指定 key 的值

func (*Map) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (Map) Value

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

type Option func(*gorm.DB)

func WithCreatedAt

func WithCreatedAt(startAt, endAt int64) Option

func WithID

func WithID(id int) Option

WithID ...

func WithLimit

func WithLimit(limit, offset int) Option

type Pager

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

type Query

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

func NewQuery

func NewQuery(l int) *Query

func (*Query) Encode

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

func (*Query) OrderBy

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

func (*Query) Select

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

func OrderBy(value any) QueryOption

OrderBy 排序条件

func Select

func Select(columns any) QueryOption

Select 指定查询列

func Unscoped

func Unscoped() QueryOption

Unscoped 查询时忽略软删除

func Where

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

Where 查询条件

type Scaner deprecated

type Scaner sql.Scanner

Deprecated: 建议使用 JSONValueScanner Scaner 所有模型内组合的结构体,必须满足该接口

type StructMap

type StructMap[T any] struct {
	Data T
	Map
}

StructMap 其目的是将已知的参数作为结构体调用,未知的参数不动 例如 s.Data.Username

func (StructMap[T]) MarshalJSON

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

MarshalJSON implements json.Marshaler.

func (*StructMap[T]) Scan

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

func (*StructMap[T]) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (StructMap[T]) Value

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 Type

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

func NewType

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

func (Type[T]) Add deprecated

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

Deprecated: 请使用 Create

func (Type[T]) Create

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

func (Type[T]) Del deprecated

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

Deprecated: 请使用 Delete

func (Type[T]) Delete

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

Delete 通用删除

func (Type[T]) Edit deprecated

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

Deprecated: 请使用 Update

func (Type[T]) Find deprecated

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

Deprecated: 请使用 List

func (Type[T]) Get

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

First 通用查询

func (Type[T]) List

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

func (Type[T]) Update

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

Update 通用更新

type Universal

type Universal[T any] interface {
	Get(context.Context, *T, ...QueryOption) error
	// olw
	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)

	// new
	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
}

Universal 通用增删改查 Deprecated: 建议使用 milady 生成代码,而非内嵌此接口

type UniversalSession

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
}

UniversalSession 通用事务

Jump to

Keyboard shortcuts

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