pack

package
v0.1.1 Latest Latest
Warning

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

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

Documentation

Overview

Example
fake := testdb.New()
db := Open(fake.Open(), pgdialect.New())

fake.Enqueue(testdb.Result{ // the account itself
	Columns: []string{"id", "email", "created_at", "nickname"},
	Rows: [][]driver.Value{
		testdb.Row(int64(1), "ada@example.com", time.Time{}, ""),
	},
})
fake.Enqueue(testdb.Result{ // Posts, batch-loaded by Preload (R9.5)
	Columns: []string{"id", "user_id", "title"},
	Rows: [][]driver.Value{
		testdb.Row(int64(10), int64(1), "Hello, Argo"),
	},
})

accounts, err := Of[testAccount](db).
	Where(accountCol.Email.Eq("ada@example.com")).
	Preload(accountRel.Posts).
	Find(context.Background())
if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(accounts[0].Email, len(accounts[0].Posts), accounts[0].Posts[0].Title)

fake.Enqueue(testdb.Result{ // Create's RETURNING id + the default: created_at column
	Columns: []string{"id", "created_at"},
	Rows:    [][]driver.Value{testdb.Row(int64(2), time.Time{})},
})
row := &testAccount{Email: "grace@example.com"}
if err := Create(context.Background(), db, row); err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(row.ID)
Output:
ada@example.com 1 Hello, Argo
2

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNoRows = fmt.Errorf("pack: no rows in result set: %w", sql.ErrNoRows)
View Source
var ErrPinnedConnUnsupported = fmt.Errorf("pack: PinnedConn: underlying connection source does not support connection pinning")

Functions

func ByID

func ByID[T Entity[ID], ID comparable](ctx context.Context, db *DB, id ID) (T, error)

func Create

func Create[T any](ctx context.Context, db *DB, row *T, opts ...WriteOption) error

func CreateAll

func CreateAll[T any](ctx context.Context, db *DB, rows []*T, opts ...WriteOption) error
Example
fake := testdb.New()
db := Open(fake.Open(), pgdialect.New())
fake.Enqueue(testdb.Result{
	Columns: []string{"id"},
	Rows:    [][]driver.Value{testdb.Row(int64(1)), testdb.Row(int64(2))},
})

rows := []*testWidget{{Count: 10}, {Count: 20}}
if err := CreateAll(context.Background(), db, rows); err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(rows[0].ID, rows[1].ID)
Output:
1 2

func Delete

func Delete[T Entity[ID], ID comparable](ctx context.Context, db *DB, id ID) error

func Raw

func Raw[T any](ctx context.Context, db *DB, sqlText string, args ...any) ([]T, error)

func Save

func Save[T Entity[ID], ID comparable](ctx context.Context, db *DB, row *T) error

func Update

func Update[T Entity[ID], ID comparable](ctx context.Context, db *DB, row *T) error

Types

type AfterDeleter

type AfterDeleter interface {
	AfterDelete(ctx context.Context) error
}

type AfterInserter

type AfterInserter interface {
	AfterInsert(ctx context.Context) error
}

type AfterScanner

type AfterScanner interface {
	AfterScan(ctx context.Context) error
}

type AfterUpdater

type AfterUpdater interface {
	AfterUpdate(ctx context.Context) error
}

type AnyCol

type AnyCol[T any] interface {
	// contains filtered or unexported methods
}

type Assignment

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

type BeforeDeleter

type BeforeDeleter interface {
	BeforeDelete(ctx context.Context) error
}

type BeforeInserter

type BeforeInserter interface {
	BeforeInsert(ctx context.Context) error
}

type BeforeUpdater

type BeforeUpdater interface {
	BeforeUpdate(ctx context.Context) error
}

type Col

type Col[T, F any] struct {
	// contains filtered or unexported fields
}

func Field

func Field[T, F any](sel func(*T) *F) Col[T, F]

func (Col[T, F]) Asc

func (c Col[T, F]) Asc() OrderTerm[T]

