lorm

package module
v1.0.0 Latest Latest
Warning

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

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

README

LORM - Lightweight ORM for Go

Go Report Card Go Reference Build Status

中文

LORM is a lightweight ORM for Go that keeps the API small, favors explicit SQL, and uses code generation to provide model metadata and typed field accessors.

Table of Contents

Why LORM

  • Repository-first data access for both simple CRUD and complex queries.
  • Flexible SQL builder inside repository implementations for queries that still need explicit control.
  • Code-generated model metadata instead of runtime reflection-heavy mapping.
  • Typed field accessors that make column names easier to reuse safely.
  • No automatic relation loading, implicit joins, or hidden query fan-out.
  • Transaction helper that automatically reuses the transactional session from context.Context.
  • Structured logging and configurable placeholder/identifier handling.

Design Philosophy

LORM keeps data access behind repository interfaces.

Use Repository[T] for simple CRUD and for most single-table business flows. It keeps application code short, stable, and easy to test.

Keep complex reads, reports, search pages, and custom joins inside repository implementations as well. The SQL builder supports repository code and keeps the final query shape explicit and reviewable. Its fluent API is inspired by Squirrel, while LORM keeps the builder scoped to repository implementations and its own generated model metadata.

LORM intentionally does not provide automatic relation loading, implicit eager loading, lazy loading, or magic model association queries. In production systems, those features are easy to lose control over: they can hide query costs, make SQL shape unpredictable, introduce accidental N+1 patterns, and turn simple code changes into performance regressions.

LORM prefers explicit joins, explicit selected columns, and explicit query boundaries. Business code should stay focused on business intent, while repository implementations own database details.

Database Support

  • First-class: MySQL/MariaDB, PostgreSQL
  • Secondary: SQLite

Installation

go get github.com/yvvlee/lorm
go install github.com/yvvlee/lorm/cmd/lormgen@latest

Quick Start

1. Define a model
type User struct {
	lorm.UnimplementedTable
	ID        int64     `lorm:"id,primary_key,auto_increment"`
	Name      string    `lorm:"name"`
	Email     string    `lorm:"email"`
	CreatedAt time.Time `lorm:"created_at,created"`
	UpdatedAt time.Time `lorm:"updated_at,updated"`
}
2. Generate the helper code
lormgen ./...

This generates _lorm_gen.go files with methods such as TableName(), Fields(), New(), LormFieldPtr(), and LormModelDescriptor().

3. Open an engine
engine, err := lorm.NewEngine(
	"mysql",
	"user:password@tcp(localhost:3306)/dbname?parseTime=true",
)
if err != nil {
	log.Fatal(err)
}
defer engine.Close()
4. Run CRUD operations
ctx := context.Background()
var u User

user := &User{
	Name:  "John Doe",
	Email: "john@example.com",
}

// Insert
_, err = lorm.Insert[*User](engine).
	AddModel(user).
	Exec(ctx)

// Query
savedUser, err := lorm.Query[*User](engine).
	Where(builder.Eq{u.Fields().ID(): user.ID}).
	Get(ctx)

// Update
_, err = lorm.Update[*User](engine).
	ID(user.ID).
	SetMap(map[string]any{
		u.Fields().Name(): "Jane Doe",
	}).
	Exec(ctx)

// Delete
_, err = lorm.DeleteModel[*User](engine).
	ID(user.ID).
	Exec(ctx)

Note: Code generation is required before using model-based APIs.

Update note: Update.SetModel(model) performs a full-field update. Zero values are written as well, so prefer SetMap / Set for partial updates.

Where note: builder.Eq{field: value} always renders field = ? and binds value as a single argument. It does not special-case nil into IS NULL, dereference pointers, call driver.Valuer, or expand slices into IN (...). Use builder.IsNull(field) / builder.IsNotNull(field) for null checks, and builder.In / builder.NotIn for membership predicates.

Insert note: batch inserts only backfill generated IDs when the driver returns one generated value per inserted row. LastInsertId-only dialects do not infer per-row IDs for multi-row inserts.

Statement builders are cheap to create. Build a fresh Query / Insert / Update / Delete chain for each operation, and do not share the same statement across goroutines. Use Clone() when one operation needs to branch from an existing statement. Terminal methods still reset only the statement they are called on.

Examples

See example/README.md for runnable, self-contained examples.

The examples live in their own module:

  • cd example && go run ./quickstart
  • cd example && go run ./repository
  • cd example && go run ./transaction
  • cd example && go run ./custom_model
  • cd example && go run ./custom_conversion
  • cd example && go run ./json_field
  • cd example && go run ./pagination
  • cd example && go run ./optimistic_lock
  • cd example && go run ./query_builder

Transactions

Engine.TX starts a transaction, passes a transactional context.Context into the callback, and automatically commits or rolls back.

err := engine.TX(context.Background(), func(ctx context.Context) error {
	_, err := lorm.Insert[*User](engine).
		AddModel(&User{Name: "User 1", Email: "user1@example.com"}).
		Exec(ctx)
	if err != nil {
		return err
	}

	_, err = lorm.Insert[*User](engine).
		AddModel(&User{Name: "User 2", Email: "user2@example.com"}).
		Exec(ctx)
	return err
})

Nested TX calls reuse the existing transactional session carried by the incoming context instead of opening a second transaction.

Use Engine.TXWithOptions when you need to pass sql.TxOptions such as isolation level or read-only mode. Nested calls still reuse the current transaction from context.

Repository Helper

lorm.Repository[T] wraps the common single-table CRUD paths. It is highly recommended to embed lorm.Repository[T] within an implementation struct and selectively expose methods through an interface.

Repository is the recommended boundary for all database access:

  • It gives business code a stable, ORM-agnostic interface.
  • It keeps method signatures independent from transaction management.
  • It keeps SQL builder usage inside repository implementations.
  • It makes testing easier by mocking repository interfaces instead of database calls.
  • It keeps table structure, joins, and query details out of business code.

Simple CRUD can reuse the built-in repository methods directly. Complex queries should still live in repository implementations, using the SQL builder internally when needed:

type UserRepository interface {
	// Common methods implemented by lorm.Repository[*User], expose as needed
	Get(ctx context.Context, id any) (*User, error)
	GetByField(ctx context.Context, field string, value any) (*User, error)
	Lock(ctx context.Context, id any) (*User, error)
	LockByField(ctx context.Context, field string, value any) (*User, error)
	Exist(ctx context.Context, id any) (bool, error)
	ExistByField(ctx context.Context, field string, value any) (bool, error)
	Update(ctx context.Context, user *User) (rowsAffected int64, err error)
	UpdateMap(ctx context.Context, id any, data map[string]any) (rowsAffected int64, err error)
	Insert(ctx context.Context, user *User) (rowsAffected int64, err error)
	InsertAll(ctx context.Context, users []*User) (rowsAffected int64, err error)
	Delete(ctx context.Context, id any) (rowsAffected int64, err error)
	DeleteByField(ctx context.Context, field string, value any) (rowsAffected int64, err error)

	// Custom methods to be implemented in UserRepositoryImpl
	PageGmailUsers(ctx context.Context, page, size uint64) ([]*User, uint64, error)
}

