orm

package
v0.0.0-20260608 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CastDatetime = "datetime"
	CastJSON     = "json"
	CastBool     = "bool"
	CastInt      = "int"
	CastFloat    = "float"
	CastString   = "string"
)

Built-in cast types (Laravel-like)

Variables

View Source
var (
	PreventLazyLoading bool
	HasUuids           bool
)

ModelConfig holds strictness rules.

View Source
var ErrCancelled = errors.New("operation cancelled by model observer")

Functions

func AddGlobalScope

func AddGlobalScope(model string, scope Scope)

AddGlobalScope registers a global scope for a given model type name.

func Attach

func Attach(db *DB, pivotTable, foreignKey, relatedKey string, parentID, relatedID any) error

Attach adds a relationship in the pivot table.

func ClearCache

func ClearCache(modelType any)

ClearCache removes cached metadata for the given model type. Call this after altering struct tags or table mappings at runtime.

func Detach

func Detach(db *DB, pivotTable, foreignKey, relatedKey string, parentID, relatedID any) error

Detach removes a specific relationship from the pivot table.

func DispatchModelEvent

func DispatchModelEvent(model any, event string) bool

DispatchModelEvent fires registered observers, interface hooks, and global events. Returning false from a "ing" event (like Creating) halts the operation.

func GetModelAttribute

func GetModelAttribute(model any, name string) any

GetModelAttribute retrieves the value of an attribute on a model. It first looks for a method Get<Name>Attribute() (e.g. GetTitleAttribute). Falls back to direct struct field access (case-insensitive). This enables Laravel-style accessors without magic.

func GetMorphType

func GetMorphType(name string) reflect.Type

GetMorphType returns the registered reflect.Type for a morph name, or nil.

func GetTableName

func GetTableName(model any) string

GetTableName resolves the table name for a model instance using metadata.

func IsPreventLazyLoading

func IsPreventLazyLoading() bool

IsPreventLazyLoading returns whether lazy loading prevention is enabled.

func Make

func Make[T any](db *DB, factory Factory[T], overrides ...map[string]any) (*T, error)

Make creates a single model instance with the factory definition.

func MakeMany

func MakeMany[T any](db *DB, factory Factory[T], count int, overrides ...map[string]any) ([]*T, error)

MakeMany creates multiple model instances.

func Observe

func Observe(model string, observer Observer)

Observe registers an observer for a model.

func RegisterMorph

func RegisterMorph(name string, model any)

RegisterMorph registers a name (used in *_type columns) to a model struct type. Call this in init() or bootstrap for each polymorphic model.

func Seed

func Seed[T any](db *DB, factory Factory[T], count int) error

Seed runs multiple factory definitions to seed the database.

func SetEventManager

func SetEventManager(m EventDispatcher)

SetEventManager injects the global event manager.

func SetModelAttribute

func SetModelAttribute(model any, name string, value any)

SetModelAttribute sets an attribute value on a model. Looks for Set<Name>Attribute(value) method first (mutator). Falls back to setting the struct field directly if exported.

func SetPreventLazyLoading

func SetPreventLazyLoading(prevent bool)

SetPreventLazyLoading enables/disables lazy loading prevention.

func Sync

func Sync(db *DB, pivotTable, foreignKey, relatedKey string, parentID any, relatedIDs []any) error

Sync replaces all existing relationships with the given list of related IDs.

func ToArray

func ToArray[T any](model *T) map[string]any

ToArray converts a model to a map for serialization.

func Toggle

func Toggle(db *DB, pivotTable, foreignKey, relatedKey string, parentID, relatedID any) error

Toggle adds the relationship if it doesn't exist, removes it if it does.

func UUID

func UUID() string

UUID returns a new UUID v4 string.

Types

type AfterCreateHook

type AfterCreateHook interface {
	AfterCreate() error
}

type AfterDeleteHook

type AfterDeleteHook interface {
	AfterDelete() error
}

type AfterRestoreHook

type AfterRestoreHook interface {
	AfterRestore() error
}

type AfterSaveHook

type AfterSaveHook interface {
	AfterSave() error
}

type AfterUpdateHook

type AfterUpdateHook interface {
	AfterUpdate() error
}

type BeforeCreateHook

type BeforeCreateHook interface {
	BeforeCreate() error
}

type BeforeDeleteHook

