database

package
v0.0.0-...-ed7afed Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package database provides a high-performance query builder, struct scanner, lifecycle hooks, and explicit eager relationship loading for OniWorks.

Design principles:

  • Query builder is lazy — nothing executes until a terminal method is called
  • Reflection cache: struct field mapping is computed once per type, never per-request
  • No lazy loading: relationships are never populated automatically (no hidden queries)
  • Batch eager loading: db.Load(&users, "Posts") fires WHERE user_id IN (...) — no N+1
  • Context-everywhere: all queries accept context.Context

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = fmt.Errorf("database: record not found")

ErrNotFound is returned by First when no matching row is found.

Functions

func SetDefault

func SetDefault(db *DB)

SetDefault sets the package-level default DB used by top-level Table() / Raw() calls.

Types

type Builder

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

Builder is a lazy, fluent SQL query builder. Nothing is executed until a terminal method (First, All, Count, Insert, Update, etc.) is called.

func Raw

func Raw(query string, args ...any) *Builder

Raw is a package-level shorthand: database.Raw("SELECT ...", args...)

func Table

func Table(table string) *Builder

Table is a package-level shorthand: database.Table("users").Where(...)

func (*Builder) All

func (b *Builder) All(dest any) error

All executes the query and scans all rows into dest (must be a pointer to a slice).

func (*Builder) Count

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

Count executes a COUNT(*) query and returns the result.

func (*Builder) Ctx

func (b *Builder) Ctx(ctx context.Context) *Builder

Ctx sets the context for this query.

func (*Builder) Delete

func (b *Builder) Delete() error

Delete removes rows matching the WHERE clause.

db.Table("users").Where("id = ?", id).Delete()

func (*Builder) Exec

func (b *Builder) Exec() error

Exec executes a raw write query (INSERT, UPDATE, DELETE) that returns no rows. Intended for use with Raw() for statements like INSERT ... ON CONFLICT DO NOTHING.

func (*Builder) Exists

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

Exists reports whether any row matches the query.

func (*Builder) First

func (b *Builder) First(dest any) error

First executes the query and scans a single row into dest. Returns ErrNotFound if no row matches.

func (*Builder) GroupBy

func (b *Builder) GroupBy(cols ...string) *Builder

GroupBy adds a GROUP BY clause.

func (*Builder) Having

func (b *Builder) Having(clause string, args ...any) *Builder

Having adds a HAVING clause.

func (*Builder) Insert

func (b *Builder) Insert(dest any) error

Insert inserts dest (a model pointer) and calls BeforeCreate / AfterCreate hooks. dest must be a struct pointer; for map[string]any use InsertMap instead.

func (*Builder) InsertMap

func (b *Builder) InsertMap(data map[string]any) error

InsertMap inserts a row from a plain map[string]any. Column order is sorted for determinism. Hooks are not called. "created_at" and "updated_at" are injected as UTC RFC3339 strings when not already present in the map.

func (*Builder) Join

func (b *Builder) Join(clause string) *Builder

Join adds an INNER JOIN.

func (*Builder) LeftJoin

func (b *Builder) LeftJoin(clause string) *Builder

LeftJoin adds a LEFT JOIN.

func (*Builder) Limit

func (b *Builder) Limit(n int) *Builder

Limit sets the maximum number of results.

func (*Builder) Offset

func (b *Builder) Offset(n int) *Builder

Offset sets the number of results to skip.

func (*Builder) OrWhere

func (b *Builder) OrWhere(clause string, args ...any) *Builder

OrWhere adds an OR WHERE condition.

func (*Builder) OrderBy

func (b *Builder) OrderBy(clause string) *Builder

OrderBy adds an ORDER BY clause.

db.Table("users").OrderBy("created_at DESC").OrderBy("name ASC")

func (*Builder) Paginate

func (b *Builder) Paginate(page, perPage int, dest any) (*Page[any], error)

Paginate executes a COUNT and a SELECT with LIMIT/OFFSET and returns a Page. page is 1-based.

func (*Builder) Pluck

func (b *Builder) Pluck(col string, dest any) error

Pluck retrieves a single column as a []T slice.

var emails []string
db.Table("users").Pluck("email", &emails)

func (*Builder) Save

func (b *Builder) Save(dest any) error

Save updates all fields of dest, calling BeforeSave / AfterSave hooks.

func (*Builder) Scan

func (b *Builder) Scan(dest any) error

Scan executes a raw query and scans a single scalar value.

func (*Builder) Select

func (b *Builder) Select(cols ...string) *Builder

Select specifies which columns to retrieve.

db.Table("users").Select("id", "email").All(&users)

func (*Builder) SoftDelete

func (b *Builder) SoftDelete() *Builder

SoftDelete tells the builder this table uses soft deletes (deleted_at column). Automatically adds "deleted_at IS NULL" to WHERE unless WithTrashed() is called.

func (*Builder) Update

func (b *Builder) Update(data Map) error

Update updates specific columns for rows matching the WHERE clause.

db.Table("users").Where("id = ?", 1).Update(database.Map{"name": "Alice"})

func (*Builder) Where

func (b *Builder) Where(clause string, args ...any) *Builder

Where adds a WHERE condition (AND-joined).

db.Table("users").Where("active = ?", true).Where("role = ?", "admin")

func (*Builder) WhereIn

func (b *Builder) WhereIn(col string, values ...any) *Builder

WhereIn adds a WHERE column IN (...) clause.

func (*Builder) WhereNotIn

func (b *Builder) WhereNotIn(col string, values ...any) *Builder