var _ UserRepository = (*UserRepositoryImpl)(nil)

type UserRepositoryImpl struct {
	*lorm.Repository[*User]
}

func NewUserRepository(engine *lorm.Engine) *UserRepositoryImpl {
	return &UserRepositoryImpl{
		Repository: lorm.NewRepository[*User](engine),
	}
}

func (r *UserRepositoryImpl) PageGmailUsers(ctx context.Context, page, size uint64) ([]*User, uint64, error) {
	var u User
	return lorm.Query[*User](r.Engine).
		Where(builder.Like(u.Fields().Email(), "%@gmail.com")).
		OrderBy(u.Fields().ID() + " DESC").
		Page(ctx, page, size)
}

Note: Lock and LockByField append FOR UPDATE. They only have practical locking effect inside Engine.TX(...) or Engine.TXWithOptions(...). Outside a transaction the database will not keep the row lock beyond the statement itself.

Custom Projection Models

When query results do not map one-to-one to a table model, embed lorm.UnimplementedModel instead of lorm.UnimplementedTable.

type UserRole struct {
	lorm.UnimplementedModel
	UserID   int64
	UserName string
	RoleName string
}

roles, err := lorm.Query[*UserRole](engine).
	Select(
		"u.id AS user_id",
		"u.name AS user_name",
		"r.name AS role_name",
	).
	From("user AS u").
	InnerJoin("role AS r ON u.role_id = r.id").
	Find(ctx)

Unlike UnimplementedTable, UnimplementedModel does not generate a TableName() method, so you must specify From(...) yourself.

Custom Field Conversion

For fields that should not be stored as plain values or JSON, implement the standard database interfaces on the field type itself:

  • driver.Valuer for writes
  • sql.Scanner for reads
import "database/sql/driver"

type CSVInts []int

func (c CSVInts) Value() (driver.Value, error) {
	return []byte("1,2,3"), nil
}

func (c *CSVInts) Scan(src any) error {
	// decode "1,2,3" back into the slice
	return nil
}

type Report struct {
	lorm.UnimplementedTable
	ID     int64   `lorm:"id,primary_key,auto_increment"`
	Title  string  `lorm:"title"`
	Scores CSVInts `lorm:"scores"`
}

LORM passes query arguments through driver.Valuer, and database/sql uses sql.Scanner when scanning result columns back into the field.

See example/custom_conversion/main.go for a runnable example.

Configuration

dialect := lorm.DefaultDialectConfig("pgx")
dialect.SupportsForUpdate = true

engine, err := lorm.NewEngine(
	"pgx",
	"postgres://user:password@localhost:5432/dbname?sslmode=disable",
	lorm.WithDialectConfig(dialect),
	lorm.WithMaxIdleConns(10),
	lorm.WithMaxOpenConns(100),
	lorm.WithConnMaxLifetime(time.Hour),
	lorm.WithConnMaxIdleTime(30*time.Minute),
	lorm.WithLogger(customLogger),
)

DialectConfig stores driver-specific SQL behavior in one place: placeholder style, identifier quoting, RETURNING, LastInsertId, FOR UPDATE, and INSERT IGNORE syntax. Built-in defaults are selected from the driver name. Use WithDialectConfig to replace the whole dialect config, or WithPlaceholderFormat, WithEscaper, and WithSupports... helpers to override one field.

Benchmarks

The benchmark suite lives in benchmarks/orm-crud.

Results below were captured on May 15, 2026 with:

cd benchmarks/orm-crud
ORMCRUD_DB=mysql go test -run '^$' -bench . -benchmem -count=1
ORMCRUD_DB=postgres go test -run '^$' -bench . -benchmem -count=1

Environment:

  • OS/arch: darwin/arm64
  • CPU: Apple M1 Pro
  • MySQL: 8.4.6
  • PostgreSQL: 18.1

MySQL, ns/op (lower is better):

Benchmark lorm gorm xorm ent
Create 1,131,710 1,637,111 1,135,509 1,175,650
ReadByID 915,563 944,430 860,244 891,313
ReadByIDComplex 864,774 844,448 877,075 893,103
UpdateByID 1,129,918 1,550,989 1,129,751 2,246,057
DeleteByID 1,031,749 1,519,377 1,040,008 1,002,177
BatchCreate100 8,568,069 9,221,738 9,517,663 9,264,969
BatchRead100 2,214,064 2,357,154 2,673,822 2,458,871
BatchRead100Complex 2,828,336 3,037,882 3,343,130 2,979,974
BatchUpdate100 6,963,767 7,179,490 6,770,990 6,630,287
BatchDelete100 5,415,382 5,366,887 5,024,017 5,089,361

PostgreSQL, ns/op (lower is better):

Benchmark lorm gorm xorm ent
Create 336,537 656,602 348,557 324,479
ReadByID 219,798 213,939 225,971 219,507
ReadByIDComplex 218,168 220,517 227,949 219,516
UpdateByID 321,847 669,114 654,825 880,432
DeleteByID 303,406 627,643 297,395 296,478
BatchCreate100 2,908,882 2,980,674 4,608,589 2,782,881
BatchRead100 987,042 1,237,686 1,407,165 1,073,514
BatchRead100Complex 1,519,387 1,882,029 2,038,405 1,636,961
BatchUpdate100 721,963 1,034,409 940,146 723,326
BatchDelete100 562,371 833,474 540,432 521,771

Notes from this run:

  • On MySQL, lorm is fastest in 4 of the 10 ns/op cases: single-row create, batch create, batch read, and complex batch read.
  • On PostgreSQL, lorm is fastest in 5 of the 10 ns/op cases, including complex single-row read, single-row update, batch read, complex batch read, and batch update.
  • lorm has the lowest B/op in 6 of the 10 MySQL cases and 7 of the 10 PostgreSQL cases in this run.

Treat these numbers as directional rather than universal. Re-run the suite on your target database, schema, driver, and hardware before making a decision.

See benchmarks/orm-crud/README.md for the benchmark scope, setup, and full ns/op, B/op, and allocs/op tables.

lormgen

