Documentation
¶
Index ¶
- Constants
- Variables
- func AddConnection(name string, db *lucid.DB)
- func ApplyPool(db *lucid.DB, p PoolConfig) error
- func Attach(db *lucid.DB, model any, relationName string, related ...any) error
- func AutoMigrateNotifications(db *lucid.DB) error
- func AutoPreload(db *lucid.DB, model any) *lucid.DB
- func CachedFind(db *lucid.DB, key string, ttl time.Duration, dest any) error
- func Chunk[T any](db *lucid.DB, size int, fn func(batch []T) error) error
- func CloseAll() error
- func Connect(driver, dsn string) (*lucid.DB, error)
- func ConnectAll(configs []ConnectionConfig) error
- func ConnectWithConfig(cfg ConnectConfig) (*lucid.DB, error)
- func Connection(name string) *lucid.DB
- func ConnectionNames() []string
- func CountBy(db *lucid.DB) (int64, error)
- func CreateDatabaseIfNotExists(cfg CreateConfig) error
- func Debug()
- func Detach(db *lucid.DB, model any, relationName string, related ...any) error
- func DetachAll(db *lucid.DB, model any, relationName string) error
- func Exec(db *lucid.DB, sql string, args ...any) error
- func Exists(db *lucid.DB) (bool, error)
- func FillableFor(model any) []string
- func FirstOrCreate[T any](db *lucid.DB, where T, attrs T) (*T, error)
- func ForceDelete(db *lucid.DB, model any) error
- func Get() *lucid.DB
- func HasRelated(db *lucid.DB, model any, relationName string, related any) (bool, error)
- func IsDirty(v any, field string) bool
- func IsTrashed(m *Model) bool
- func Load(db *lucid.DB, model any, relations ...string) error
- func MigratePivots(db *lucid.DB, models ...any) error
- func MustConnection(name string) *lucid.DB
- func OnlyTrashed(db *lucid.DB) *lucid.DB
- func Pluck[T any](db *lucid.DB, column string) ([]T, error)
- func Preload(db *lucid.DB, name string, args ...any) *lucid.DB
- func PrettyPrintQueries()
- func Raw(db *lucid.DB, sql string, dest any, args ...any) error
- func RegisterHooks(db *lucid.DB, name string, h Hooks)
- func Related(db *lucid.DB, model any, relationName string) *lucid.DB
- func RequireConnection(name string) (*lucid.DB, error)
- func Restore(db *lucid.DB, model any) error
- func RunMigrationsFromDir(db *lucid.DB, dir string) error
- func Serialize(v any, opts SerializeOptions) (map[string]any, error)
- func SetDefault(name string) error
- func Sync(db *lucid.DB, model any, relationName string, related ...any) error
- func TableNameFor(model any) string
- func Transaction(db *lucid.DB, fn func(tx *lucid.DB) error) error
- func TransactionWithDB(fn func(tx *lucid.DB) error) error
- func UpdateOrCreate[T any](db *lucid.DB, where T, update T) (*T, error)
- func WithTrashed(db *lucid.DB) *lucid.DB
- type BaseModel
- type ConnectConfig
- type ConnectionConfig
- type ConnectionManager
- type CreateConfig
- type CursorPaginateOptions
- type CursorPaginator
- type DatabaseNotification
- type Factory
- type FactoryWithAttrs
- type Faker
- type FillableProvider
- type HookFunc
- type Hooks
- type Migration
- type MigrationStatus
- type Migrator
- type Model
- type Notifiable
- type NotificationStore
- func (s *NotificationStore) All(notifiable Notifiable) ([]DatabaseNotification, error)
- func (s *NotificationStore) Delete(id string) error
- func (s *NotificationStore) DeleteAll(notifiable Notifiable) error
- func (s *NotificationStore) MarkAllAsRead(notifiable Notifiable) error
- func (s *NotificationStore) MarkAsRead(id string) error
- func (s *NotificationStore) Read(notifiable Notifiable) ([]DatabaseNotification, error)
- func (s *NotificationStore) Send(notifiable Notifiable, notifType string, data any) error
- func (s *NotificationStore) Unread(notifiable Notifiable) ([]DatabaseNotification, error)
- func (s *NotificationStore) UnreadCount(notifiable Notifiable) (int64, error)
- type Paginator
- type PoolConfig
- type Query
- func (q *Query) Avg(column string) (float64, error)
- func (q *Query) Count() (int64, error)
- func (q *Query) Create(value any) error
- func (q *Query) DB() *lucid.DB
- func (q *Query) Delete(value any, conds ...any) error
- func (q *Query) Distinct(columns ...string) *Query
- func (q *Query) Exists() (bool, error)
- func (q *Query) Find(dest any, conds ...any) error
- func (q *Query) First(dest any) error
- func (q *Query) FirstOrFail(dest any) error
- func (q *Query) Get(dest any) error
- func (q *Query) GroupBy(columns ...string) *Query
- func (q *Query) Having(query string, args ...any) *Query
- func (q *Query) Join(query string, args ...any) *Query
- func (q *Query) Last(dest any) error
- func (q *Query) LeftJoin(table, condition string) *Query
- func (q *Query) Limit(limit int) *Query
- func (q *Query) Max(column string) (float64, error)
- func (q *Query) Min(column string) (float64, error)
- func (q *Query) Offset(offset int) *Query
- func (q *Query) OrWhere(query any, args ...any) *Query
- func (q *Query) OrderBy(value string) *Query
- func (q *Query) Paginate(dest any, page, perPage int) (*Paginator, error)
- func (q *Query) Pluck(column string, dest any) error
- func (q *Query) Preload(name string, args ...any) *Query
- func (q *Query) RightJoin(table, condition string) *Query
- func (q *Query) Scopes(scopes ...func(*lucid.DB) *lucid.DB) *Query
- func (q *Query) Select(columns ...string) *Query
- func (q *Query) Sum(column string) (float64, error)
- func (q *Query) Unscoped() *Query
- func (q *Query) Update(column string, value any) error
- func (q *Query) Updates(values any) error
- func (q *Query) Where(query any, args ...any) *Query
- func (q *Query) WhereBetween(column string, low, high any) *Query
- func (q *Query) WhereIn(column string, values ...any) *Query
- func (q *Query) WhereLike(column, pattern string) *Query
- func (q *Query) WhereNotIn(column string, values ...any) *Query
- func (q *Query) WhereNotNull(column string) *Query
- func (q *Query) WhereNull(column string) *Query
- func (q *Query) WhereRaw(sql string, args ...any) *Query
- type QueryPayload
- type Relation
- type RelationKind
- type RelationProvider
- type Scope
- type SeedFunc
- type SeedRunner
- type Seeder
- type SerializeOptions
- type SimplePaginatorResult
- type TableNamer
Constants ¶
const ( EventQuery = "db:query" EventInsert = "db:insert" EventUpdate = "db:update" EventDelete = "db:delete" )
Event constants for database operations.
const SerializeAsNull = "-"
SerializeAsNull returns a struct tag value to omit a field from JSON. In Go, use: `json:"-"` to omit. This helper documents the pattern.
Variables ¶
var DB *lucid.DB
DB is the global GORM instance (AdonisJS Lucid-style; in production use DI).
Functions ¶
func AddConnection ¶
AddConnection registers a named database connection. The first connection registered is also set as the global DB.
func ApplyPool ¶
func ApplyPool(db *lucid.DB, p PoolConfig) error
ApplyPool applies non-zero pool settings to the given GORM handle.
func Attach ¶
Attach adds related models to a manyToMany relation via the pivot table. AdonisJS equivalent: await user.related('teams').attach([teamId1, teamId2])
database.Attach(db, &user, "Teams", &team1, &team2)
func AutoMigrateNotifications ¶
AutoMigrateNotifications creates the notifications table.
func AutoPreload ¶
AutoPreload applies preloads based on either:
- RelationProvider.Relations(), when the model implements it, or
- struct tags parsed via ParseRelations as a fallback.
For belongsTo / hasOne / hasMany it delegates to GORM's Preload (convention- based). For manyToMany it uses Nimbus's custom Load function which handles pivot tables automatically.
Usage:
db := AutoPreload(database.Get(), &models.Blog{})
if err := db.Find(&blogs).Error; err != nil { ... }
func CachedFind ¶
CachedFind runs the query and caches the result. Use for read-heavy, rarely-changing data. Key should be unique per query (e.g. "users:list", "user:1").
Example:
var users []User
err := database.CachedFind(db.Model(&User{}).Where("active = ?", true), "users:active", 10*time.Minute, &users)
func Chunk ¶
Chunk processes records in batches.
database.Chunk(db.Model(&User{}), 100, func(users []User) error {
for _, u := range users {
process(u)
}
return nil
})
func CloseAll ¶
func CloseAll() error
CloseAll closes all registered connections (call at shutdown).
func ConnectAll ¶
func ConnectAll(configs []ConnectionConfig) error
ConnectAll establishes multiple database connections from config.
func ConnectWithConfig ¶
func ConnectWithConfig(cfg ConnectConfig) (*lucid.DB, error)
ConnectWithConfig opens a connection with full config and sets the package-global DB to this handle.
func Connection ¶
Connection returns a named database connection. Returns nil if the connection name is not registered.
func ConnectionNames ¶
func ConnectionNames() []string
ConnectionNames returns all registered connection names.
func CreateDatabaseIfNotExists ¶
func CreateDatabaseIfNotExists(cfg CreateConfig) error
CreateDatabaseIfNotExists creates the configured database when supported by the driver. For sqlite, this is effectively a no-op (the file is created automatically when connecting).
func Detach ¶
Detach removes related models from a manyToMany relation via the pivot table. AdonisJS equivalent: await user.related('teams').detach([teamId1])
database.Detach(db, &user, "Teams", &team1)
func DetachAll ¶
DetachAll removes all related models from a manyToMany pivot table.
database.DetachAll(db, &user, "Teams")
func FillableFor ¶
FillableFor returns the list of mass-assignable fields for a model. Resolution order:
- FillableProvider.Fillable()
- All exported struct fields excluding the embedded database.Model and common timestamp/soft-delete fields.
func FirstOrCreate ¶
FirstOrCreate finds the first matching record or creates it.
func ForceDelete ¶
ForceDelete permanently deletes a record (bypasses soft delete).
func HasRelated ¶
HasRelated checks if a manyToMany relation has a specific related model attached.
attached, err := database.HasRelated(db, &user, "Teams", &team)
func IsDirty ¶
IsDirty checks if a struct field was modified (for hooks). GORM tracks this via Statement.Changed(). This is a helper for custom logic.
func Load ¶
Load eagerly loads one or more relations onto an already-fetched model. This is the AdonisJS-style post-query loading:
var user User db.First(&user, 1) database.Load(db, &user, "Posts", "Teams") // user.Posts and user.Teams are now populated
For belongsTo / hasOne / hasMany, the function queries the related table using conventional foreign key names. For manyToMany, it queries through the pivot table (auto-generated or specified via pivotTable tag option).
The model must be a pointer to a struct.
func MigratePivots ¶
MigratePivots scans nimbus tags on the given models and creates any missing manyToMany pivot tables. Call after database.Boot().
database.MigratePivots(db, &User{}, &Post{}, &Tag{})
func MustConnection ¶
MustConnection returns a named connection or panics if not found.
func OnlyTrashed ¶
OnlyTrashed returns only soft-deleted records.
func Preload ¶
Preload loads associations via GORM's built-in eager loading. For belongsTo / hasOne / hasMany, GORM detects relationships automatically from Go conventions (e.g. UserID + User field).
For manyToMany relations, use database.Load() instead — it handles pivot tables using nimbus tags without requiring gorm:"many2many" tags.
Model definition (convention-based, no tags needed):
type Post struct {
database.Model
UserID uint
User *User
Comments []Comment
}
type User struct {
database.Model
Posts []Post
Teams []Team
}
Loading relations:
// GORM Preload (belongsTo / hasMany / hasOne)
db.Preload("User").Preload("Comments").Find(&posts)
// Nimbus Load (all relation types, including manyToMany)
database.Load(db, &user, "Posts", "Teams")
// Nimbus query builder for relations
database.Related(db, &user, "Posts").Where("published = ?", true).Find(&posts)
// ManyToMany pivot operations
database.Attach(db, &user, "Teams", &team1, &team2)
database.Detach(db, &user, "Teams", &team1)
database.Sync(db, &user, "Teams", &team1, &team3)
func PrettyPrintQueries ¶
func PrettyPrintQueries()
PrettyPrintQueries logs SQL to stdout (development).
func RegisterHooks ¶
RegisterHooks registers the given hooks for the model. Hooks are registered globally per callback name; for model-specific hooks, use GORM's Scopes or register in your model's init.
func Related ¶
Related returns a scoped GORM query for a relation on the given model. This is like AdonisJS's user.related('posts').query():
var publishedPosts []Post
database.Related(db, &user, "Posts").Where("published = ?", true).Find(&publishedPosts)
func RequireConnection ¶
RequireConnection returns a named connection or an error if not found. Prefer this in runtime paths where panic is undesirable.
func RunMigrationsFromDir ¶
RunMigrationsFromDir discovers Go files in dir and runs Up on a migrator. Convention: each file defines a Migration and registers via RegisterMigration. This is a placeholder; real usage would use go:generate or a separate migration runner.
func Serialize ¶
func Serialize(v any, opts SerializeOptions) (map[string]any, error)
Serialize converts a model to a map, applying omit/pick. Use for API responses to exclude sensitive fields.
func SetDefault ¶
SetDefault sets which named connection is the "default" one (returned by Get() and used globally).
func Sync ¶
Sync replaces all existing pivot records with the given related models. AdonisJS equivalent: await user.related('teams').sync([teamId1, teamId3])
database.Sync(db, &user, "Teams", &team1, &team3)
func TableNameFor ¶
TableNameFor returns the logical table name for a model. Resolution order:
- TableNamer.Table()
- Pluralized struct name (Blog -> blogs, UserProfile -> user_profiles)
func Transaction ¶
Transaction runs fn inside a transaction. On success it commits; on error it rolls back. Lucid-style managed transaction.
func TransactionWithDB ¶
TransactionWithDB runs fn inside a transaction using the global DB.
func UpdateOrCreate ¶
UpdateOrCreate finds a record by where conditions and updates it, or creates a new one.
Types ¶
type BaseModel ¶
type BaseModel = Model
BaseModel allows embedding in app models for consistent fields.
type ConnectConfig ¶
type ConnectConfig struct {
Driver string
DSN string
// Debug enables SQL logging (pretty-print in development).
Debug bool
PoolConfig
}
ConnectConfig holds options for Connect.
type ConnectionConfig ¶
type ConnectionConfig struct {
// Name is the connection identifier (e.g. "default", "analytics", "logs").
Name string
// Driver: "postgres", "mysql", "sqlite"
Driver string
// DSN is the full connection string.
DSN string
// Debug enables SQL logging.
Debug bool
PoolConfig
}
ConnectionConfig holds configuration for a single database connection.
type ConnectionManager ¶
type ConnectionManager struct {
// contains filtered or unexported fields
}
ConnectionManager manages named database connections.
type CreateConfig ¶
type CreateConfig struct {
Driver string
Host string
Port string
User string
Password string
Database string
}
CreateConfig holds the minimal information needed to create a database when it does not exist. It mirrors the generated config.Database struct.
type CursorPaginateOptions ¶
type CursorPaginateOptions struct {
// Column to paginate by (default: "id")
Column string
// After is the cursor value after which to fetch results.
After string
// Before is the cursor value before which to fetch results.
Before string
// PerPage is the number of records per page (default: 20).
PerPage int
// Order: "asc" or "desc" (default: "desc")
Order string
}
CursorPaginateOptions configures cursor pagination.
type CursorPaginator ¶
type CursorPaginator struct {
Data any `json:"data"`
PerPage int `json:"per_page"`
NextCursor string `json:"next_cursor"`
PrevCursor string `json:"previous_cursor"`
HasMore bool `json:"has_more"`
}
CursorPaginator holds cursor-paginated results (keyset pagination). More efficient than offset-based for large datasets.
func CursorPaginate ¶
func CursorPaginate(db *lucid.DB, dest any, opts CursorPaginateOptions) (*CursorPaginator, error)
CursorPaginate performs cursor/keyset pagination. Requires a sortable, unique column (typically ID or created_at).
type DatabaseNotification ¶
type DatabaseNotification struct {
ID string `gorm:"primaryKey;size:36" json:"id"`
Type string `gorm:"size:255;not null;index" json:"type"`
NotifiableType string `gorm:"size:255;not null;index" json:"notifiable_type"`
NotifiableID string `gorm:"size:255;not null;index" json:"notifiable_id"`
Data json.RawMessage `gorm:"type:text" json:"data"`
ReadAt *time.Time `json:"read_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
DatabaseNotification represents a notification stored in the database. Similar to Laravel's database notification channel.
func (DatabaseNotification) TableName ¶
func (DatabaseNotification) TableName() string
TableName returns the table name for notifications.
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory generates fake data for models (Lucid-style factories).
func (*Factory) Create ¶
Create inserts one record with fake data. Override specific fields with attrs.
func (*Factory) CreateMany ¶
CreateMany inserts n records with fake data.
type FactoryWithAttrs ¶
type FactoryWithAttrs struct {
// contains filtered or unexported fields
}
FactoryWithAttrs is a factory with pre-set overrides.
type FillableProvider ¶
type FillableProvider interface {
Fillable() []string
}
FillableProvider can be implemented by models that want to declare which fields are mass-assignable. This metadata can be used by higher-level helpers (request binding, scaffolding, admin UIs, etc).
Example:
func (Blog) Fillable() []string {
return []string{"title", "content", "published"}
}
type Hooks ¶
type Hooks struct {
BeforeCreate HookFunc
AfterCreate HookFunc
BeforeUpdate HookFunc
AfterUpdate HookFunc
BeforeSave HookFunc
AfterSave HookFunc
BeforeDelete HookFunc
AfterDelete HookFunc
}
RegisterHooks registers GORM callbacks for a model (Lucid-style hooks). Use with db.Callback() or pass the model's table name.
Example:
database.RegisterHooks(db, "users", database.Hooks{
BeforeCreate: func(db *lucid.DB) { /* hash password */ },
AfterCreate: func(db *lucid.DB) { /* send welcome email */ },
})
type Migration ¶
type Migration struct {
Name string
Up func(*lucid.DB) error
Down func(*lucid.DB) error
// NonTransactional disables transaction wrapping for this migration.
// Useful for DDL operations that cannot run inside a transaction.
NonTransactional bool
}
Migration runs a single migration (Up/Down).
type MigrationStatus ¶
MigrationStatus represents the status of a single migration.
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator runs migrations from a directory or list (AdonisJS database/migrations).
func NewMigrator ¶
NewMigrator creates a migrator with the given migrations.
func (*Migrator) Fresh ¶
Fresh drops all tables and re-runs all migrations from scratch. Equivalent to Laravel's migrate:fresh.
func (*Migrator) PrintStatus ¶
PrintStatus prints a formatted migration status table to stdout.
func (*Migrator) Status ¶
func (m *Migrator) Status() ([]MigrationStatus, error)
Status returns the status of all migrations (ran and pending).
type Model ¶
type Model struct {
ID uint `gorm:"primaryKey" json:"id"`
CreatedAt timex.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt timex.Time `gorm:"autoUpdateTime" json:"updated_at"`
// DeletedAt stays gorm.DeletedAt (via lucid.DeletedAt) so GORM soft-delete queries work unchanged.
// It maps to DATETIME(6) / TIMESTAMPTZ via the same conventions as timex.Time in migrations.
DeletedAt lucid.DeletedAt `gorm:"index" json:"-"`
}
Model is a base model with ID and timestamps (AdonisJS Lucid BaseModel style).
func (*Model) BeforeCreate ¶
BeforeCreate GORM hook to set CreatedAt and UpdatedAt timestamps if they are zero.
type Notifiable ¶
Notifiable is an interface for entities that can receive notifications.
type NotificationStore ¶
NotificationStore provides methods for working with database notifications.
func NewNotificationStore ¶
func NewNotificationStore(db *lucid.DB) *NotificationStore
NewNotificationStore creates a new notification store.
func (*NotificationStore) All ¶
func (s *NotificationStore) All(notifiable Notifiable) ([]DatabaseNotification, error)
All returns all notifications for a notifiable entity.
func (*NotificationStore) Delete ¶
func (s *NotificationStore) Delete(id string) error
Delete deletes a notification by ID.
func (*NotificationStore) DeleteAll ¶
func (s *NotificationStore) DeleteAll(notifiable Notifiable) error
DeleteAll deletes all notifications for a notifiable entity.
func (*NotificationStore) MarkAllAsRead ¶
func (s *NotificationStore) MarkAllAsRead(notifiable Notifiable) error
MarkAllAsRead marks all notifications for a notifiable as read.
func (*NotificationStore) MarkAsRead ¶
func (s *NotificationStore) MarkAsRead(id string) error
MarkAsRead marks a notification as read.
func (*NotificationStore) Read ¶
func (s *NotificationStore) Read(notifiable Notifiable) ([]DatabaseNotification, error)
Read returns read notifications for a notifiable entity.
func (*NotificationStore) Send ¶
func (s *NotificationStore) Send(notifiable Notifiable, notifType string, data any) error
Send stores a notification for the given notifiable entity.
func (*NotificationStore) Unread ¶
func (s *NotificationStore) Unread(notifiable Notifiable) ([]DatabaseNotification, error)
Unread returns unread notifications for a notifiable entity.
func (*NotificationStore) UnreadCount ¶
func (s *NotificationStore) UnreadCount(notifiable Notifiable) (int64, error)
UnreadCount returns the count of unread notifications.
type Paginator ¶
type Paginator struct {
Data any `json:"data"`
Total int64 `json:"total"`
PerPage int `json:"per_page"`
CurrentPage int `json:"current_page"`
LastPage int `json:"last_page"`
FirstPage int `json:"first_page"`
// URLs for building pagination links
FirstPageURL string `json:"first_page_url"`
LastPageURL string `json:"last_page_url"`
NextPageURL string `json:"next_page_url"`
PrevPageURL string `json:"previous_page_url"`
// contains filtered or unexported fields
}
Paginator holds paginated results and metadata (Lucid-style).
func PaginateQuery ¶
PaginateQuery is a convenience that paginates a model query. Example: PaginateQuery(Post.Query().Where("status","published"), &posts, page, 20)
func PaginateWithBaseURL ¶
func PaginateWithBaseURL(db *lucid.DB, dest any, page, perPage int, baseURL string) (*Paginator, error)
PaginateWithBaseURL runs Paginate and sets the base URL.
func (*Paginator) GetUrlsForRange ¶
GetUrlsForRange returns anchors for building pagination UI.
type PoolConfig ¶
type PoolConfig struct {
// MaxOpenConns caps open connections (0 = leave default, often unlimited).
MaxOpenConns int
// MaxIdleConns caps idle connections in the pool (0 = leave default).
MaxIdleConns int
// ConnMaxLifetime is the maximum amount of time a connection may be reused
// (0 = leave default). Set this in production behind load balancers or
// managed databases so connections are recycled before the server drops them.
ConnMaxLifetime time.Duration
// ConnMaxIdleTime is how long idle connections stay in the pool (0 = leave default).
ConnMaxIdleTime time.Duration
}
PoolConfig tunes the underlying database/sql connection pool. Zero values for each field mean "do not change" (keep Go or driver defaults).
func PoolConfigFromFields ¶
func PoolConfigFromFields(maxOpen, maxIdle int, connMaxLifetime, connMaxIdleTime string) PoolConfig
PoolConfigFromFields builds a PoolConfig from typical config/env strings. Duration values use time.ParseDuration (e.g. "5m", "90s", "1h"). Invalid strings are ignored.
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query wraps GORM's query builder for Lucid-style fluent API. Use db.Table("posts") or Model.Query() to start.
func On ¶
On returns a Query builder on a specific named connection.
database.On("analytics").Where("event_type = ?", "click").Get(&events)
func OnModel ¶
OnModel returns a Query builder for a model on a specific named connection.
database.OnModel("analytics", &AnalyticsEvent{}).Where("user_id = ?", uid).Get(&events)
func (*Query) FirstOrFail ¶
FirstOrFail returns the first record or returns a record-not-found error.
func (*Query) Preload ¶
Preload eager-loads an association. Chain for multiple:
query.Preload("User").Preload("Comments").Get(&posts)
func (*Query) Where ¶
Where adds a condition. Supports: Where("status", "published"), Where("id", ">", 5).
func (*Query) WhereBetween ¶
WhereBetween adds WHERE column BETWEEN low AND high.
func (*Query) WhereNotIn ¶
WhereNotIn adds WHERE column NOT IN (values...).
func (*Query) WhereNotNull ¶
WhereNotNull adds WHERE column IS NOT NULL.
type QueryPayload ¶
type QueryPayload struct {
SQL string
Vars []any
RowsAffected int64
Duration time.Duration
Error error
Connection string
}
QueryPayload is dispatched for every executed query.
type Relation ¶
type Relation struct {
Kind RelationKind
FieldName string // Go struct field name (e.g. "User", "Posts", "Teams")
TargetType reflect.Type // Element type (e.g. User, Post, Team — never a pointer/slice)
ForeignKey string // FK column (belongsTo: on this model; hasMany/hasOne: on related)
LocalKey string // PK on this model (default "ID")
OwnerKey string // PK on related model (default "ID")
PivotTable string // manyToMany: pivot table name (auto-generated if empty)
JoinForeignKey string // manyToMany: FK in pivot pointing to this model
JoinReferences string // manyToMany: FK in pivot pointing to related model
TagRaw string
}
User User `nimbus:"belongsTo,foreignKey:AuthorID"` Posts []Post `nimbus:"hasMany,foreignKey:AuthorID"` Teams []Team `nimbus:"manyToMany,pivotTable:user_teams"`
Auto-inferred (no tag needed):
ClientID uint // FK field Client *Client // belongsTo — inferred because ClientID exists Posts []Post // hasMany — inferred because Post has UserID Profile *Profile // hasOne — inferred (single struct, no FK on this model) Teams []Team // manyToMany — inferred because Team has no UserID
Tags are only needed to override conventions (custom FK names, pivot tables, etc.). The shorter "relation" tag key also works:
Teams []Team `nimbus:"manyToMany,pivotTable:custom_pivot"`
func ParseRelations ¶
ParseRelations inspects a model and returns all relations — both explicitly tagged and auto-inferred from Go struct conventions.
Inference rules (when no nimbus/relation tag is present):
- belongsTo: exported struct/pointer field where FieldNameID exists on the same model (e.g. Client *Client + ClientID uint → belongsTo).
- hasMany: exported slice-of-structs field (e.g. Posts []Post).
- hasOne: exported struct/pointer field where FieldNameID does NOT exist on this model (e.g. Profile *Profile without ProfileID).
- manyToMany: CANNOT be inferred — must use explicit nimbus:"manyToMany" or relation:"manyToMany" tag.
Explicitly tagged fields always take precedence over inference.
type RelationKind ¶
type RelationKind string
RelationKind describes the type of relationship between models.
const ( RelationBelongsTo RelationKind = "belongsTo" RelationHasMany RelationKind = "hasMany" RelationHasOne RelationKind = "hasOne" RelationManyToMany RelationKind = "manyToMany" )
type RelationProvider ¶
type RelationProvider interface {
Relations() []string
}
RelationProvider can be implemented by models that want to declare which relations should be auto-preloaded.
Example:
func (Blog) Relations() []string {
return []string{"User", "Comments"}
}
type Scope ¶
Scope is a reusable query modifier (like Laravel/Lucid scopes). Example:
var Published Scope = func(db *lucid.DB) *lucid.DB {
return db.Where("published_at IS NOT NULL")
}
db.Scopes(Published).Find(&posts)
func WhenScope ¶
WhenScope conditionally applies a scope.
db.Scopes(database.WhenScope(isAdmin, func(db *lucid.DB) *lucid.DB {
return db.Where("role = ?", "admin")
})).Find(&users)
func WhereScope ¶
WhereScope creates a simple WHERE scope.
active := database.WhereScope("active = ?", true)
db.Scopes(active).Find(&users)
type SeedRunner ¶
type SeedRunner struct {
// contains filtered or unexported fields
}
SeedRunner runs multiple seeders in order.
func NewSeedRunner ¶
func NewSeedRunner(db *lucid.DB, seeders []Seeder) *SeedRunner
NewSeedRunner creates a runner for the given seeders.
type SerializeOptions ¶
type SerializeOptions struct {
// Omit excludes these field names from output (e.g. "password", "remember_token").
Omit []string
// Pick includes only these fields (if non-empty).
Pick []string
}
SerializeOptions configures which fields to include when serializing.
type SimplePaginatorResult ¶
type SimplePaginatorResult struct {
Data any `json:"data"`
PerPage int `json:"per_page"`
CurrentPage int `json:"current_page"`
HasMore bool `json:"has_more"`
}
SimplePaginatorResult holds simple-paginated results (no total count).
func SimplePaginate ¶
SimplePaginate returns results without counting total (faster for large tables).
type TableNamer ¶
type TableNamer interface {
Table() string
}
TableNamer can be implemented by models that want to explicitly declare their logical table name (Laravel-style). This is separate from GORM's TableName() so Nimbus can remain ORM-agnostic.
Example:
func (Blog) Table() string {
return "blogs"
}