WhereNotIn adds a WHERE column NOT IN (...) clause.

func (*Builder) WhereNotNull

func (b *Builder) WhereNotNull(col string) *Builder

WhereNotNull adds WHERE column IS NOT NULL.

func (*Builder) WhereNull

func (b *Builder) WhereNull(col string) *Builder

WhereNull adds WHERE column IS NULL.

func (*Builder) WhereRaw

func (b *Builder) WhereRaw(clause string, args ...any) *Builder

WhereRaw adds a raw WHERE clause without any quoting or escaping. Use this for complex conditions or when you need full control over the SQL.

db.Table("users").WhereRaw("1=1").Delete() // delete all rows

func (*Builder) With

func (b *Builder) With(relations ...string) *Builder

With eager-loads the named relationships after the main query executes.

db.Table("users").With("Posts", "Role").All(&users)

func (*Builder) WithTrashed

func (b *Builder) WithTrashed() *Builder

WithTrashed includes soft-deleted rows (does not add "deleted_at IS NULL").

type ColumnDef

type ColumnDef struct {
	Name       string
	Type       string // "string","text","int","bigint","bool","float","decimal","json","time","uuid","binary"
	PrimaryKey bool
	AutoIncr   bool
	Nullable   bool
	Unique     bool
	Default    string
	Length     int
	FKTable    string
	FKCol      string
	FKOnDelete string
}

ColumnDef is a portable column definition shared between the Postgres and MySQL grammars.

type Config

type Config struct {
	Driver   Driver
	Host     string
	Port     int
	Name     string
	User     string
	Password string
	SSLMode  string

	// Pool settings
	MaxOpen     int
	MaxIdle     int
	MaxLifetime time.Duration

	// PostgreSQL-specific: use pgxpool directly for best performance
	PgxConfig *pgxpool.Config
}

Config holds all database connection parameters.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a localhost PostgreSQL config suitable for development.

type DB

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

DB is the central database handle. It wraps *sql.DB and provides the query builder API. Create one DB per database connection and share it.

func Default

func Default() *DB

Default returns the package-level default DB, or panics if not set.

func MustOpen

func MustOpen(cfg Config) *DB

MustOpen is like Open but panics on error.

func Open

func Open(cfg Config) (*DB, error)

Open connects to the database using cfg and returns a *DB.

func (*DB) Close

func (db *DB) Close() error

Close closes the underlying connection pool.

func (*DB) Driver

func (db *DB) Driver() Driver

Driver returns the database driver type.

func (*DB) Load

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

Load populates the named relationship(s) on a slice of model pointers. It fires exactly one batch query per relationship — never N individual queries.

db.Load(&users, "Posts")         // SELECT * FROM posts WHERE user_id IN (1,2,3)
db.Load(&users, "Posts", "Role") // two batch queries

func (*DB) LoadContext

func (db *DB) LoadContext(ctx context.Context, dest any, relations ...string) error

LoadContext is like Load but with context.

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping verifies the connection is alive.

func (*DB) Raw

func (db *DB) Raw(sql string, args ...any) *Builder

Raw returns a Builder for a raw SQL query. Terminal methods Scan, All, and Count all work on Raw builders.

db.Raw("SELECT COUNT(*) FROM users WHERE active = ?", true).Scan(&count)
db.Raw("SELECT * FROM users WHERE role = ?", "admin").All(&users)

func (*DB) SQLDB

func (db *DB) SQLDB() *sql.DB

SQLDB exposes the underlying *sql.DB for advanced use (migrations, raw exec, etc.).

func (*DB) SetLogLevel

func (db *DB) SetLogLevel(level slog.Level)

SetLogLevel sets the minimum log level for query logging (default: slog.LevelDebug).

func (*DB) Table

func (db *DB) Table(table string) *Builder

Table returns a new Builder for the given table name.

db.Table("users").Where("active = ?", true).All(&users)

func (*DB) Transaction

func (db *DB) Transaction(fn func(tx *DB) error) error

Transaction executes fn inside a database transaction. If fn returns nil, the transaction is committed; otherwise it is rolled back. Nested calls create savepoints so inner failures can be rolled back independently.

func (*DB) TransactionContext

func (db *DB) TransactionContext(ctx context.Context, fn func(tx *DB) error) error

TransactionContext is like Transaction but accepts a context.

func (*DB) WithLogger

func (db *DB) WithLogger(l *slog.Logger) *DB

WithLogger sets a custom logger.

type Driver

type Driver string

Driver identifies the database backend.

const (
	DriverPostgres Driver = "postgres"
	DriverMySQL    Driver = "mysql"
)

type Grammar

type Grammar interface {
	Placeholder(n int) string
	QuoteIdent(s string) string
	DropTableSQL(table string) string
	CreateTableSQL(table string, cols []ColumnDef) string
	AddColumnSQL(table string, col ColumnDef) string
	DropColumnSQL(table, col string) string
	AddIndexSQL(table string, cols []string, unique bool) string
}

Grammar generates database-dialect-specific SQL fragments and DDL statements.

type Map

type Map = map[string]any

Map is a convenience alias used in Insert/Update calls.

type Page

type Page[T any] struct {
	Items       []T   `json:"items"`
	Total       int64 `json:"total"`
	PerPage     int   `json:"per_page"`
	CurrentPage int   `json:"current_page"`
	LastPage    int   `json:"last_page"`
	From        int64 `json:"from"`
	To          int64 `json:"to"`
}

Page holds paginated query results.

Jump to

Keyboard shortcuts

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