lormgen scans Go files that embed lorm.UnimplementedTable or lorm.UnimplementedModel and generates the model helper methods that LORM needs.

Usage:

lormgen [flags] <directory|file>...

Common flags:

  • --field-mapper: snake, camel, or same
  • --table-mapper: snake, camel, or same
  • --table-prefix: prefix added to generated table names
  • --table-suffix: suffix added to generated table names
  • --tag-key: struct tag key, default lorm
  • --file-suffix: generated file suffix, default _lorm_gen
  • --ignore: glob pattern for ignored files, repeatable

Examples:

lormgen .
lormgen ./models/...
lormgen --table-prefix=t_ --table-suffix=_tab --field-mapper=camel ./models
lormgen --ignore="*_temp.go" --ignore="*_old.go" ./models

Built-in tags:

  • primary_key: marks a primary key field
  • auto_increment: marks an auto-increment field
  • json: stores the field as JSON
  • created: fills the field on insert when it is zero-valued
  • updated: fills the field on insert/update when it is zero-valued
  • version: enables optimistic-lock style version increments on update

Generator behavior worth knowing:

  • Table names default to snake_case and can be overridden with a tag on the embedded lorm.UnimplementedTable.
  • Field names default to snake_case and can be overridden with field tags.
  • If a field needs a lorm tag, declare it on its own line instead of grouped declarations such as A, B int.
  • Embedded structs are flattened into the generated field accessors.
  • Tags on embedded structs can prepend a prefix to the flattened field names.

Contributing

Contributions are welcome. Feel free to open an issue or submit a pull request.

License

This project is licensed under the MIT License. See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FlagTagMap = map[FieldFlag]string{
	FlagPrimaryKey:    "primary_key",
	FlagAutoIncrement: "auto_increment",
	FlagJson:          "json",
	FlagCreated:       "created",
	FlagUpdated:       "updated",
	FlagVersion:       "version",
}

FlagTagMap maps field flags to struct tag names.

Functions

func Escaper

func Escaper(driverName string) names.Escaper

Escaper returns the default identifier escaper for a driver name.

func ModelToInsertData

func ModelToInsertData[T Model](model T, ignoreFields ...string) (columns []string, values []any)

ModelToInsertData builds insert columns and values for a single model.

func ModelsToInsertData

func ModelsToInsertData[T Model](models []T, ignoreFields ...string) (columns []string, values [][]any)

ModelsToInsertData builds shared insert columns and per-row values for models.

func Placeholder

func Placeholder(driverName string) builder.PlaceholderFormat

Placeholder returns the default placeholder format for a driver name.

func ScanCol

func ScanCol[T any](row *sql.Rows, t T) error

ScanCol scans the first column of the first row into t. t must be a pointer (e.g. *int, *string) so the scanned value can be written back to the caller.

func ScanCols

func ScanCols[T any](rows *sql.Rows, v *[]T) error

ScanCols scans the first column of each row into v.

func ScanModel

func ScanModel[T Model](row *sql.Rows, m T) error

ScanModel scans the first row into m using column names to locate fields.

func ScanModels

func ScanModels[T Model](rows *sql.Rows, models *[]T) error

ScanModels scans all rows into models using their descriptor field mapping.

Types

type Config

type Config struct {

	// Dialect holds SQL dialect behavior for generated statements.
	Dialect DialectConfig
	// contains filtered or unexported fields
}

Config holds engine settings assembled from Option values.

type DBProxy

type DBProxy interface {
	Execer
	Querier
}

DBProxy is the common interface shared by *sql.DB and *sql.Tx.

type DeleteStmt

type DeleteStmt[T Table] struct {
	// contains filtered or unexported fields
}

DeleteStmt is a fluent DELETE builder for table T.

func Delete

func Delete[T Table](engine *Engine) *DeleteStmt[T]

Delete builds a DELETE statement for table T.

func (*DeleteStmt[T]) Clone added in v1.0.0

func (s *DeleteStmt[T]) Clone() *DeleteStmt[T]

Clone returns a copy of the statement state. Terminal methods still reset only the statement they are called on.

func (*DeleteStmt[T]) Exec

func (s *DeleteStmt[T]) Exec(ctx context.Context) (rowsAffected int64, err error)

Exec executes the built DELETE statement.

func (*DeleteStmt[T]) From

func (s *DeleteStmt[T]) From(from string) *DeleteStmt[T]

From overrides the target table name.

func (*DeleteStmt[T]) ID

func (s *DeleteStmt[T]) ID(id any) *DeleteStmt[T]

ID adds a single-column primary key predicate using the model metadata.

func (*DeleteStmt[T]) Limit

func (s *DeleteStmt[T]) Limit(limit uint64) *DeleteStmt[T]

Limit sets a LIMIT clause on the query.

func (*DeleteStmt[T]) Offset

func (s *DeleteStmt[T]) Offset(offset uint64) *DeleteStmt[T]

Offset sets a OFFSET clause on the query.

func (*DeleteStmt[T]) OrderBy

func (s *DeleteStmt[T]) OrderBy(orderBys ...string) *DeleteStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*DeleteStmt[T]) Prefix

func (s *DeleteStmt[T]) Prefix(sql string, args ...any) *DeleteStmt[T]

Prefix adds an expression to the beginning of the query.

func (*DeleteStmt[T]) PrefixExpr

func (s *DeleteStmt[T]) PrefixExpr(expr builder.Sqlizer) *DeleteStmt[T]

PrefixExpr adds an expression to the very beginning of the query.

func (*DeleteStmt[T]) Suffix

func (s *DeleteStmt[T]) Suffix(sql string, args ...any) *DeleteStmt[T]

Suffix adds an expression to the end of the query.

func (*DeleteStmt[T]) SuffixExpr

func (s *DeleteStmt[T]) SuffixExpr(expr builder.Sqlizer) *DeleteStmt[T]

SuffixExpr adds an expression to the end of the query.

func (*DeleteStmt[T]) Where

func (s *DeleteStmt[T]) Where(pred any, args ...any) *DeleteStmt[T]

Where adds WHERE expressions to the query.

type DialectConfig added in v1.0.0

type DialectConfig struct {
	// PlaceholderFormat specifies the format of placeholders used in SQL queries (e.g. ?, $1, :1).
	PlaceholderFormat builder.PlaceholderFormat
	// Escaper escapes table names and column names.
	Escaper names.Escaper
	// SupportsReturning indicates whether the dialect supports RETURNING clauses.
	SupportsReturning bool
	// SupportsLastInsertID indicates whether the dialect supports LastInsertId.
	SupportsLastInsertID bool
	// SupportsForUpdate indicates whether the dialect supports FOR UPDATE.
	SupportsForUpdate bool
	// IgnoreStrategy defines the dialect-specific INSERT IGNORE syntax.
	IgnoreStrategy IgnoreStrategy
}

