database

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventQuery  = "db:query"
	EventInsert = "db:insert"
	EventUpdate = "db:update"
	EventDelete = "db:delete"
)

Event constants for database operations.

View Source
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

View Source
var DB *lucid.DB

DB is the global GORM instance (AdonisJS Lucid-style; in production use DI).

Functions

func AddConnection

func AddConnection(name string, db *lucid.DB)

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

func Attach(db *lucid.DB, model any, relationName string, related ...any) error

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

func AutoMigrateNotifications(db *lucid.DB) error

AutoMigrateNotifications creates the notifications table.

func AutoPreload

func AutoPreload(db *lucid.DB, model any) *lucid.DB

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

func CachedFind(db *lucid.DB, key string, ttl time.Duration, dest any) error

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

func Chunk[T any](db *lucid.DB, size int, fn func(batch []T) error) error

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 Connect

func Connect(driver, dsn string) (*lucid.DB, error)

Connect opens a connection based on driver and DSN (from config).

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

func Connection(name string) *lucid.DB

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 CountBy

func CountBy(db *lucid.DB) (int64, error)

CountBy counts records matching the conditions.

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 Debug

func Debug()

Debug enables query logging for the global DB.

func Detach

func Detach(db *lucid.DB, model any, relationName string, related ...any) error

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

func DetachAll(db *lucid.DB, model any, relationName string) error

DetachAll removes all related models from a manyToMany pivot table.

database.DetachAll(db, &user, "Teams")

func Exec

func Exec(db *lucid.DB, sql string, args ...any) error

Exec executes a raw SQL statement (INSERT, UPDATE, DELETE).

func Exists

func Exists(db *lucid.DB) (bool, error)

Exists returns true if any record matches the query.

func FillableFor

func FillableFor(model any) []string

FillableFor returns the list of mass-assignable fields for a model. Resolution order:

  1. FillableProvider.Fillable()
  2. All exported struct fields excluding the embedded database.Model and common timestamp/soft-delete fields.

func FirstOrCreate

func FirstOrCreate[T any](db *lucid.DB, where T, attrs T) (*T, error)

FirstOrCreate finds the first matching record or creates it.

func ForceDelete

func ForceDelete(db *lucid.DB, model any) error

ForceDelete permanently deletes a record (bypasses soft delete).

func Get

func Get() *lucid.DB

Get returns the global DB (panic if not connected).

func HasRelated

func HasRelated(db *lucid.DB, model any, relationName string, related any) (bool, error)

HasRelated checks if a manyToMany relation has a specific related model attached.

attached, err := database.HasRelated(db, &user, "Teams", &team)

func IsDirty

func IsDirty(v any, field string) bool

IsDirty checks if a struct field was modified (for hooks). GORM tracks this via Statement.Changed(). This is a helper for custom logic.

func IsTrashed

func IsTrashed(m *Model) bool

IsTrashed checks if a model's DeletedAt field is set.

func Load

func Load(db *lucid.DB, model any, relations ...string) error

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

func MigratePivots(db *lucid.DB, models ...any) error

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

func MustConnection(name string) *lucid.DB

MustConnection returns a named connection or panics if not found.

func OnlyTrashed

func OnlyTrashed(db *lucid.DB) *lucid.DB

OnlyTrashed returns only soft-deleted records.

func Pluck

func Pluck[T any](db *lucid.DB, column string) ([]T, error)

Pluck retrieves a single column from a query as a slice.

func Preload

func Preload(db *lucid.DB, name string, args ...any) *lucid.DB

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 Raw

func Raw(db *lucid.DB, sql string, dest any, args ...any) error

Raw executes a raw SQL query and scans into dest.

func RegisterHooks

func RegisterHooks(db *lucid.DB, name string, h Hooks)

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(db *lucid.DB, model any, relationName string) *lucid.DB

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

func RequireConnection(name string) (*lucid.DB, error)

RequireConnection returns a named connection or an error if not found. Prefer this in runtime paths where panic is undesirable.