type BeforeDeleteHook interface {
	BeforeDelete() error
}

type BeforeRestoreHook

type BeforeRestoreHook interface {
	BeforeRestore() error
}

type BeforeSaveHook

type BeforeSaveHook interface {
	BeforeSave() error
}

type BeforeUpdateHook

type BeforeUpdateHook interface {
	BeforeUpdate() error
}

type BelongsTo

type BelongsTo[T any] struct {
	Model *T
}

BelongsTo represents an inverse one-to-many relationship.

type BelongsToMany

type BelongsToMany[T any] struct {
	Models []T
}

BelongsToMany represents a many-to-many relationship via a pivot table.

type BoolCast

type BoolCast struct{}

func (*BoolCast) Get

func (c *BoolCast) Get(value any) (any, error)

func (*BoolCast) Set

func (c *BoolCast) Set(value any) (any, error)

type Cast

type Cast interface {
	Get(value any) (any, error)
	Set(value any) (any, error)
}

Cast represents an attribute casting strategy.

type Castable

type Castable interface {
	Casts() map[string]string
}

Castable models declare their attribute casts.

type DB

type DB struct {
	Conn    query.QueryExecer
	Builder *query.Builder
	// contains filtered or unexported fields
}

DB represents the ORM database connection.

func (*DB) Begin

func (db *DB) Begin(ctx context.Context) (*DB, error)

Begin starts a new database transaction and returns a new *DB instance that operates within that transaction.

func (*DB) BeginTx

func (db *DB) BeginTx() (*DB, error)

BeginTx is a convenience method equivalent to Begin(context.Background()).

func (*DB) Commit

func (db *DB) Commit() error

Commit commits the current transaction. It only works if this DB instance was created via Begin() or Transaction().

func (*DB) Dialect

func (db *DB) Dialect() (dialect.Dialect, error)

Dialect returns the SQL dialect used by this connection.

func (*DB) InTransaction

func (db *DB) InTransaction() bool

InTransaction returns true if this DB instance is operating inside a transaction.

func (*DB) RawDB

func (db *DB) RawDB() query.QueryExecer

RawDB returns the underlying query executor (usually *sql.DB or *sql.Tx).

func (*DB) Rollback

func (db *DB) Rollback() error

Rollback rolls back the current transaction.

func (*DB) Transaction

func (db *DB) Transaction(ctx context.Context, fn func(txDB *DB) error) error

Transaction executes a function within a database transaction.

func (*DB) TransactionFn

func (db *DB) TransactionFn(fn func(txDB *DB) error) error

TransactionFn is a convenience method that runs the given function inside a transaction using context.Background(). Useful for simple cases.

type DateTimeCast

type DateTimeCast struct{}

func (*DateTimeCast) Get

func (c *DateTimeCast) Get(value any) (any, error)

func (*DateTimeCast) Set

func (c *DateTimeCast) Set(value any) (any, error)

type EventDispatcher

type EventDispatcher interface {
	Dispatch(event any)
}

EventDispatcher interface allows ORM to dispatch global events without strong coupling to the events package.

type Factory

type Factory[T any] interface {
	Definition() map[string]any
}

Factory defines a model factory for creating test/seed data.

type FieldMeta

type FieldMeta struct {
	Name      string // struct field name
	Column    string // db tag value
	Index     int    // reflect field index for fast access
	IsPrimary bool
	IsAuto    bool // auto-increment
}

FieldMeta represents cached metadata for a struct field.

type FloatCast

type FloatCast struct{}

func (*FloatCast) Get

func (c *FloatCast) Get(value any) (any, error)

func (*FloatCast) Set

func (c *FloatCast) Set(value any) (any, error)

type HasMany

type HasMany[T any] struct {
	// Represents the related models
	Models []T
}

HasMany represents a one-to-many relationship.

type HasOne

type HasOne[T any] struct {
	Model *T
}

HasOne represents a one-to-one relationship.

type IntCast

type IntCast struct{}

func (*IntCast) Get

func (c *IntCast) Get(value any) (any, error)

func (*IntCast) Set

func (c *IntCast) Set(value any) (any, error)

type JSONCast

type JSONCast struct{}

func (*JSONCast) Get

func (c *JSONCast) Get(value any) (any, error)

func (*JSONCast) Set

func (c *JSONCast) Set(value any) (any, error)

type MassAssignable