DialectConfig holds SQL dialect behavior used by an Engine.

func DefaultDialectConfig added in v1.0.0

func DefaultDialectConfig(driverName string) DialectConfig

DefaultDialectConfig returns the built-in dialect behavior for a driver name.

type Engine

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

Engine wraps a sql.DB and the driver-specific behavior lorm needs. An Engine should be created once per database and used as a global singleton. Do not copy an Engine value; transaction isolation relies on pointer identity.

func NewEngine

func NewEngine(driverName, dsn string, option ...Option) (*Engine, error)

NewEngine opens a database connection and applies the provided options. It uses a background context for the initial connectivity check; use NewEngineContext to supply a context with timeout or cancellation.

func NewEngineContext added in v1.0.0

func NewEngineContext(ctx context.Context, driverName, dsn string, option ...Option) (*Engine, error)

NewEngineContext is like NewEngine but accepts a context for the initial connectivity check so callers can enforce a timeout.

func (*Engine) Close

func (e *Engine) Close() error

Close closes the underlying database pool.

func (*Engine) DriverName

func (e *Engine) DriverName() string

DriverName returns the configured database driver name.

func (*Engine) Escaper

func (e *Engine) Escaper() names.Escaper

Escaper returns the identifier escaper configured for the engine.

func (*Engine) Exec

func (e *Engine) Exec(ctx context.Context, query string, args ...any) (result sql.Result, err error)

Exec executes a statement against the current session or transaction.

func (*Engine) Exist

func (e *Engine) Exist(ctx context.Context, query string, args ...any) (exist bool, err error)

Exist reports whether the query returns at least one row.

func (*Engine) IgnoreStrategy added in v1.0.0

func (e *Engine) IgnoreStrategy() IgnoreStrategy

IgnoreStrategy returns the configured insert-ignore strategy for the dialect.

func (*Engine) Placeholder

func (e *Engine) Placeholder() builder.PlaceholderFormat

Placeholder returns the placeholder format configured for the engine.

func (*Engine) Query

func (e *Engine) Query(ctx context.Context, query string, args ...any) (rows *sql.Rows, err error)

Query executes a query against the current session or transaction.

func (*Engine) SupportsForUpdate added in v1.0.0

func (e *Engine) SupportsForUpdate() bool

SupportsForUpdate returns true if the database driver supports FOR UPDATE.

func (*Engine) SupportsLastInsertId

func (e *Engine) SupportsLastInsertId() bool

SupportsLastInsertId returns true if the database driver supports LastInsertId

func (*Engine) SupportsReturning

func (e *Engine) SupportsReturning() bool

SupportsReturning returns true if the database driver supports RETURNING clause

func (*Engine) TX

func (e *Engine) TX(ctx context.Context, fn func(context.Context) error) error

TX runs fn in a transaction and reuses the current session for nested calls.

func (*Engine) TXWithOptions added in v1.0.0

func (e *Engine) TXWithOptions(ctx context.Context, opts *sql.TxOptions, fn func(context.Context) error) error

TXWithOptions runs fn in a transaction using the provided sql.TxOptions.

Nested calls still reuse the existing transaction from the incoming context.

type Execer

type Execer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

Execer executes SQL statements with context.

type FieldDescriptor

type FieldDescriptor struct {
	Name           string
	FullName       string
	DBField        string
	Type           string
	Flag           FieldFlag
	EnsureFullName string `json:",omitempty"`
	EnsureType     string `json:",omitempty"`
}

FieldDescriptor stores field information

type FieldFlag

type FieldFlag uint8

FieldFlag describes special handling for a model field.

const (
	FlagPrimaryKey FieldFlag = 1 << iota
	FlagAutoIncrement
	FlagJson
	FlagCreated
	FlagUpdated
	FlagVersion
)

Field flag bits stored in FieldDescriptor.Flag.

func (FieldFlag) HasFlag

func (f FieldFlag) HasFlag(flag FieldFlag) bool

HasFlag reports whether f includes flag.

type FileDescriptor

type FileDescriptor struct {
	Path            string
	LormImportAlias string
	Package         string
	Imports         []*Import
	Structs         []*ModelDescriptor
}

FileDescriptor describes a source file used by lorm metadata/code generation.

func (*FileDescriptor) JsonMarshal

func (d *FileDescriptor) JsonMarshal() string

JsonMarshal returns d encoded as JSON.

func (*FileDescriptor) RawVarPrefix

func (d *FileDescriptor) RawVarPrefix() string

RawVarPrefix returns the stable generated variable prefix for the file.

type IgnoreStrategy added in v1.0.0

type IgnoreStrategy uint8

IgnoreStrategy defines how INSERT IGNORE is expressed in different SQL dialects.

const (
	// IgnoreKeyword uses "INSERT IGNORE INTO ..." (MySQL/MariaDB default).
	IgnoreKeyword IgnoreStrategy = iota
	// IgnoreOrKeyword uses "INSERT OR IGNORE INTO ..." (SQLite).
	IgnoreOrKeyword
	// IgnoreConflictSuffix appends "ON CONFLICT DO NOTHING" (PostgreSQL).
	IgnoreConflictSuffix
)

type Import

type Import struct {
	Path  string
	Alias string
}

Import describes an imported package reference.

type InsertStmt

type InsertStmt[T Table] struct {
	// contains filtered or unexported fields
}

InsertStmt is a fluent INSERT builder for table T.

func Insert

func Insert[T Table](engine *Engine) *InsertStmt[T]

Insert builds an INSERT statement for table T.

func (*InsertStmt[T]) AddModel

func (s *InsertStmt[T]) AddModel(model T) *InsertStmt[T]

AddModel appends a model to the insert batch.

func (*InsertStmt[T]) AddModels

func (s *InsertStmt[T]) AddModels(models ...T) *InsertStmt[T]

AddModels appends models to the insert batch.

func (*InsertStmt[T]) Clone added in v1.0.0

func (s *InsertStmt[T]) Clone() *InsertStmt[T]

Clone returns a copy of the statement state. Terminal methods still reset only the statement they are called on.

func (*InsertStmt[T]) Columns

func (s *InsertStmt[T]) Columns(columns ...string) *InsertStmt[T]

Columns overrides the INSERT column list.

Prefer AddModel/AddModels for model-based inserts. When Columns/Values are used together with AddModel/AddModels, the model-derived values still take effect during Exec.

func (*InsertStmt[T]) Exec

func (s *InsertStmt[T]) Exec(ctx context.Context) (rowsAffected int64, err error)