func Restore

func Restore(db *lucid.DB, model any) error

Restore un-deletes a soft-deleted record by setting deleted_at to NULL.

func RunMigrationsFromDir

func RunMigrationsFromDir(db *lucid.DB, dir string) error

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

func SetDefault(name string) error

SetDefault sets which named connection is the "default" one (returned by Get() and used globally).

func Sync

func Sync(db *lucid.DB, model any, relationName string, related ...any) error

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

func TableNameFor(model any) string

TableNameFor returns the logical table name for a model. Resolution order:

  1. TableNamer.Table()
  2. Pluralized struct name (Blog -> blogs, UserProfile -> user_profiles)

func Transaction

func Transaction(db *lucid.DB, fn func(tx *lucid.DB) error) error

Transaction runs fn inside a transaction. On success it commits; on error it rolls back. Lucid-style managed transaction.

func TransactionWithDB

func TransactionWithDB(fn func(tx *lucid.DB) error) error

TransactionWithDB runs fn inside a transaction using the global DB.

func UpdateOrCreate

func UpdateOrCreate[T any](db *lucid.DB, where T, update T) (*T, error)

UpdateOrCreate finds a record by where conditions and updates it, or creates a new one.

func WithTrashed

func WithTrashed(db *lucid.DB) *lucid.DB

WithTrashed returns all records including soft-deleted ones.

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 Define

func Define(tableName string, fn func(f *Faker) map[string]any) *Factory

Define creates a factory for the given table.

func (*Factory) Create

func (fac *Factory) Create(db *lucid.DB, attrs ...map[string]any) error

Create inserts one record with fake data. Override specific fields with attrs.

func (*Factory) CreateMany

func (fac *Factory) CreateMany(db *lucid.DB, n int) error

CreateMany inserts n records with fake data.

func (*Factory) Merge

func (fac *Factory) Merge(attrs map[string]any) *FactoryWithAttrs

Merge overrides factory data with the given attrs (for Create).

type FactoryWithAttrs

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

FactoryWithAttrs is a factory with pre-set overrides.

func (*FactoryWithAttrs) Create

func (f *FactoryWithAttrs) Create(db *lucid.DB) error

Create creates one record with merged attributes.

type Faker

type Faker struct{}

Faker provides simple fake data helpers.

func (*Faker) Email

func (f *Faker) Email() string

Email returns a fake email.

func (*Faker) Int

func (f *Faker) Int(min, max int) int

Int returns a random int in [min, max].

func (*Faker) Paragraph

func (f *Faker) Paragraph() string

Paragraph returns a few sentences.

func (*Faker) Sentence

func (f *Faker) Sentence() string

Sentence returns a short fake sentence.

func (*Faker) Word

func (f *Faker) Word() string

Word returns a random word.

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 HookFunc

type HookFunc func(db *lucid.DB)

HookFunc is a function that runs at a model lifecycle point.

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

type MigrationStatus struct {
	Name  string
	Ran   bool
	Batch int
	RanAt string
}

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

func NewMigrator(db *lucid.DB, migrations []Migration) *Migrator

NewMigrator creates a migrator with the given migrations.

func (*Migrator) Down

func (m *Migrator) Down() error

Down rolls back the last batch of migrations (Laravel tyle).

func (*Migrator) Fresh

func (m *Migrator) Fresh() error

Fresh drops all tables and re-runs all migrations from scratch. Equivalent to Laravel's migrate:fresh.

func (*Migrator) PrintStatus

func (m *Migrator) PrintStatus() error

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).

func (*Migrator) Up

func (m *Migrator) Up() error

Up runs all pending migrations.

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

func (m *Model) BeforeCreate(tx *gorm.DB) error

BeforeCreate GORM hook to set CreatedAt and UpdatedAt timestamps if they are zero.

func (*Model) BeforeUpdate

func (m *Model) BeforeUpdate(tx *gorm.DB) error

BeforeUpdate GORM hook to set UpdatedAt timestamp.

