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 ¶
- Variables
- func SetDefault(db *DB)
- type Builder
- func (b *Builder) All(dest any) error
- func (b *Builder) Count() (int64, error)
- func (b *Builder) Ctx(ctx context.Context) *Builder
- func (b *Builder) Delete() error
- func (b *Builder) Exec() error
- func (b *Builder) Exists() (bool, error)
- func (b *Builder) First(dest any) error
- func (b *Builder) GroupBy(cols ...string) *Builder
- func (b *Builder) Having(clause string, args ...any) *Builder
- func (b *Builder) Insert(dest any) error
- func (b *Builder) InsertMap(data map[string]any) error
- func (b *Builder) Join(clause string) *Builder
- func (b *Builder) LeftJoin(clause string) *Builder
- func (b *Builder) Limit(n int) *Builder
- func (b *Builder) Offset(n int) *Builder
- func (b *Builder) OrWhere(clause string, args ...any) *Builder
- func (b *Builder) OrderBy(clause string) *Builder
- func (b *Builder) Paginate(page, perPage int, dest any) (*Page[any], error)
- func (b *Builder) Pluck(col string, dest any) error
- func (b *Builder) Save(dest any) error
- func (b *Builder) Scan(dest any) error
- func (b *Builder) Select(cols ...string) *Builder
- func (b *Builder) SoftDelete() *Builder
- func (b *Builder) Update(data Map) error
- func (b *Builder) Where(clause string, args ...any) *Builder
- func (b *Builder) WhereIn(col string, values ...any) *Builder
- func (b *Builder) WhereNotIn(col string, values ...any) *Builder
- func (b *Builder) WhereNotNull(col string) *Builder
- func (b *Builder) WhereNull(col string) *Builder
- func (b *Builder) WhereRaw(clause string, args ...any) *Builder
- func (b *Builder) With(relations ...string) *Builder
- func (b *Builder) WithTrashed() *Builder
- type ColumnDef
- type Config
- type DB
- func (db *DB) Close() error
- func (db *DB) Driver() Driver
- func (db *DB) Load(dest any, relations ...string) error
- func (db *DB) LoadContext(ctx context.Context, dest any, relations ...string) error
- func (db *DB) Ping(ctx context.Context) error
- func (db *DB) Raw(sql string, args ...any) *Builder
- func (db *DB) SQLDB() *sql.DB
- func (db *DB) SetLogLevel(level slog.Level)
- func (db *DB) Table(table string) *Builder
- func (db *DB) Transaction(fn func(tx *DB) error) error
- func (db *DB) TransactionContext(ctx context.Context, fn func(tx *DB) error) error
- func (db *DB) WithLogger(l *slog.Logger) *DB
- type Driver
- type Grammar
- type Map
- type Page
Constants ¶
This section is empty.
Variables ¶
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 (*Builder) All ¶
All executes the query and scans all rows into dest (must be a pointer to a slice).
func (*Builder) Delete ¶
Delete removes rows matching the WHERE clause.
db.Table("users").Where("id = ?", id).Delete()
func (*Builder) Exec ¶
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) First ¶
First executes the query and scans a single row into dest. Returns ErrNotFound if no row matches.
func (*Builder) Insert ¶
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 ¶
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) OrderBy ¶
OrderBy adds an ORDER BY clause.
db.Table("users").OrderBy("created_at DESC").OrderBy("name ASC")
func (*Builder) Paginate ¶
Paginate executes a COUNT and a SELECT with LIMIT/OFFSET and returns a Page. page is 1-based.
func (*Builder) Pluck ¶
Pluck retrieves a single column as a []T slice.
var emails []string
db.Table("users").Pluck("email", &emails)
func (*Builder) Select ¶
Select specifies which columns to retrieve.
db.Table("users").Select("id", "email").All(&users)
func (*Builder) SoftDelete ¶
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 ¶
Update updates specific columns for rows matching the WHERE clause.
db.Table("users").Where("id = ?", 1).Update(database.Map{"name": "Alice"})
func (*Builder) Where ¶
Where adds a WHERE condition (AND-joined).
db.Table("users").Where("active = ?", true).Where("role = ?", "admin")
func (*Builder) WhereNotIn ¶
WhereNotIn adds a WHERE column NOT IN (...) clause.
func (*Builder) WhereNotNull ¶
WhereNotNull adds WHERE column IS NOT NULL.
func (*Builder) WhereRaw ¶
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 ¶
With eager-loads the named relationships after the main query executes.
db.Table("users").With("Posts", "Role").All(&users)
func (*Builder) WithTrashed ¶
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 (*DB) Load ¶
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 ¶
LoadContext is like Load but with context.
func (*DB) Raw ¶
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 ¶
SQLDB exposes the underlying *sql.DB for advanced use (migrations, raw exec, etc.).
func (*DB) SetLogLevel ¶
SetLogLevel sets the minimum log level for query logging (default: slog.LevelDebug).
func (*DB) Table ¶
Table returns a new Builder for the given table name.
db.Table("users").Where("active = ?", true).All(&users)
func (*DB) Transaction ¶
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 ¶
TransactionContext is like Transaction but accepts a context.
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.