Exec executes the INSERT and backfills generated primary keys when possible.

Generated primary keys are only backfilled when the driver can return a stable one-to-one mapping between inserted rows and generated values. Batch inserts on LastInsertId-only dialects intentionally do not infer or synthesize per-row IDs.

func (*InsertStmt[T]) Ignore

func (s *InsertStmt[T]) Ignore() *InsertStmt[T]

Ignore enables duplicate-conflict suppression for drivers that support it.

func (*InsertStmt[T]) Prefix

func (s *InsertStmt[T]) Prefix(sql string, args ...any) *InsertStmt[T]

func (*InsertStmt[T]) PrefixExpr

func (s *InsertStmt[T]) PrefixExpr(expr builder.Sqlizer) *InsertStmt[T]

func (*InsertStmt[T]) Suffix

func (s *InsertStmt[T]) Suffix(sql string, args ...any) *InsertStmt[T]

func (*InsertStmt[T]) SuffixExpr

func (s *InsertStmt[T]) SuffixExpr(expr builder.Sqlizer) *InsertStmt[T]

func (*InsertStmt[T]) Values

func (s *InsertStmt[T]) Values(values ...any) *InsertStmt[T]

Values appends a raw VALUES row to the underlying builder.

Prefer AddModel/AddModels for model-based inserts. When Columns/Values are used together with AddModel/AddModels, the model-derived values still take effect during Exec.

type JSONFieldWrapper

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

JSONFieldWrapper adapts a field value to database/sql and JSON interfaces.

func NewJSONFieldWrapper

func NewJSONFieldWrapper(v any) *JSONFieldWrapper

NewJSONFieldWrapper wraps v so lorm can scan and write it as JSON.

func (*JSONFieldWrapper) MarshalJSON

func (s *JSONFieldWrapper) MarshalJSON() ([]byte, error)

MarshalJSON returns the wrapped value encoded as JSON.

func (*JSONFieldWrapper) Scan

func (s *JSONFieldWrapper) Scan(src any) error

Scan implements sql.Scanner for JSON-encoded columns.

func (*JSONFieldWrapper) String

func (s *JSONFieldWrapper) String() string

String returns the JSON encoding of the wrapped value.

func (*JSONFieldWrapper) UnmarshalJSON

func (s *JSONFieldWrapper) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON into the wrapped value.

func (*JSONFieldWrapper) Value

func (s *JSONFieldWrapper) Value() (driver.Value, error)

Value implements driver.Valuer.

type Logger

type Logger interface {
	DebugContext(ctx context.Context, msg string, args ...any)
	InfoContext(ctx context.Context, msg string, args ...any)
	WarnContext(ctx context.Context, msg string, args ...any)
	ErrorContext(ctx context.Context, msg string, args ...any)
}

Logger is the minimal structured logger interface used by Engine.

type Model

type Model interface {

	// New create a new model instance
	New() Model
	// LormFieldPtr returns a field pointer by db field name. JSON fields should
	// return a JSONFieldWrapper around the underlying field pointer.
	LormFieldPtr(name string) any
	// LormModelDescriptor return db fields of this Model
	LormModelDescriptor() *ModelDescriptor
	// contains filtered or unexported methods
}

Model describes the metadata and field access lorm needs for persistence.

type ModelDescriptor

type ModelDescriptor struct {
	Name      string
	TableName string
	Fields    []*FieldDescriptor
}

ModelDescriptor stores struct information

func (*ModelDescriptor) AllFields

func (m *ModelDescriptor) AllFields() []string

AllFields returns all database column names in declaration order.

func (*ModelDescriptor) FlagFields

func (m *ModelDescriptor) FlagFields(flag FieldFlag) []string

FlagFields returns database column names whose flags include flag.

type Option

type Option func(*Config)

Option mutates Config during engine construction.

func WithConnMaxIdleTime

func WithConnMaxIdleTime(connMaxIdleTime time.Duration) Option

WithConnMaxIdleTime sets the maximum idle time of a connection

func WithConnMaxLifetime

func WithConnMaxLifetime(connMaxLifetime time.Duration) Option

WithConnMaxLifetime sets the maximum lifetime of a connection

func WithDialectConfig added in v1.0.0

func WithDialectConfig(dialect DialectConfig) Option

WithDialectConfig sets the dialect behavior as a single config value.

func WithEscaper

func WithEscaper(escaper names.Escaper) Option

WithEscaper sets the escaper

func WithLogSQLArgs added in v1.0.0

func WithLogSQLArgs(enabled bool) Option

WithLogSQLArgs controls whether engine logs include SQL argument values.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets the logger

func WithMaxIdleConns

func WithMaxIdleConns(maxIdleConns int) Option

WithMaxIdleConns sets the maximum number of idle connections

func WithMaxOpenConns

func WithMaxOpenConns(maxOpenConns int) Option

WithMaxOpenConns sets the maximum number of open connections

func WithPlaceholderFormat

func WithPlaceholderFormat(format builder.PlaceholderFormat) Option

WithPlaceholderFormat sets the placeholder format

func WithSupportsForUpdate added in v1.0.0

func WithSupportsForUpdate(enabled bool) Option

WithSupportsForUpdate overrides FOR UPDATE support detection.

func WithSupportsLastInsertID added in v1.0.0

func WithSupportsLastInsertID(enabled bool) Option

WithSupportsLastInsertID overrides LastInsertId support detection.

func WithSupportsReturning added in v1.0.0

func WithSupportsReturning(enabled bool) Option

WithSupportsReturning overrides RETURNING support detection.

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

Querier executes SQL queries with context.

type QueryColStmt

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

QueryColStmt is a fluent SELECT builder that scans scalar values of T.

func QueryCol

func QueryCol[T any](engine *Engine) *QueryColStmt[T]

QueryCol builds a SELECT statement that scans into a single column of T.

func (*QueryColStmt[T]) AddColumn

func (s *QueryColStmt[T]) AddColumn(column any, args ...any) *QueryColStmt[T]

AddColumn adds a result column to the query. Unlike Select, AddColumn accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryColStmt[T]) Clone added in v1.0.0

func (s *QueryColStmt[T]) Clone() *QueryColStmt[T]

Clone returns a copy of the statement state. Terminal methods still reset only the statement they are called on.

func (*QueryColStmt[T]) Column

func (s *QueryColStmt[T]) Column(column any, args ...any) *QueryColStmt[T]

Column adds a result column to the query. Unlike Select, Column accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryColStmt[T]) CrossJoin

func (s *QueryColStmt[T]) CrossJoin(join string, rest ...any) *QueryColStmt[T]