func (Col[T, F]) Between

func (c Col[T, F]) Between(lo, hi F) Predicate

func (Col[T, F]) Desc

func (c Col[T, F]) Desc() OrderTerm[T]

func (Col[T, F]) Eq

func (c Col[T, F]) Eq(v F) Predicate

func (Col[T, F]) Gt

func (c Col[T, F]) Gt(v F) Predicate

func (Col[T, F]) Gte

func (c Col[T, F]) Gte(v F) Predicate

func (Col[T, F]) In

func (c Col[T, F]) In(vs ...F) Predicate

func (Col[T, F]) IsNotNull

func (c Col[T, F]) IsNotNull() Predicate

func (Col[T, F]) IsNull

func (c Col[T, F]) IsNull() Predicate

func (Col[T, F]) Lt

func (c Col[T, F]) Lt(v F) Predicate

func (Col[T, F]) Lte

func (c Col[T, F]) Lte(v F) Predicate

func (Col[T, F]) Ne

func (c Col[T, F]) Ne(v F) Predicate

func (Col[T, F]) NotIn

func (c Col[T, F]) NotIn(vs ...F) Predicate

func (Col[T, F]) Set

func (c Col[T, F]) Set(v F) Assignment

func (Col[T, F]) SetExpr

func (c Col[T, F]) SetExpr(sqlExpr string, args ...any) Assignment

type ConflictBuilder

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

func OnConflict

func OnConflict[T any](cols ...AnyCol[T]) *ConflictBuilder[T]
Example
fake := testdb.New()
db := Open(fake.Open(), pgdialect.New())
fake.Enqueue(testdb.Result{RowsAffected: 1})

row := &testWidget{Count: 5}
err := Create(context.Background(), db, row, OnConflict[testWidget](widgetCol.ID).DoNothing())
fmt.Println(err)
Output:
<nil>

func (*ConflictBuilder[T]) DoNothing

func (c *ConflictBuilder[T]) DoNothing() WriteOption

func (*ConflictBuilder[T]) DoUpdate

func (c *ConflictBuilder[T]) DoUpdate(assignments ...Assignment) WriteOption

type DB

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

func Connect

func Connect(d driver.Driver, dsn string, opts ...Option) (*DB, error)

func Open

func Open(db *sql.DB, d dialect.Dialect, opts ...Option) *DB

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*DB, error)

func (*DB) Commit

func (db *DB) Commit() error

func (*DB) Dialect

func (db *DB) Dialect() dialect.Dialect

func (*DB) ExecContext

func (db *DB) ExecContext(ctx context.Context, op, model, sqlText string, args []any) (sql.Result, error)

func (*DB) InTransaction

func (db *DB) InTransaction() bool

func (*DB) PinnedConn

func (db *DB) PinnedConn(ctx context.Context, fn func(pinned *DB) error) error

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, op, model, sqlText string, args []any) (*sql.Rows, error)

func (*DB) Rollback

func (db *DB) Rollback() error

func (*DB) Tx

func (db *DB) Tx(ctx context.Context, fn TransactionFunc) error
Example
fake := testdb.New()
db := Open(fake.Open(), pgdialect.New())
fake.Enqueue(testdb.Result{
	Columns: []string{"id"},
	Rows:    [][]driver.Value{testdb.Row(int64(1))},
})

err := db.Tx(context.Background(), func(tx *DB) error {
	return Create(context.Background(), tx, &testWidget{Count: 1})
})
fmt.Println(err)
Output:
<nil>

type Entity

type Entity[ID comparable] interface {
	PK() ID
}

type ErrCheckViolation

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

func (*ErrCheckViolation) Error

func (e *ErrCheckViolation) Error() string

func (*ErrCheckViolation) Unwrap

func (e *ErrCheckViolation) Unwrap() error

type ErrForeignKeyViolation

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

func (*ErrForeignKeyViolation) Error

func (e *ErrForeignKeyViolation) Error() string

