torm

package module
v0.0.0-...-6596822 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ThinkORM

ThinkORM is a batteries-included ORM for Go — query builder, active-record style models, relations, schema builder and migrations.

Build Status Go Report Card GoDoc License

Features

  • Query Builder — full where family (nested / sub-query / JSON / fulltext / binary / row values), joins (incl. lateral & join-sub), unions, aggregates, group limit, in-order-of, index hints, locks & timeouts, CTE (WithExpression / WithRecursiveExpression), cursor pagination (boundary-aware), chunkByIdDesc / lazyByIdDesc
  • Multiple dialects — MySQL, MariaDB, Postgres, SQLite, SQL Server (identifier quoting, limit/offset rewrites, upsert, returning, ctid/rowid deletes, JSON compilation)
  • Active-record style Models — timestamps (customizable columns), soft deletes, dirty tracking, mass-assignment guards (Unguard/Reguard), casts (cast:datetime:<layout>), UUID/ULID keys, increment, events & observers, serialization (ToMap/ToJson with hidden/visible), Replicate, PG/SQLServer RETURNING-based id backfill
  • Relations — hasOne / hasMany / hasOneThrough / hasManyThrough / belongsTo / morphOne / morphMany / morphTo / belongsToMany / morphToMany with eager loading, WhereHas family, withCount aggregates (all relation shapes incl. pivot/through joins), pivot read (WithPivot + backfill into torm:"pivot:..." fields) & write side (incl. MorphToMany attach/detach/sync), relation-level soft-delete scopes, automatic parent touches
  • Connections — named connections, read/write splitting with sticky (optional time window), reconnect with lost-connection retry, query log & pretend, before/after hooks, pool tuning (MaxOpenConns/ConnMaxLifetimeSec...), pool-safe session config (MySQL connector wrapper / PG options=-c / SQLite DSN pragmas), SQLite foreign_keys default on, MySQL parseTime default injection
  • Transactions — nested savepoints, deadlock retry, AfterCommit / AfterRollBack hooks, transaction events, panic-safe rollback
  • Schema Builder & Migrations — full Blueprint (25+ column types, morphs, index kinds), per-dialect introspection, registered migrations with batching, step/batch/pretend, SQL-file LoadDir, Fresh, advisory locking (PG/MySQL), per-migration WithinTransaction
  • Error classification — deadlock / lost connection / unique constraint detection by driver error codes and messages

Requirements

  • Go 1.27+

Installation

go get github.com/go-think/torm

Testing

The test suite does not require a live database — an in-memory fake driver (internal/faketb) stubs SQL results, so everything passes offline:

go test -race ./...

CI runs build, vet and the full test suite on every push and pull request to master (see .github/workflows/build.yml).

Quick Start