type Notifiable

type Notifiable interface {
	NotifiableType() string
	NotifiableID() string
}

Notifiable is an interface for entities that can receive notifications.

type NotificationStore

type NotificationStore struct {
	DB *lucid.DB
}

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 Paginate

func Paginate(db *lucid.DB, dest any, page, perPage int) (*Paginator, error)

Paginate runs the query with limit/offset and returns a Paginator.

func PaginateQuery

func PaginateQuery(q *lucid.DB, dest any, page, perPage int) (*Paginator, error)

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) BaseUrl

func (p *Paginator) BaseUrl(url string) *Paginator

BaseUrl sets the base URL for pagination links (e.g. "/posts").

func (*Paginator) GetUrlsForRange

func (p *Paginator) GetUrlsForRange(start, end int) []struct {
	Page     int
	URL      string
	IsActive bool
}

GetUrlsForRange returns anchors for building pagination UI.

func (*Paginator) Meta

func (p *Paginator) Meta() map[string]any

Meta returns pagination metadata.

func (*Paginator) String

func (p *Paginator) String() string

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 From

func From(db *lucid.DB, table string) *Query

From starts a query on the given table (returns plain objects).

func On

func On(connectionName string) *Query

On returns a Query builder on a specific named connection.

database.On("analytics").Where("event_type = ?", "click").Get(&events)

func OnModel

func OnModel(connectionName string, model any) *Query

OnModel returns a Query builder for a model on a specific named connection.

database.OnModel("analytics", &AnalyticsEvent{}).Where("user_id = ?", uid).Get(&events)

func QueryFor

func QueryFor(db *lucid.DB, model any) *Query

Query returns a query builder for the model's table.

func (*Query) Avg

func (q *Query) Avg(column string) (float64, error)

Avg returns the AVG of a column.

func (*Query) Count

func (q *Query) Count() (int64, error)

Count returns the count of matching records.

func (*Query) Create

func (q *Query) Create(value any) error

Create inserts a new record.

func (*Query) DB

func (q *Query) DB() *lucid.DB

DB returns the underlying GORM DB for advanced usage.

func (*Query) Delete

func (q *Query) Delete(value any, conds ...any) error

Delete deletes matching records (soft delete if model has DeletedAt).

func (*Query) Distinct

func (q *Query) Distinct(columns ...string) *Query

Distinct adds DISTINCT to the query.

func (*Query) Exists

func (q *Query) Exists() (bool, error)

Exists returns true if any matching record exists.

func (*Query) Find

func (q *Query) Find(dest any, conds ...any) error

Find finds records matching primary key(s).

func (*Query) First

func (q *Query) First(dest any) error

First returns the first record (ORDER BY primary key).

func (*Query) FirstOrFail

func (q *Query) FirstOrFail(dest any) error

FirstOrFail returns the first record or returns a record-not-found error.

func (*Query) Get

func (q *Query) Get(dest any) error

Get executes the query and scans into dest (slice or single struct).

func (*Query) GroupBy

func (q *Query) GroupBy(columns ...string) *Query

GroupBy adds GROUP BY columns.

func (*Query) Having

func (q *Query) Having(query string, args ...any) *Query

Having adds a HAVING clause.

func (*Query) Join

func (q *Query) Join(query string, args ...any) *Query

Join adds an INNER JOIN clause.

func (*Query) Last

func (q *Query) Last(dest any) error

Last returns the last record (ORDER BY primary key DESC).

func (*Query) LeftJoin

func (q *Query) LeftJoin(table, condition string) *Query

LeftJoin adds a LEFT JOIN clause.

func (*Query) Limit

func (q *Query) Limit(limit int) *Query

Limit sets the maximum number of rows.

func (*Query) Max

func (q *Query) Max(column string) (float64, error)

Max returns the MAX of a column.

func (*Query) Min

func (q *Query) Min(column string) (float64, error)

Min returns the MIN of a column.

func (*Query) Offset

func (q *Query) Offset(offset int) *Query