func (*ErrForeignKeyViolation) Unwrap

func (e *ErrForeignKeyViolation) Unwrap() error

type ErrNotNullViolation

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

func (*ErrNotNullViolation) Error

func (e *ErrNotNullViolation) Error() string

func (*ErrNotNullViolation) Unwrap

func (e *ErrNotNullViolation) Unwrap() error

type ErrSetOperationBlockedByHooks

type ErrSetOperationBlockedByHooks struct {
	Model     string
	Operation string
}

func (*ErrSetOperationBlockedByHooks) Error

type ErrUintOverflow

type ErrUintOverflow struct {
	Model  string
	Field  string
	Column string
	Value  uint64
}

func (*ErrUintOverflow) Error

func (e *ErrUintOverflow) Error() string

type ErrUniqueViolation

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

func (*ErrUniqueViolation) Error

func (e *ErrUniqueViolation) Error() string

func (*ErrUniqueViolation) Unwrap

func (e *ErrUniqueViolation) Unwrap() error

type ErrZeroCompositeKey

type ErrZeroCompositeKey struct {
	Model string
}

func (*ErrZeroCompositeKey) Error

func (e *ErrZeroCompositeKey) Error() string

type Model

type Model[ID comparable] struct {
	ID ID `db:"id,pk,auto_increment"`
}

func (Model[ID]) PK

func (m Model[ID]) PK() ID

func (*Model[ID]) SetPK

func (m *Model[ID]) SetPK(v ID)

type Option

type Option func(o *dbOptions)

func WithErrorDecoder

func WithErrorDecoder(d driver.ErrorDecoder) Option

func WithQueryHook

func WithQueryHook(h QueryHook) Option

func WithQueryHookArgs

func WithQueryHookArgs() Option

type OrderTerm

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

type Predicate

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

func And

func And(preds ...Predicate) Predicate

func ILike

func ILike[T any](c Col[T, string], pattern string) Predicate

func Like

func Like[T any](c Col[T, string], pattern string) Predicate

func Not

func Not(p Predicate) Predicate

func NotLike

func NotLike[T any](c Col[T, string], pattern string) Predicate

func On

func On[L, R, F any](left Col[L, F], right Col[R, F]) Predicate

func Or

func Or(preds ...Predicate) Predicate

type PreloadOption

type PreloadOption interface {
	// contains filtered or unexported methods
}

func Preload

func Preload[T, U any](rel Rel[T, U], opts ...PreloadOption) PreloadOption

func Where

func Where(p Predicate) PreloadOption

type Query

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

func Of

func Of[T any](db *DB) *Query[T]

func (*Query[T]) Count

func (q *Query[T]) Count(ctx context.Context) (int64, error)

func (*Query[T]) Delete

func (q *Query[T]) Delete(ctx context.Context) (int64, error)

func (*Query[T]) DeleteAll

func (q *Query[T]) DeleteAll(ctx context.Context) (int64, error)

func (*Query[T]) Distinct

func (q *Query[T]) Distinct() *Query[T]

func (*Query[T]) Exists

func (q *Query[T]) Exists(ctx context.Context) (bool, error)

func (*Query[T]) Find

func (q *Query[T]) Find(ctx context.Context) ([]T, error)

func (*Query[T]) First

func (q *Query[T]) First(ctx context.Context) (T, error)

func (*Query[T]) ForShare

func (q *Query[T]) ForShare() *Query[T]

func (*Query[T]) ForUpdate

func (q *Query[T]) ForUpdate() *Query[T]

func (*Query[T]) GroupBy

func (q *Query[T]) GroupBy(cols ...AnyCol[T]) *Query[T]

func (*Query[T]) Having

func (q *Query[T]) Having(p Predicate) *Query[T]

func (*Query[T]) Join

func (q *Query[T]) Join[U any](on Predicate) *Query[T]

func (*Query[T]) LeftJoin

func (q *Query[T]) LeftJoin[U any](on Predicate) *Query[T]

