db

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 6 Imported by: 0

README

db

Dialect-agnostic bun tooling — nothing here imports a specific driver:

  • Repository[T] — a generic repository (GetOne, GetMany, Count, Exists, Create, Update, UpdateByMap, Delete) over any bun model. Works with T as a struct (Repository[Model]) or a pointer to one (Repository[*Model]); use the pointer form when you need a DB-assigned field (a generated ULID, a defaulted timestamp) to land back on your own variable after Create/Update — those methods take item by value, so with a non-pointer T the mutation only reaches the method's own copy.
  • ConditionalUpdate[M] — a guarded UPDATE ... WHERE that reports whether a row actually matched, for flipping a row's state only if it's still in an expected prior one (avoids a race between a check and a write).
  • Model / IdentityModel — embeddable base structs that assign a ULID primary key on insert (Model also stamps created_at/updated_at).

Anything driver-specific lives in its own subpackage instead:

  • db/postgres — a *bun.DB connection builder and Postgres error classification (unique/foreign-key violation → constraint name). New() reads DB_URL and the DB_* pool variables itself; a service that loads its own configuration builds a postgres.Config and calls Open(cfg), which returns an error (never a panic) whose text never contains the DSN's password. A Config never prints its password, through slog, fmt or JSON. pgdriver still fills what a DSN leaves out from PGHOST/PGPORT/PGUSER/PGDATABASE, so name all four in the DSN.

A future MySQL (or other) driver would get the same treatment: its own db/mysql subpackage, db's repository and models reused as-is.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConditionalUpdate

func ConditionalUpdate[M any](ctx context.Context, database bun.IDB, queryFn UpdateQueryFn) (bool, error)

ConditionalUpdate runs an UPDATE guarded by queryFn's own WHERE clause and reports whether any row matched — the shared shape behind every "flip this row's status if it's still in an expected prior state" repository method (e.g. PayoutRepository.MarkProcessing, PaymentLinkPaymentRepository. ReleaseEscrow), used instead of a plain check-then-write to avoid a race between the check and the write. M must be the model type itself, not a pointer, e.g. db.ConditionalUpdate[models.Payout](ctx, r.DB(), ...) — db.ConditionalUpdate[*models.Payout] is a compile-time-legal but wrong instantiation this function rejects at runtime rather than handing bun a nil double pointer.

Types

type IdentityModel

type IdentityModel struct {
	ID string `bun:"id,pk" json:"id"`
}

IdentityModel embeds a ULID primary key, auto-populated on insert. Embed this (instead of Model) for tables with no created_at/updated_at columns.

func (*IdentityModel) BeforeAppendModel

func (m *IdentityModel) BeforeAppendModel(_ context.Context, query bun.Query) error

BeforeAppendModel assigns a new ULID to ID on insert if it isn't already set, mirroring Laravel's automatic key generation on model creation.

type Model

type Model struct {
	IdentityModel

	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time `bun:"updated_at,notnull,default:current_timestamp" json:"updated_at"`
}

Model embeds a ULID primary key plus created_at/updated_at timestamps, auto-populated via BeforeAppendModel.

func (*Model) BeforeAppendModel

func (m *Model) BeforeAppendModel(ctx context.Context, query bun.Query) error

BeforeAppendModel delegates to IdentityModel for ID assignment (Go's method shadowing means it wouldn't otherwise run), stamps CreatedAt on insert without overwriting a caller-supplied value (e.g. for backfills), and refreshes UpdatedAt on every insert/update.

type QueryFn

type QueryFn func(*bun.SelectQuery) *bun.SelectQuery

type Repository

type Repository[T any] interface {
	GetOne(ctx context.Context, queryFn QueryFn) (T, error)
	GetMany(ctx context.Context, queryFn QueryFn) ([]T, error)
	// Count reports how many rows match queryFn's own filters (ignoring any
	// Limit/Offset it sets) - the real pagination total, run as its own
	// query alongside GetMany's page fetch rather than derived from
	// "did a full page come back."
	Count(ctx context.Context, queryFn QueryFn) (int, error)
	Exists(ctx context.Context, queryFn QueryFn) (bool, error)
	Create(ctx context.Context, item T) error
	Update(ctx context.Context, item T) error
	UpdateByMap(ctx context.Context, values map[string]any, queryFn UpdateQueryFn) error
	Delete(ctx context.Context, item T) error
	// DB returns the underlying connection, for callers that embed a
	// Repository but need to build one custom query (a conditional UPDATE,
	// an ON CONFLICT insert) this interface has no method for.
	DB() bun.IDB
}

Repository works with T as either a struct (Repository[Model]) or a pointer to one (Repository[*Model]) — every method runs either way. Create and Update still mutate the row through bun's model hooks (e.g. BeforeAppendModel assigning a ULID) regardless of T's shape, but that mutation is only visible to the caller when T is a pointer: Create/Update take item by value, so with a non-pointer T the hook mutates the method's own local copy, not the caller's variable. Use Repository[*Model] when you need to read back a DB-assigned field (ULID, defaulted timestamp) after Create.

func NewRepository

func NewRepository[T any](db bun.IDB) Repository[T]

type UpdateQueryFn

type UpdateQueryFn func(*bun.UpdateQuery) *bun.UpdateQuery

Directories

Path Synopsis
Package postgres builds a *bun.DB connection to Postgres.
Package postgres builds a *bun.DB connection to Postgres.

Jump to

Keyboard shortcuts

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