type MassAssignable interface {
	// Fillable returns the list of fields that are allowed to be mass assigned.
	// If empty, all fields are allowed unless Guarded is specified.
	Fillable() []string

	// Guarded returns the list of fields that are not allowed to be mass assigned.
	// Use ["*"] to guard all fields by default.
	Guarded() []string
}

MassAssignable allows models to control mass assignment protection, similar to Laravel's $fillable and $guarded properties.

type Model

type Model interface {
	TableName() string
}

Model represents a generic interface for all Goquent models.

type ModelCreated

type ModelCreated struct{ Model any }

type ModelCreating

type ModelCreating struct{ Model any }

type ModelDeleted

type ModelDeleted struct{ Model any }

type ModelDeleting

type ModelDeleting struct{ Model any }

type ModelMetadata

type ModelMetadata struct {
	TableName     string
	PrimaryKey    string
	SoftDeleteCol string // empty string if no soft delete field
	Fields        []FieldMeta
}

ModelMetadata holds cached reflection data for an ORM model.

type ModelQuery

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

ModelQuery is an ORM-wrapper around the Query Builder.

func NewQuery

func NewQuery[T any](db *DB) *ModelQuery[T]

func (*ModelQuery[T]) Chunk

func (q *ModelQuery[T]) Chunk(size int, callback func([]T) error) error

Chunk processes results in batches of the given size, calling the callback for each batch. Stops if callback returns error. Excellent for large data processing (Laravel equivalent).

func (*ModelQuery[T]) CursorPaginate

func (q *ModelQuery[T]) CursorPaginate(perPage int, after any) (*pagination.CursorPaginator[T], error)

CursorPaginate is a basic cursor-based paginator (keyset pagination).

func (*ModelQuery[T]) Delete

func (q *ModelQuery[T]) Delete(model *T) error

Delete deletes the given model (or rows matching the query if model is nil).

func (*ModelQuery[T]) Distinct

func (q *ModelQuery[T]) Distinct() *ModelQuery[T]

Distinct adds a DISTINCT clause to the query.

func (*ModelQuery[T]) Find

func (q *ModelQuery[T]) Find(id any) (*T, error)

Find fetches a model by its primary key.

func (*ModelQuery[T]) FindOrFail

func (q *ModelQuery[T]) FindOrFail(id any) (*T, error)

FindOrFail fetches a model by its primary key or returns an error if not found.

func (*ModelQuery[T]) First

func (q *ModelQuery[T]) First() (*T, error)

First fetches the first matching record.

func (*ModelQuery[T]) FirstOrCreate

func (q *ModelQuery[T]) FirstOrCreate(attributes map[string]any, values ...map[string]any) (*T, bool, error)

FirstOrCreate returns the first record matching the attributes, or creates it if not found.

func (*ModelQuery[T]) FirstOrNew

func (q *ModelQuery[T]) FirstOrNew(attributes map[string]any, values ...map[string]any) (*T, bool, error)

FirstOrNew returns the first record matching the attributes, or creates a new instance (not saved).

func (*ModelQuery[T]) ForceDelete

func (q *ModelQuery[T]) ForceDelete(model *T) error

ForceDelete permanently deletes the model.

func (*ModelQuery[T]) Get

func (q *ModelQuery[T]) Get() ([]*T, error)

Get fetches all matching records.

func (*ModelQuery[T]) Insert

func (q *ModelQuery[T]) Insert(model *T) error

Insert creates a new record from the model struct.

func (*ModelQuery[T]) LockForUpdate

func (q *ModelQuery[T]) LockForUpdate() *ModelQuery[T]

LockForUpdate enables pessimistic lock on the query (FOR UPDATE).

func (*ModelQuery[T]) OnlyTrashed

func (q *ModelQuery[T]) OnlyTrashed() *ModelQuery[T]

OnlyTrashed limits the query to only soft-deleted records.

func (*ModelQuery[T]) Paginate

func (q *ModelQuery[T]) Paginate(perPage, page int) (*pagination.LengthAwarePaginator[T], error)

Paginate returns a length-aware paginator (with total count).

func (*ModelQuery[T]) Restore

func (q *ModelQuery[T]) Restore(model *T) error

Restore restores a soft-deleted model.

func (*ModelQuery[T]) Save

func (q *ModelQuery[T]) Save(model *T) error

Save inserts a new model or updates an existing one based on primary key presence.