func (*Query[T]) Limit

func (q *Query[T]) Limit(n int64) *Query[T]

func (*Query[T]) Offset

func (q *Query[T]) Offset(n int64) *Query[T]

func (*Query[T]) Or

func (q *Query[T]) Or(p Predicate) *Query[T]

func (*Query[T]) Order

func (q *Query[T]) Order(terms ...OrderTerm[T]) *Query[T]

func (*Query[T]) OrderRaw

func (q *Query[T]) OrderRaw(fragment string) *Query[T]

func (*Query[T]) Preload

func (q *Query[T]) Preload[U any](rel Rel[T, U], opts ...PreloadOption) *Query[T]

func (*Query[T]) Project

func (q *Query[T]) Project[U any]() *Query[U]

func (*Query[T]) Rows

func (q *Query[T]) Rows(ctx context.Context) iter.Seq2[T, error]
Example
fake := testdb.New()
db := Open(fake.Open(), pgdialect.New())
fake.Enqueue(testdb.Result{
	Columns: []string{"id", "name"},
	Rows: [][]driver.Value{
		testdb.Row(int64(1), "a"),
		testdb.Row(int64(2), "b"),
	},
})

for row, err := range Of[testHookedItem](db).Rows(context.Background()) {
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(row.ID, row.Name)
}
Output:
1 a
2 b

func (*Query[T]) Scopes

func (q *Query[T]) Scopes(scopes ...Scope[T]) *Query[T]
Example
fake := testdb.New()
db := Open(fake.Open(), pgdialect.New())

fake.Enqueue(testdb.Result{
	Columns: []string{"id", "email", "created_at", "nickname"},
	Rows: [][]driver.Value{
		testdb.Row(int64(1), "ada@example.com", time.Time{}, ""),
	},
})

accounts, err := Of[testAccount](db).
	Scopes(adultAccounts, withAccountEmail("ada@example.com")).
	Find(context.Background())
if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(accounts[0].Email)
Output:
ada@example.com

func (*Query[T]) Select

func (q *Query[T]) Select(cols ...AnyCol[T]) *Query[T]

func (*Query[T]) SelectRaw

func (q *Query[T]) SelectRaw(fragment string) *Query[T]

func (*Query[T]) SkipHooks

func (q *Query[T]) SkipHooks() *Query[T]

func (*Query[T]) SkipLocked

func (q *Query[T]) SkipLocked() *Query[T]

func (*Query[T]) Update

func (q *Query[T]) Update(ctx context.Context, assignments ...Assignment) (int64, error)

func (*Query[T]) Where

func (q *Query[T]) Where(p Predicate) *Query[T]

func (*Query[T]) WhereRaw

func (q *Query[T]) WhereRaw(fragment string, args ...any) *Query[T]

type QueryEvent

type QueryEvent struct {
	Operation    string
	Model        string
	SQL          string
	Args         []any
	Start        time.Time
	Duration     time.Duration
	RowsAffected int64
	Err          error
}

type QueryHook

type QueryHook interface {
	BeforeQuery(ctx context.Context, ev *QueryEvent) context.Context
	AfterQuery(ctx context.Context, ev *QueryEvent)
}

type Rel

type Rel[T, U any] struct {
	// contains filtered or unexported fields
}

func Relation

func Relation[T, U any](sel func(*T) *[]*U) Rel[T, U]

func RelationOne

func RelationOne[T, U any](sel func(*T) **U) Rel[T, U]

type Scope

type Scope[T any] func(*Query[T]) *Query[T]

Scope is a reusable, composable query modifier, applied via Query[T].Scopes.

type TransactionFunc

type TransactionFunc func(tx *DB) error

type WriteOption

type WriteOption interface {
	// contains filtered or unexported methods
}

func WithBatchSize

func WithBatchSize(n int) WriteOption

Directories

Path Synopsis
mysql module
postgres module
sqlite module
internal

Jump to

Keyboard shortcuts

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