config := torm.Config{
	Driver: "mysql",
	Dsn:    "root:abc-123@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=true",
}
db, _ := torm.Open(config)
Query Builder
type User struct {
	Name      string    `torm:"column:name"`
	Gender    string    `torm:"column:gender"`
	Addr      string
	BirthDate string
	Balance   float64
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (u *User) TableName() string { return "users" }

var users []User
db.Table("users").
	Where("gender", "M").
	Where("name", "like", "%a%").
	WhereColumn("created_at", "!=", "updated_at").
	WhereIn("addr", []interface{}{"Columbia", "Alaska"}).
	WhereBetween("birth_date", []interface{}{"1990-01-01", "1999-12-31"}).
	Get(&users)

Query Builder

Where family
db.Table("users").
	Where("name", "like", "%a%").
	WhereIn("id", []interface{}{1, 2, 3}).
	WhereNull("deleted_at").
	WhereBetween("age", []interface{}{18, 60}).
	WhereJSONContains("options", []interface{}{"beta"}).
	WhereExists(func(q *torm.Builder) *torm.Builder {
		return q.Select("1").From("orders").WhereColumn("orders.user_id", "=", "users.id")
	}).
	OrWhere("active", true).
	Get(&users)
Aggregates, pagination & cursor streaming
n, _ := db.Table("users").Where("active", true).Count()
maxAge, _ := db.Table("users").Max("age")

page, _ := db.Table("users").Paginate(&users, 1, 15) // *LengthAwarePaginator
cursor, _ := db.Table("users").Cursor()              // iter.Seq2[map[string]any, error]
for row, err := range cursor {
	_ = row
	_ = err
}
Joins, unions & group limit
db.Table("users").
	Join("orders", "orders.user_id", "=", "users.id").
	LeftJoinLateral(func(n *torm.Builder) *torm.Builder {
		return n.Select("top_1_order.*").From("orders").WhereColumn("orders.user_id", "=", "users.id")
	}, "top_1_order").
	Get(&rows)

db.Table("posts").GroupLimit(3, "created_at") // top-N per group

db.Table("users_a").Union(db.Table("users_b")).Get(&rows)
Insert / Upsert / Returning
db.Table("users").Insert(map[string]interface{}{"name": "A"})
db.Table("users").InsertOrIgnore([]interface{}{map[string]interface{}{"email": "a@x"}})
db.Table("users").Upsert([]interface{}{map[string]interface{}{"email": "a@x", "name": "A"}},
	[]string{"email"}, []string{"name"})

// Postgres / SQLite: insert ... on conflict do nothing returning ...
rows, _ := db.Table("users").InsertOrIgnoreReturning(
	[]interface{}{map[string]interface{}{"email": "a@x"}}, []string{"id"})
SQL inspection
sql := db.Table("users").Where("id", 1).ToSql()
raw := db.Table("users").Where("id", 1).ToRawSql() // bindings interpolated

Model

Struct tags
type Post struct {
	ID        int64          `torm:"primary_key;column:id"`
	Slug      string         `torm:"column:slug;unique_id"`   // auto UUID (unique_id:ulid for ULID)
	Title     string         `torm:"column:title;fillable"`
	Secret    string         `torm:"column:secret;guarded;hidden"`
	Config    map[string]any `torm:"column:config;cast:json"` // also: cast:array/date/datetime/decimal:N/bool/int/float
	DeletedAt *time.Time     `torm:"column:deleted_at"`       // presence enables soft deletes
	CreatedAt time.Time      `torm:"column:created_at"`
	UpdatedAt time.Time      `torm:"column:updated_at"`
	// torm:"timestamps=false" disables automatic timestamps
}

func (p *Post) TableName() string { return "posts" }

Available tags: primary_key, column, fillable, guarded, hidden, cast:*, unique_id[:ulid], timestamps=false, touches:<relation>.

CRUD
// Create (auto timestamps, auto-increment backfill, creating/created events)
var post Post
_ = torm.Fill(&post, map[string]any{"title": "hello"})
_ = db.Create(&post)
fmt.Println(torm.WasRecentlyCreated(&post)) // true

// Retrieve
_ = db.Model(Post{}).Where("id", 1).First(&post)
_ = db.Model(Post{}).Where("title", "like", "%go%").Get(&posts)
_ = db.Model(Post{}).Where("id", 1).FirstOrFail(&post)

// Update (Fill + Save; clean saves write nothing, dirty saves write changed columns only)
_ = db.UpdateModel(&post, map[string]any{"title": "updated"})

// firstOrCreate family
_ = db.FirstOrCreate(&post, map[string]any{"slug": "x"}, map[string]any{"title": "X"})
_ = db.UpdateOrCreate(&post, map[string]any{"slug": "x"}, map[string]any{"title": "Y"})

// Delete / soft delete / restore
_ = db.DeleteModel(&post) // UPDATE deleted_at (soft) or DELETE (hard)
_ = db.Restore(&post)
_ = db.ForceDelete(&post)
Soft deletes
// Default queries exclude trashed rows
db.Model(Post{}).WithTrashed().Get(&all)   // include trashed
db.Model(Post{}).OnlyTrashed().Get(&only)  // trashed only
_ = db.Restore(&post)
Increment & dirty tracking
_ = db.Increment(&post, "views", 1)
_ = db.IncrementEach(&post, map[string]int64{"views": 1, "likes": 2})

if torm.IsDirty(&post) {
	changes := torm.GetChanges(&post)
}
original := torm.GetOriginal(&post, "title")
torm.SyncOriginal(&post)
Events & observers
conn.Observe(&Post{}, &torm.Observer{
	Retrieved:     func(m any) error { return nil },
	Saving:        func(m any) error { return nil }, // return an error to abort
	Saved:         func(m any) error { return nil },
	Deleting:      func(m any) error { return nil },
	Trashed:       func(m any) error { return nil },
	ForceDeleting: func(m any) error { return nil },
})

bus := torm.NewEventBus()
bus.Listen(torm.EventRetrieved, func(e torm.Event) {})
conn.SetEventDispatcher(bus)
// events: retrieved / creating / created / updating / updated / saving / saved /
//         deleting / deleted / trashed / restoring / restored / forceDeleting /
//         forceDeleted

Relations

Relations are declared as structs and passed to With (eager loading), WhereHas (existence constraints) and WithCount (aggregates):

hasPosts := torm.HasMany{Model: Post{}}
belongsToUser := torm.BelongsTo{Model: User{}}
Eager loading & constraints
db.Table("users").With("posts", hasPosts).Get(&users)

db.Table("users").With("posts", hasPosts, func(q *torm.Builder) *torm.Builder {
	return q.Where("published", true).OrderBy("created_at", "desc").Limit(3)
}).Get(&users)

// Lazy loading
_ = conn.Load(&user, "posts", hasPosts)
if !conn.RelationLoaded(&user, "posts") { /* ... */ }
WhereHas family & aggregates
db.Table("users").WhereHas(hasPosts, func(q *torm.Builder) *torm.Builder {
	return q.Where("votes", ">", 100)
}).Get(&users)
db.Table("users").WhereDoesntHave(hasPosts).Get(&users)
db.Table("posts").WhereBelongsTo(user).Get(&posts)

db.Table("users").WithCount("posts", hasPosts).Get(&users)
db.Table("users").WithMax("posts", hasPosts, "votes").Get(&users)
BelongsToMany with pivot read & write side
btm := torm.BelongsToMany{RelatedModel: Role{}, Table: "role_user",
	ForeignPivotKey: "user_id", RelatedPivotKey: "role_id"}

db.Table("users").With("roles", btm).WithPivot("expires_at").Get(&users)

_ = conn.Attach(user, btm, []any{roleID}, map[string]any{"expires_at": t})
result, _ := conn.Sync(user, btm, []any{roleID, role2}) // attached/detached/updated
_, _ = conn.Detach(user, btm, []any{roleID})

Connections

// Named connections via Manager
m := torm.NewManager(map[string]torm.Config{
	"mysql": {Driver: "mysql", Dsn: "..."},
	"pg":    {Driver: "postgres", Dsn: "..."},
})
conn, _ := m.Connect("pg")
_ = m.UsingConnection("pg", func() error { return nil })

// Read / write splitting (sticky + multi-host read pool)
config := torm.Config{
	Driver:  "mysql",
	Dsn:     "root:pw@tcp(master:3306)/app",
	ReadDsns: []string{"replica1:3306", "replica2:3306"},
	Sticky:  true,
}
Transactions
// Nested transactions become savepoints; only the outermost level retries on deadlock
err := db.Transaction(func(c *torm.Connection) error {
	if _, _, err := c.Insert("insert into users (name) values (?)", "A"); err != nil {
		return err
	}
	return nil // commit; AfterCommit hooks fire
}, 3) // retry up to 3 attempts on deadlock

db.AfterCommit(func() { /* runs after the outermost commit */ })
db.AfterRollBack(func() { /* runs when the surrounding transaction rolls back */ })
fmt.Println(db.TransactionLevel())
Error classification
_, err := conn.Select("select * from users", nil, &users)
var qe *torm.Error
if errors.As(err, &qe) {
	switch qe.Kind {
	case torm.KindDeadlock:        // retry
	case torm.KindLostConnection:  // reconnect
	case torm.KindUniqueConstraint:
	}
	fmt.Println(qe.ConnectionName(), qe.RawSql())
}

Schema Builder & Migrations

s := db.Schema()

// Create / alter / drop
_ = s.Create("users", func(t *grammar.Blueprint) {
	t.ID()
	t.String("name")
	t.String("email").Unique()
	t.Timestamps()
})
_ = s.Table("users", func(t *grammar.Blueprint) {
	t.String("nickname").Nullable().After("name")
})
_ = s.HasTable("users")
_ = s.HasColumn("users", "email")
columns, _ := s.GetColumns("users")
indexes, _ := s.GetIndexes("users")
_ = s.DropIfExists("users")
Migrations
import "github.com/go-think/torm/migrations"

mig := migrations.NewMigrator(conn,
	migrations.Migration{
		Name: "2026_01_01_create_users",
		Up:   func(s *torm.SchemaBuilder) error {
			return s.Create("users", func(t *grammar.Blueprint) {
				t.ID()
				t.String("email").Unique()
			})
		},
		Down: func(s *torm.SchemaBuilder) error { return s.DropIfExists("users") },
	},
)

ran, _ := mig.Migrate()
rolled, _ := mig.Rollback() // last batch
rolled, _ = mig.Rollback(migrations.RollbackOptions{Step: 2})
rolled, ran, _ = mig.Refresh() // reset + migrate

License

This project is licensed under the Apache 2.0 license.

Contact

If you have any issues or feature requests, please contact us. PR is welcomed.

Documentation

Overview

Package torm 根包中的 events 内容已迁移至 events 子包 (数据库事件类型);此处保留类型与常量别名以兼容既有引用。

Index

Constants

View Source
const (
	EventRetrieving    = events.Retrieving
	EventRetrieved     = events.Retrieved
	EventCreating      = events.Creating
	EventCreated       = events.Created
	EventUpdating      = events.Updating
	EventUpdated       = events.Updated
	EventSaving        = events.Saving
	EventSaved         = events.Saved
	EventDeleting      = events.Deleting
	EventDeleted       = events.Deleted
	EventTrashed       = events.Trashed
	EventRestoring     = events.Restoring
	EventRestored      = events.Restored
	EventReplicating   = events.Replicating
	EventForceDeleting = events.ForceDeleting
	EventForceDeleted  = events.ForceDeleted
)

模型生命周期事件名。

Variables

View Source
var ErrMultipleColumnsSelected = errors.New("torm: multiple columns selected")

ErrMultipleColumnsSelected 单行查询命中多列时返回的错误 (Scalar 命中多列时抛出)。

View Source
var NewEventBus = events.NewEventBus

Functions

func Associate

func Associate(parent, owner any) error

Associate 把 owner 的主键写入 parent 的外键列 (外键缺省 = singular(owner 表名)_id;不自动 save)。

func DiscardChanges

func DiscardChanges(model any) error

DiscardChanges 把属性回滚到 original; 无快照的新模型清零全部字段。json 快照为序列化字符串,回滚时反序列化还原。

func Dissociate

func Dissociate(parent any, foreignKey string) error

Dissociate 将 parent 的外键列置空(Go 无方法名魔法,外键列需显式给出; 不自动 save)。

func EnforceMorphMap

func EnforceMorphMap(m map[string]any)

func Exists

func Exists(model any) bool

Exists 判断模型是否对应一条已持久化的记录(水合或写入成功后为 true)。

func FactoryHas

func FactoryHas[P any, C any](conn *Connection, parentFactory Factory[P], childFactory Factory[C], foreignKey string, count int) (P, []C, error)

FactoryHas 最小可用的 has 关系工厂组合(has 语义): 先用 parentFactory 创建父模型,再以 parent 主键填充 childFactory 模型的 foreignKey 外键列创建 count 个子模型;返回 (父模型, 子模型集合)。

func Fill

func Fill(model any, attrs map[string]any) error

Fill 按守卫规则批量赋值:遇到不可填字段返回 *MassAssignmentError,已过滤字段不写入(原子性,见守卫契约说明)。

func Flip

func Flip[K comparable](c Collection[K]) map[K]int

Flip 值翻转为键:元素值 → 首次出现的下标; 重复值保留首次出现。Go 方法不能新增 comparable 约束, 以包级泛型函数提供。

func ForceFill

func ForceFill(model any, attrs map[string]any) error

ForceFill 绕过守卫批量赋值。

func ForgetLoadedRelations

func ForgetLoadedRelations(model any)

ForgetLoadedRelations 释放模型的全部关系缓存(测试与长生命周期防泄漏用)。

func ForgetModel

func ForgetModel(model any)

ForgetModel 释放模型在全局状态表中的快照(对象弃用时的清理路径)。 内嵌 field.ModelStateAttr 的模型状态随实例走 GC,无需调用; 未内嵌的模型状态表以指针为键持强引用,长驻进程建议调用或改用内嵌基座。

func GetChanges

func GetChanges(model any) map[string]any

GetChanges 返回最近一次成功更新写库的变更集。

func GetDirty

func GetDirty(model any) map[string]any

GetDirty 返回相对 original 的脏列。

func GetHidden

func GetHidden(model any) []string

GetHidden 返回隐藏列列表(副本)。

func GetOriginal

func GetOriginal(model any, keys ...string) any

GetOriginal 返回列的 original 值;无快照时退回当前值。 不传 key 时返回整个 original map 的副本 (无 key 全量形态);无快照时退回当前属性全量快照。

func IsClean

func IsClean(model any, keys ...string) bool

IsClean 是 IsDirty 的否定。

func IsDirty

func IsDirty(model any, keys ...string) bool

IsDirty 判断模型(或指定列)相对 original 是否有未持久化的变更。

func IsFillable

func IsFillable(model any, key string) bool

IsFillable 判断列是否可被 Fill 赋值。 支持前缀通配(fillable tag "col_*",模式匹配)。

func IsGuarded

func IsGuarded(model any, key string) bool

IsGuarded 判断列是否被守卫("*" 匹配全部)。

func IsHidden

func IsHidden(model any, key string) bool

IsHidden 判断列是否隐藏。

func LoadedRelation

func LoadedRelation(model any, name string) ([]any, bool)

LoadedRelation 取惰性加载的关系结果(不存在时 ok=false)。

func MakeHidden

func MakeHidden(model any, keys ...string)

MakeHidden 追加隐藏列。

func MakeVisible

func MakeVisible(model any, keys ...string)

MakeVisible 解除隐藏列。

func MapsToSlice

func MapsToSlice(slice any, opts ...SerializeOptions) ([]map[string]any, error)

MapsToSlice 把模型切片/数组序列化为 []map。

func MorphAliasOf

func MorphAliasOf(model any) (string, bool)

MorphAliasOf 反查:模型(或其指针)对应的多态别名。

func MorphModelForAlias

func MorphModelForAlias(alias string) any

MorphModelForAlias 按别名解析模型零值(未知别名返回 nil)。

func MorphToAssociate

func MorphToAssociate(parent, owner any, morphName string) error

MorphToAssociate 写外键与类型双列(对应 MorphTo::associate): 类型取值 = morph map 别名,未注册时回退 owner 表名。

func MorphToDissociate

func MorphToDissociate(parent any, morphName string) error

MorphToDissociate 同时清空 id 列与 type 列(对应 MorphTo::dissociate)。

func Reguard

func Reguard()

Reguard 恢复守卫状态(嵌套计数归零后生效)。

func RelationLoaded

func RelationLoaded(model any, name string) bool

RelationLoaded 关系是否已加载。

func ResetMorphMap

func ResetMorphMap()

ResetMorphMap 清空映射(测试辅助)。

func Seed

func Seed(conn *Connection, seeders ...SeederFunc) error

Seed 依次执行种子;单个种子失败即中止。

func SetDateWriteFormats

func SetDateWriteFormats(date, datetime string)

SetDateWriteFormats 覆写 cast:date / cast:datetime 的写入格式(Go 布局)。

func SetDefaultUnguarded

func SetDefaultUnguarded(v bool)

SetDefaultUnguarded 修改"未声明守卫模型"的默认方向: true = 默认全可填(本库契约,默认值);false = 全守卫方向 (未声明守卫的模型完全守卫,Fill 抛错)。仅影响"既无 fillable 也无 guarded tag/注册"的模型类型。

func SetDeletedAtColumn

func SetDeletedAtColumn(column string)

SetDeletedAtColumn 设置全局软删列名默认值(软删时间戳列)。

func SetFillable

func SetFillable(model any, keys ...string)

SetFillable 设置模型类型的可填充列(keys 为空 = 清空列表)。

func SetGuarded

func SetGuarded(model any, keys ...string)

SetGuarded 设置模型类型的守卫列;不传 keys 等价 ["*"](全部守卫)。

func SetLoadedRelation

func SetLoadedRelation(model any, name string, models []any)

SetLoadedRelation 把关系结果缓存到模型。

func SetMorphMap

func SetMorphMap(m map[string]any)

SetMorphMap 注册别名→模型映射(覆盖同名别名;全局生效)。

func SetTimestampColumns

func SetTimestampColumns(created, updated string)

SetTimestampColumns 设置全局 created_at/updated_at 列名默认值 (覆写全局 created_at/updated_at 列名常量;空串保持默认)。 单模型可用 tag `torm:"created=col"` / `torm:"updated=col"` / `torm:"deleted=col"` 覆盖。

func SliceToJson

func SliceToJson(slice any, opts ...SerializeOptions) (string, error)

SliceToJson 把模型切片序列化为 JSON 数组。

func SortKeys

func SortKeys[V any](m map[string]V) []string

SortKeys 返回 map 键的升序切片(Go 形态: map 遍历无序,供 GroupBy/CountBy/MapWithKeys 结果取确定性键序)。

func StudlyCase

func StudlyCase(s string) string

Studly 导出常用命名转换(集合/关系场景使用)。

func SyncChanges

func SyncChanges(model any)

SyncChanges 依据 original 重算变更集。

func SyncOriginal

func SyncOriginal(model any)

SyncOriginal 把当前属性整体固化为 original。

func TimestampsIgnored

func TimestampsIgnored() bool

TimestampsIgnored 当前是否处于 WithoutTimestamps 作用域内。

func ToJson

func ToJson(model any, opts ...SerializeOptions) (string, error)

ToJson 把模型序列化为 JSON(hidden 语义同 ToMap)。

func ToMap

func ToMap(model any, opts ...SerializeOptions) (map[string]any, error)

ToMap 把模型序列化为 map: hidden(tag `torm:"hidden"` + MakeHidden + options.Hidden)列被剔除; options.Visible 非空时仅输出其交集;json cast 字段输出解码后的值。

func TotallyGuarded

func TotallyGuarded(model any) bool

TotallyGuarded 判断模型是否完全守卫(无 fillable 且 guarded == ["*"])。

func Touches

func Touches(model any, relation string) bool

Touches 模型是否声明触碰指定关系。

func Unguard

func Unguard(fn func())

Unguard 全局解除守卫(fn 执行期间可填任意字段)。

func WasChanged

func WasChanged(model any, keys ...string) bool

WasChanged 判断最近一次更新是否有(指定列的)实际写库变更。

func WasRecentlyCreated

func WasRecentlyCreated(model any) bool

WasRecentlyCreated 判断模型是否由最近一次 Create 写入。

func WithoutTimestamps

func WithoutTimestamps(fn func())

WithoutTimestamps 在 fn 执行期间禁用时间戳写入(Save/Create/软删均不写 created_at/updated_at;支持嵌套)。注意:作用域计数是进程级的静态 开关,作用域内不要并发执行其它模型的写入。

Types

type AppendedLengthAware

type AppendedLengthAware struct {
	LengthAwarePaginator
	// Query 经 Appends 追加的公共查询参数。
	Query map[string]string
}

AppendedLengthAware 携带 Appends 查询参数的 LengthAwarePaginator 副本。

func (AppendedLengthAware) URL

func (p AppendedLengthAware) URL(page int, query map[string]string) string

URL 合并 Appends 参数后再生成:同名键以本次传入的 query 覆盖。

type AppendedSimple

type AppendedSimple struct {
	SimplePaginator
	// Query 经 Appends 追加的公共查询参数。
	Query map[string]string
}

AppendedSimple 携带 Appends 查询参数的 SimplePaginator 副本。

func (AppendedSimple) URL

func (p AppendedSimple) URL(page int, query map[string]string) string

URL 合并 Appends 参数后再生成:同名键以本次传入的 query 覆盖。

type BelongsTo

type BelongsTo struct {
	ForeignKey string // 本表列(默认 *_id)
	OwnerKey   string // 目标表键(默认 id)
	Model      any    // 目标模型零值
	// withDefault(对应 SupportsDefaultModels):关系未命中时返回空实例而非 nil;
	// DefaultFn 非 nil 时以新实例调用,返回值非 nil 则使用之
	HasDefault bool
	DefaultFn  func(inst any) any
}

BelongsTo 反向一对一:本表持有外键。

func (BelongsTo) GetResults

func (r BelongsTo) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:按 parent 的外键取 owner(对应 BelongsTo::getResults, 未命中时 withDefault 生效返回默认实例)。

func (BelongsTo) WithDefault

func (r BelongsTo) WithDefault(fn ...func(inst any) any) BelongsTo

WithDefault 启用默认模型(对应 SupportsDefaultModels::withDefault): 关系未命中(外键为空或 owner 查询无结果)时返回目标模型新实例; fn 可选,非 nil 时以新实例调用,返回值非 nil 则使用返回值。

type BelongsToMany

type BelongsToMany struct {
	RelatedModel    any // 目标模型零值(Role{})
	Table           string
	ForeignPivotKey string // 本表在 pivot 中的键(user_id)
	RelatedPivotKey string // 目标表在 pivot 中的键(role_id)
	RelatedKey      string // 目标表主键(id)

	// pivot 读侧选项(对应 InteractsWithPivotTable / BelongsToMany 链式配置)
	PivotColumns    []string // WithPivot:select 附加的 pivot 列(pivot_ 前缀别名)
	PivotTimestamps bool     // WithTimestamps:pivot 表 created_at/updated_at
	// contains filtered or unexported fields
}

BelongsToMany 多对多(经 pivot 表)。 默认命名:pivot 表 = 两表单数按字典序拼接(role_user),外键 = 表名_id。

func (BelongsToMany) GetResults

func (r BelongsToMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:经 pivot 中间表取关联模型(对应 BelongsToMany::getResults)。

func (BelongsToMany) OrWherePivot

func (r BelongsToMany) OrWherePivot(column, operator string, value any) BelongsToMany

OrWherePivot 作用于 pivot 表列的 or where(对应 orWherePivot)。

func (BelongsToMany) OrWherePivotBetween

func (r BelongsToMany) OrWherePivotBetween(column string, values []any) BelongsToMany

OrWherePivotBetween pivot 列 between(or 布尔)。

func (BelongsToMany) OrWherePivotIn

func (r BelongsToMany) OrWherePivotIn(column string, values []any) BelongsToMany

OrWherePivotIn pivot 列 in(or 布尔,对应 orWherePivotIn)。

func (BelongsToMany) OrWherePivotNotBetween

func (r BelongsToMany) OrWherePivotNotBetween(column string, values []any) BelongsToMany

OrWherePivotNotBetween pivot 列 not between(or 布尔)。

func (BelongsToMany) OrWherePivotNotIn

func (r BelongsToMany) OrWherePivotNotIn(column string, values []any) BelongsToMany

OrWherePivotNotIn pivot 列 not in(or 布尔)。

func (BelongsToMany) OrWherePivotNotNull

func (r BelongsToMany) OrWherePivotNotNull(column string) BelongsToMany

OrWherePivotNotNull pivot 列 is not null(or 布尔)。

func (BelongsToMany) OrWherePivotNull

func (r BelongsToMany) OrWherePivotNull(column string) BelongsToMany

OrWherePivotNull pivot 列 is null(or 布尔)。

func (BelongsToMany) OrderByPivot

func (r BelongsToMany) OrderByPivot(column string, direction ...string) BelongsToMany

OrderByPivot 按 pivot 表列排序(对应 orderByPivot)。

func (BelongsToMany) WherePivot

func (r BelongsToMany) WherePivot(column, operator string, value any) BelongsToMany

WherePivot 作用于 pivot 表列的 where(对应 wherePivot)。

func (BelongsToMany) WherePivotBetween

func (r BelongsToMany) WherePivotBetween(column string, values []any) BelongsToMany

WherePivotBetween pivot 列 between(对应 wherePivotBetween,values 取前两个)。

func (BelongsToMany) WherePivotIn

func (r BelongsToMany) WherePivotIn(column string, values []any) BelongsToMany

WherePivotIn 作用于 pivot 表列的 where in(对应 wherePivotIn)。

func (BelongsToMany) WherePivotNotBetween

func (r BelongsToMany) WherePivotNotBetween(column string, values []any) BelongsToMany

WherePivotNotBetween pivot 列 not between(对应 wherePivotNotBetween)。

func (BelongsToMany) WherePivotNotIn

func (r BelongsToMany) WherePivotNotIn(column string, values []any) BelongsToMany

WherePivotNotIn pivot 列 not in(对应 wherePivotNotIn)。

func (BelongsToMany) WherePivotNotNull

func (r BelongsToMany) WherePivotNotNull(column string) BelongsToMany

WherePivotNotNull pivot 列 is not null(对应 wherePivotNotNull)。

func (BelongsToMany) WherePivotNull

func (r BelongsToMany) WherePivotNull(column string) BelongsToMany

WherePivotNull pivot 列 is null(对应 wherePivotNull)。

func (BelongsToMany) WithPivot

func (r BelongsToMany) WithPivot(columns ...string) BelongsToMany

WithPivot 附加 pivot 列到 select(别名带 pivot_ 前缀,对应 withPivot)。

func (BelongsToMany) WithPivotValue

func (r BelongsToMany) WithPivotValue(column string, value any) BelongsToMany

WithPivotValue attach/sync 附加的每行 pivot 固定值(对应 BelongsToMany.php:494 withPivotValue($column, $value)):显式传入的 pivotAttrs 优先于固定值。

func (BelongsToMany) WithTimestamps

func (r BelongsToMany) WithTimestamps() BelongsToMany

WithTimestamps pivot 表带 created_at/updated_at(对应 withTimestamps)。

type Builder

type Builder struct {
	Connection *Connection

	Query    *query.Query
	Bindings map[string][]interface{}
	// contains filtered or unexported fields
}

Builder 查询构建器:封装 query.Query,经 grammar 编译为方言 SQL。

func NewBuilder

func NewBuilder(connection *Connection, g grammar.Grammar) *Builder

func (*Builder) AddBinding

func (b *Builder) AddBinding(value interface{}, segment string)

AddBinding 添加绑定(导出入口)。

func (*Builder) AddSelect

func (b *Builder) AddSelect(columns ...interface{}) *Builder

AddSelect 追加查询列;支持列表展开并跳过重复列。

func (*Builder) AddWhereExistsQuery

func (b *Builder) AddWhereExistsQuery(sub *Builder, boolean string, not bool) *Builder

AddWhereExistsQuery 将 exists 子查询挂为 where 条件。

func (*Builder) AfterQuery

func (b *Builder) AfterQuery(callback func(any) any) *Builder

AfterQuery 注册查询执行后回调(Get 成功后应用)。

func (*Builder) Aggregate

func (b *Builder) Aggregate(function string, columns []interface{}, dest ...interface{}) error

Aggregate 在克隆上执行聚合,不污染原查询: 无 unions/havings 时 cloneWithout(['columns']) + cloneWithoutBindings(['select']), 再由 setAggregate 在 groups 为空时清除 orders 与 order 段绑定。

func (*Builder) Average

func (b *Builder) Average(columns string, dest ...interface{}) error

Average Avg 的别名。

func (*Builder) Avg

func (b *Builder) Avg(columns string, dest ...interface{}) error

func (*Builder) BeforeQuery

func (b *Builder) BeforeQuery(callback func(*Builder)) *Builder

BeforeQuery 注册查询执行前回调(toSql 与写入族执行前应用)。

func (*Builder) BuilderAddBinding

func (b *Builder) BuilderAddBinding(value interface{}, segment string)

BuilderAddBinding 添加绑定;未知段 panic。

func (*Builder) Chunk

func (b *Builder) Chunk(perPage uint64, makeDest func() any, callback func(page any) (bool, error)) error

Chunk 分块处理:每块通过 makeDest 创建扫描目标(如 func() any { return &[]User{} }), 回调返回 false 提前终止。

func (*Builder) ChunkById

func (b *Builder) ChunkById(perPage uint64, makeDest func() any, callback func(page any) (bool, error), column ...string) error

ChunkById 基于列游标的分块处理,避免大 offset。 makeDest 每页创建扫描目标(如 func() any { return &[]User{} });回调返回 false 提前终止。 首块 lastId=nil 走 whereNotNull(起始游标不硬编码 0, 字符串主键/负值主键同样适用)。

func (*Builder) ChunkByIdDesc

func (b *Builder) ChunkByIdDesc(perPage uint64, makeDest func() any, callback func(page any) (bool, error), column ...string) error

ChunkByIdDesc 基于列游标的降序分块: 游标向更小值推进,取块内最后一行的列值(降序排列时最小)。

func (*Builder) Clone

func (b *Builder) Clone() *Builder

Clone 深拷贝查询状态(切片复制,嵌套 Query/Join 引用共享,与 PHP clone 语义一致)。 软删 scope 的物化状态(scopesApplied/softDelete)随 wheres 一并继承, 避免克隆链(ChunkById/lazy 翻页)重复追加约束。

func (*Builder) CloneWithout

func (b *Builder) CloneWithout(properties ...string) *Builder

CloneWithout 克隆并清除指定属性(columns/orders/limit/offset/aggregate/distinct/unions)。

func (*Builder) CloneWithoutBindings

func (b *Builder) CloneWithoutBindings(except ...string) *Builder

CloneWithoutBindings 克隆并移除指定段的绑定。

func (*Builder) Count

func (b *Builder) Count(dest ...interface{}) error

Count 检索 count 结果,写入 dest 指针。

func (*Builder) CreateOrFirst

func (b *Builder) CreateOrFirst(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

CreateOrFirst 先尝试创建,唯一约束冲突时回退按 attributes 查询 (转发 Connection.CreateOrFirst 的并发安全语义)。

func (*Builder) CrossJoin

func (b *Builder) CrossJoin(table interface{}, first interface{}, args ...interface{}) *Builder

func (*Builder) CrossJoinSub

func (b *Builder) CrossJoinSub(q interface{}, as string) *Builder

CrossJoinSub 交叉 join 子查询(无 on 条件,对应 crossJoinSub)。

func (*Builder) Cursor

func (b *Builder) Cursor() (iter.Seq2[map[string]any, error], error)

Cursor 全表流式读取:逐行产出 map(错误经第二通道传出)。

func (*Builder) CursorPaginate

func (b *Builder) CursorPaginate(dest any, perPage int64, cursor ...*Cursor) (*CursorPaginator, error)

CursorPaginate 游标分页: 依据 order 列生成游标条件(支持多列嵌套 or),cursor 为 "" 或 nil 表示首页。

func (*Builder) DD

func (b *Builder) DD()

DD 输出 SQL 后终止进程。

func (*Builder) DDRawSql

func (b *Builder) DDRawSql() *Builder

DDRawSql 打印内联绑定后的 SQL。 与 dd 的差异:dd 是 die-dump(打印后终止脚本); Go 侧不做 os.Exit(终止宿主进程的职责在调用方),仅打印后返回 builder。

func (*Builder) Decrement

func (b *Builder) Decrement(column string, amount ...interface{}) (int64, error)

func (*Builder) DecrementEach

func (b *Builder) DecrementEach(columns map[string]float64, extra map[string]interface{}) (int64, error)

DecrementEach 按列批量递减。

func (*Builder) Delete

func (b *Builder) Delete(args ...interface{}) (int64, error)

Delete 删除;可传主键值(对应 delete($id))。 关联软删模型时编译为 update set deleted_at = now(软删宏 onDelete 语义), 并分发 deleting/trashed/deleted 事件; 无关联模型且无任何 where 条件时返回错误,拒绝整表 DELETE。

func (*Builder) Distinct

func (b *Builder) Distinct(args ...interface{}) *Builder

Distinct 无参时 distinct;传列名时对应 Postgres 的 distinct on。

func (*Builder) DoesntExist

func (b *Builder) DoesntExist() (bool, error)

func (*Builder) DoesntExistOr

func (b *Builder) DoesntExistOr(callback func() error) (bool, error)

DoesntExistOr 不存在返回 true,否则执行回调。

func (*Builder) DoesntHave

func (b *Builder) DoesntHave(rel Relation) *Builder

DoesntHave 关系不存在性约束:where not exists (...)。

func (*Builder) Dump

func (b *Builder) Dump() *Builder

Dump 输出当前 SQL 到 stderr。

func (*Builder) DumpRawSql

func (b *Builder) DumpRawSql() *Builder

DumpRawSql 输出内联绑定后的 SQL。

func (*Builder) Each

func (b *Builder) Each(makeDest func() any, callback func(item any) (bool, error)) error

Each 为 Chunk 的逐行封装:dest 为单个元素模板指针。

func (*Builder) EachById

func (b *Builder) EachById(makeDest func() any, callback func(item any) (bool, error), column ...string) error

EachById 为 ChunkById 的逐行封装。

func (*Builder) Exists

func (b *Builder) Exists() (bool, error)

Exists 存在性检查:select exists(...) as "exists"。 必须先应用模型全局 scope(软删等),否则软删模型会把已删行当作存在。

func (*Builder) ExistsOr

func (b *Builder) ExistsOr(callback func() error) (bool, error)

ExistsOr 存在返回 true,否则执行回调。

func (*Builder) Explain

func (b *Builder) Explain() ([]map[string]any, error)

Explain 返回执行计划(explain + SQL)。 Explain 输出执行计划;SQLServer 不支持 "explain select" 语法,显式报错。

func (*Builder) Find

func (b *Builder) Find(id interface{}, dest interface{}, columns ...interface{}) error

Find 按主键取单行(等价 whereKey(id) 后 first)。

func (*Builder) FindMany

func (b *Builder) FindMany(ids interface{}, dest interface{}, columns ...interface{}) error

FindMany 按主键批量取行(等价 whereKey(ids) 后 get); ids 为任意切片。空集直接返回空 dest,不发 SQL。

func (*Builder) FindOr

func (b *Builder) FindOr(id interface{}, dest interface{}, fallback func() error, columns ...interface{}) error

FindOr 按主键取单行,未命中执行 fallback。

func (*Builder) FindOrFail

func (b *Builder) FindOrFail(id interface{}, dest interface{}, columns ...interface{}) error

FindOrFail 按主键取单行,未命中返回 *ErrNotFound (即记录不存在错误)。

func (*Builder) FindOrNew

func (b *Builder) FindOrNew(id interface{}, dest interface{}, columns ...interface{}) error

FindOrNew 按主键查找;未命中时把 dest 重置为空白实例并仅设主键 (不落库)。

func (*Builder) First

func (b *Builder) First(dest interface{}, columns ...interface{}) error

First 取第一行。

func (*Builder) FirstOr

func (b *Builder) FirstOr(dest interface{}, fallback func() error, columns ...interface{}) error

FirstOr 未命中时执行 fallback。

func (*Builder) FirstOrCreate

func (b *Builder) FirstOrCreate(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

FirstOrCreate 按 attributes 查找;未命中则合并 attributes+values 创建 (转发 Connection.FirstOrCreate,保持两者语义一致)。

func (*Builder) FirstOrFail

func (b *Builder) FirstOrFail(dest interface{}, columns ...interface{}) error

FirstOrFail 未命中返回 ErrNotFound。

func (*Builder) FirstOrNew

func (b *Builder) FirstOrNew(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

FirstOrNew 按 attributes 查找;未命中仅构造不落库(转发 Connection.FirstOrNew)。

func (*Builder) ForPage

func (b *Builder) ForPage(page, perPage uint64) *Builder

ForPage 分页:page 从 1 开始。

func (*Builder) ForPageAfterId

func (b *Builder) ForPageAfterId(perPage uint64, lastId interface{}, column ...string) *Builder

ForPageAfterId 基于列游标的分页:where column > lastId + orderBy column asc + limit 不使用 offset;lastId 为 nil 时约束列非空。

func (*Builder) ForPageBeforeId

func (b *Builder) ForPageBeforeId(perPage uint64, lastId interface{}, column ...string) *Builder

ForPageBeforeId 基于列游标向前翻页:where column < lastId + orderBy column desc + limit lastId 为 nil 时约束列非空。

func (*Builder) ForceDelete

func (b *Builder) ForceDelete() (int64, error)

ForceDelete 硬删除:跳过软删宏,编译为裸 DELETE(绕过模型层 直接走底层 delete)。

func (*Builder) ForceIndex

func (b *Builder) ForceIndex(index string) *Builder

ForceIndex 设置索引提示(force index)。

func (*Builder) From

func (b *Builder) From(table interface{}) *Builder

func (*Builder) FromRaw

func (b *Builder) FromRaw(sql interface{}) *Builder

FromRaw 设置原始 from 表达式。

func (*Builder) FromSub

func (b *Builder) FromSub(q interface{}, as string) *Builder

FromSub 以子查询作为表:from (select ...) as "as"。

func (*Builder) Get

func (b *Builder) Get(dest interface{}, columns ...interface{}) error

Get 执行查询并扫描进 dest;columns 可为 string / []string / []interface{}。

func (*Builder) GetBindings

func (b *Builder) GetBindings() []interface{}

GetBindings 按固定段顺序(select→from→join→where→groupBy→having→order→union→unionOrder)合并绑定。 GetBindings 按 grammar.BindingSegments 顺序合并绑定段("with" 居首: CTE 编译在最终 SQL 最前,其占位符最先求值)。

func (*Builder) GetConnection

func (b *Builder) GetConnection() *Connection

func (*Builder) GetCountForPagination

func (b *Builder) GetCountForPagination(columns ...string) (int64, error)

GetCountForPagination 取分页总数: 有 group/having 时包裹子查询计数,否则去除 columns/orders/limit/offset 后聚合。

func (*Builder) GetGrammar

func (b *Builder) GetGrammar() grammar.Grammar

func (*Builder) GetRawBindings

func (b *Builder) GetRawBindings() map[string][]interface{}

GetRawBindings 返回按段分组的原始绑定。

func (*Builder) GroupBy

func (b *Builder) GroupBy(groups ...interface{}) *Builder

func (*Builder) GroupByRaw

func (b *Builder) GroupByRaw(sql string, bindings ...interface{}) *Builder

func (*Builder) GroupLimit

func (b *Builder) GroupLimit(value int, column string) *Builder

GroupLimit 分组限额: value >= 0 时设置(编译为 row_number() over (partition by column) <= value, 预加载分组限额的基础入口)。

func (*Builder) Has

func (b *Builder) Has(rel Relation, args ...any) *Builder

Has 关系存在性/计数阈值(has($relation, $operator, $count) 形态): Has(rel) 等价 Has(rel, ">=", 1);Has(rel, 3) 默认操作符 >=; Has(rel, ">", 2) 自定义操作符。实现见 builder.go hasImpl。

func (*Builder) Having

func (b *Builder) Having(column interface{}, args ...interface{}) *Builder

Having 基础 having。

func (*Builder) HavingBetween

func (b *Builder) HavingBetween(column interface{}, values []interface{}) *Builder

HavingBetween / OrHavingBetween / HavingNotBetween / OrHavingNotBetween 绑定取 flatten 后前两个。

func (*Builder) HavingNested

func (b *Builder) HavingNested(callback func(*Builder), boolean ...string) *Builder

HavingNested / OrHavingNested / addNestedHavingQuery:嵌套 having 条件组。

func (*Builder) HavingNotBetween

func (b *Builder) HavingNotBetween(column interface{}, values []interface{}) *Builder

func (*Builder) HavingNotNull

func (b *Builder) HavingNotNull(columns interface{}, args ...interface{}) *Builder

func (*Builder) HavingNull

func (b *Builder) HavingNull(columns interface{}, args ...interface{}) *Builder

HavingNull / OrHavingNull / HavingNotNull / OrHavingNotNull: columns 支持多列(每列一条 having)。

func (*Builder) HavingRaw

func (b *Builder) HavingRaw(sql interface{}, bindings ...interface{}) *Builder

HavingRaw / OrHavingRaw(sql + bindings,boolean 缺省 and): 可选末位 string 参数为 boolean 关键字。

func (*Builder) IgnoreIndex

func (b *Builder) IgnoreIndex(index string) *Builder

IgnoreIndex 设置索引提示(ignore index)。

func (*Builder) Implode

func (b *Builder) Implode(column string, glue string) (string, error)

Implode 取某列的值并连接为字符串。

func (*Builder) InOrderOf

func (b *Builder) InOrderOf(column interface{}, values []interface{}) *Builder

InOrderOf 按取值序列排序: order by case "col" = ? then 0 ... else N end。

func (*Builder) InRandomOrder

func (b *Builder) InRandomOrder(seed ...interface{}) *Builder

func (*Builder) Increment

func (b *Builder) Increment(column string, amount ...interface{}) (int64, error)

Increment / Decrement 数值增减(列包裹后拼算式,负数转减法)。

func (*Builder) IncrementEach

func (b *Builder) IncrementEach(columns map[string]float64, extra map[string]interface{}) (int64, error)

IncrementEach 按列批量递增: 值编译为 raw "col + amount",extra 为附加 set 值。

func (*Builder) IncrementOrCreate

func (b *Builder) IncrementOrCreate(model interface{}, attributes map[string]interface{}, column string, rest ...interface{}) error

IncrementOrCreate 创建匹配 attributes 的记录(column 取 default),已存在 则对 column 自增 step:

firstOrCreate(attributes, {column: default}) → !wasRecentlyCreated 时 increment。

rest 依次为 default(缺省 1)、step(缺省 1)、extra map[string]interface{}(附加列)。

func (*Builder) Insert

func (b *Builder) Insert(value interface{}) (int64, int64, error)

Insert 插入单行:map(确定性排序)或 query.Row(保序)。

func (*Builder) InsertGetId

func (b *Builder) InsertGetId(value interface{}, sequence ...string) (int64, error)

InsertGetId 插入并返回自增 id。

func (*Builder) InsertOrIgnore

func (b *Builder) InsertOrIgnore(values []interface{}) (int64, error)

InsertOrIgnore 插入并忽略冲突行。

func (*Builder) InsertOrIgnoreReturning

func (b *Builder) InsertOrIgnoreReturning(values []interface{}, returning []string, uniqueBy ...[]string) ([]map[string]any, error)

InsertOrIgnoreReturning 插入并忽略冲突行,按 returning 列返回结果行 (本库扩展 API,上游无对应实现): values 为空返回空结果不发 SQL;returning/uniqueBy 为空切片报错; 经写连接执行(对应 selectFromWriteConnection)。 编译依赖 grammar 的 CompileInsertOrIgnoreReturning 钩子——PG/SQLite 已实现, MySQL/SqlServer/MariaDB 方言未实现时调用 panic ErrUnsupported。

func (*Builder) InsertOrIgnoreUsing

func (b *Builder) InsertOrIgnoreUsing(columns []string, q interface{}) (int64, error)

InsertOrIgnoreUsing insert ignore ... select。

func (*Builder) InsertUsing

func (b *Builder) InsertUsing(columns []string, q interface{}) (int64, error)

InsertUsing insert ... select: 只使用子查询的 cleanBindings 执行,不并入 builder 的绑定段。

func (*Builder) Inserts

func (b *Builder) Inserts(values []interface{}) (int64, int64, error)

Inserts 批量插入:元素为 map 或 query.Row。

func (*Builder) Join

func (b *Builder) Join(table interface{}, first interface{}, args ...interface{}) *Builder

Join 添加 join 子句:Join(table, first, operator, second, type, where), operator/second 可省略,type 缺省 "inner",where 缺省 false。 first 亦可为 func(*Builder)(复杂 on 子句,JoinClause 闭包形式)。

func (*Builder) JoinLateral

func (b *Builder) JoinLateral(q interface{}, as string, typeStr ...string) *Builder

JoinLateral 添加 lateral join(MySQL/PG 支持,对应 joinLateral)。

func (*Builder) JoinSub

func (b *Builder) JoinSub(q interface{}, as string, first, operator, second interface{}) *Builder

JoinSub 以子查询作为 join 表:inner join (select ...) as "as" on ...

func (*Builder) JoinWhere

func (b *Builder) JoinWhere(table interface{}, first string, operator string, second interface{}) *Builder

JoinWhere 对应 join(..., $where=true):把第二操作数作为绑定值。

func (*Builder) Latest

func (b *Builder) Latest(column ...string) *Builder

func (*Builder) Lazy

func (b *Builder) Lazy(perPage uint64) (iter.Seq2[map[string]any, error], error)

Lazy 分页懒加载:内部按 limit/offset 翻页,逐行产出 map。

func (*Builder) LazyById

func (b *Builder) LazyById(perPage uint64, column ...string) (iter.Seq2[map[string]any, error], error)

LazyById 基于 id 游标的懒加载(无大 offset 问题)。

func (*Builder) LazyByIdDesc

func (b *Builder) LazyByIdDesc(perPage uint64, column ...string) (iter.Seq2[map[string]any, error], error)

LazyByIdDesc 基于 id 游标的降序懒加载。

func (*Builder) LeftJoin

func (b *Builder) LeftJoin(table interface{}, first interface{}, args ...interface{}) *Builder

func (*Builder) LeftJoinLateral

func (b *Builder) LeftJoinLateral(q interface{}, as string) *Builder

LeftJoinLateral 添加 left lateral join。

func (*Builder) LeftJoinSub

func (b *Builder) LeftJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder

func (*Builder) LeftJoinWhere

func (b *Builder) LeftJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder

func (*Builder) Limit

func (b *Builder) Limit(value uint64) *Builder

func (*Builder) Lock

func (b *Builder) Lock(value interface{}) *Builder

func (*Builder) LockForUpdate

func (b *Builder) LockForUpdate() *Builder

func (*Builder) Max

func (b *Builder) Max(columns string, dest ...interface{}) error

func (*Builder) MergeBindings

func (b *Builder) MergeBindings(q *Builder)

MergeBindings 合并另一 builder 的绑定。

func (*Builder) MergeWheres

func (b *Builder) MergeWheres(wheres []*query.Where, bindings []interface{}) *Builder

MergeWheres 合并外部 where 数组与绑定。

func (*Builder) Min

func (b *Builder) Min(columns string, dest ...interface{}) error

func (*Builder) MorphToConstrain

func (b *Builder) MorphToConstrain(name string, rel MorphTo, constraints ...func(*Builder)) *Builder

MorphToConstrain morphTo 预加载全类型通用约束(对应 MorphTo::constrain): 约束闭包应用在每个类型的 owner 查询上(先于 MorphWith 的按类型约束)。

func (*Builder) MorphToOnlyTrashed

func (b *Builder) MorphToOnlyTrashed(name string, rel MorphTo) *Builder

MorphToOnlyTrashed morphTo 预加载仅取已软删 owner(对应 morphTo->onlyTrashed())。

func (*Builder) MorphToWithCount

func (b *Builder) MorphToWithCount(name string, rel MorphTo, perType map[string][]MorphCountSpec) *Builder

MorphToWithCount morphTo 预加载按类型的计数聚合(对应 MorphTo::morphWithCount): perType 键为类型串,值为该类型 owner 查询要加载的计数规格 (morphWithCount([Post::class => ['comments']]) 形态;Go 侧需显式 携带关系描述符,见 MorphCountSpec)。

func (*Builder) MorphToWithTrashed

func (b *Builder) MorphToWithTrashed(name string, rel MorphTo) *Builder

MorphToWithTrashed morphTo 预加载跳过目标模型软删过滤(对应 morphTo->withTrashed())。

func (*Builder) MorphToWithoutTrashed

func (b *Builder) MorphToWithoutTrashed(name string, rel MorphTo) *Builder

MorphToWithoutTrashed morphTo 预加载显式排除已软删 owner(对应 morphTo->withoutTrashed(); 与默认行为一致,作为显式变体提供)。

func (*Builder) MorphWith

func (b *Builder) MorphWith(name string, rel MorphTo, perType map[string]func(*Builder)) *Builder

MorphWith morphTo 预加载按类型附加约束: perType 键为类型串(type 列取值),值为该类型 owner 查询的约束闭包。

func (*Builder) Offset

func (b *Builder) Offset(value uint64) *Builder

func (*Builder) Oldest

func (b *Builder) Oldest(column ...string) *Builder

Oldest / Latest / InRandomOrder / Reorder

func (*Builder) On

func (b *Builder) On(first interface{}, args ...interface{}) *Builder

On 在 JoinClause 上添加 on 条件:列比较或嵌套闭包(对应 JoinClause::on)。

func (*Builder) OnlyTrashed

func (b *Builder) OnlyTrashed() *Builder

OnlyTrashed 只查已软删的行:deleted_at IS NOT NULL(对应 onlyTrashed 宏)。

func (*Builder) OrHas

func (b *Builder) OrHas(rel Relation) *Builder

OrHas 无约束关系存在性(or 布尔)。

func (*Builder) OrHaving

func (b *Builder) OrHaving(column interface{}, args ...interface{}) *Builder

func (*Builder) OrHavingBetween

func (b *Builder) OrHavingBetween(column interface{}, values []interface{}) *Builder

func (*Builder) OrHavingNested

func (b *Builder) OrHavingNested(callback func(*Builder)) *Builder

func (*Builder) OrHavingNotBetween

func (b *Builder) OrHavingNotBetween(column interface{}, values []interface{}) *Builder

func (*Builder) OrHavingNotNull

func (b *Builder) OrHavingNotNull(columns interface{}) *Builder

func (*Builder) OrHavingNull

func (b *Builder) OrHavingNull(columns interface{}) *Builder

func (*Builder) OrHavingRaw

func (b *Builder) OrHavingRaw(sql interface{}, bindings ...interface{}) *Builder

func (*Builder) OrOn

func (b *Builder) OrOn(first interface{}, args ...interface{}) *Builder

OrOn 在 JoinClause 上添加 or on 条件(对应 JoinClause::orOn)。

func (*Builder) OrWhere

func (b *Builder) OrWhere(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereAll

func (b *Builder) OrWhereAll(columns []interface{}, operator string, value interface{}) *Builder

OrWhereAll 对应 orWhereAll。

func (*Builder) OrWhereAny

func (b *Builder) OrWhereAny(columns []interface{}, operator string, value interface{}) *Builder

OrWhereAny 对应 orWhereAny。

func (*Builder) OrWhereBetween

func (b *Builder) OrWhereBetween(column interface{}, values []interface{}) *Builder

func (*Builder) OrWhereBetweenColumns

func (b *Builder) OrWhereBetweenColumns(column interface{}, values []interface{}) *Builder

func (*Builder) OrWhereColumn

func (b *Builder) OrWhereColumn(first interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereDate

func (b *Builder) OrWhereDate(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereDay

func (b *Builder) OrWhereDay(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereDoesntHave

func (b *Builder) OrWhereDoesntHave(rel Relation, constraints func(*Builder)) *Builder

OrWhereDoesntHave 关系不存在性约束(or 布尔)。

func (*Builder) OrWhereExists

func (b *Builder) OrWhereExists(q interface{}) *Builder

func (*Builder) OrWhereExpression

func (b *Builder) OrWhereExpression(condition interface{}) *Builder

OrWhereExpression 以 or 连接条件表达式。

func (*Builder) OrWhereFullText

func (b *Builder) OrWhereFullText(columns interface{}, value interface{}, options ...map[string]interface{}) *Builder

func (*Builder) OrWhereHas

func (b *Builder) OrWhereHas(rel Relation, constraints func(*Builder)) *Builder

OrWhereHas 关系存在性约束(or 布尔)。

func (*Builder) OrWhereHasMorph

func (b *Builder) OrWhereHasMorph(rel MorphMany, types []string, constraints ...func(*Builder)) *Builder

OrWhereHasMorph 多态关系存在性约束(or 布尔)。

func (*Builder) OrWhereIn

func (b *Builder) OrWhereIn(column interface{}, values interface{}) *Builder

func (*Builder) OrWhereIntegerInRaw

func (b *Builder) OrWhereIntegerInRaw(column interface{}, values []interface{}) *Builder

func (*Builder) OrWhereIntegerNotInRaw

func (b *Builder) OrWhereIntegerNotInRaw(column interface{}, values []interface{}) *Builder

func (*Builder) OrWhereJsonContains

func (b *Builder) OrWhereJsonContains(column interface{}, value interface{}) *Builder

func (*Builder) OrWhereJsonContainsKey

func (b *Builder) OrWhereJsonContainsKey(column interface{}) *Builder

func (*Builder) OrWhereJsonDoesntContain

func (b *Builder) OrWhereJsonDoesntContain(column interface{}, value interface{}) *Builder

func (*Builder) OrWhereJsonDoesntContainKey

func (b *Builder) OrWhereJsonDoesntContainKey(column interface{}) *Builder

func (*Builder) OrWhereJsonDoesntHaveLength

func (b *Builder) OrWhereJsonDoesntHaveLength(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereJsonDoesntOverlap

func (b *Builder) OrWhereJsonDoesntOverlap(column interface{}, value interface{}) *Builder

OrWhereJsonDoesntOverlap 以 or 连接的 JSON 不相交( 即 whereJsonDoesntOverlap 的 or 版本)。

func (*Builder) OrWhereJsonLength

func (b *Builder) OrWhereJsonLength(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereJsonOverlaps

func (b *Builder) OrWhereJsonOverlaps(column interface{}, value interface{}) *Builder

func (*Builder) OrWhereKey

func (b *Builder) OrWhereKey(id interface{}) *Builder

OrWhereKey 以 or 连接主键条件(括号分组 + or)。

func (*Builder) OrWhereKeyNot

func (b *Builder) OrWhereKeyNot(id interface{}) *Builder

OrWhereKeyNot 以 or 连接主键排除条件。

func (*Builder) OrWhereLike

func (b *Builder) OrWhereLike(column interface{}, value interface{}, caseSensitive bool) *Builder

func (*Builder) OrWhereMonth

func (b *Builder) OrWhereMonth(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereMorphedTo

func (b *Builder) OrWhereMorphedTo(morphName string, target any) *Builder

OrWhereMorphedTo 匹配多态列指向特定目标的行(or 布尔)。

func (*Builder) OrWhereNested

func (b *Builder) OrWhereNested(callback func(*Builder)) *Builder

func (*Builder) OrWhereNone

func (b *Builder) OrWhereNone(columns []interface{}, operator string, value interface{}) *Builder

OrWhereNone 对应 orWhereNone。

func (*Builder) OrWhereNot

func (b *Builder) OrWhereNot(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereNotBetween

func (b *Builder) OrWhereNotBetween(column interface{}, values []interface{}) *Builder

func (*Builder) OrWhereNotBetweenColumns

func (b *Builder) OrWhereNotBetweenColumns(column interface{}, values []interface{}) *Builder

func (*Builder) OrWhereNotExists

func (b *Builder) OrWhereNotExists(q interface{}) *Builder

func (*Builder) OrWhereNotIn

func (b *Builder) OrWhereNotIn(column interface{}, values interface{}) *Builder

func (*Builder) OrWhereNotLike

func (b *Builder) OrWhereNotLike(column interface{}, value interface{}, caseSensitive bool) *Builder

func (*Builder) OrWhereNotNull

func (b *Builder) OrWhereNotNull(columns interface{}) *Builder

func (*Builder) OrWhereNull

func (b *Builder) OrWhereNull(columns interface{}) *Builder

func (*Builder) OrWhereNullSafeEquals

func (b *Builder) OrWhereNullSafeEquals(column interface{}, value interface{}) *Builder

OrWhereNullSafeEquals 以 or 连接的空安全等值(对应 orWhereNullSafeEquals)。

func (*Builder) OrWhereRaw

func (b *Builder) OrWhereRaw(sql interface{}, bindings ...interface{}) *Builder

func (*Builder) OrWhereRowValues

func (b *Builder) OrWhereRowValues(columns []interface{}, operator string, values []interface{}) *Builder

func (*Builder) OrWhereTime

func (b *Builder) OrWhereTime(column interface{}, args ...interface{}) *Builder

func (*Builder) OrWhereValueBetween

func (b *Builder) OrWhereValueBetween(value interface{}, columns []interface{}) *Builder

OrWhereValueBetween 以 or 连接(对应 orWhereValueBetween)。

func (*Builder) OrWhereValueNotBetween

func (b *Builder) OrWhereValueNotBetween(value interface{}, columns []interface{}) *Builder

OrWhereValueNotBetween 以 or 连接(对应 orWhereValueNotBetween)。

func (*Builder) OrWhereYear

func (b *Builder) OrWhereYear(column interface{}, args ...interface{}) *Builder

func (*Builder) OrderBy

func (b *Builder) OrderBy(column interface{}, direction ...string) *Builder

OrderBy 排序;direction 只接受 asc/desc(大小写不敏感),非法值 panic。 column 可为 *Builder / 闭包(编译为子查询列:order by (select ...))。

func (*Builder) OrderByDesc

func (b *Builder) OrderByDesc(column interface{}) *Builder

func (*Builder) OrderByRaw

func (b *Builder) OrderByRaw(sql string, bindings ...interface{}) *Builder

func (*Builder) Paginate

func (b *Builder) Paginate(dest any, page, perPage int64) (*LengthAwarePaginator, error)

Paginate 长度感知分页: 总数为 0 时不执行取数查询。

func (*Builder) Pluck

func (b *Builder) Pluck(column string, dest interface{}) error

Pluck 取某列的值集合,扫入 dest(*[]T / *[]any / *[]string 等)。

func (*Builder) RawValue

func (b *Builder) RawValue(expression string) (any, error)

RawValue 取原始表达式的单值。

func (*Builder) Reorder

func (b *Builder) Reorder(column ...interface{}) *Builder

Reorder 清除或重设排序: 清空 orders、unionOrders 及 order/unionOrder 段绑定;Reorder(col, dir...) 重设。

func (*Builder) ReorderDesc

func (b *Builder) ReorderDesc(column interface{}) *Builder

ReorderDesc 降序重设排序。

func (*Builder) RightJoin

func (b *Builder) RightJoin(table interface{}, first interface{}, args ...interface{}) *Builder

func (*Builder) RightJoinSub

func (b *Builder) RightJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder

func (*Builder) RightJoinWhere

func (b *Builder) RightJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder

func (*Builder) Scan

func (b *Builder) Scan(dest ...interface{}) error

Scan 直接以当前查询执行扫描(聚合等场景)。

func (*Builder) Select

func (b *Builder) Select(columns ...interface{}) *Builder

Select 设置查询列;元素为列名字符串或 grammar.Expression。

func (*Builder) SelectRaw

func (b *Builder) SelectRaw(sql string, bindings ...interface{}) *Builder

SelectRaw 追加原始表达式列。

func (*Builder) SelectSub

func (b *Builder) SelectSub(q interface{}, as string) *Builder

SelectSub 以子查询作为列:select (select ...) as "as"。

func (*Builder) SetAggregate

func (b *Builder) SetAggregate(function string, columns []interface{}) *Builder

SetAggregate 设置聚合组件: groups 为空时清除 orders 与 order 段绑定。

func (*Builder) SetBindings

func (b *Builder) SetBindings(bindings []interface{}, segment string)

SetBindings 覆盖某段的全部绑定。

func (*Builder) SharedLock

func (b *Builder) SharedLock() *Builder

func (*Builder) SimplePaginate

func (b *Builder) SimplePaginate(dest any, page, perPage int64) (*SimplePaginator, error)

SimplePaginate 简单分页: 多取一条判断 hasMore,无 total。

func (*Builder) Skip

func (b *Builder) Skip(value uint64) *Builder

func (*Builder) Sole

func (b *Builder) Sole(dest interface{}, columns ...interface{}) error

Sole 要求恰好一行;零行 ErrNotFound,多行 ErrMultiple。

func (*Builder) SoleValue

func (b *Builder) SoleValue(column string) (any, error)

SoleValue 取唯一一行的单列值:零行 ErrNotFound、多行 ErrMultiple (sole 的单列形式)。

func (*Builder) StraightJoin

func (b *Builder) StraightJoin(table interface{}, first string, operator string, second interface{}) *Builder

StraightJoin 编译为 straight_join(仅 MySQL 支持,其它方言编译时抛错)。

func (*Builder) StraightJoinSub

func (b *Builder) StraightJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder

StraightJoinSub 以子查询作为 straight join 表 (仅 MySQL 支持,其它方言编译时抛错)。

func (*Builder) StraightJoinWhere

func (b *Builder) StraightJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder

StraightJoinWhere straight_join 且 where=true(第二操作数作为绑定值)。

func (*Builder) Sum

func (b *Builder) Sum(columns string, dest ...interface{}) error

func (*Builder) Take

func (b *Builder) Take(value uint64) *Builder

func (*Builder) Timeout

func (b *Builder) Timeout(seconds int64) *Builder

Timeout 设置查询执行超时(秒),MySQL 编译为 MAX_EXECUTION_TIME 提示。

func (*Builder) ToRawSql

func (b *Builder) ToRawSql() string

ToRawSql 以字面值内联绑定输出 SQL。

func (*Builder) ToSql

func (b *Builder) ToSql() string

func (*Builder) Touch

func (b *Builder) Touch(columns ...string) (int64, error)

Touch 批量刷新时间戳:把匹配行的时间戳列更新为 now。 指定列时仅更新该列(对应 touch($column));缺省列刷新 updated_at, 且仅对带时间戳列的模型建器生效(无时间戳返回 0、不发 SQL)。 直接编译 UPDATE(对应 toBase()->update):不自动追加 updated_at。

func (*Builder) Truncate

func (b *Builder) Truncate() error

Truncate 清空表。

func (*Builder) Union

func (b *Builder) Union(q interface{}) *Builder

func (*Builder) UnionAll

func (b *Builder) UnionAll(q interface{}) *Builder

func (*Builder) Unless

func (b *Builder) Unless(condition bool, callback func(*Builder), defaultCallback ...func(*Builder)) *Builder

func (*Builder) Update

func (b *Builder) Update(value map[string]interface{}) (int64, error)

Update 更新记录。模型建器自动补 updated_at。

func (*Builder) UpdateFrom

func (b *Builder) UpdateFrom(value map[string]interface{}) (int64, error)

UpdateFrom 对应 Postgres 的 update ... from(compileUpdateFrom): 基础方言不支持(抛 ErrUnsupported)。

func (*Builder) UpdateOrCreate

func (b *Builder) UpdateOrCreate(model interface{}, attributes, values map[string]interface{}) error

UpdateOrCreate 按 attributes 查找;命中则更新 values,未命中则创建 (转发 Connection.UpdateOrCreate)。

func (*Builder) UpdateOrInsert

func (b *Builder) UpdateOrInsert(attributes, value map[string]interface{}) (bool, error)

UpdateOrInsert 存在则更新,否则插入。

func (*Builder) Upsert

func (b *Builder) Upsert(values []interface{}, uniqueBy, update []string) (int64, error)

Upsert upsert:uniqueBy 为唯一键列,update 为冲突时更新的列。 update 为空切片 → 普通 insert;update 为 nil → 全列更新(取首行的列); uniqueBy 为空抛错;values 为空返回 0。 map 行按 key 排序;query.Row 保序。

func (*Builder) UseIndex

func (b *Builder) UseIndex(index string) *Builder

UseIndex 设置索引提示(use index)。

func (*Builder) UseWritePdo

func (b *Builder) UseWritePdo() *Builder

UseWritePdo 强制 select 走写连接。

func (*Builder) Value

func (b *Builder) Value(column string) (any, error)

Value 取单个值(select col limit 1)。

func (*Builder) When

func (b *Builder) When(condition bool, callback func(*Builder), defaultCallback ...func(*Builder)) *Builder

When / Unless 条件执行:Go 侧条件为 bool。

func (*Builder) Where

func (b *Builder) Where(column interface{}, args ...interface{}) *Builder

Where 基础 where:Where(column, value) / Where(column, operator, value, boolean...)。 column 可为字符串、grammar.Expression、map(批量 and)、func(*Builder)(括号分组)或 *Builder(子查询比较)。

func (*Builder) WhereAll

func (b *Builder) WhereAll(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder

WhereAll 多列 and 组内条件: where (a = ? and b = ?)。

func (*Builder) WhereAny

func (b *Builder) WhereAny(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder

WhereAny 多列 or 组内条件:where (a = ? or b = ?)。

func (*Builder) WhereBelongsTo

func (b *Builder) WhereBelongsTo(parent any, foreignKey ...string) *Builder

WhereBelongsTo 按父模型过滤: where <singular(parentTable)_id | foreignKey> = parent 主键。

func (*Builder) WhereBetween

func (b *Builder) WhereBetween(column interface{}, values []interface{}, args ...interface{}) *Builder

WhereBetween / OrWhereBetween / WhereNotBetween / OrWhereNotBetween

func (*Builder) WhereBetweenColumns

func (b *Builder) WhereBetweenColumns(column interface{}, values []interface{}) *Builder

WhereBetweenColumns / OrWhereBetweenColumns / WhereNotBetweenColumns / OrWhereNotBetweenColumns 两列比较的 between:values 为列名,不产生绑定。

func (*Builder) WhereColumn

func (b *Builder) WhereColumn(first interface{}, args ...interface{}) *Builder

WhereColumn 比较两列:WhereColumn(first, second) / (first, operator, second, boolean...)。 非法操作符时回退为两参等值比较(first = second)。

func (*Builder) WhereDate

func (b *Builder) WhereDate(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereDay

func (b *Builder) WhereDay(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereDoesntHave

func (b *Builder) WhereDoesntHave(rel Relation, constraints func(*Builder)) *Builder

WhereDoesntHave 关系不存在性约束。

func (*Builder) WhereExists

func (b *Builder) WhereExists(q interface{}) *Builder

WhereExists / OrWhereExists / WhereNotExists / OrWhereNotExists q 可为 func(*Builder)/func(*Builder) *Builder/ *Builder/*query.Query 闭包或子查询。

func (*Builder) WhereExpression

func (b *Builder) WhereExpression(condition interface{}, boolean ...string) *Builder

WhereExpression 添加条件表达式: 条件原样进入 where,不追加操作符与绑定。

func (*Builder) WhereFullText

func (b *Builder) WhereFullText(columns interface{}, value interface{}, options ...map[string]interface{}) *Builder

WhereFullText 全文检索:columns、value 与可选 options。

func (*Builder) WhereHas

func (b *Builder) WhereHas(rel Relation, constraints func(*Builder)) *Builder

WhereHas 关系存在性约束:where exists (select * from target where keys... and constraints...) 支持 HasOne/HasMany/MorphMany/MorphOne/BelongsToMany(经 pivot 中间表)/ HasManyThrough/MorphToMany;MorphTo 无法静态判定目标类型,静默跳过(防 panic)。

func (*Builder) WhereHasMorph

func (b *Builder) WhereHasMorph(rel MorphMany, types []string, constraints ...func(*Builder)) *Builder

WhereHasMorph 多态关系存在性约束: 子查询带 type 列 in (types) 过滤,types 为候选 morph key (如 []string{"posts", "videos"});constraints 应用在目标查询上。

func (*Builder) WhereIn

func (b *Builder) WhereIn(column interface{}, values interface{}, args ...interface{}) *Builder

WhereIn / OrWhereIn / WhereNotIn / OrWhereNotIn

func (*Builder) WhereIntegerInRaw

func (b *Builder) WhereIntegerInRaw(column interface{}, values []interface{}) *Builder

WhereIntegerInRaw / OrWhereIntegerInRaw / WhereIntegerNotInRaw / OrWhereIntegerNotInRaw 整型值以 raw 形式内联进 SQL,不产生绑定。

func (*Builder) WhereIntegerNotInRaw

func (b *Builder) WhereIntegerNotInRaw(column interface{}, values []interface{}) *Builder

func (*Builder) WhereJsonContains

func (b *Builder) WhereJsonContains(column interface{}, value interface{}) *Builder

func (*Builder) WhereJsonContainsKey

func (b *Builder) WhereJsonContainsKey(column interface{}) *Builder

func (*Builder) WhereJsonDoesntContain

func (b *Builder) WhereJsonDoesntContain(column interface{}, value interface{}) *Builder

func (*Builder) WhereJsonDoesntContainKey

func (b *Builder) WhereJsonDoesntContainKey(column interface{}) *Builder

func (*Builder) WhereJsonDoesntHaveLength

func (b *Builder) WhereJsonDoesntHaveLength(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereJsonDoesntOverlap

func (b *Builder) WhereJsonDoesntOverlap(column interface{}, value interface{}) *Builder

func (*Builder) WhereJsonLength

func (b *Builder) WhereJsonLength(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereJsonOverlaps

func (b *Builder) WhereJsonOverlaps(column interface{}, value interface{}) *Builder

func (*Builder) WhereKey

func (b *Builder) WhereKey(id interface{}) *Builder

WhereKey 按主键添加 where:id 可为主键值、 模型实例(取其主键值)或切片(编译为 whereIn)。

func (*Builder) WhereKeyNot

func (b *Builder) WhereKeyNot(id interface{}) *Builder

WhereKeyNot 按主键添加排除 where: 切片编译为 whereNotIn,单值编译为 !=。

func (*Builder) WhereLike

func (b *Builder) WhereLike(column interface{}, value interface{}, caseSensitive bool) *Builder

WhereLike / OrWhereLike / WhereNotLike / OrWhereNotLike 大小写敏感性由 caseSensitive 参数控制。

func (*Builder) WhereMonth

func (b *Builder) WhereMonth(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereMorphedTo

func (b *Builder) WhereMorphedTo(morphName string, target any) *Builder

WhereMorphedTo 匹配多态列指向特定目标的行: target 为已持久化模型实例(匹配 type + id)或模型零值(仅匹配 type)。

func (*Builder) WhereNested

func (b *Builder) WhereNested(callback func(*Builder), boolean ...string) *Builder

WhereNested 括号分组:WhereNested(func(nb *Builder){ nb.Where(...) })。

func (*Builder) WhereNone

func (b *Builder) WhereNone(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder

WhereNone 多列均不满足(or 组内条件整体取反)。

func (*Builder) WhereNot

func (b *Builder) WhereNot(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereNotBetween

func (b *Builder) WhereNotBetween(column interface{}, values []interface{}, args ...interface{}) *Builder

func (*Builder) WhereNotBetweenColumns

func (b *Builder) WhereNotBetweenColumns(column interface{}, values []interface{}) *Builder

func (*Builder) WhereNotExists

func (b *Builder) WhereNotExists(q interface{}) *Builder

func (*Builder) WhereNotIn

func (b *Builder) WhereNotIn(column interface{}, values interface{}, args ...interface{}) *Builder

func (*Builder) WhereNotLike

func (b *Builder) WhereNotLike(column interface{}, value interface{}, caseSensitive bool) *Builder

func (*Builder) WhereNotNull

func (b *Builder) WhereNotNull(columns interface{}, args ...interface{}) *Builder

func (*Builder) WhereNull

func (b *Builder) WhereNull(columns interface{}, args ...interface{}) *Builder

WhereNull / OrWhereNull / WhereNotNull / OrWhereNotNull 签名等价 whereNull(columns, boolean='and', not=false):columns 支持单列、 []string / []interface{} 多列(每列一条 where),第二参数为 boolean。

func (*Builder) WhereNullSafeEquals

func (b *Builder) WhereNullSafeEquals(column interface{}, value interface{}) *Builder

WhereNullSafeEquals 空安全等值比较(对应 whereNullSafeEquals): 编译为 is not distinct from(MySQL/SqlServer/SQLite 有方言实现, 基础方言走 is not distinct from)。

func (*Builder) WhereRaw

func (b *Builder) WhereRaw(sql interface{}, bindings ...interface{}) *Builder

WhereRaw / OrWhereRaw 签名等价 whereRaw(sql, bindings, boolean='and'):可选末位 string 参数 为 boolean 关键字(and / or / and not / or not)。

func (*Builder) WhereRowValues

func (b *Builder) WhereRowValues(columns []interface{}, operator string, values []interface{}) *Builder

WhereRowValues / OrWhereRowValues: 行值比较 (a, b) = (?, ?);列数与值数必须一致。

func (*Builder) WhereTime

func (b *Builder) WhereTime(column interface{}, args ...interface{}) *Builder

func (*Builder) WhereValueBetween

func (b *Builder) WhereValueBetween(value interface{}, columns []interface{}) *Builder

WhereValueBetween 值介于两列之间:where ? between min and max (第一参数为值, 第二参数为 [下界列, 上界列] 两元素切片)。

func (*Builder) WhereValueNotBetween

func (b *Builder) WhereValueNotBetween(value interface{}, columns []interface{}) *Builder

WhereValueNotBetween 值不介于两列之间(对应 whereValueNotBetween)。

func (*Builder) WhereYear

func (b *Builder) WhereYear(column interface{}, args ...interface{}) *Builder

func (*Builder) With

func (b *Builder) With(name string, rel Relation) *Builder

With 预加载关系:Get 时自动执行关联查询并填充结构体字段 (字段名 = 关系名 StudlyCase;BelongsTo/HasOne 填 *T,HasMany 填 []T)。

func (*Builder) WithAggregate

func (b *Builder) WithAggregate(name string, rel Relation, function, column string, alias ...string) *Builder

WithAggregate 通用关系聚合子查询: select (select fn(col) from target where keys...) as "name_fn_col | alias"。

func (*Builder) WithAvg

func (b *Builder) WithAvg(name string, rel Relation, column string, alias ...string) *Builder

WithAvg 关系平均值聚合。

func (*Builder) WithConstraints

func (b *Builder) WithConstraints(name string, rel Relation, constraints ...func(*Builder)) *Builder

WithConstraints 带约束闭包的预加载(对应 with(['name' => fn($q) => ...]))。

func (*Builder) WithCount

func (b *Builder) WithCount(name string, rel Relation, rest ...any) *Builder

WithCount 关系计数子查询:select (select count(*) ...) as "name_count"。 增强形态(对应 QueriesRelationships::withCount):

  • 约束闭包:WithCount("posts", HasMany{...}, func(nb *Builder){...})
  • 多关系:链式多次调用
  • 嵌套点语法:WithCount("posts.comments", postsRel, commentsRel) (后续描述符逐层下钻,编译为嵌套 exists)

func (*Builder) WithExists

func (b *Builder) WithExists(name string, rel Relation, alias ...string) *Builder

WithExists 关系存在性聚合:select (select exists(...) ...) as "name_exists"。

func (*Builder) WithExpression

func (b *Builder) WithExpression(name string, q interface{}, columns ...string) *Builder

WithExpression 注册公用表表达式:with "name" (columns...) as (sub) q 可为 *Builder / *query.Query / 闭包。

func (*Builder) WithLimit

func (b *Builder) WithLimit(name string, rel Relation, limit int64, constraints ...func(*Builder)) *Builder

WithLimit 带限额的预加载:自动经 GroupLimit(row_number 分组)实现每组限额。

func (*Builder) WithMax

func (b *Builder) WithMax(name string, rel Relation, column string, alias ...string) *Builder

WithMax 关系最大值聚合。

func (*Builder) WithMin

func (b *Builder) WithMin(name string, rel Relation, column string, alias ...string) *Builder

WithMin 关系最小值聚合。

func (*Builder) WithRecursiveExpression

func (b *Builder) WithRecursiveExpression(name string, q interface{}, columns ...string) *Builder

WithRecursiveExpression 注册递归 CTE(with recursive)。

func (*Builder) WithSum

func (b *Builder) WithSum(name string, rel Relation, column string, alias ...string) *Builder

WithSum 关系求和聚合。

func (*Builder) WithTrashed

func (b *Builder) WithTrashed() *Builder

WithTrashed 去掉软删约束(对应 SoftDeletingScope 的 withTrashed 宏)。

func (*Builder) WithoutTrashed

func (b *Builder) WithoutTrashed() *Builder

WithoutTrashed 只查未软删的行:deleted_at IS NULL(对应 withoutTrashed 宏,默认态)。

type Collection

type Collection[T any] []T

Collection 泛型集合。

func Col

func Col[T any](items []T) Collection[T]

Col 把切片包装为集合。

func Collapse

func Collapse[T any](nested Collection[[]T]) Collection[T]

Collapse 展开嵌套集合一层。 集合元素为切片类型时的包级形态(Go 方法不能按 T 约束特化)。

func (Collection[T]) Average

func (c Collection[T]) Average(fields ...string) float64

Average 数值平均(空集合返回 0)。

func (Collection[T]) Chunk

func (c Collection[T]) Chunk(size int) [][]T

Chunk 按 size 固定大小切块:最后一块可小于 size; size <= 0 返回 nil;空集合返回空切片。

func (Collection[T]) Clone

func (c Collection[T]) Clone() Collection[T]

Clone 浅拷贝(返回独立切片)。

func (Collection[T]) Contains

func (c Collection[T]) Contains(pred func(T) bool) bool

Contains 是否存在满足条件的元素(谓词形态)。

func (Collection[T]) ContainsValue

func (c Collection[T]) ContainsValue(want T) bool

ContainsValue 精确值形态(DeepEqual 比较)。

func (Collection[T]) ContainsWhere

func (c Collection[T]) ContainsWhere(field string, args ...any) bool

ContainsWhere 字段条件形态的 contains(支持 ('field', 'value') 与 ('field', '>', value) 两种形态)。

func (Collection[T]) CountBy

func (c Collection[T]) CountBy(keyFn func(T) string) map[string]int

CountBy 按回调结果分组计数(返回 map[回调值]计数; 仅有 bool 谓词形态时键为 "true"/"false")。

func (Collection[T]) CountWhere

func (c Collection[T]) CountWhere(pred func(T) bool) int

CountWhere 满足谓词的元素个数(torm 保留的原"CountBy"语义)。

func (Collection[T]) CrossJoin

func (c Collection[T]) CrossJoin[U any](other []U) []ZipPair[T, U]

CrossJoin 与另一切片做笛卡尔积(单数组形态): 复用 ZipPair 泛型对承载 (本集合元素, other 元素);任一侧为空返回空切片。

func (Collection[T]) Diff

func (c Collection[T]) Diff(other Collection[T]) Collection[T]

Diff 差集:本集合有、other 没有的元素。

func (Collection[T]) DoesntContain

func (c Collection[T]) DoesntContain(pred func(T) bool) bool

DoesntContain contains 的否定形态。

func (Collection[T]) DoesntContainWhere

func (c Collection[T]) DoesntContainWhere(field string, args ...any) bool

DoesntContainWhere 字段条件的否定形态。

func (Collection[T]) Duplicates

func (c Collection[T]) Duplicates() Collection[T]

Duplicates 重复元素:所有出现次数大于 1 的 值的全部出现位置,保持原顺序(与 Unique/Diff 一致按 Sprint 键判定)。

func (Collection[T]) Each

func (c Collection[T]) Each(fn func(item T, index int) bool)

Each 遍历;回调返回 false 停止(break 语义)。

func (Collection[T]) Every

func (c Collection[T]) Every(pred func(T) bool) bool

Every 是否全部元素满足条件:空集合返回 true。

func (Collection[T]) Except

func (c Collection[T]) Except(keys ...string) []map[string]any

Except 排除指定字段后的投影。

func (Collection[T]) Filter

func (c Collection[T]) Filter(pred func(T) bool) Collection[T]

Filter 过滤。

func (Collection[T]) FilterBoth

func (c Collection[T]) FilterBoth(pred func(item T, index int) bool) Collection[T]

FilterBoth 带索引的过滤(回调同时接收元素与下标的双参形态)。

func (Collection[T]) Find

func (c Collection[T]) Find(id any) (T, bool)

Find 按主键值查找;Go 侧按 pluck 字段比对。

func (Collection[T]) FindOrFail

func (c Collection[T]) FindOrFail(id any) (T, error)

FindOrFail 按主键查找,找不到返回错误。

func (Collection[T]) First

func (c Collection[T]) First(pred func(T) bool) (T, bool)

First 返回首个满足条件的元素(pred 为 nil 时取第一个)。

func (Collection[T]) FirstWhere

func (c Collection[T]) FirstWhere(field string, args ...any) (T, bool)

FirstWhere 按字段条件取首个元素:

FirstWhere("name", "A")            // 等于
FirstWhere("age", ">", 18)         // 运算符形态(= != <> < <= > >=)

func (Collection[T]) Flatten

func (c Collection[T]) Flatten(depth ...int) Collection[any]

Flatten 展开嵌套切片(depth 缺省 1 层, 元素展开为 any)。

func (Collection[T]) Forget

func (c Collection[T]) Forget(indices ...int) Collection[T]

Forget 移除指定下标(可变参)的元素: 越界下标忽略;返回保留原顺序的新集合;无下标时等价 Clone。

func (Collection[T]) Fresh

func (c Collection[T]) Fresh(conn *Connection) (Collection[T], error)

Fresh 按主键重查每个模型为新集合:原集合不变;行未命中的位置保留 零值占位(指针元素为 nil,保留原键位)。

func (Collection[T]) GetDictionary

func (c Collection[T]) GetDictionary() map[string]T

GetDictionary 按主键的字典 map:键 = 模型主键的 Sprint 形式;非模型元素 以元素本身的 Sprint 为键。

func (Collection[T]) GetVisible

func (c Collection[T]) GetVisible() ([]string, error)

GetVisible 可见列集(torm 只维护 hidden 注册表,此处返回首模型全部列减去隐藏列的可见集)。

func (Collection[T]) GroupBy

func (c Collection[T]) GroupBy(keyFn func(T) string) map[string][]T

GroupBy 按回调结果分组:键为分组值,组内保持 出现顺序;Go map 无序,确定性键序用 SortKeys(grouped) 取。

func (Collection[T]) Implode

func (c Collection[T]) Implode(glue string, fields ...string) string

Implode 拼接:给定时按字段提取,否则对元素 Sprint 后拼接。

func (Collection[T]) Intersect

func (c Collection[T]) Intersect(other Collection[T]) Collection[T]

Intersect 交集:两边都有的元素,保留本集合顺序。

func (Collection[T]) IsEmpty

func (c Collection[T]) IsEmpty() bool

IsEmpty / IsNotEmpty。

func (Collection[T]) IsNotEmpty

func (c Collection[T]) IsNotEmpty() bool

func (Collection[T]) KeyBy

func (c Collection[T]) KeyBy(keyFn func(T) string) map[string]T

KeyBy 以回调结果为键重建 map:重复键后出现覆盖 先出现(PHP 数组赋值语义);空集合返回空 map。

func (Collection[T]) Keys

func (c Collection[T]) Keys() []int

Keys 键序列:Go 集合底座为切片,键即下标 0..n-1。

func (Collection[T]) Last

func (c Collection[T]) Last(pred func(T) bool) (T, bool)

Last 返回最后一个满足条件的元素:pred 为 nil 时取 最后一个;空集合或无匹配返回零值与 false。

func (Collection[T]) Len

func (c Collection[T]) Len() int

Len 元素个数。

func (Collection[T]) MakeHidden

func (c Collection[T]) MakeHidden(keys ...string) (Collection[T], error)

MakeHidden 集合内全部模型追加隐藏列。

func (Collection[T]) MakeVisible

func (c Collection[T]) MakeVisible(keys ...string) (Collection[T], error)

MakeVisible 集合内全部模型解除隐藏列。

func (Collection[T]) Map

func (c Collection[T]) Map[U any](fn func(T) U) []U

Map 映射为新切片。

func (Collection[T]) MapWithKeys

func (c Collection[T]) MapWithKeys[K comparable, V any](fn func(T) (K, V)) map[K]V

MapWithKeys 映射为 map(回调返回 (key, value))。

func (Collection[T]) Max

func (c Collection[T]) Max(fields ...string) any

Max 最大值。

func (Collection[T]) Median

func (c Collection[T]) Median(fields ...string) float64

Median 中位数:数值升序取中位,偶数个取中间 两数的平均;可传字段名(sum/average 同风格);无数值或空集合返回 0。

func (Collection[T]) Merge

func (c Collection[T]) Merge(other Collection[T]) Collection[T]

Merge 追加合并。

func (Collection[T]) MergeHidden

func (c Collection[T]) MergeHidden(keys ...string) (Collection[T], error)

MergeHidden 集合内全部模型合并隐藏列(语义与 MakeHidden 一致,追加去重)。

func (Collection[T]) Min

func (c Collection[T]) Min(fields ...string) any

Min 最小值:无字段名时比较元素本身, 返回 any(空集合返回 nil)。

func (Collection[T]) Mode

func (c Collection[T]) Mode() (T, bool)

Mode 众数:按 Sprint 键计数取频次最高的元素; 并列时取原顺序中最先出现者;空集合返回 (零值, false)。

func (Collection[T]) ModelKeys

func (c Collection[T]) ModelKeys() []any

ModelKeys 提取主键集合。

func (Collection[T]) Only

func (c Collection[T]) Only(keys ...string) []map[string]any

Only 取每项的指定字段投影为 map(结构体集合上按 Go 字段名/torm 列名提取)。

func (Collection[T]) Pad

func (c Collection[T]) Pad(size int, def T) Collection[T]

Pad 补齐到指定长度:size 为正从尾部补 def, 为负从头部补;|size| 不大于原长度时截断。

func (Collection[T]) Partition

func (c Collection[T]) Partition(pred func(T) bool) (Collection[T], Collection[T])

Partition 按谓词一分为二:(满足, 不满足)。

func (Collection[T]) Pluck

func (c Collection[T]) Pluck(field string) []any

Pluck 按字段名(torm 列名或 Go 字段名)提取值集合。

func (Collection[T]) Pop

func (c Collection[T]) Pop() (T, Collection[T], bool)

Pop 弹出最后一个元素:返回 (末元素, 去掉末元素的 新集合, 是否成功);空集合返回 (零值, 空集合, false)。

func (Collection[T]) Pull

func (c Collection[T]) Pull(index int) (T, Collection[T], bool)

Pull 取走指定下标元素并从集合移除(键即切片 下标):返回 (元素, 移除后的新集合, 是否成功);下标越界返回 (零值, 原集合, false)。

func (Collection[T]) Push

func (c Collection[T]) Push(item T) Collection[T]

Push 追加单个元素。Go 侧沿用本集合层的不可变 约定:返回追加后的新集合,原集合不变。

func (Collection[T]) Random

func (c Collection[T]) Random(n int) Collection[T]

Random 随机取 n 个:抽 n 个不重复下标后按 原顺序输出(保序语义);n <= 0 返回空集合; n 大于长度时收敛为长度(Go 侧按惯例收敛)。

func (Collection[T]) Reduce

func (c Collection[T]) Reduce[U any](fn func(acc U, item T) U, initial U) U

Reduce 折叠。

func (Collection[T]) Reject

func (c Collection[T]) Reject(pred func(T) bool) Collection[T]

Reject 过滤的逆操作。

func (Collection[T]) Reverse

func (c Collection[T]) Reverse() Collection[T]

Reverse 倒序。

func (Collection[T]) SetHidden

func (c Collection[T]) SetHidden(keys ...string) (Collection[T], error)

SetHidden 替换集合内全部模型的隐藏列集:先全量 MakeVisible 清空再追加新集。

func (Collection[T]) Shuffle

func (c Collection[T]) Shuffle() Collection[T]

Shuffle 随机打乱:math/rand 全局 rand.Shuffle, 返回打乱后的新集合,原集合不变。

func (Collection[T]) Skip

func (c Collection[T]) Skip(n int) Collection[T]

Skip 跳过前 n 个。

func (Collection[T]) Slice

func (c Collection[T]) Slice() []T

Slice 返回底层切片。

func (Collection[T]) SliceRange

func (c Collection[T]) SliceRange(offset, length int) Collection[T]

SliceRange 子切片(slice($offset, $length) 语义):offset 起始, length 为个数,负值 length 表示取到末尾(等价 null 语义)。 与 Slice()(返回底层切片)并存,以 Range 后缀区分。

func (Collection[T]) Some

func (c Collection[T]) Some(pred func(T) bool) bool

Some 是否存在满足条件的元素(contains 的别名)。

func (Collection[T]) SortBy

func (c Collection[T]) SortBy(less func(a, b T) bool) Collection[T]

SortBy 比较函数排序(稳定;Go 侧传 less 闭包)。

func (Collection[T]) SortByDesc

func (c Collection[T]) SortByDesc(less func(a, b T) bool) Collection[T]

SortByDesc 降序排序:对齐既有 SortBy 的 less 比较器约定,稳定排序;返回新集合。

func (Collection[T]) Split

func (c Collection[T]) Split(n int) [][]T

Split 按组数均分:组大小取 ceil(len/n)(向上取整),末组可更短;n <= 0 返回 nil;空集合返回空切片。

func (Collection[T]) Sum

func (c Collection[T]) Sum(fields ...string) float64

Sum 数值求和:无字段名时直接对元素求和,有字段名时按字段提取 (非数值跳过)。

func (Collection[T]) Take

func (c Collection[T]) Take(n int) Collection[T]

Take 取前 n 个。

func (Collection[T]) TakeUntil

func (c Collection[T]) TakeUntil(pred func(T) bool) Collection[T]

TakeUntil 取到首个满足条件的元素为止(不含该元素,任务清单中的 Until 方法):无元素满足时返回全量;空集合返回空。

func (Collection[T]) Tap

func (c Collection[T]) Tap(fn func(Collection[T])) Collection[T]

Tap 副作用钩子:调用 fn(c) 后原样返回集合。

func (Collection[T]) ToJson

func (c Collection[T]) ToJson() (string, error)

ToJson 序列化为 JSON。

func (Collection[T]) ToQuery

func (c Collection[T]) ToQuery(conn *Connection) (*Builder, error)

ToQuery 首个模型的新查询构造器(以集合首模型 的 newQuery 为底座)。集合为空、conn 为 nil 或元素不是模型时报错 (Go 模型不内嵌连接,需显式传入连接上下文)。

func (Collection[T]) Union

func (c Collection[T]) Union(other Collection[T]) Collection[T]

Union 合并去重(保留首次出现;Go 侧按 Sprint 键判定重复)。

func (Collection[T]) Unique

func (c Collection[T]) Unique() Collection[T]

Unique 去重(保留首次出现)。

func (Collection[T]) UniqueBy

func (c Collection[T]) UniqueBy(key func(T) any) Collection[T]

UniqueBy 按键函数去重。

func (Collection[T]) Unless

func (c Collection[T]) Unless(cond bool, fn func(Collection[T]) Collection[T]) Collection[T]

Unless 条件为假时应用变换。

func (Collection[T]) When

func (c Collection[T]) When(cond bool, fn func(Collection[T]) Collection[T]) Collection[T]

When 条件为真时应用变换。

func (Collection[T]) Zip

func (c Collection[T]) Zip[U any](other []U) []ZipPair[T, U]

Zip 与另一切片按位配对,长度取较小者(Go 侧不产生 null 占位,多余元素丢弃)。

type Config

type Config struct {
	// Database 数据库名(对应 config['database'],内省与
	// CreateDatabase 使用)
	Database string

	Driver  string
	Prefix  string
	Dsn     string
	ReadDsn string // 兼容:单个只读 DSN(读写分离,select 类查询路由到此)
	// ReadDsns 只读 DSN 池:建连时随机选一(对应配置 read 数组 + Arr::random)。
	ReadDsns []string
	// Sticky sticky 模式:本连接发生写操作后,后续读强制走主连接
	// (对应配置 sticky,配合 recordsModified 跟踪)。
	Sticky bool
	// StickyWindowSec sticky 时间窗(秒):>0 时写后该窗口内读走主库、
	// 窗口外恢复读写分离(默认 0 = 进程生命周期内永久粘主,1.x 语义;
	// 其他实现为请求级语义,Go 无请求上下文时建议配置窗口)。
	StickyWindowSec int

	// MySQL 连接参数(MySqlConnector 自动附加到 DSN,已有参数不覆盖)
	Charset   string // NAMES charset
	Collation string // COLLATE collation
	SqlMode   string // SESSION sql_mode
	Timezone  string // time_zone
	// Modes sql_mode 数组(对应 config['modes'],join 后优先于 SqlMode 单串)
	Modes []string

	// Postgres / SQLServer
	IsolationLevel string // 会话事务隔离级别(建连后以 SET 语句生效)
	SslMode        string // Postgres sslmode
	SearchPath     string // Postgres search_path
	SslCert        string // Postgres sslcert DSN 参数
	SslKey         string // Postgres sslkey DSN 参数
	SslRootCert    string // Postgres sslrootcert DSN 参数
	// SynchronousCommit Postgres synchronous_commit(建连后 set synchronous_commit to)
	SynchronousCommit string
	// ClientEncoding / ApplicationName Postgres DSN 参数
	ClientEncoding  string
	ApplicationName string

	// SQLite pragmas
	ForeignKeys *bool  // PRAGMA foreign_keys(nil = 默认开启,与 sqlite 默认 foreign_keys=true 一致)
	BusyTimeout int    // PRAGMA busy_timeout(毫秒,0 表示不设置)
	JournalMode string // PRAGMA journal_mode
	Synchronous string // PRAGMA synchronous
	// Pragmas 自定义 pragma 集合(对应 config['pragmas'],经 DSN _pragma 参数生效,
	// 连接池下每个物理连接均生效)
	Pragmas map[string]string

	// MySQL 方言开关(GetQueryGrammar 注入;此前仅 schema 侧可达,查询侧死代码)
	ServerVersion       string // 如 "8.0.36" / "10.5.2-MariaDB"(MySQL 5.7 分支、JSON 能力判定)
	IsMariaDB           bool   // driver="mysql" 但实际为 MariaDB 时标记(影响 JSON/upsert 编译)
	UseUpsertAlias      *bool  // MySQL 8.0.19+ 关闭 as 别名 upsert(nil = 按版本推断)
	UseLegacyGroupLimit bool   // SQLite < 3.25 的 groupLimit 降级分支

	// 连接池调优(对应 database/sql 的 Set* API;0 值 = 不设置,保留驱动默认)
	MaxOpenConns       int
	MaxIdleConns       int
	ConnMaxLifetimeSec int // 连接最长存活时间(秒,0 = 不设置)
	ConnMaxIdleTimeSec int // 连接最长空闲时间(秒,0 = 不设置)

	// ParseTime MySQL DSN 是否自动附加 parseTime=true(nil/true = 附加,
	// time.Time 字段扫描必需;显式 false 关闭注入)
	ParseTime *bool
}

Config 连接配置(对应配置文件中的 database.connections 节点)。

type Connection

type Connection struct {
	DB *sql.DB
	// contains filtered or unexported fields
}

func Open

func Open(config Config) (*Connection, error)

Open 按配置建立连接(连接池惰性建连;驱动路由到对应 Connector)。

func (*Connection) AddObserver

func (c *Connection) AddObserver(model any, o *Observer)

AddObserver 追加注册观察者(observe 可叠加语义; 按注册顺序执行,任一返回 error 中断)。

func (*Connection) AfterCommit

func (c *Connection) AfterCommit(fn func())

AfterCommit 注册事务提交后的回调;注册时无活动事务则立即执行,嵌套事务中 注册的回调在其所在层级提交时上浮,最外层提交后统一执行;所在事务回滚时被 丢弃(对齐 DatabaseTransactionsManager::addCallback)。

func (*Connection) AfterRollBack

func (c *Connection) AfterRollBack(fn func())

AfterRollBack 注册回滚回调:所在事务(或其内层)发生回滚时执行。无活动 事务时回调被静默丢弃(对齐 DatabaseTransactionsManager::addCallbackForRollback)。

func (*Connection) Attach

func (c *Connection) Attach(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) error

Attach 建立 pivot 关联(对应 attach;BelongsToMany / MorphToMany 均可): 单条多值 INSERT(每 100 行一批,规避 SQLite 变量上限与 SQLServer 1000 行 限制);pivotAttrs 为附加列值,WithPivotValue 固定值打底、显式 attrs 覆盖; PivotTimestamps 时自动带 created_at/updated_at。parent 可为模型或其主键值。

func (*Connection) AttachOrFail

func (c *Connection) AttachOrFail(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any)

AttachOrFail 建立 pivot 关联,失败 panic *FailError{Op:"attach"}。

func (*Connection) BeforeExecuting

func (c *Connection) BeforeExecuting(fn func(query string, bindings []any))

BeforeExecuting 注册每条语句执行前的回调。

func (*Connection) BeforeStartingTransaction

func (c *Connection) BeforeStartingTransaction(fn func())

BeforeStartingTransaction 注册事务开始前的回调。

func (*Connection) BeginTransaction

func (c *Connection) BeginTransaction() error

BeginTransaction 开启事务;嵌套时创建 savepoint(嵌套事务管理)。 level 0 的 BEGIN 遇断连错误重连后重试一次 (handleBeginTransactionException)。

func (*Connection) Commit

func (c *Connection) Commit() error

Commit 提交当前事务层;仅最外层提交到数据库。afterCommit 回调在释放事务 锁之后执行:回调内允许再次调用 TransactionLevel/AfterCommit/Commit 而不会 自死锁(commit() 在锁外通知 manager)。

func (*Connection) Create

func (c *Connection) Create(model interface{}) error

Create Save a new model to the database(保存新模型,事件顺序: saving → creating → 时间戳 → insert → created → saved)。

func (*Connection) CreateManyQuietly

func (c *Connection) CreateManyQuietly(model any, rows []map[string]any) error

CreateManyQuietly 以 model 为原型批量静默创建(每行一个新实例)。

func (*Connection) CreateOrFirst

func (c *Connection) CreateOrFirst(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

CreateOrFirst 先尝试创建,唯一约束冲突时回退按 attributes 查询 (createOrFirst 的并发安全语义)。

func (*Connection) CreateOrRestore

func (c *Connection) CreateOrRestore(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

CreateOrRestore 软删模型版 createOrFirst:先创建,唯一约束冲突时 withTrashed 查回已存在行并恢复(createOrRestore 语义)。

func (*Connection) CreateQuietly

func (c *Connection) CreateQuietly(model any) error

CreateQuietly 创建模型但不触发任何事件。

func (*Connection) CursorQuery

func (c *Connection) CursorQuery(query string, bindings []interface{}, forceWrite bool) (iter.Seq2[map[string]any, error], error)

CursorQuery 打开流式查询;返回的迭代器逐行产出 map,迭代结束或提前终止时自动关闭。 扫描/驱动错误通过 iter.Seq2 的 error 通道传出。

func (*Connection) Decrement

func (c *Connection) Decrement(model any, column string, amount ...any) error

Decrement 自减一列;amount 缺省 1,可传 map[string]any 作为 extra 附加列。

func (*Connection) DecrementEach

func (c *Connection) DecrementEach(model any, columns map[string]int64, extra ...map[string]any) error

DecrementEach 一条 UPDATE 内自减多列。

func (*Connection) Delete

func (c *Connection) Delete(query string, args ...interface{}) (int64, error)

Delete Run a delete statement against the database.

func (*Connection) DeleteModel

func (c *Connection) DeleteModel(model interface{}) error

DeleteModel 删除模型:软删除模型置 deleted_at(同步 updated_at), 否则硬删除(命名避开 Connection.Delete 的原生 SQL 方法;模型删除 与软删:deleting → UPDATE → trashed → deleted)。

func (*Connection) DeleteOrFail

func (c *Connection) DeleteOrFail(model any) error

DeleteOrFail 删除模型,失败 panic *FailError。

func (*Connection) DeleteQuietly

func (c *Connection) DeleteQuietly(model any) error

DeleteQuietly 删除模型但不触发任何事件。

func (*Connection) Destroy

func (c *Connection) Destroy(model interface{}) error

Destroy 按主键硬删除模型行(delete 的硬删分支); 主键为空时返回错误,绝不执行整表 DELETE。

func (*Connection) DestroyByIDs

func (c *Connection) DestroyByIDs(model interface{}, ids ...interface{}) (int, error)

DestroyByIDs 按主键批量删除(静态 destroy 语义:逐个加载模型并 走完整删除生命周期,软删模型执行软删)。返回成功删除的个数。

func (*Connection) Detach

func (c *Connection) Detach(parent any, rel PivotRelation, ids ...any) (int64, error)

Detach 解除 pivot 关联(对应 detach):ids 为空时解除全部,返回受影响行数。

func (*Connection) DetachOrFail

func (c *Connection) DetachOrFail(parent any, rel PivotRelation, ids ...any) int64

DetachOrFail 解除 pivot 关联,失败 panic *FailError{Op:"detach"},返回受影响行数。

func (*Connection) DisableQueryLog

func (c *Connection) DisableQueryLog()

DisableQueryLog 关闭内存查询日志(不清空已记录内容)。

func (*Connection) Driver

func (c *Connection) Driver() string

Driver 返回连接驱动名。

func (*Connection) Dsn

func (c *Connection) Dsn() string

SetDsn 内部接线(Open 后由 Connection 注入)。

func (*Connection) EnableQueryLog

func (c *Connection) EnableQueryLog()

EnableQueryLog 开启内存查询日志。

func (*Connection) Escape

func (c *Connection) Escape(value any, binary ...bool) (string, error)

Escape 为安全 SQL 内嵌转义值(对应 Connection::escape):null → 'null'、 bool 按 escapeBool、整数/浮点原样、字符串单引号双写(含 NUL 字节或非法 UTF-8 时报错);binary=true 时按方言转义二进制。

func (*Connection) FirstOrCreate

func (c *Connection) FirstOrCreate(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

FirstOrCreate 按 attributes 查找;未命中则合并 attributes+values 创建模型 (firstOrCreate(attributes, values) 语义:赋值走 fill 守卫语义)。

func (*Connection) FirstOrNew

func (c *Connection) FirstOrNew(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

FirstOrNew 按 attributes 查找;未命中仅以 attributes+values 构造不落库 (firstOrNew(attributes, values) 语义)。

func (*Connection) FlushQueryLog

func (c *Connection) FlushQueryLog()

FlushQueryLog 清空查询日志。

func (*Connection) ForceDelete

func (c *Connection) ForceDelete(model interface{}) error

ForceDelete 绕过软删除硬删除;主键为空时返回错误,绝不执行整表 DELETE。

func (*Connection) ForceDeleteQuietly

func (c *Connection) ForceDeleteQuietly(model any) error

ForceDeleteQuietly 硬删模型但不触发任何事件。

func (*Connection) ForgetRecordModificationState

func (c *Connection) ForgetRecordModificationState()

ForgetRecordModificationState 重置写标记(对应 forgetRecordModificationState)。

func (*Connection) Fresh

func (c *Connection) Fresh(model any) (any, error)

Fresh 按主键重查一个全新实例(fresh 语义):原模型保持不变; 模型未持久化或行未命中返回 nil。

func (*Connection) GetConfig

func (c *Connection) GetConfig() Config

GetConfig 返回连接配置(对应 Connection::getConfig)。

func (*Connection) GetDatabaseName

func (c *Connection) GetDatabaseName() string

GetDatabaseName 返回数据库名(对应 Connection::getDatabaseName)。

func (*Connection) GetName

func (c *Connection) GetName() string

GetName 返回连接名。

func (*Connection) GetQueryGrammar

func (c *Connection) GetQueryGrammar() grammar.Grammar

GetQueryGrammar 按 driver 构造方言 grammar,并接线上表前缀与 Config 方言 开关(ServerVersion/IsMariaDB/UseUpsertAlias/UseLegacyGroupLimit——此前这些 setter 只有 schema 侧可达,查询路径上是死代码)。 按 driver 做方言分发:PG/SQLite/ SqlServer/MariaDb 连接必须路由到各自的语法编译器,否则运行时全部按 MySQL 语法编译。

func (*Connection) GetQueryLog

func (c *Connection) GetQueryLog() []QueryExecuted

GetQueryLog 返回已记录的查询日志快照。

func (*Connection) GetRawQueryLog

func (c *Connection) GetRawQueryLog() []RawQueryLog

GetRawQueryLog 返回绑定插值后的查询日志(对应 Connection::getRawQueryLog: substituteBindingsIntoRawSql 套用在现有 QueryLog 上)。

func (*Connection) GetSchemaGrammar

func (c *Connection) GetSchemaGrammar() grammar.SchemaGrammar

GetSchemaGrammar 按驱动返回 DDL 编译器。 对应各驱动的 getConnection → getSchemaGrammar 方言分发。

func (*Connection) HasModifiedRecords

func (c *Connection) HasModifiedRecords() bool

HasModifiedRecords 报告自上次重置以来是否发生过写操作。

func (*Connection) Increment

func (c *Connection) Increment(model any, column string, amount ...any) error

Increment 自增一列;amount 缺省 1,可传 map[string]any 作为 extra 附加列。

func (*Connection) IncrementEach

func (c *Connection) IncrementEach(model any, columns map[string]int64, extra ...map[string]any) error

IncrementEach 一条 UPDATE 内自增多列; extra 为附加列。金额为负值时转为自减。

func (*Connection) Insert

func (c *Connection) Insert(query string, args ...interface{}) (int64, int64, error)

Insert Run an insert statement against the database.

func (*Connection) InsertGetId

func (c *Connection) InsertGetId(query string, args ...interface{}) (int64, error)

InsertGetId 执行 insert 并返回自增 id。 PG/SQLServer 的 grammar 编译同款 insert ... returning/output 语句, 驱动不支持 LastInsertId(lib/pq、mssqldb 返回 0 或报错)——改为消费返回行, 从 returning/output 结果集中取自增 id。

func (*Connection) IsMaria

func (c *Connection) IsMaria() bool

IsMaria 报告服务器是否为 MariaDB:仅 mysql/mariadb 驱动按版本串判断 (含 "MariaDB"),其余驱动恒为 false。

func (*Connection) Listen

func (c *Connection) Listen(fn func(QueryExecuted))

Listen 注册查询事件监听器(对应 Connection::listen,支持多监听器)。

func (*Connection) Load

func (c *Connection) Load(model any, name string, rel Relation, constraints ...func(*Builder)) error

Load 显式触发关系加载并缓存到模型: 结果经 SetLoadedRelation 缓存;模型存在同名关系字段(StudlyCase)时同步回填。

func (*Connection) LoadAggregate

func (c *Connection) LoadAggregate(model any, name string, rel Relation, function, column string, rest ...any) error

LoadAggregate 通用关系聚合加载: function/column 组合如 ("count","*") / ("sum","votes");rest 支持 约束闭包、嵌套 Relation 与 string 别名(与 Builder.WithAggregate 一致)。

func (*Connection) LoadAvg

func (c *Connection) LoadAvg(model any, name string, rel Relation, column string, rest ...any) error

LoadAvg 加载关系列平均(对应 loadAvg)。

func (*Connection) LoadCount

func (c *Connection) LoadCount(model any, name string, rel Relation, rest ...any) error

LoadCount 加载关系计数到模型 {relation}_count 属性。

func (*Connection) LoadExists

func (c *Connection) LoadExists(model any, name string, rel Relation, rest ...any) error

LoadExists 加载关系存在性到模型 {relation}_exists 属性(对应 loadExists)。

func (*Connection) LoadMany

func (c *Connection) LoadMany(model any, rels map[string]Relation) error

LoadMany 一次加载多个关系。

func (*Connection) LoadMax

func (c *Connection) LoadMax(model any, name string, rel Relation, column string, rest ...any) error

LoadMax 加载关系列最大值到模型 {relation}_max_{column} 属性(对应 loadMax)。

func (*Connection) LoadMin

func (c *Connection) LoadMin(model any, name string, rel Relation, column string, rest ...any) error

LoadMin 加载关系列最小值(对应 loadMin)。

func (*Connection) LoadMissing

func (c *Connection) LoadMissing(model any, name string, rel Relation, constraints ...func(*Builder)) error

LoadMissing 惰性加载已加载则跳过的关系(relationLoaded 时直接返回, 不发关联查询)。

func (*Connection) LoadMorph

func (c *Connection) LoadMorph(model any, name string, rel Relation) error

LoadMorph 加载单模型的多态关系(实例级入口): MorphMany/MorphOne 经 builder 内部 loadMorph 查回子模型并填充同名关系 字段,同时写入 LoadedRelation 缓存;其它关系类型走 Load 通道。

func (*Connection) LoadMorphCount

func (c *Connection) LoadMorphCount(model any, name string, rel Relation) error

LoadMorphCount 加载多态关系计数到模型 {relation}_count 属性 (loadMorphCount 的实例级入口)。

func (*Connection) LoadSum

func (c *Connection) LoadSum(model any, name string, rel Relation, column string, rest ...any) error

LoadSum 加载关系列求和(对应 loadSum)。

func (*Connection) Model

func (c *Connection) Model(model interface{}) *Builder

Model Begin a fluent query against a database Model. 含软删除全局 scope(deleted_at IS NULL)。

func (*Connection) Observe

func (c *Connection) Observe(model any, o *Observer)

Observe 为模型类型注册观察者(覆盖式:替换该类型当前的全部观察者, 与 1.x 行为一致)。需要叠加多个观察者时使用 AddObserver。

func (*Connection) OnQuery

func (c *Connection) OnQuery(fn func(QueryExecuted))

OnQuery 注册查询事件回调(兼容接口:单回调,重复设置时覆盖)。

func (*Connection) Pretend

func (c *Connection) Pretend(fn func(*Connection)) []QueryExecuted

Pretend 以 dry-run 方式执行回调(对应 Connection::pretend):查询被记录 但不真正发往数据库;返回期间记录的查询日志。

func (*Connection) Push

func (c *Connection) Push(model any) error

Push 保存模型及其全部已加载关系(递归): 关系取 LoadedRelation 缓存(Load/LoadMany 显式加载的结果), 逐个递归 Push;已访问模型跳过(防环)。

func (*Connection) PushQuietly

func (c *Connection) PushQuietly(model any) error

PushQuietly 保存模型与已加载关系但不触发任何事件。

func (*Connection) Query

func (c *Connection) Query() *Builder

Query Get a new query builder instance.

func (*Connection) Raw

func (c *Connection) Raw(value string) grammar.Expression

Raw 返回原始 SQL 表达式(对应 Connection::raw)。

func (*Connection) RecordsHaveBeenModified

func (c *Connection) RecordsHaveBeenModified(value bool)

RecordsHaveBeenModified 显式设置写标记。

func (*Connection) Refresh

func (c *Connection) Refresh(model any) error

Refresh 重查并刷新原模型属性(refresh 语义):按主键重查 (不带软删 scope,已软删模型同样可刷新),把查得属性整体覆盖进原模型 并同步 original 快照;行已消失返回 *ErrNotFound(firstOrFail 语义)。

func (*Connection) RelationCreate

func (c *Connection) RelationCreate(parent any, rel Relation, attributes map[string]any) (any, error)

---- 关系级写方法(对应 HasOneOrMany.php:228-485、MorphOneOrMany.php:330-370)---- RelationCreate 创建关联模型并自动填外键(morph 关系同时填类型列), 走完整 Create 生命周期;rel 支持 HasOne/HasMany/MorphOne/MorphMany。

func (*Connection) RelationFind

func (c *Connection) RelationFind(parent any, rel Relation, id any) (any, error)

RelationFind 关系内按目标模型主键查找(对应 BelongsToMany::find / HasOneOrMany::find):按主键在关系结果内匹配,无命中返回 (nil, nil)。 统一在内存中按主键过滤——对 pivot/中间表 join 形态(BelongsToMany 等 GetResults 不做约束下推的关系)与普通关系行为一致。

func (*Connection) RelationFirst

func (c *Connection) RelationFirst(parent any, rel Relation, constraints ...func(*Builder)) (any, error)

RelationFirst 关系内取首条(对应 first):constraints 附加在关系查询上 (键形态关系做 SQL 下推;BelongsToMany/MorphToMany/through 形态的 GetResults 不下推约束,为 best-effort);无命中返回 (nil, nil)。

func (*Connection) RelationFirstOr

func (c *Connection) RelationFirstOr(parent any, rel Relation, fallback func() (any, error), constraints ...func(*Builder)) (any, error)

RelationFirstOr 关系内取首条,无命中走 fallback(对应 firstOr($callback))。

func (*Connection) RelationFirstOrCreate

func (c *Connection) RelationFirstOrCreate(parent any, rel Relation, attributes map[string]any, values ...map[string]any) (any, error)

RelationFirstOrCreate 按外键 + attributes 查找或创建关联模型。

func (*Connection) RelationFirstOrFail

func (c *Connection) RelationFirstOrFail(parent any, rel Relation, constraints ...func(*Builder)) any

RelationFirstOrFail 关系内取首条;无命中或查询出错 panic *FailError (对应 firstOrFail 抛 ModelNotFoundException,ErrNotFound 可经 Unwrap 取回)。

func (*Connection) RelationSave

func (c *Connection) RelationSave(parent any, rel Relation, related any) error

RelationSave 保存关联模型:先填外键(+morph type)再 Save (无主键 → insert,有主键 → update 脏列)。

func (*Connection) RelationSole

func (c *Connection) RelationSole(parent any, rel Relation, constraints ...func(*Builder)) (any, error)

RelationSole 关系内取唯一一条(对应 sole):0 条 → ErrNotFound, 多条 → ErrMultiple。

func (*Connection) RelationUpdateOrCreate

func (c *Connection) RelationUpdateOrCreate(parent any, rel Relation, attributes, values map[string]any) (any, error)

RelationUpdateOrCreate 按外键 + attributes 查找并更新,或创建新关联模型。

func (*Connection) Replicate

func (c *Connection) Replicate(dst, src any) error

Replicate 把已持久化模型复制为未持久化新实例写入 dst: 主键与时间戳清零、状态清除(对齐 replicate 语义:excluding $primaryKey / createdAt / updatedAt);replicating 观察者在副本上触发 (可修改副本、返回 error 取消)。

func (*Connection) ResetTotalQueryDuration

func (c *Connection) ResetTotalQueryDuration()

ResetTotalQueryDuration 清零累计查询耗时。

func (*Connection) Restore

func (c *Connection) Restore(model interface{}) error

Restore 恢复软删除的模型(事件顺序: Restoring → deleted_at 置空 + updated_at 刷新(经完整 save 生命周期)→ Restored)。

func (*Connection) RestoreOrCreate

func (c *Connection) RestoreOrCreate(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error

RestoreOrCreate 软删模型版 firstOrCreate:withTrashed 查找,命中且已软删 则恢复(restoreOrCreate 语义)。

func (*Connection) RestoreQuietly

func (c *Connection) RestoreQuietly(model any) error

RestoreQuietly 恢复软删模型但不触发任何事件。

func (*Connection) RollBack

func (c *Connection) RollBack() error

RollBack 回滚到上一层事务;toLevel<0 或越界时为 no-op。

func (*Connection) RollBackToLevel

func (c *Connection) RollBackToLevel(toLevel int) error

RollBackToLevel 回滚到指定事务层。

func (*Connection) Save

func (c *Connection) Save(model interface{}) error

Save Save the model to the database(保存/更新): saving → 干净模型 short-circuit(仅 saved,不发 SQL 不触发 updating/updated); 存在记录(exists)→ updating → 时间戳 → 脏列 UPDATE → updated;否则 → creating → 时间戳 → INSERT(以 exists 而非主键 是否为空决定插入/更新)。

func (*Connection) SaveOrFail

func (c *Connection) SaveOrFail(model any) error

SaveOrFail 事务内保存模型,失败 panic *FailError。

func (*Connection) SaveOrIgnore

func (c *Connection) SaveOrIgnore(model any) (bool, error)

SaveOrIgnore 未持久化模型以 insert or ignore 写入:唯一约束冲突时静默 跳过并返回 (false, nil);已持久化(exists)模型返回错误。 成功时固时间戳、回填自增主键、置 exists/wasRecentlyCreated 并触发 creating/created/saved 事件(对齐 performInsertOrIgnore 生命周期)。 差异说明:uniqueBy 形参需经 insertOrIgnoreReturning 下推到方言 编译,Go 侧编译钩子待接线(见待接线清单),故不提供该参数。

func (*Connection) SaveQuietly

func (c *Connection) SaveQuietly(model any) error

SaveQuietly 保存模型但不触发任何事件。

func (*Connection) Scalar

func (c *Connection) Scalar(query string, bindings []interface{}) (any, error)

Scalar Run a select statement and return the first column of the first row (对应 Connection::scalar);多列时返回 ErrMultipleColumnsSelected。

func (*Connection) Scan

func (c *Connection) Scan(query string, bindings []interface{}, dest ...interface{}) error

Scan Run a query and scan columns into given destinations.

func (*Connection) Schema

func (c *Connection) Schema() *SchemaBuilder

Schema 返回连接的 Schema 构建器。

func (*Connection) Select

func (c *Connection) Select(query string, bindings []interface{}, dest interface{}) error

Select Run a select statement against the database.

func (*Connection) SelectFromWrite

func (c *Connection) SelectFromWrite(query string, bindings []interface{}, dest interface{}) error

SelectFromWrite 强制走写连接的 select(忽略读连接路由)。

func (*Connection) SelectMaps

func (c *Connection) SelectMaps(query string, bindings []interface{}) ([]map[string]any, error)

SelectMaps 执行查询并把行结果输出为 map 切片(explain/内省用)。

func (*Connection) SelectOne

func (c *Connection) SelectOne(query string, bindings []interface{}, dest interface{}) error

SelectOne Run a select statement and return a single result(只取第一行, 等价于 select 后 array_shift 的语义)。

func (*Connection) SelectResultSets

func (c *Connection) SelectResultSets(query string, bindings []interface{}) ([][]map[string]any, error)

SelectResultSets 执行查询并返回全部结果集(对应 selectResultSets)。 Go database/sql 单条语句只产出单个结果集,故返回包含一个结果集的切片。

func (*Connection) ServerVersion

func (c *Connection) ServerVersion() (string, error)

ServerVersion 返回数据库服务器版本(对应 PDO::ATTR_SERVER_VERSION)。 惰性求值并按驱动选择版本查询:mysql/mariadb/postgres 走 select version(), sqlite 走 select sqlite_version(),sqlserver 走 select serverproperty('ProductVersion');仅首次真正查询,结果加锁缓存。

func (*Connection) SetConnectionName

func (c *Connection) SetConnectionName(name string)

SetConnectionName 设置连接名(错误消息与事件将携带该名称)。

func (*Connection) SetDatabaseName

func (c *Connection) SetDatabaseName(name string)

SetDatabaseName 设置数据库名(对应 Connection::setDatabaseName)。

func (*Connection) SetEventDispatcher

func (c *Connection) SetEventDispatcher(d events.Dispatcher)

SetEventDispatcher 挂载事件分发器;生命周期点将同步分发事件对象。 ConnectionEstablished 由 Open/Manager 在建连时经已挂载的分发器分发 (Manager.SetEventDispatcher 提供管理器级挂载点)。

func (*Connection) SetReconnector

func (c *Connection) SetReconnector(fn func(*Connection) error)

SetReconnector 设置断连重连回调(对应 Connection::setReconnector): reconnect() 优先调用该回调。

func (*Connection) SetRecordModificationState

func (c *Connection) SetRecordModificationState(value bool)

SetRecordModificationState 无条件设置写标记。

func (*Connection) Statement

func (c *Connection) Statement(query string, args ...interface{}) error

Statement Execute an SQL statement and return the boolean result.

func (*Connection) Sync

func (c *Connection) Sync(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) (*SyncResult, error)

Sync 全量同步 pivot(对应 sync):附加缺失、解除多余、更新现存(带 pivotAttrs 时),返回 attached/detached/updated。

func (*Connection) SyncOrFail

func (c *Connection) SyncOrFail(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) *SyncResult

SyncOrFail 全量同步 pivot,失败 panic *FailError{Op:"sync"}。

func (*Connection) SyncWithPivotValues

func (c *Connection) SyncWithPivotValues(parent any, rel PivotRelation, ids []any, values map[string]any, detaching ...bool) (*SyncResult, error)

SyncWithPivotValues 以给定 pivot 值同步 ids(对应 syncWithPivotValues): 缺失的附加(带 values)、现存的更新 values;detaching=false 时 syncWithoutDetaching 语义(不解除其它关联)。ids 可为模型或裸键。

func (*Connection) SyncWithoutDetaching

func (c *Connection) SyncWithoutDetaching(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) (*SyncResult, error)

SyncWithoutDetaching 同步但不解除缺失项(对应 syncWithoutDetaching)。

func (*Connection) Table

func (c *Connection) Table(table string) *Builder

Table Begin a fluent query against a database table.

func (*Connection) ThreadCount

func (c *Connection) ThreadCount() (int, error)

ThreadCount 返回数据库打开的连接/线程数(对应 Connection::threadCount): 驱动不支持时返回 (-1, nil)。

func (*Connection) Toggle

func (c *Connection) Toggle(parent any, rel PivotRelation, ids []any) (*SyncResult, error)

Toggle 切换 pivot 关联(对应 toggle):已关联的解除、未关联的附加。

func (*Connection) ToggleOrFail

func (c *Connection) ToggleOrFail(parent any, rel PivotRelation, ids []any) *SyncResult

ToggleOrFail 切换 pivot 关联,失败 panic *FailError{Op:"toggle"}。

func (*Connection) TotalQueryDuration

func (c *Connection) TotalQueryDuration() float64

TotalQueryDuration 返回累计查询耗时(毫秒)。

func (*Connection) Touch

func (c *Connection) Touch(model any) error

Touch 以 now 刷新 updated_at 后走完整 save 生命周期。

func (*Connection) TouchOwners

func (c *Connection) TouchOwners(model any) error

TouchOwners 触碰模型声明关系(torm:"touches=name" tag)指向的父模型时间戳 (对应 HasRelationships::touchOwners,最小实现)。关系已惰性加载 (LoadedRelation)时逐个 touch 已加载的父模型实例并递归其 touches; 否则按 belongsTo 键约定反查:父表 = pluralize(关系名),外键 = 关系名_id, 执行 update <parent> set updated_at = now where id = <fk 值>。 Save/Delete/软删生命周期自动触发(model.go 的 Save/DeleteModel/Restore 在成功写库后调用 TouchOwners)。

func (*Connection) TouchQuietly

func (c *Connection) TouchQuietly(model any) error

TouchQuietly 刷新 updated_at 但不触发任何事件。

func (*Connection) Transaction

func (c *Connection) Transaction(fn func(*Connection) error, attempts ...int) error

Transaction 在事务中执行回调。最外层遇到死锁/锁等待时回滚并重试(最多 attempts 次,默认 1);嵌套调用降级为 savepoint,任何错误都回滚到进入前的 层级并把错误交还外层处理——嵌套层级不自行重试 (handleTransactionException:仅最外层事务参与重试)。

func (*Connection) TransactionLevel

func (c *Connection) TransactionLevel() int

TransactionLevel 返回当前事务层数。

func (*Connection) Unobserve

func (c *Connection) Unobserve(model any)

Unobserve 移除模型类型的全部观察者。

func (*Connection) Unprepared

func (c *Connection) Unprepared(query string) (bool, error)

Unprepared 直发一条未预处理 SQL(对应 Connection::unprepared):绕过 run 包装(不重试、不计时不写查询日志),成功后标记已发生写操作; pretending 时返回 (true, nil)。

func (*Connection) UnsetEventDispatcher

func (c *Connection) UnsetEventDispatcher()

UnsetEventDispatcher 卸载事件分发器(对应 Connection::unsetEventDispatcher)。

func (*Connection) Update

func (c *Connection) Update(query string, args ...interface{}) (int64, error)

Update Run an update statement against the database.

func (*Connection) UpdateExistingPivot

func (c *Connection) UpdateExistingPivot(parent any, rel PivotRelation, id any, attrs map[string]any) (int64, error)

UpdateExistingPivot 更新现存 pivot 行(对应 updateExistingPivot),返回受影响行数。

func (*Connection) UpdateExistingPivotOrFail

func (c *Connection) UpdateExistingPivotOrFail(parent any, rel PivotRelation, id any, attrs map[string]any) int64

UpdateExistingPivotOrFail 更新现存 pivot 行,失败 panic *FailError{Op:"updateExistingPivot"},返回受影响行数。

func (*Connection) UpdateModel

func (c *Connection) UpdateModel(model any, attrs map[string]any) error

UpdateModel 模型级批量赋值更新(fill + save): Fill 走守卫规则,Save 的干净保存语义(无脏列不发 SQL)自动生效。 命名避开 Connection.Update(原生 SQL 方法),与 DestroyByIDs 先例一致。

func (*Connection) UpdateOrCreate

func (c *Connection) UpdateOrCreate(model interface{}, attributes, values map[string]interface{}) error

UpdateOrCreate 按 attributes 查找;命中则更新 values,未命中则创建 (updateOrCreate(attributes, values) 语义:赋值走 fill 守卫语义)。

func (*Connection) UpdateQuietly

func (c *Connection) UpdateQuietly(model any, attrs map[string]any) error

UpdateQuietly 批量赋值后静默保存(与 UpdateModel 一致走守卫 Fill)。

func (*Connection) UseWriteConnectionWhenReading

func (c *Connection) UseWriteConnectionWhenReading(value ...bool)

UseWriteConnectionWhenReading 强制读语句走写连接(对应 useWriteConnectionWhenReading)。

func (*Connection) WhenQueryingForLongerThan

func (c *Connection) WhenQueryingForLongerThan(thresholdMs int64, handler func(QueryExecuted))

WhenQueryingForLongerThan 当累计查询耗时超过 thresholdMs 毫秒时触发一次 handler(随附触发时的 QueryExecuted)。

func (*Connection) WithoutPretending

func (c *Connection) WithoutPretending(fn func() error) error

WithoutPretending 在临时关闭 dry-run 的状态下执行回调(对应 Connection::withoutPretending):回调结束后恢复原 pretending 状态。

func (*Connection) WriteDB

func (c *Connection) WriteDB() *sql.DB

WriteDB 返回主(写)句柄快照(connMu 保护;迁移锁等需要专用物理连接的 场景经 db.Conn 再取独占连接)。

type Connector

type Connector interface {
	// Connect 打开数据库连接(实现可在连接前对 DSN 做方言化增强/校验)。
	Connect(dsn string) (*sql.DB, error)
}

Connector 数据库连接器接口:建立数据库连接。

type Cursor

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

Cursor 游标:参数集合 + 方向标记, 编码为 base64(json)(url 安全:+ → -、/ → _、= 剔除)。

func CursorFromEncoded

func CursorFromEncoded(encoded string) *Cursor

CursorFromEncoded 从编码串解码游标(对应 Cursor::fromEncoded;非法返回 nil)。

func NewCursor

func NewCursor(parameters map[string]any, pointsToNextItems bool) *Cursor

NewCursor 构造游标。

func (*Cursor) Encode

func (c *Cursor) Encode() string

Encode 编码为 url 安全 base64(对应 Cursor::encode)。

func (*Cursor) Parameter

func (c *Cursor) Parameter(name string) any

Parameter 取游标参数(缺失时 panic)。

func (*Cursor) PointsToNextItems

func (c *Cursor) PointsToNextItems() bool

PointsToNextItems 游标是否指向后一页。

type CursorPaginator

type CursorPaginator struct {
	Items          any
	PerPage        int64
	HasMore        bool
	Cursor         *Cursor
	NextCursor     *Cursor
	PreviousCursor *Cursor
}

CursorPaginator 游标分页结果结构。

func (CursorPaginator) HasMorePages

func (p CursorPaginator) HasMorePages() bool

HasMorePages 是否还有下一页(基于 nextCursor 是否非空判断)。

func (CursorPaginator) Parameter

func (p CursorPaginator) Parameter(name string) any

Parameter 取当前游标参数(转发 Cursor.Parameter:无游标返回 nil; 有游标但缺参时沿用 Cursor.Parameter 的 panic 语义)。

func (CursorPaginator) PointsToNextItems

func (p CursorPaginator) PointsToNextItems() bool

PointsToNextItems 当前游标是否指向后一页(转发 Cursor 同名方法; 无游标返回 false)。

type Dispatcher

type Dispatcher = events.Dispatcher

Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。

type ErrInvalid

type ErrInvalid struct{ Msg string }

ErrInvalid 参数无效错误(无效参数异常)。

func (ErrInvalid) Error

func (e ErrInvalid) Error() string

type ErrMultiple

type ErrMultiple struct{ Msg string }

ErrMultiple 记录命中多行错误(sole 期望单行时命中多行)。

func (ErrMultiple) Error

func (e ErrMultiple) Error() string

type ErrNotFound

type ErrNotFound struct{ Msg string }

ErrNotFound 记录未找到错误(firstOrFail/sole 未命中)。

func (ErrNotFound) Error

func (e ErrNotFound) Error() string

type Error

type Error struct {
	Kind     ErrorKind
	Err      error
	Sql      string
	Bindings []any
	ConnName string
}

Error 携带 SQL 与分类的查询错误(查询异常包装)。

func (*Error) ConnectionName

func (e *Error) ConnectionName() string

ConnectionName 返回发生错误的连接名。

func (*Error) Error

func (e *Error) Error() string

func (*Error) GetBindings

func (e *Error) GetBindings() []any

GetBindings 返回绑定。

func (*Error) GetSql

func (e *Error) GetSql() string

GetSql 返回原始 SQL。

func (*Error) RawSql

func (e *Error) RawSql() string

RawSql 返回绑定插值后的 SQL(getRawSql:字符串加引号转义、nil→NULL)。

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorKind

type ErrorKind int

ErrorKind 错误分类(按驱动错误码/SQLSTATE 解析)。

const (
	KindGeneric ErrorKind = iota
	KindUniqueConstraint
	KindDeadlock
	KindLostConnection
)

type Event

type Event = events.Event

Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。

type EventBus

type EventBus = events.EventBus

Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。

type Factory

type Factory[T any] struct {
	Definition func(seq int) T
	Table      string // 可选:批量插入的表名(Create 用 Create 生命周期则不需要)
	// contains filtered or unexported fields
}

Factory 模型工厂:Definition 按 1 起始的序号生成模型。 T 为模型指针类型(如 *Post)以支持 Create 走完整生命周期。

func (Factory[T]) AfterCreating

func (f Factory[T]) AfterCreating(fn func(T)) Factory[T]

AfterCreating 注册落库成功后的钩子(afterCreating; 此时主键已回填)。

func (Factory[T]) AfterMaking

func (f Factory[T]) AfterMaking(fn func(T)) Factory[T]

AfterMaking 注册 make 生命周期钩子(afterMaking)。

func (Factory[T]) Count

func (f Factory[T]) Count(n int) Factory[T]

Count 设置默认生成数量(配合 MakeMany/CreateMany)。

func (Factory[T]) Create

func (f Factory[T]) Create(conn *Connection, count int) ([]T, error)

Create 生成并落库:逐条走 Create 生命周期(时间戳/观察者/主键回填)。

func (Factory[T]) CreateMany

func (f Factory[T]) CreateMany(conn *Connection) ([]T, error)

CreateMany 按 Count(n) 数量生成并落库(未设置时 1 个)。

func (Factory[T]) CreateOne

func (f Factory[T]) CreateOne(conn *Connection) (T, error)

CreateOne 生成单个模型并落库(createOne 语义)。

func (Factory[T]) For

func (f Factory[T]) For(parent any, foreignKey ...string) Factory[T]

For 注册 belongsTo 父模型:make/create 时把 parent 主键写入外键列 (外键缺省 = singular(parent 表名)_id)。

func (Factory[T]) Make

func (f Factory[T]) Make(count int) []T

Make 生成 count 个模型实例(不落库,make 语义)。 工厂带 Count(n) 时可用 MakeMany 按默认数量生成。

func (Factory[T]) MakeMany

func (f Factory[T]) MakeMany() []T

MakeMany 按 Count(n) 数量生成(未设置时 1 个)。

func (Factory[T]) MakeOne

func (f Factory[T]) MakeOne() T

MakeOne 生成单个模型实例(makeOne 语义)。

func (Factory[T]) Sequence

func (f Factory[T]) Sequence(mutators ...func(seq int, m T)) Factory[T]

Sequence 注册轮换序列(sequence):第 i 个模型应用 sequence[(i-1) % len]。

func (Factory[T]) SequenceAttrs

func (f Factory[T]) SequenceAttrs(attrs ...map[string]any) Factory[T]

SequenceAttrs 属性 map 形态的轮换序列(每个 map 为一轮属性)。

func (Factory[T]) State

func (f Factory[T]) State(name string, mutator func(T)) Factory[T]

State 注册命名状态变更器(state); name 仅作标识,make/create 时按注册顺序应用。

type FailError

type FailError struct {
	Op  string
	Err error
}

FailError 是 OrFail 族失败时的 panic 载荷。

func (*FailError) Error

func (e *FailError) Error() string

func (*FailError) Unwrap

func (e *FailError) Unwrap() error

type Field

type Field struct {
	Value       reflect.Value
	StructField reflect.StructField
	Attrs       map[string]string
	Primary     bool
	Name        string
	Ignored     bool
	IsBlank     bool
	Cast        string // 原始 cast 标签值(cast:json 等);cast:array 内部归一为 "json"
	CastName    string // cast 基名:json/date/datetime/decimal/bool/int/float/uuid/ulid
	CastArg     string // cast 参数(decimal:N 的 N 等)
	UniqueID    string // unique_id 生成类型:"uuid" / "ulid"(空 = 不生成)
}

Field The model field definition

func NewField

func NewField(value reflect.Value, structField reflect.StructField) *Field

func (*Field) GetAttr

func (f *Field) GetAttr(key string) (string, bool)

GetParams Get the attr of tag

func (*Field) ReadCast

func (f *Field) ReadCast() error

ReadCast 读取后转换:把扫描结果规范化为字段语义类型。

json cast 把字符串反序列化进结构体/切片(connection 层 holder 已完成时为 no-op); date cast 把 time.Time 截断到当天零点(asDate 语义); decimal cast 把字符串值规范化到指定精度。 读侧要求驱动返回时间值(MySQL parseTime=true 惯例),字符串列无法在扫描后补救。

func (*Field) SetValue

func (f *Field) SetValue(value interface{}) (err error)

Set set a value to the field

func (*Field) WriteCast

func (f *Field) WriteCast() (any, bool)

WriteCast 写入前转换:把字段 Go 值转为数据库绑定值。

cast:json / cast:array —— 结构体/切片/映射序列化为字符串;空值约定: nil/零值集合写 "[]"(空集合语义),零值结构体写 null。 cast:date / cast:datetime —— time.Time 按格式序列化(cast:datetime:Y-m-d 自定义, 否则全局默认 = 方言 GetDateFormat)。 cast:decimal:N —— 数字/字符串规范化为 N 位定点字符串。 cast:bool / cast:int / cast:float —— 规范化为对应标量。

type HasMany

type HasMany struct {
	ForeignKey string
	LocalKey   string
	Model      any
}

HasMany 一对多。

func (HasMany) GetResults

func (r HasMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:按父键取关联集合(对应 HasMany::getResults)。

type HasManyThrough

type HasManyThrough struct {
	ThroughModel   any
	FirstKey       string
	SecondKey      string
	LocalKey       string
	SecondLocalKey string
	TargetModel    any
	// WithTrashedParents 跳过中间表软删过滤(对应 withTrashedParents 语义;
	// 默认:中间模型有 deleted_at 字段时 join 条件追加 deleted_at is null)
	WithTrashedParents bool
}

HasManyThrough 远程一对多(经中间表)。 例:User HasManyThrough Comment,经 Post:

ThroughModel: Post{}; FirstKey: "user_id"(posts 上的父外键);
SecondKey: "post_id"(comments 上的中间表键); LocalKey: "id"; SecondLocalKey: "id"

func (HasManyThrough) GetResults

func (r HasManyThrough) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:经中间表取远程关联(对应 HasManyThrough::getResults)。

func (HasManyThrough) WithTrashed

func (r HasManyThrough) WithTrashed() HasManyThrough

WithTrashedParents 跳过中间模型软删过滤。

type HasOne

type HasOne struct {
	ForeignKey string // 目标表列
	LocalKey   string // 本表键(默认 id)
	Model      any
	// withDefault(对应 SupportsDefaultModels,HasOne.php 亦实现):
	// 关系未命中时返回目标模型新实例而非空;
	// DefaultFn 非 nil 时以新实例调用,返回值非 nil 则使用之
	HasDefault bool
	DefaultFn  func(inst any) any
	// one-of-many 变体(对应 CanBeOneOfMany):OfManyColumn/OfManyAggregate
	// 非空时 GetResults/预加载按该列取极值一行(latestOfMany → max(created_at)、
	// oldestOfMany → min(created_at))。
	OfManyColumn    string
	OfManyAggregate string // "max" | "min";空串 = 关闭
	// Partial one() 显式标记:GetResults/预加载只取单行(对应
	// SupportsPartialRelations::one();HasOne 本就单行,此标记使查询显式 limit 1)
	Partial bool
}

HasOne 正向一对一:目标表持有外键。

func (HasOne) GetResults

func (r HasOne) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:按父键取关联(对应 HasOne::getResults)。 one-of-many 时按极值列 + 主键 tie-break 排序取一行(对应 CanBeOneOfMany 的 row_number 子查询 join 语义);withDefault 生效时未命中返回默认实例。

func (HasOne) LatestOfMany

func (r HasOne) LatestOfMany(column ...string) HasOne

LatestOfMany 取该列最新一行(对应 latestOfMany,缺省列 created_at)。

func (HasOne) OfMany

func (r HasOne) OfMany(column, aggregate string) HasOne

OfMany 自定义极值列与聚合(对应 ofMany(column, aggregate))。

func (HasOne) OldestOfMany

func (r HasOne) OldestOfMany(column ...string) HasOne

OldestOfMany 取该列最早一行(对应 oldestOfMany,缺省列 created_at)。

func (HasOne) One

func (r HasOne) One() HasOne

One 标记关系为单行形态(对应 SupportsPartialRelations::one())。

func (HasOne) WithDefault

func (r HasOne) WithDefault(fn ...func(inst any) any) HasOne

WithDefault 启用默认模型(对应 SupportsDefaultModels::withDefault,HasOne.php 亦实现):关系未命中(父键为空或查询无结果)时返回目标模型新实例; fn 可选,非 nil 时以新实例调用,返回值非 nil 则使用返回值。

type HasOneThrough

type HasOneThrough struct {
	ThroughModel   any
	FirstKey       string
	SecondKey      string
	LocalKey       string
	SecondLocalKey string
	TargetModel    any
	// WithTrashedParents 跳过中间表软删过滤(同 HasManyThrough)
	WithTrashedParents bool
}

HasOneThrough 远程一对一(HasManyThrough 的 单行变体):键约定与 HasManyThrough 相同,仅取首条结果。 例:Mechanic HasOneThrough CarOwner(经 Car):

ThroughModel: Car{}; FirstKey: "mechanic_id"(cars 上的父外键);
SecondKey: "car_id"(owners 上的中间表键); LocalKey: "id"; SecondLocalKey: "id"

func (HasOneThrough) GetResults

func (r HasOneThrough) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:经中间表取首条关联(对应 HasOneThrough::getResults = first() ?: default;父键为空时无默认实例直接返回空)。

func (HasOneThrough) WithTrashed

func (r HasOneThrough) WithTrashed() HasOneThrough

WithTrashed 跳过中间模型软删过滤。

type LengthAwarePaginator

type LengthAwarePaginator struct {
	Items       any
	Total       int64
	PerPage     int64
	CurrentPage int64
	LastPage    int64
}

LengthAwarePaginator 长度感知分页结果结构。

func (LengthAwarePaginator) Appends

Appends 追加公共查询参数,返回携带参数的链式副本: 分页器结构体未存储查询参数字段,以包装副本 AppendedLengthAware 承载(内嵌类型转发其余方法)。

func (LengthAwarePaginator) FirstItem

func (p LengthAwarePaginator) FirstItem() int

FirstItem 当前页首条目的全局序号(1 起): 当前页无条目时返回 0。

func (LengthAwarePaginator) From

func (p LengthAwarePaginator) From() int

From 当前页起始条目序号(firstItem 别名)。

func (LengthAwarePaginator) HasMorePages

func (p LengthAwarePaginator) HasMorePages() bool

HasMorePages 是否还有下一页。

func (LengthAwarePaginator) LastItem

func (p LengthAwarePaginator) LastItem() int

LastItem 当前页末条目的全局序号:无条目返回 0。

func (p LengthAwarePaginator) PageLinks(onEachSide int) []int

PageLinks 页码窗口:首页 + 当前页 ±onEachSide + 尾页;首/尾页与窗口之间的缺口以 -1 表示省略号 (即 "...")。采用旧版窗口算法(输出为当前页±n + 首尾锚 + -1 省略号): 当前页 > onEachSide+2 时补前省略号,当前页 < 尾页-(onEachSide+1) 时 补后省略号。

func (LengthAwarePaginator) To

func (p LengthAwarePaginator) To() int

To 当前页结束条目序号(lastItem 别名)。

func (LengthAwarePaginator) URL

func (p LengthAwarePaginator) URL(page int, query map[string]string) string

URL 分页链接查询串:分页器结构未存储路径 (path),返回以 "?" 起始的查询串,由调用方拼接到自身路径;query 键 升序拼接,page 参数置于末尾(覆盖 query 中的同名键); page < 1 归一为 1。

type Listener

type Listener = events.Listener

Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。

type Manager

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

DatabaseManager 具名连接管理器(连接复用 + 并发安全)。

func NewManager

func NewManager(configs ...map[string]Config) *Manager

NewManager 创建管理器并可预置配置。

func (*Manager) AddConfig

func (m *Manager) AddConfig(name string, config Config)

AddConfig 注册一个具名配置。

func (*Manager) Connect

func (m *Manager) Connect(name string) (*Connection, error)

Connect 获取具名连接实例;同一名称复用同一连接(*sql.DB 自带连接池)。 name 为空时使用默认连接;支持 "name::read" / "name::write" 读写路由。

func (*Manager) ConnectUsing

func (m *Manager) ConnectUsing(name string, config Config, force ...bool) (*Connection, error)

ConnectUsing 以显式配置立即建立具名连接(对应 DatabaseManager::connectUsing)。 force 为 true 时先断开并替换同名既有连接;否则同名连接已存在时报错。

func (*Manager) Disconnect

func (m *Manager) Disconnect(name string) error

Disconnect 关闭具名连接并移出缓存,使后续 Connect 重新建立连接 (对应 DatabaseManager::disconnect;Go 侧 *sql.DB 关闭后不可复用, 故移出缓存以实现重连)。

func (*Manager) Extend

func (m *Manager) Extend(driver string, resolver func(Config) (*Connection, error))

Extend 注册连接解析扩展(对应 DatabaseManager::extend):优先按连接名命中, 其次按驱动名。

func (*Manager) ForgetExtension

func (m *Manager) ForgetExtension(driver string)

ForgetExtension 移除连接解析扩展。

func (*Manager) GetConnections

func (m *Manager) GetConnections() []string

GetConnections 返回已创建连接的名称列表(对应 DatabaseManager::getConnections)。

func (*Manager) GetDefaultConnection

func (m *Manager) GetDefaultConnection() string

GetDefaultConnection 返回默认连接名。

func (*Manager) Purge

func (m *Manager) Purge(name string) error

Purge 断开并移除具名连接(name 为空时使用默认连接)。

func (*Manager) Reconnect

func (m *Manager) Reconnect(name string) (*Connection, error)

Reconnect 重连具名连接(对应 DatabaseManager::reconnect):与 Disconnect+ Connect 不同,保留同一 Connection 实例(连接名/事件/事务状态不丢),仅用 其配置重建底层句柄并重发 ConnectionEstablished;连接尚未建立时等价 Connect。

func (*Manager) SetDefaultConnection

func (m *Manager) SetDefaultConnection(name string)

SetDefaultConnection 设置默认连接名(Connect("") 时使用)。

func (*Manager) SetEventDispatcher

func (m *Manager) SetEventDispatcher(d events.Dispatcher)

SetEventDispatcher 挂载管理器级事件分发器:每次成功建立新连接后分发 ConnectionEstablished 事件(对应 DatabaseManager::dispatchConnectionEstablishedEvent)。

func (*Manager) SetReconnector

func (m *Manager) SetReconnector(fn func(*Connection) error)

SetReconnector 设置重连回调:之后建立的连接将挂载该回调 (对应 DatabaseManager::setReconnector + configure 的接线;未设置时使用 默认回调,即 Manager.Reconnect 保留实例重建句柄)。

func (*Manager) Transaction

func (m *Manager) Transaction(name string, fn func(*Connection) error, attempts ...int) error

Transaction 在具名连接上执行事务回调(转发 Connection::Transaction)。

func (*Manager) UsingConnection

func (m *Manager) UsingConnection(name string, callback func() error) error

UsingConnection 在回调期间把默认连接临时切换为 name (对应 DatabaseManager::usingConnection)。

type MassAssignmentError

type MassAssignmentError struct {
	Key string
}

MassAssignmentError 质量赋值异常: Fill 时试图写入被守卫的字段。

func (*MassAssignmentError) Error

func (e *MassAssignmentError) Error() string

type Model

Model 是内嵌属性集合(兼容旧用法)。内嵌后除 id/created_at/updated_at 列外 还携带 ModelStateAttr:original/changes/exists 状态随实例存储, 长驻进程无需手动 ForgetModel(模型自持 original 状态随实例存活)。

type ModelEvent

type ModelEvent = events.ModelEvent

Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。

type MorphCountSpec

type MorphCountSpec struct {
	Name     string   // 计数别名(对应 withCount('comments') → comments_count)
	Relation Relation // 被计数的关系描述符
}

MorphCountSpec morphTo morphWithCount 的单条计数规格: morphWithCount([类型 => [关系名, ...]]) 的一项;原按关系名隐式解析, Go 侧无容器需显式给出关系描述符。

type MorphMany

type MorphMany struct {
	MorphName   string // 多态名(决定默认列名 morphName_type / morphName_id)
	MorphKey    string
	TypeColumn  string
	IDColumn    string
	TargetModel any
}

MorphMany 多态一对多:目标表持有 type 列(commentable_type)与 id 列(commentable_id)。 MorphKey 为类型列取值,缺省 = 父表名(Go 侧约定,非 FQCN 形态)。

func (MorphMany) GetResults

func (r MorphMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:按父键 + 类型列取多态关联(对应 MorphMany::getResults)。

type MorphOne

type MorphOne struct {
	MorphName   string
	MorphKey    string
	TypeColumn  string
	IDColumn    string
	TargetModel any
	// withDefault(对应 SupportsDefaultModels,HasOne.php 同款实现):
	// 关系未命中时返回目标模型新实例而非 nil;DefaultFn 非 nil 时以新实例
	// 调用,返回值非 nil 则使用之
	HasDefault bool
	DefaultFn  func(inst any) any
	// one-of-many 变体(对应 CanBeOneOfMany,语义同 HasOne 同名字段)
	OfManyColumn    string
	OfManyAggregate string // "max" | "min";空串 = 关闭
	Partial         bool   // one():显式标记只取单行
}

MorphOne 多态一对一。

func (MorphOne) GetResults

func (r MorphOne) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:按父键 + 类型列取多态关联(对应 MorphOne::getResults)。 one-of-many 取极值一行(极值列 + 主键 tie-break 排序,对应 CanBeOneOfMany); withDefault 生效时未命中返回默认实例。

func (MorphOne) LatestOfMany

func (r MorphOne) LatestOfMany(column ...string) MorphOne

LatestOfMany 取该列最新一行(对应 MorphOne::latestOfMany,缺省列 created_at)。

func (MorphOne) OfMany

func (r MorphOne) OfMany(column, aggregate string) MorphOne

OfMany 自定义极值列与聚合(对应 ofMany(column, aggregate))。

func (MorphOne) OldestOfMany

func (r MorphOne) OldestOfMany(column ...string) MorphOne

OldestOfMany 取该列最早一行(对应 MorphOne::oldestOfMany,缺省列 created_at)。

func (MorphOne) One

func (r MorphOne) One() MorphOne

One 标记关系为单行形态(对应 SupportsPartialRelations::one())。

func (MorphOne) WithDefault

func (r MorphOne) WithDefault(fn ...func(inst any) any) MorphOne

WithDefault 启用默认模型(对应 SupportsDefaultModels::withDefault): 关系未命中时返回目标模型新实例而非空;fn 可选,非 nil 时以新实例调用, 返回值非 nil 则使用返回值。

type MorphTo

type MorphTo struct {
	MorphName  string
	TypeColumn string
	IDColumn   string
	TypeMap    map[string]any
	// OwnerKey 目标表键(默认 id,对应 MorphTo $ownerKey)
	OwnerKey string
	// WithTrashed 目标模型为软删时跳过 deleted_at 过滤(对应 morphTo withTrashed)
	WithTrashed bool
	// OnlyTrashed 仅取已软删的 owner(对应 morphTo onlyTrashed;描述符级变体,
	// 预加载级变体见 Builder.MorphToOnlyTrashed)
	OnlyTrashed bool
	// withDefault(对应 SupportsDefaultModels):关系未命中时返回空实例而非 nil;
	// DefaultFn 非 nil 时以新实例调用,返回值非 nil 则使用之
	HasDefault bool
	DefaultFn  func(inst any) any
}

MorphTo 反向多态:本表持有类型列与 id 列;TypeMap 把类型串映射到模型零值。

func (MorphTo) GetResults

func (r MorphTo) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:按类型列解析目标模型后取 owner(对应 MorphTo::getResults)。 MorphName/TypeColumn 均空时从父模型 schema 推断(唯一 *_type 列)。

func (MorphTo) WithDefault

func (r MorphTo) WithDefault(fn ...func(inst any) any) MorphTo

WithDefault 启用默认模型(对应 SupportsDefaultModels::withDefault): 关系未命中时返回默认实例而非 nil。Go 侧 MorphTo 描述符无解析出的目标 类型(targetModel 为 nil),无回调时仅在类型已解析(行存在但查询未命中) 的情况下能以 TypeMap 的零值类型实例化;类型列也为空时必须提供回调 构造实例(fn 的 inst 参可能为 nil)。返回值非 nil 时使用返回值。

func (MorphTo) WithDeleted

func (r MorphTo) WithDeleted() MorphTo

WithDeleted 跳过目标模型软删过滤(对应 withTrashed 的链式形态)。

func (MorphTo) WithOnlyTrashed

func (r MorphTo) WithOnlyTrashed() MorphTo

WithOnlyTrashed 仅取已软删的 owner(对应 onlyTrashed 的链式形态)。

type MorphToMany

type MorphToMany struct {
	RelatedModel    any
	MorphName       string
	MorphKey        string // 类型列取值(缺省 = 父表名)
	Table           string // 缺省 = plural(morphName)
	TypeColumn      string // 缺省 morphName_type
	ForeignPivotKey string // 缺省 morphName_id(本表在 pivot 的键)
	RelatedPivotKey string // 缺省 目标单数_id
	RelatedKey      string // 缺省 id
}

MorphToMany 多态多对多: pivot 表(缺省 = morphName 的复数,如 taggable → taggables)持有 morphName_type / morphName_id 与目标表外键(目标单数_id)。

func (MorphToMany) GetResults

func (r MorphToMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)

GetResults 单父查询:经 pivot 表按类型列取多态多对多关联。

type MorphedByMany

type MorphedByMany = MorphToMany

MorphedByMany 反向多态多对多: 与 morphToMany 共用同一 pivot 表,仅语义方向相反。

type MySqlConnector

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

MySqlConnector MySQL 连接器(对应 Connectors\MySqlConnector):校验 DSN 并 自动附加 charset/collation/sql_mode/timezone/parseTime 参数(来自 Config, 已有参数不覆盖);隔离级别经 driver.Connector 包装在每个物理连接上生效。

func (*MySqlConnector) BuildDsn

func (c *MySqlConnector) BuildDsn(dsn string) string

BuildDsn 校验(非标准 DSN 原样返回,交给驱动在连接时报错)并增强 DSN。

func (*MySqlConnector) Connect

func (c *MySqlConnector) Connect(dsn string) (*sql.DB, error)

Connect 打开 MySQL 连接。

type Observer

type Observer struct {
	Retrieving func(model any) error // 水合前触发,返回 error 取消该行水合(行保持扫描零值仍留在结果中,其他实现为不进结果集)
	Retrieved  func(model any)

	Saving   func(model any) error
	Saved    func(model any) error
	Creating func(model any) error
	Created  func(model any) error
	Updating func(model any) error
	Updated  func(model any) error
	Deleting func(model any) error
	Deleted  func(model any) error
	Trashed  func(model any) error

	ForceDeleting func(model any) error

	Restoring    func(model any) error
	Restored     func(model any) error
	Replicating  func(model any) error
	ForceDeleted func(model any) error
}

Observer 模型观察者:按模型类型注册可选回调。 回调返回 error 时中断当前操作(异常中断生命周期)。

type PivotRelation

type PivotRelation interface {
	Relation
	// contains filtered or unexported methods
}

PivotRelation belongsToMany / morphToMany 的 pivot 写侧关系接口。

type PivotScopeCond

type PivotScopeCond struct {
	Col    string
	Op     string
	Value  any
	Values []any
	Kind   string
}

PivotScopeCond wherePivot 族的单条条件(basic/in/notIn/between/notBetween/null/notNull)。

type PivotSpec

type PivotSpec struct {
	Pivot      string // pivot 表名
	FPK        string // 父侧键列
	RPK        string // 目标侧键列
	TypeCol    string // 多态类型列(BTM 为空)
	MorphKey   string // 类型列取值(HasType 时有效)
	HasType    bool
	Timestamps bool // attach/sync 更新时自动补 created_at/updated_at
	// Attrs WithPivotValue 固定值(attach 属性打底;同时参与 sync/detach 范围)
	Attrs map[string]any
	// ScopeConds wherePivot 族条件(参与读取与 sync/detach 范围)
	ScopeConds []PivotScopeCond
}

PivotSpec pivot 写侧归一规格。

type PostgresConnector

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

PostgresConnector Postgres 连接器(对应 Connectors\PostgresConnector): 自动附加 sslmode/search_path/timezone DSN 参数;isolation_level/ synchronous_commit 经 DSN options=-c 参数生效(连接池下每个物理连接 均有效——libpq 标准参数,lib/pq 支持)。

func (*PostgresConnector) BuildDsn

func (c *PostgresConnector) BuildDsn(dsn string) string

BuildDsn 附加 sslmode/sslcert/sslkey/sslrootcert/search_path/client_encoding/ application_name/TimeZone/options 参数(已有参数不覆盖)。

func (*PostgresConnector) Connect

func (c *PostgresConnector) Connect(dsn string) (*sql.DB, error)

Connect 打开 Postgres 连接。

type QueryExecuted

type QueryExecuted = events.QueryExecuted

Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。

type RawQueryLog

type RawQueryLog struct {
	RawSql string
	TimeNs int64
}

RawQueryLog 绑定插值后的查询日志条目(对应 getRawQueryLog 的 raw_query/time)。

type Relation

type Relation interface {

	// GetResults 单父查询:
	// 返回关联模型指针(*T)切片;无关联时返回空切片。
	GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
	// contains filtered or unexported methods
}

Relation 关系定义(约定关系两侧的键命名)。

type SQLiteConnector

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

SQLiteConnector SQLite 连接器(对应 Connectors\SQLiteConnector):全部 pragmas 经驱动 DSN 参数生效(_foreign_keys/_busy_timeout/_journal_mode/ _synchronous/_pragma)——连接池下每个物理连接均生效;旧实现自定义 pragmas 用 db.Exec 只落在池内随机一个连接上。

func (*SQLiteConnector) BuildDsn

func (c *SQLiteConnector) BuildDsn(dsn string) string

BuildDsn 附加 sqlite pragma 参数。foreign_keys 缺省开启 (与 SQLite 默认 foreign_keys=true 对齐;显式 false 可关闭)。

func (*SQLiteConnector) Connect

func (c *SQLiteConnector) Connect(dsn string) (*sql.DB, error)

Connect 打开 SQLite 连接。

type Schema

type Schema struct {
	Fields       []*Field
	PrimaryField *Field
	// contains filtered or unexported fields
}

Schema model definition

func NewSchema

func NewSchema(model interface{}) (*Schema, error)

NewSchema 反射解析模型结构为字段列表:

  • 跳过未导出字段(旧实现对未导出字段 Addr().Interface() 会 panic);
  • 内嵌(anonymous)结构体字段扁平化为其子字段(子字段保留自身 tag), 使 field.IDAttr / torm.Model / SoftDeletes 等基座可用;
  • 带 torm tag 的内嵌字段按原语义视为普通列。

func (*Schema) Attributes

func (s *Schema) Attributes() map[string]interface{}

func (*Schema) SetId

func (s *Schema) SetId(id int64) error

type SchemaBuilder

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

SchemaBuilder 为 Schema 构建器门面(挂在具名连接上)。

func (*SchemaBuilder) AlterTable

func (s *SchemaBuilder) AlterTable(table string, fn func(t *grammar.Blueprint)) error

AlterTable 兼容别名(= Table,修改表)。

func (*SchemaBuilder) Create

func (s *SchemaBuilder) Create(table string, fn func(t *grammar.Blueprint)) error

Create 新建表(Blueprint 处于 create 模式)。

func (*SchemaBuilder) CreateDatabase

func (s *SchemaBuilder) CreateDatabase(name string) error

CreateDatabase 创建数据库。

func (*SchemaBuilder) CreateTable

func (s *SchemaBuilder) CreateTable(table string, fn func(t *grammar.Blueprint)) error

CreateTable 兼容别名(= Create,新建表)。

func (*SchemaBuilder) DisableForeignKeyConstraints

func (s *SchemaBuilder) DisableForeignKeyConstraints() error

DisableForeignKeyConstraints 禁用外键约束。

func (*SchemaBuilder) Drop

func (s *SchemaBuilder) Drop(table string) error

Drop 删表。

func (*SchemaBuilder) DropAllTables

func (s *SchemaBuilder) DropAllTables() error

DropAllTables 删除当前 schema 下全部表。 MySQL/PG:外键开关包裹 + 逐表 drop(对应 MySqlBuilder/PostgresBuilder); SQLite:writable_schema + sqlite_master delete + vacuum(SQLiteBuilder::dropAllTables, 统一走 writable_schema 路径保证连接内一致;文件级清空 TODO 接线点: 按 DSN 判定文件库后 os.Truncate); SQL Server:先 drop 全部外键,再 sp_msforeachtable(SqlServerBuilder::dropAllTables)。

func (*SchemaBuilder) DropAllTypes

func (s *SchemaBuilder) DropAllTypes() error

DropAllTypes 删除当前 schema 下全部用户自定义类型(仅 Postgres 支持, 其余驱动对应基类的 LogicException 语义)。

func (*SchemaBuilder) DropAllViews

func (s *SchemaBuilder) DropAllViews() error

DropAllViews 删除当前 schema 下全部视图。

func (*SchemaBuilder) DropColumns

func (s *SchemaBuilder) DropColumns(table string, columns ...string) error

DropColumns 删除列(对应 Builder.php:560 dropColumns)。统一走各方言 grammar 的 CompileDropColumn(Blueprint 编译路径): SQLite 产出合法的 alter table x drop column y (>= 3.35,避免缺 COLUMN 关键字的方言非法 SQL);SQL Server 含默认约束 前置块;方言不支持时返回明确错误(RuntimeException 对应物)。

func (*SchemaBuilder) DropDatabaseIfExists

func (s *SchemaBuilder) DropDatabaseIfExists(name string) error

DropDatabaseIfExists 条件删除数据库。

func (*SchemaBuilder) DropIfExists

func (s *SchemaBuilder) DropIfExists(table string) error

DropIfExists 条件删表。

func (*SchemaBuilder) EnableForeignKeyConstraints

func (s *SchemaBuilder) EnableForeignKeyConstraints() error

EnableForeignKeyConstraints 启用外键约束。

func (*SchemaBuilder) GetColumnListing

func (s *SchemaBuilder) GetColumnListing(table string) ([]string, error)

GetColumnListing 列名列表。

func (*SchemaBuilder) GetColumnType

func (s *SchemaBuilder) GetColumnType(table, column string) (string, error)

GetColumnType 返回列的完整类型(对应 getColumnType 的 fullDefinition 分支); 列不存在时报错(InvalidArgumentException 语义)。

func (*SchemaBuilder) GetColumns

func (s *SchemaBuilder) GetColumns(table string) ([]SchemaColumn, error)

GetColumns 返回表列元数据(name/type_name/type/nullable/default/ autoincrement/comment)。

func (*SchemaBuilder) GetForeignKeys

func (s *SchemaBuilder) GetForeignKeys(table string) ([]SchemaForeignKey, error)

GetForeignKeys 返回表外键元数据。

func (*SchemaBuilder) GetIndexListing

func (s *SchemaBuilder) GetIndexListing(table string) ([]string, error)

GetIndexListing 返回索引名列表。

func (*SchemaBuilder) GetIndexes

func (s *SchemaBuilder) GetIndexes(table string) ([]SchemaIndex, error)

GetIndexes 返回表索引元数据。

func (*SchemaBuilder) GetTableListing

func (s *SchemaBuilder) GetTableListing(schema ...string) ([]string, error)

GetTableListing 返回当前连接的表名列表(不含视图)。

func (*SchemaBuilder) GetTables

func (s *SchemaBuilder) GetTables(schema ...string) ([]SchemaTable, error)

GetTables 返回当前连接的表元数据(结果过滤视图;可传 schema 收窄范围)。

func (*SchemaBuilder) GetTypes

func (s *SchemaBuilder) GetTypes(schema ...string) ([]SchemaType, error)

GetTypes 返回用户自定义类型元数据(仅 Postgres;其余驱动不支持)。

func (*SchemaBuilder) GetViews

func (s *SchemaBuilder) GetViews(schema ...string) ([]SchemaView, error)

GetViews 返回视图元数据(可传 schema 收窄范围)。

func (*SchemaBuilder) HasColumn

func (s *SchemaBuilder) HasColumn(table, column string) (bool, error)

HasColumn 列是否存在(大小写不敏感)。

func (*SchemaBuilder) HasColumns

func (s *SchemaBuilder) HasColumns(table string, columns []string) (bool, error)

HasColumns 全部列都存在才返回 true(对应 hasColumns 的 array_all 语义)。

func (*SchemaBuilder) HasForeignKey

func (s *SchemaBuilder) HasForeignKey(table string, foreignKey any) (bool, error)

HasForeignKey 表是否拥有指定外键:foreignKey 可传外键名(string)或列集 ([]string)。

func (*SchemaBuilder) HasIndex

func (s *SchemaBuilder) HasIndex(table string, index any, typ ...string) (bool, error)

HasIndex 表是否拥有指定索引:index 可传索引名(string)或列集([]string); typ 可选 "primary"/"unique"/方言类型名(对应 hasIndex 的 $type 过滤)。

func (*SchemaBuilder) HasTable

func (s *SchemaBuilder) HasTable(table string) (bool, error)

HasTable 表是否存在(引用支持 schema.table 拆分)。

func (*SchemaBuilder) HasView

func (s *SchemaBuilder) HasView(view string) (bool, error)

HasView 视图是否存在(大小写不敏感,引用支持 schema.table 拆分)。

func (*SchemaBuilder) Rename

func (s *SchemaBuilder) Rename(from, to string) error

Rename 重命名表(对应 Builder.php:610 rename)。走各方言 grammar 的 CompileRename(MySQL rename table ... to ...、SQL Server sp_rename、 PG/SQLite alter table ... rename to ...),方言不支持时返回明确错误。

func (*SchemaBuilder) Statement

func (s *SchemaBuilder) Statement(query string, args ...any) error

Statement 在连接上执行原生 SQL(Builder::statement 语义)。 供 SQL 文件迁移等无 Blueprint 场景使用;多语句文件要求驱动支持单次 Exec 执行多语句(MySQL 需 DSN multiStatements=true,SQLite 原生支持)。 Statement 执行原生 SQL(SQL 文件迁移的执行通道)。 **无参数时绕过预编译、直走连接级 Exec**:SQLite(mattn)与 MySQL (multiStatements=true)只在连接级 Execer 路径处理多语句脚本, 预编译路径只执行首条且余下语句被静默丢弃(已实证)。

func (*SchemaBuilder) Table

func (s *SchemaBuilder) Table(table string, fn func(t *grammar.Blueprint)) error

Table 修改表(Blueprint 处于 alter 模式)。

func (*SchemaBuilder) WhenTableDoesntHaveColumn

func (s *SchemaBuilder) WhenTableDoesntHaveColumn(table, column string, fn func(t *grammar.Blueprint)) error

WhenTableDoesntHaveColumn 表缺少指定列时执行表构建回调。

func (*SchemaBuilder) WhenTableDoesntHaveIndex

func (s *SchemaBuilder) WhenTableDoesntHaveIndex(table string, index any, fn func(t *grammar.Blueprint), typ ...string) error

WhenTableDoesntHaveIndex 表缺少指定索引时执行表构建回调。

func (*SchemaBuilder) WhenTableHasColumn

func (s *SchemaBuilder) WhenTableHasColumn(table, column string, fn func(t *grammar.Blueprint)) error

WhenTableHasColumn 表拥有指定列时执行表构建回调。

func (*SchemaBuilder) WhenTableHasIndex

func (s *SchemaBuilder) WhenTableHasIndex(table string, index any, fn func(t *grammar.Blueprint), typ ...string) error

WhenTableHasIndex 表拥有指定索引(名称或列集,可选类型过滤)时执行表构建回调。

func (*SchemaBuilder) WithoutForeignKeyConstraints

func (s *SchemaBuilder) WithoutForeignKeyConstraints(fn func() error) error

WithoutForeignKeyConstraints 在回调执行期间禁用外键约束(无论成败都恢复)。

type SchemaColumn

type SchemaColumn struct {
	Name          string
	TypeName      string // 基础类型名(如 varchar / int4)
	Type          string // 完整类型(如 varchar(255))
	Nullable      bool
	Default       any
	AutoIncrement bool
	Comment       string
}

SchemaColumn 内省结果:表列元数据(getColumns 返回的行结构)。

type SchemaForeignKey

type SchemaForeignKey struct {
	Name           string
	Columns        []string
	ForeignSchema  string
	ForeignTable   string
	ForeignColumns []string
	OnUpdate       string
	OnDelete       string
}

SchemaForeignKey 内省结果:外键元数据(对应 getForeignKeys 行结构)。

type SchemaIndex

type SchemaIndex struct {
	Name    string
	Columns []string
	Type    string // btree / hash 等(方言相关)
	Unique  bool
	Primary bool
}

SchemaIndex 内省结果:索引元数据(对应 getIndexes 行结构)。

type SchemaTable

type SchemaTable struct {
	Name      string
	Schema    string
	Size      int64
	Comment   string
	Engine    string
	Collation string
}

SchemaTable 内省结果:表元数据(对应 getTables 行结构)。

type SchemaType

type SchemaType struct {
	Name     string
	Schema   string
	Type     string // typtype:c(composite)/e(enum)/d(domain)/m(range) 等
	Category string // typcategory
	Implicit bool
}

SchemaType 内省结果:用户自定义类型元数据(对应 getTypes 行结构,仅 Postgres)。

type SchemaView

type SchemaView struct {
	Name       string
	Schema     string
	Definition string
}

SchemaView 内省结果:视图元数据(对应 getViews 行结构)。

type SeederFunc

type SeederFunc func(*Connection) error

SeederFunc 种子函数。

type SerializeOptions

type SerializeOptions struct {
	Hidden  []string // 追加隐藏的列
	Visible []string // 仅输出的列(非空时优先于 hidden)
}

SerializeOptions 控制单次序列化的隐藏/可见列(实例级语义——类型级 MakeHidden/MakeVisible 之外的一次性覆盖,临时 makeHidden 形态)。

func WithHidden

func WithHidden(keys ...string) SerializeOptions

WithHidden 追加隐藏列的选项(makeHidden 的临时形态)。

func WithVisible

func WithVisible(keys ...string) SerializeOptions

WithVisible 仅输出指定列(makeVisible / visible 的临时形态)。

type SimplePaginator

type SimplePaginator struct {
	Items       any
	PerPage     int64
	CurrentPage int64
	HasMore     bool
}

SimplePaginator 简单分页结果结构(多取一条判断 hasMore)。

func (SimplePaginator) Appends

func (p SimplePaginator) Appends(query map[string]string) AppendedSimple

Appends 追加公共查询参数,返回携带参数的链式副本。

func (SimplePaginator) FirstItem

func (p SimplePaginator) FirstItem() int

FirstItem 当前页首条目的全局序号(简单分页器 同样具备;无条目返回 0)。

func (SimplePaginator) From

func (p SimplePaginator) From() int

From 当前页起始条目序号(firstItem 别名)。

func (SimplePaginator) HasMorePages

func (p SimplePaginator) HasMorePages() bool

HasMorePages 是否还有下一页(基于 simplePaginate 多取一条判断出的 HasMore)。

func (SimplePaginator) LastItem

func (p SimplePaginator) LastItem() int

LastItem 当前页末条目的全局序号:无条目返回 0。

func (SimplePaginator) To

func (p SimplePaginator) To() int

To 当前页结束条目序号(lastItem 别名)。

func (SimplePaginator) URL

func (p SimplePaginator) URL(page int, query map[string]string) string

URL 分页链接查询串(语义同 LengthAwarePaginator.URL)。

type SoftDeletes

type SoftDeletes struct {
	field.DeletedAtAttr
}

SoftDeletes 是软删除内嵌属性(兼容旧用法)。

type SqlServerConnector

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

SqlServerConnector SQLServer 连接器(对应 Connectors\SqlServerConnector)。 注意:go-mssqldb 的 DSN 不支持隔离级别参数,isolation_level 仍以建连后 SET 执行——连接池下仅对执行时选中的连接生效(已知限制,需要精确控制时 建议在事务内显式 set transaction isolation level)。

func (*SqlServerConnector) Connect

func (c *SqlServerConnector) Connect(dsn string) (*sql.DB, error)

Connect 打开 SQLServer 连接。

type SyncResult

type SyncResult struct {
	Attached []any
	Detached []any
	Updated  []any
}

SyncResult sync 的返回(attached/detached/updated 三组)。

type TableName

type TableName interface {
	TableName() string
}

type ZipPair

type ZipPair[T any, U any] struct {
	First  T
	Second U
}

ZipPair zip 配对结果。

Directories

Path Synopsis
driver
Package events 数据库层事件包: 查询与模型生命周期事件对象、分发器接口与默认总线实现。
Package events 数据库层事件包: 查询与模型生命周期事件对象、分发器接口与默认总线实现。
internal
faketb
Package faketb provides an in-memory fake database/sql driver so the torm test suites can exercise the connection layer without a real MySQL server.
Package faketb provides an in-memory fake database/sql driver so the torm test suites can exercise the connection layer without a real MySQL server.

Jump to

Keyboard shortcuts

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