CrossJoin adds a CROSS JOIN clause to the query.

func (*QueryColStmt[T]) Distinct

func (s *QueryColStmt[T]) Distinct() *QueryColStmt[T]

Distinct adds a DISTINCT clause to the query.

func (*QueryColStmt[T]) Find

func (s *QueryColStmt[T]) Find(ctx context.Context) ([]T, error)

Find returns all values from the first selected column.

func (*QueryColStmt[T]) From

func (s *QueryColStmt[T]) From(from string) *QueryColStmt[T]

From sets the FROM clause of the query.

func (*QueryColStmt[T]) FromSelect

func (s *QueryColStmt[T]) FromSelect(from *builder.SelectBuilder, alias string) *QueryColStmt[T]

FromSelect sets a subquery into the FROM clause of the query.

func (*QueryColStmt[T]) Get

func (s *QueryColStmt[T]) Get(ctx context.Context) (T, bool, error)

Get returns the first column value and whether a row was found.

func (*QueryColStmt[T]) GroupBy

func (s *QueryColStmt[T]) GroupBy(groupBys ...string) *QueryColStmt[T]

GroupBy adds GROUP BY expressions to the query.

func (*QueryColStmt[T]) Having

func (s *QueryColStmt[T]) Having(pred any, rest ...any) *QueryColStmt[T]

Having adds an expression to the HAVING clause of the query.

See Where.

func (*QueryColStmt[T]) InnerJoin

func (s *QueryColStmt[T]) InnerJoin(join string, rest ...any) *QueryColStmt[T]

InnerJoin adds a INNER JOIN clause to the query.

func (*QueryColStmt[T]) Join

func (s *QueryColStmt[T]) Join(join string, rest ...any) *QueryColStmt[T]

Join adds a JOIN clause to the query.

func (*QueryColStmt[T]) JoinClause

func (s *QueryColStmt[T]) JoinClause(pred any, args ...any) *QueryColStmt[T]

JoinClause adds a join clause to the query.

func (*QueryColStmt[T]) LeftJoin

func (s *QueryColStmt[T]) LeftJoin(join string, rest ...any) *QueryColStmt[T]

LeftJoin adds a LEFT JOIN clause to the query.

func (*QueryColStmt[T]) Limit

func (s *QueryColStmt[T]) Limit(limit uint64) *QueryColStmt[T]

Limit sets a LIMIT clause on the query.

func (*QueryColStmt[T]) Offset

func (s *QueryColStmt[T]) Offset(offset uint64) *QueryColStmt[T]

Offset sets a OFFSET clause on the query.

func (*QueryColStmt[T]) Options

func (s *QueryColStmt[T]) Options(options ...string) *QueryColStmt[T]

Options adds select option to the query

func (*QueryColStmt[T]) OrderBy

func (s *QueryColStmt[T]) OrderBy(orderBys ...string) *QueryColStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*QueryColStmt[T]) OrderByClause

func (s *QueryColStmt[T]) OrderByClause(pred any, args ...any) *QueryColStmt[T]

OrderByClause adds ORDER BY clause to the query.

func (*QueryColStmt[T]) Prefix

func (s *QueryColStmt[T]) Prefix(sql string, args ...any) *QueryColStmt[T]

Prefix adds an expression to the beginning of the query

func (*QueryColStmt[T]) PrefixExpr

func (s *QueryColStmt[T]) PrefixExpr(expr builder.Sqlizer) *QueryColStmt[T]

PrefixExpr adds an expression to the very beginning of the query

func (*QueryColStmt[T]) RemoveColumns

func (s *QueryColStmt[T]) RemoveColumns() *QueryColStmt[T]

RemoveColumns remove all columns from query. Must add a new column with Column or Select methods, otherwise return a error.

func (*QueryColStmt[T]) RemoveLimit

func (s *QueryColStmt[T]) RemoveLimit() *QueryColStmt[T]

RemoveLimit removes the LIMIT clause.

func (*QueryColStmt[T]) RemoveOffset

func (s *QueryColStmt[T]) RemoveOffset() *QueryColStmt[T]

RemoveOffset removes OFFSET clause.

func (*QueryColStmt[T]) RightJoin

func (s *QueryColStmt[T]) RightJoin(join string, rest ...any) *QueryColStmt[T]

RightJoin adds a RIGHT JOIN clause to the query.

func (*QueryColStmt[T]) Select

func (s *QueryColStmt[T]) Select(columns ...string) *QueryColStmt[T]

Select set result columns to the query.

func (*QueryColStmt[T]) Suffix

func (s *QueryColStmt[T]) Suffix(sql string, args ...any) *QueryColStmt[T]

Suffix adds an expression to the end of the query

func (*QueryColStmt[T]) SuffixExpr

func (s *QueryColStmt[T]) SuffixExpr(expr builder.Sqlizer) *QueryColStmt[T]

SuffixExpr adds an expression to the end of the query

func (*QueryColStmt[T]) Where

func (s *QueryColStmt[T]) Where(pred any, args ...any) *QueryColStmt[T]

Where adds an expression to the WHERE clause of the query.

Expressions are ANDed together in the generated SQL.

Where accepts several types for its pred argument:

nil OR "" - ignored.

string - SQL expression. If the expression has SQL placeholders then a set of arguments must be passed as well, one for each placeholder.

map[string]any OR Eq - map of SQL expressions to values. Each key is transformed into an expression like "<key> = ?", with the corresponding value bound to the placeholder. Nil, slices, arrays, pointers, and driver values are passed as one bound value; use builder.IsNull, builder.IsNotNull, builder.In, or builder.NotIn explicitly when you need those predicate forms.

Where will panic if pred isn't any of the above types.

type QueryModelStmt

type QueryModelStmt[T Model] struct {
	// contains filtered or unexported fields
}

QueryModelStmt is a fluent SELECT builder that scans rows into models of T.

func Query

func Query[T Model](engine *Engine) *QueryModelStmt[T]

Query builds a SELECT statement that scans rows into models of T.

func (*QueryModelStmt[T]) AddColumn

func (s *QueryModelStmt[T]) AddColumn(column any, args ...any) *QueryModelStmt[T]

AddColumn adds a result column to the query. Unlike Select, AddColumn accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryModelStmt[T]) Clone added in v1.0.0

func (s *QueryModelStmt[T]) Clone() *QueryModelStmt[T]

Clone returns a copy of the statement state. Terminal methods still reset only the statement they are called on.

func (*QueryModelStmt[T]) Column

func (s *QueryModelStmt[T]) Column(column any, args ...any) *QueryModelStmt[T]

Column adds a result column to the query. Unlike Select, Column accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryModelStmt[T]) CrossJoin