func (*ModelQuery[T]) SharedLock

func (q *ModelQuery[T]) SharedLock() *ModelQuery[T]

SharedLock enables shared lock (FOR SHARE).

func (*ModelQuery[T]) SimplePaginate

func (q *ModelQuery[T]) SimplePaginate(perPage, page int) (*pagination.SimplePaginator[T], error)

SimplePaginate returns a simple paginator (no total count).

func (*ModelQuery[T]) ToJSON

func (q *ModelQuery[T]) ToJSON(model *T) (string, error)

ToJSON serializes the model to a JSON string.

func (*ModelQuery[T]) Update

func (q *ModelQuery[T]) Update(model *T) error

Update updates an existing model.

func (*ModelQuery[T]) Where

func (q *ModelQuery[T]) Where(column, operator string, value any) *ModelQuery[T]

Where adds a where clause.

func (*ModelQuery[T]) WhereDoesntHave

func (q *ModelQuery[T]) WhereDoesntHave(relation string) *ModelQuery[T]

WhereDoesntHave adds a condition that the relationship has NO related records.

func (*ModelQuery[T]) WhereHas

func (q *ModelQuery[T]) WhereHas(relation string, callback func(b *query.Builder) *query.Builder) *ModelQuery[T]

WhereHas adds a condition that the relationship has related records.

func (*ModelQuery[T]) WhereRelation

func (q *ModelQuery[T]) WhereRelation(relation, column, operator string, value any) *ModelQuery[T]

WhereRelation adds a condition on a related model's column.

func (*ModelQuery[T]) With

func (q *ModelQuery[T]) With(relation string) *ModelQuery[T]

With adds a relationship to be eager-loaded.

func (*ModelQuery[T]) WithTrashed

func (q *ModelQuery[T]) WithTrashed() *ModelQuery[T]

WithTrashed includes soft-deleted records in the query.

type ModelRestored

type ModelRestored struct{ Model any }

type ModelRestoring

type ModelRestoring struct{ Model any }

type ModelSaved

type ModelSaved struct{ Model any }

type ModelSaving

type ModelSaving struct{ Model any }

type ModelUpdated

type ModelUpdated struct{ Model any }

type ModelUpdating

type ModelUpdating struct{ Model any }

type MorphMany

type MorphMany[T any] struct {
	Models []T
}

MorphMany and MorphOne wrapper types

type MorphOne

type MorphOne[T any] struct {
	Model *T
}

type MorphTo

type MorphTo struct {
	Model any
}

MorphTo holds dynamically resolved related model for inverse polymorphic relation.

type Observer

type Observer interface {
	Creating(model any) bool
	Created(model any)
	Updating(model any) bool
	Updated(model any)
	Deleting(model any) bool
	Deleted(model any)
}

Observer represents model event hooks.

type Scope

type Scope interface {
	Apply(builder *query.Builder) *query.Builder
}

Scope represents a query scope that can be applied to a builder.

type ScopeFunc

type ScopeFunc func(builder *query.Builder) *query.Builder

ScopeFunc is a convenience wrapper to use a function as a Scope.

func (ScopeFunc) Apply

func (f ScopeFunc) Apply(builder *query.Builder) *query.Builder

type SerializesAttributes

type SerializesAttributes interface {
	Hidden() []string  // fields to hide in serialization
	Appends() []string // virtual attributes to always include (must have getters)
}

SerializesAttributes optional interface for controlling JSON/API output.

type StringCast

type StringCast struct{}

func (*StringCast) Get

func (c *StringCast) Get(value any) (any, error)

func (*StringCast) Set

func (c *StringCast) Set(value any) (any, error)

type Touches

type Touches interface {
	Touches() []string // relation names (e.g. ["post", "author"])
}

Touches allows a model to declare relations that should have their timestamps updated when this model is saved/updated.

type UUIDModel

type UUIDModel struct {
	ID string `json:"id" db:"id" gow:"uuid"`
}

UUIDModel is a base struct implementing UUIDTrait.

func (*UUIDModel) GenerateUUID

func (u *UUIDModel) GenerateUUID() string

GenerateUUID generates a new UUID v4.

type UUIDTrait

type UUIDTrait interface {
	GenerateUUID() string
}

UUIDTrait is an interface for models using UUID primary keys.

Jump to

Keyboard shortcuts

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