Offset sets the number of rows to skip.

func (*Query) OrWhere

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

OrWhere adds an OR condition.

func (*Query) OrderBy

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

OrderBy adds ORDER BY (use "created_at desc" or "name asc").

func (*Query) Paginate

func (q *Query) Paginate(dest any, page, perPage int) (*Paginator, error)

Paginate returns paginated results.

func (*Query) Pluck

func (q *Query) Pluck(column string, dest any) error

Pluck retrieves a single column as a slice.

func (*Query) Preload

func (q *Query) Preload(name string, args ...any) *Query

Preload eager-loads an association. Chain for multiple:

query.Preload("User").Preload("Comments").Get(&posts)

func (*Query) RightJoin

func (q *Query) RightJoin(table, condition string) *Query

RightJoin adds a RIGHT JOIN clause.

func (*Query) Scopes

func (q *Query) Scopes(scopes ...func(*lucid.DB) *lucid.DB) *Query

Scopes applies one or more scopes to the query.

func (*Query) Select

func (q *Query) Select(columns ...string) *Query

Select specifies columns to fetch.

func (*Query) Sum

func (q *Query) Sum(column string) (float64, error)

Sum returns the SUM of a column.

func (*Query) Unscoped

func (q *Query) Unscoped() *Query

Unscoped removes soft delete filter.

func (*Query) Update

func (q *Query) Update(column string, value any) error

Update updates a single column.

func (*Query) Updates

func (q *Query) Updates(values any) error

Updates updates multiple columns with a map or struct.

func (*Query) Where

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

Where adds a condition. Supports: Where("status", "published"), Where("id", ">", 5).

func (*Query) WhereBetween

func (q *Query) WhereBetween(column string, low, high any) *Query

WhereBetween adds WHERE column BETWEEN low AND high.

func (*Query) WhereIn

func (q *Query) WhereIn(column string, values ...any) *Query

WhereIn adds WHERE column IN (values...).

func (*Query) WhereLike

func (q *Query) WhereLike(column, pattern string) *Query

WhereLike adds WHERE column LIKE pattern.

func (*Query) WhereNotIn

func (q *Query) WhereNotIn(column string, values ...any) *Query

WhereNotIn adds WHERE column NOT IN (values...).

func (*Query) WhereNotNull

func (q *Query) WhereNotNull(column string) *Query

WhereNotNull adds WHERE column IS NOT NULL.

func (*Query) WhereNull

func (q *Query) WhereNull(column string) *Query

WhereNull adds WHERE column IS NULL.

func (*Query) WhereRaw

func (q *Query) WhereRaw(sql string, args ...any) *Query

WhereRaw adds a raw WHERE clause.

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

func ParseRelations(model any) []Relation

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

type Scope = func(db *lucid.DB) *lucid.DB

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 LatestScope

func LatestScope() Scope

LatestScope orders by created_at DESC.

func LimitScope

func LimitScope(n int) Scope

LimitScope limits the number of results.

func OldestScope

func OldestScope() Scope

OldestScope orders by created_at ASC.

func OrderScope

func OrderScope(column string) Scope

OrderScope creates an ORDER BY scope.

func WhenScope

func WhenScope(condition bool, scope Scope) Scope

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

func WhereScope(query string, args ...any) Scope

WhereScope creates a simple WHERE scope.

active := database.WhereScope("active = ?", true)
db.Scopes(active).Find(&users)

type SeedFunc

type SeedFunc func(*lucid.DB) error

SeedFunc adapts a function to Seeder.

func (SeedFunc) Run

func (f SeedFunc) Run(db *lucid.DB) error

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.

func (*SeedRunner) Run

func (r *SeedRunner) Run() error

Run executes all seeders.

type Seeder

type Seeder interface {
	Run(db *lucid.DB) error
}

Seeder runs seed data (AdonisJS database/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

func SimplePaginate(db *lucid.DB, dest any, page, perPage int) (*SimplePaginatorResult, error)

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"
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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