func (s *QueryModelStmt[T]) CrossJoin(join string, rest ...any) *QueryModelStmt[T]

CrossJoin adds a CROSS JOIN clause to the query.

func (*QueryModelStmt[T]) Distinct

func (s *QueryModelStmt[T]) Distinct() *QueryModelStmt[T]

Distinct adds a DISTINCT clause to the query.

func (*QueryModelStmt[T]) Exist

func (s *QueryModelStmt[T]) Exist(ctx context.Context) (bool, error)

Exist reports whether the query returns at least one row.

func (*QueryModelStmt[T]) Find

func (s *QueryModelStmt[T]) Find(ctx context.Context) ([]T, error)

Find returns all matching models.

func (*QueryModelStmt[T]) From

func (s *QueryModelStmt[T]) From(from string) *QueryModelStmt[T]

From sets the FROM clause of the query.

func (*QueryModelStmt[T]) FromSelect

func (s *QueryModelStmt[T]) FromSelect(from *builder.SelectBuilder, alias string) *QueryModelStmt[T]

FromSelect sets a subquery into the FROM clause of the query.

func (*QueryModelStmt[T]) Get

func (s *QueryModelStmt[T]) Get(ctx context.Context) (T, error)

Get returns the first matching model or the zero value when no row matches.

func (*QueryModelStmt[T]) GroupBy

func (s *QueryModelStmt[T]) GroupBy(groupBys ...string) *QueryModelStmt[T]

GroupBy adds GROUP BY expressions to the query.

func (*QueryModelStmt[T]) Having

func (s *QueryModelStmt[T]) Having(pred any, rest ...any) *QueryModelStmt[T]

Having adds an expression to the HAVING clause of the query.

See Where.

func (*QueryModelStmt[T]) ID

func (s *QueryModelStmt[T]) ID(id any) *QueryModelStmt[T]

ID adds a single-column primary key predicate derived from the model metadata.

func (*QueryModelStmt[T]) InnerJoin

func (s *QueryModelStmt[T]) InnerJoin(join string, rest ...any) *QueryModelStmt[T]

InnerJoin adds a INNER JOIN clause to the query.

func (*QueryModelStmt[T]) Join

func (s *QueryModelStmt[T]) Join(join string, rest ...any) *QueryModelStmt[T]

Join adds a JOIN clause to the query.

func (*QueryModelStmt[T]) JoinClause

func (s *QueryModelStmt[T]) JoinClause(pred any, args ...any) *QueryModelStmt[T]

JoinClause adds a join clause to the query.

func (*QueryModelStmt[T]) LeftJoin

func (s *QueryModelStmt[T]) LeftJoin(join string, rest ...any) *QueryModelStmt[T]

LeftJoin adds a LEFT JOIN clause to the query.

func (*QueryModelStmt[T]) Limit

func (s *QueryModelStmt[T]) Limit(limit uint64) *QueryModelStmt[T]

Limit sets a LIMIT clause on the query.

func (*QueryModelStmt[T]) Offset

func (s *QueryModelStmt[T]) Offset(offset uint64) *QueryModelStmt[T]

Offset sets a OFFSET clause on the query.

func (*QueryModelStmt[T]) Options

func (s *QueryModelStmt[T]) Options(options ...string) *QueryModelStmt[T]

Options adds select option to the query

func (*QueryModelStmt[T]) OrderBy

func (s *QueryModelStmt[T]) OrderBy(orderBys ...string) *QueryModelStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*QueryModelStmt[T]) OrderByClause

func (s *QueryModelStmt[T]) OrderByClause(pred any, args ...any) *QueryModelStmt[T]

OrderByClause adds ORDER BY clause to the query.

func (*QueryModelStmt[T]) Page

func (s *QueryModelStmt[T]) Page(ctx context.Context, page, size uint64) ([]T, uint64, error)

Page returns the requested page of results together with the total row count.

func (*QueryModelStmt[T]) Prefix

func (s *QueryModelStmt[T]) Prefix(sql string, args ...any) *QueryModelStmt[T]

Prefix adds an expression to the beginning of the query

func (*QueryModelStmt[T]) PrefixExpr

func (s *QueryModelStmt[T]) PrefixExpr(expr builder.Sqlizer) *QueryModelStmt[T]

PrefixExpr adds an expression to the very beginning of the query

func (*QueryModelStmt[T]) RemoveColumns

func (s *QueryModelStmt[T]) RemoveColumns() *QueryModelStmt[T]

RemoveColumns remove all columns from query. Must add a new column with Column or Select methods, otherwise return a error.

func (*QueryModelStmt[T]) RemoveLimit

func (s *QueryModelStmt[T]) RemoveLimit() *QueryModelStmt[T]

RemoveLimit removes the LIMIT clause.

func (*QueryModelStmt[T]) RemoveOffset

func (s *QueryModelStmt[T]) RemoveOffset() *QueryModelStmt[T]

RemoveOffset removes OFFSET clause.

func (*QueryModelStmt[T]) RightJoin

func (s *QueryModelStmt[T]) RightJoin(join string, rest ...any) *QueryModelStmt[T]

RightJoin adds a RIGHT JOIN clause to the query.

func (*QueryModelStmt[T]) Select

func (s *QueryModelStmt[T]) Select(columns ...string) *QueryModelStmt[T]

Select set result columns to the query.

func (*QueryModelStmt[T]) Suffix

func (s *QueryModelStmt[T]) Suffix(sql string, args ...any) *QueryModelStmt[T]

Suffix adds an expression to the end of the query

func (*QueryModelStmt[T]) SuffixExpr

func (s *QueryModelStmt[T]) SuffixExpr(expr builder.Sqlizer) *QueryModelStmt[T]

SuffixExpr adds an expression to the end of the query

func (*QueryModelStmt[T]) Where

func (s *QueryModelStmt[T]) Where(pred any, args ...any) *QueryModelStmt[T]

Where adds an expression to the WHERE clause of the query.

Expressions are ANDed together in the generated SQL.

Where accepts several types for its pred argument:

nil OR "" - ignored.

string - SQL expression. If the expression has SQL placeholders then a set of arguments must be passed as well, one for each placeholder.

map[string]any OR Eq - map of SQL expressions to values. Each key is transformed into an expression like "<key> = ?", with the corresponding value bound to the placeholder. Nil, slices, arrays, pointers, and driver values are passed as one bound value; use builder.IsNull, builder.IsNotNull, builder.In, or builder.NotIn explicitly when you need those predicate forms.

Where will panic if pred isn't any of the above types.

type Repository

type Repository[T Table] struct {
	Engine *Engine
	// contains filtered or unexported fields
}

Repository provides common CRUD helpers for table T.

func NewRepository

func NewRepository[T Table](engine *Engine) *Repository[T]

NewRepository creates a Repository backed by engine.

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(ctx context.Context, id any) (rowsAffected int64, err error)

Delete deletes a row by its single-column primary key.

func (*Repository[T]) DeleteByField

func (r *Repository[T]) DeleteByField(ctx context.Context, field string, value any) (rowsAffected int64, err error)

DeleteByField deletes rows matching field = value.

func (*Repository[T]) Exist

func (r *Repository[T]) Exist(ctx context.Context, id any) (bool, error)

Exist reports whether a row with the given primary key exists.

func (*Repository[T]) ExistByField

func (r *Repository[T]) ExistByField(ctx context.Context, field string, value any) (bool, error)

ExistByField reports whether any row matches field = value.

func (*Repository[T]) Get

func (r *Repository[T]) Get(ctx context.Context, id any) (T, error)

Get loads a row by its single-column primary key.

func (*Repository[T]) GetByField

func (r *Repository[T]) GetByField(ctx context.Context, field string, value any) (T, error)

GetByField loads the first row matching field = value.

func (*Repository[T]) Insert

func (r *Repository[T]) Insert(ctx context.Context, model T) (rowsAffected int64, err error)

Insert inserts a model.

func (*Repository[T]) InsertAll

func (r *Repository[T]) InsertAll(ctx context.Context, models []T) (rowsAffected int64, err error)

InsertAll inserts models in one batch.

func (*Repository[T]) InsertIgnore

func (r *Repository[T]) InsertIgnore(ctx context.Context, model T) (rowsAffected int64, err error)

InsertIgnore inserts a model while ignoring duplicate conflicts when supported.

func (*Repository[T]) InsertIgnoreAll

func (r *Repository[T]) InsertIgnoreAll(ctx context.Context, models []T) (rowsAffected int64, err error)

InsertIgnoreAll inserts models while ignoring duplicate conflicts when supported.

func (*Repository[T]) Lock

func (r *Repository[T]) Lock(ctx context.Context, id any) (T, error)

Lock loads a row by primary key and appends FOR UPDATE when supported.

func (*Repository[T]) LockByField

func (r *Repository[T]) LockByField(ctx context.Context, field string, value any) (T, error)

LockByField loads the first row matching field = value and locks it for update.

func (*Repository[T]) Update

func (r *Repository[T]) Update(ctx context.Context, model T) (rowsAffected int64, err error)

Update updates model using its primary key fields.

func (*Repository[T]) UpdateMap

func (r *Repository[T]) UpdateMap(ctx context.Context, id any, data map[string]any) (rowsAffected int64, err error)

UpdateMap updates the row identified by id with the provided column values.

type Table

type Table interface {
	TableName
	Model
	// contains filtered or unexported methods
}

Table is a model that also exposes a database table name.

type TableName

type TableName interface {
	TableName() string
}

TableName lets a model override its database table name.

type UnimplementedModel

type UnimplementedModel struct{}

UnimplementedModel can be embedded to satisfy the Model marker method.

type UnimplementedTable

type UnimplementedTable struct{}

UnimplementedTable can be embedded to satisfy the Table marker methods.

type UpdateStmt

type UpdateStmt[T Table] struct {
	// contains filtered or unexported fields
}

UpdateStmt is a fluent UPDATE builder for table T.

func Update

func Update[T Table](engine *Engine) *UpdateStmt[T]

Update builds an UPDATE statement for table T.

func (*UpdateStmt[T]) Clone added in v1.0.0

func (s *UpdateStmt[T]) Clone() *UpdateStmt[T]

Clone returns a copy of the statement state. Terminal methods still reset only the statement they are called on.

func (*UpdateStmt[T]) Exec

func (s *UpdateStmt[T]) Exec(ctx context.Context) (rowsAffected int64, err error)

Exec executes the built UPDATE statement.

func (*UpdateStmt[T]) ID

func (s *UpdateStmt[T]) ID(id any) *UpdateStmt[T]

ID adds a single-column primary key predicate derived from the model metadata.

func (*UpdateStmt[T]) Limit

func (s *UpdateStmt[T]) Limit(limit uint64) *UpdateStmt[T]

Limit sets a LIMIT clause on the query.

func (*UpdateStmt[T]) Offset

func (s *UpdateStmt[T]) Offset(offset uint64) *UpdateStmt[T]

Offset sets a OFFSET clause on the query.

func (*UpdateStmt[T]) OrderBy

func (s *UpdateStmt[T]) OrderBy(orderBys ...string) *UpdateStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*UpdateStmt[T]) Prefix

func (s *UpdateStmt[T]) Prefix(sql string, args ...any) *UpdateStmt[T]

Prefix adds an expression to the beginning of the query

func (*UpdateStmt[T]) PrefixExpr

func (s *UpdateStmt[T]) PrefixExpr(expr builder.Sqlizer) *UpdateStmt[T]

PrefixExpr adds an expression to the very beginning of the query

func (*UpdateStmt[T]) Set

func (s *UpdateStmt[T]) Set(column string, value any) *UpdateStmt[T]

Set adds SET clauses to the query.

func (*UpdateStmt[T]) SetMap

func (s *UpdateStmt[T]) SetMap(clauses map[string]any) *UpdateStmt[T]

SetMap is a convenience method which calls .Set for each key/value pair in clauses.

func (*UpdateStmt[T]) SetModel

func (s *UpdateStmt[T]) SetModel(t T) *UpdateStmt[T]

SetModel maps model fields into SET and WHERE clauses using descriptor metadata.

SetModel performs a full-field update for regular columns. Zero values are not ignored automatically, so partial updates should prefer SetMap/Set.

func (*UpdateStmt[T]) Suffix

func (s *UpdateStmt[T]) Suffix(sql string, args ...any) *UpdateStmt[T]

Suffix adds an expression to the end of the query

func (*UpdateStmt[T]) SuffixExpr

func (s *UpdateStmt[T]) SuffixExpr(expr builder.Sqlizer) *UpdateStmt[T]

SuffixExpr adds an expression to the end of the query

func (*UpdateStmt[T]) Table

func (s *UpdateStmt[T]) Table(table string) *UpdateStmt[T]

Table overrides the target table name.

func (*UpdateStmt[T]) Where

func (s *UpdateStmt[T]) Where(pred any, args ...any) *UpdateStmt[T]

Where adds WHERE expressions to the query.

See SelectBuilder.Where for more information.

Directories

Path Synopsis
try
cmd
lormgen command

Jump to

Keyboard shortcuts

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