models

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 25 Imported by: 3

Documentation

Overview

Package models provides core infrastructure for GORM-based domain models.

This package contains the building blocks that all domain models depend on:

  • BaseModel: Embedded struct providing ID, timestamps, soft-delete, metadata
  • Repository[T]: Generic CRUD repository with query options
  • Trait interfaces: Sluggable, GeoLocatable, Nameable, Auditable
  • Errors: Sentinel errors and ValidationError for consistent error handling
  • Hooks: Lifecycle hook system for audit logging and extensibility

Usage

Domain models embed BaseModel and implement desired traits:

type State struct {
    models.BaseModel
    Name         string `gorm:"size:100;not null"`
    Abbreviation string `gorm:"size:2;uniqueIndex"`
}

func (s *State) GetName() string { return s.Name }  // Implements Nameable

Repositories embed the generic Repository:

type stateRepository struct {
    *models.Repository[State]
}

Query Options

Use QueryOption functions to build flexible queries:

states, err := repo.FindAll(ctx,
    models.WithLimit(10),
    models.WithOrderBy("name", false),
    models.WithPreload("Cities"),
)

Temporal edges

TemporalEdge is append-only. Change an edge only with SupersedeEdge (correct it), EndEdge or EndEdgeAt (record its end, now or at a given time, with a closed copy), or SuppressEdge (take it down), inside a transaction (see Transactor). Each acts only on an active edge (ActiveEdgePredicate) that matches the id and the caller's EdgeWhere conditions, and returns ErrNotFound otherwise. On any error, roll the transaction back; WithinTx does when its callback returns the error:

err := transactor.WithinTx(ctx, func(ctx context.Context) error {
    _, err := models.EndEdge[PartyPhone](ctx, edgeID, models.EdgeWhere("person_id = ?", personID))
    return err
})

EndEdgeAt ends an edge at a given time instead of now, such as the date a source reports: the closed copy's ValidTo is that time, which may be neither zero, nor after the clock's now, nor before the edge's ValidFrom. EndEdgeAtWith also lets a callback set the closed copy's own columns:

_, err := models.EndEdgeAt[Membership](ctx, edgeID, endedAt, models.EdgeWhere("member_id = ?", memberID))

The helpers above act only on an active edge. To act on an edge after it has ended, SupersedeCurrentEdge and SuppressCurrentEdge match its current row (CurrentEdgePredicate): supersede an ended edge's closed copy with an open copy to reopen it, or with another closed copy to correct its end, and suppress it to take the edge down.

The superseded_by_id column must carry no immediate foreign key to its own table (none, or one declared DEFERRABLE INITIALLY DEFERRED), because a supersede points it at the row it inserts next. The VerificationStatus constants (VerificationStatusUnverified and the rest) are the conventional statuses.

Normalizers

NormalizeEmail, ParsePhone, and NormalizePersonName validate and canonicalize the email addresses, phone numbers, and personal names people type. They fail with a ValidationError that never includes the input.

Input is flexible and output is standard. NormalizeEmail trims, folds case, and removes the wrappers an address is pasted in (mailto:, enclosing angle brackets or quotes, a trailing comma or semicolon). It returns the Mailbox mail is delivered to, the canonical Address with provider domain aliases applied (googlemail.com is gmail.com), and the alias Root; its options (RejectQuotedLocal, RejectTrailingDot, RequireDottedDomain, or StrictEmail for all three) refuse forms the broad RFC set allows. ParsePhone drops all but the digits and plus signs (labels, punctuation, tel: and sms: schemes), validates the number against its region's numbering plan, and returns its E.164 and international forms; its options set a default region, require a number in use (RequireValidNumber), or read keypad letters (KeypadLetters):

email, err := models.NormalizeEmail(" <Jane@Example.COM> ", models.StrictEmail())
// email.Address == "jane@example.com"

phone, err := models.ParsePhone("Phone: (305) 555-0100",
    models.WithDefaultRegion("US"), models.RequireValidNumber())
// phone.E164 == "+13055550100", phone.International == "+1 305-555-0100"

NormalizePhone, which checks only the shape of E.164, is deprecated in favor of ParsePhone.

Civil dates

Date is a calendar date with no time zone. It maps to a SQL date column and to YYYY-MM-DD text and JSON. NewDate, ParseDate, and DateOf build one, and ErrInvalidDate reports anything that is not a real calendar date from 0001-01-01 through 9999-12-31. Store an optional date as *Date.

Database Compatibility

All components are designed for PostgreSQL (production) and SQLite (testing). See BaseModel documentation for type mapping details.

Index

Constants

View Source
const (
	OpCreate     = "create"
	OpUpdate     = "update"
	OpDelete     = "delete"
	OpSoftDelete = "soft_delete"
	OpRestore    = "restore"
	OpQuery      = "query"
)

Operation type constants

View Source
const (
	VerificationStatusUnverified = "unverified" // nothing has verified the value; the default
	VerificationStatusVerified   = "verified"   // a verification step confirmed the value
	VerificationStatusDisputed   = "disputed"   // a source or reviewer contests the value
	VerificationStatusSuppressed = "suppressed" // a verification outcome that withholds the value; not SuppressedAt
)

The conventional TemporalEdge.VerificationStatus values. The storage layer does not enforce the set; writers use these constants.

View Source
const ActiveEdgePredicate = "valid_to IS NULL AND superseded_by_id IS NULL AND suppressed_at IS NULL"

ActiveEdgePredicate is the SQL condition that selects active edges: not ended, not superseded, and not suppressed. Its column names are unqualified; qualify them when joining. A partial "active" index on an edge table should use the same condition, so queries that filter on it can use the index.

View Source
const CurrentEdgePredicate = "superseded_by_id IS NULL AND suppressed_at IS NULL"

CurrentEdgePredicate is the SQL condition that selects an edge's current row: the one no later row supersedes and that is not suppressed, whether or not it has ended. An active edge's current row is the active row; an ended edge's is the closed copy that recorded its end. Its column names are unqualified; qualify them when joining.

View Source
const MaxPersonNameLength = 100

MaxPersonNameLength is the longest name NormalizePersonName accepts, in Unicode code points of the normalized result.

View Source
const RequestIDKey contextKey = "request_id"

RequestIDKey is the context key for request ID.

Deprecated: stamp the request id with ctxutil.WithRequestID and read it with ctxutil.RequestIDFrom (or GetRequestIDFromContext). This key is no longer consulted by GetRequestIDFromContext, so values stored under it will not be found.

Variables

View Source
var (
	// ErrNotFound indicates the requested resource was not found.
	ErrNotFound = errors.New("resource not found")

	// ErrValidation indicates the input data failed validation.
	ErrValidation = errors.New("validation failed")

	// ErrDuplicateKey indicates a unique constraint violation occurred.
	ErrDuplicateKey = errors.New("duplicate key violation")

	// ErrForeignKey indicates a foreign key constraint violation occurred.
	ErrForeignKey = errors.New("foreign key constraint violated")

	// ErrDatabaseError indicates a general database operation failure.
	ErrDatabaseError = errors.New("database operation failed")

	// ErrCascadeDelete indicates deletion was blocked due to dependent records.
	ErrCascadeDelete = errors.New("cannot delete: dependent records exist")

	// ErrInvalidID indicates the provided ID is not a valid UUID.
	ErrInvalidID = errors.New("invalid id format")

	// ErrHook indicates a hook execution failed.
	ErrHook = errors.New("hook error")

	// ErrNoTransaction indicates that an operation which must run inside a database
	// transaction was called with a context that carries none (see Transactor, WithTx).
	ErrNoTransaction = errors.New("operation requires a transaction")
)

Sentinel errors for model operations. Use errors.Is() to check for these errors in handlers and services.

View Source
var ErrInvalidDate = errors.New("invalid calendar date")

ErrInvalidDate indicates a value that is not a real calendar date written YYYY-MM-DD, from 0001-01-01 through 9999-12-31. Its text is fixed and never includes the value.

View Source
var ErrUnknownPhoneRegion = errors.New("models: unknown phone region")

ErrUnknownPhoneRegion is returned by ParsePhone when WithDefaultRegion names a region the numbering-plan metadata doesn't know. It is a caller's configuration error, not a ValidationError.

View Source
var ProviderRules = map[string]ProviderRule{
	"gmail.com":      {Separator: '+', StripDots: true},
	"outlook.com":    {Separator: '+'},
	"hotmail.com":    {Separator: '+'},
	"hotmail.co.uk":  {Separator: '+'},
	"hotmail.fr":     {Separator: '+'},
	"hotmail.de":     {Separator: '+'},
	"live.com":       {Separator: '+'},
	"msn.com":        {Separator: '+'},
	"yahoo.com":      {Separator: '+'},
	"yahoo.co.uk":    {Separator: '+'},
	"yahoo.fr":       {Separator: '+'},
	"yahoo.de":       {Separator: '+'},
	"ymail.com":      {Separator: '+'},
	"rocketmail.com": {Separator: '+'},
	"yandex.ru":      {Separator: '+'},
	"fastmail.com":   {Separator: '+'},
	"fastmail.fm":    {Separator: '+'},
	"icloud.com":     {Separator: '+'},
	"proton.me":      {Separator: '+'},
	"protonmail.com": {Separator: '+'},
	"protonmail.ch":  {Separator: '+'},
	"pm.me":          {Separator: '+'},
}

ProviderRules holds the per-provider alias collapse policy, keyed by the canonical domain (post domainAliases lookup).

Functions

func ApplyOptions

func ApplyOptions(db *gorm.DB, opts ...QueryOption) *gorm.DB

ApplyOptions applies all query options to the database connection.

func BoundingBox

func BoundingBox(lat, lon, radiusKm float64) (minLat, maxLat, minLon, maxLon float64)

BoundingBox calculates lat/lng bounds for a center point and radius. Returns (minLat, maxLat, minLon, maxLon). Uses the approximation that 1 degree latitude ≈ 111km.

func CosApprox

func CosApprox(degrees float64) float64

CosApprox provides a simple cosine approximation for geo calculations. Uses Taylor series approximation for small angles.

func DBFrom

func DBFrom(ctx context.Context, fallback *gorm.DB) *gorm.DB

DBFrom returns the *gorm.DB attached to ctx, or fallback when none is attached. Repositories call DBFrom(ctx, r.db) so that calls made inside a Transactor.WithinTx block automatically pick up the transaction handle.

func EndEdge added in v0.9.0

func EndEdge[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, conds ...EdgeCondition,
) (PT, error)

EndEdge records that the active edge id has ended now, without updating it in place: it is EndEdgeAt with the context clock's now as the end, so the closed copy's ValidTo, RecordedAt, and CreatedAt are one instant. It supersedes the edge with the copy and returns the copy. The copy has the edge's fields (valid_from, event time, provenance, and every model column) and a new ID. The original keeps what was believed; the copy records that the relationship held from ValidFrom until now. The original's valid_to is never written. Unlike EndEdgeAt, it never compares the end with the edge's ValidFrom, so an edge whose ValidFrom is later than now still ends, at now.

It locks the active row as it reads it (FOR UPDATE where the database has row locks), so no other transaction changes the row between that read and the supersede, and the copy holds the row's committed values. A lost race is still no match: after waiting for the lock, PostgreSQL re-checks the predicate.

It runs only in the transaction ctx carries, and returns ErrNoTransaction otherwise. It acts only on an active edge (ActiveEdgePredicate) that matches id and every condition. Before any SQL runs, it refuses a malformed id with ErrInvalidID, and a condition that is blank, whose parentheses don't balance, or that holds ";", "--", or "/*", with an error wrapping ErrValidation. When no edge matches, it returns an error wrapping ErrNotFound and writes nothing.

As with SupersedeEdge, superseded_by_id must carry no immediate foreign key to its own table (none, or one declared DEFERRABLE INITIALLY DEFERRED), and on any error the caller must roll back. Under PostgreSQL's READ COMMITTED, of two concurrent calls on one edge exactly one succeeds.

func EndEdgeAt added in v0.12.0

func EndEdgeAt[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, validTo time.Time, conds ...EdgeCondition,
) (PT, error)

EndEdgeAt records that the active edge id ended at validTo, without updating it in place: it supersedes the edge with a closed copy and returns the copy. Use it when the end is a known time, such as one a source reports; EndEdge ends an edge at the clock's now. The copy has the edge's fields, a new ID, ValidTo set to validTo as given, and RecordedAt and CreatedAt set to the context clock's now, read once before any SQL runs. The original's valid_to is never written.

It runs only in the transaction ctx carries, and returns ErrNoTransaction otherwise. It acts only on an active edge (ActiveEdgePredicate) that matches id and every condition. Before any SQL runs, it refuses a malformed id with ErrInvalidID; and, with an error wrapping ErrValidation, a condition that is blank, whose parentheses don't balance, or that holds ";", "--", or "/*", and a validTo that is zero or after the clock's now. After the read, it returns an error wrapping ErrNotFound when no edge matches, and an error wrapping ErrValidation when validTo is before the edge's ValidFrom; an end equal to ValidFrom is allowed. A refused call writes nothing.

The time refusals are programming errors, not a *ValidationError: a caller that takes the time from a person checks it first and reports its own field error.

Like EndEdge, it locks the active row as it reads it, so the copy holds the row's committed values; superseded_by_id must carry no immediate foreign key to its own table (none, or one declared DEFERRABLE INITIALLY DEFERRED); on any error the caller must roll back; and under PostgreSQL's READ COMMITTED, of two concurrent calls on one edge exactly one succeeds. It is EndEdgeAtWith with no finish.

func EndEdgeAtWith added in v0.12.0

func EndEdgeAtWith[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, validTo time.Time, finish func(closed PT), conds ...EdgeCondition,
) (PT, error)

EndEdgeAtWith is EndEdgeAt with one more step, for a closed copy that carries columns of its own, such as why the edge ended or what ended it. After the read and the start check, and before anything is written, it calls finish once with the copy, while the edge's row is locked. It then sets the copy's ID, ValidTo, RecordedAt, and CreatedAt itself, so finish can't change them. A copy that finish leaves superseded or suppressed is refused with an error wrapping ErrValidation, and nothing is written. A call that EndEdgeAt would refuse never calls finish. finish should only set fields; a nil finish is EndEdgeAt.

func GenerateSlug

func GenerateSlug(s string) string

GenerateSlug creates a URL-friendly slug from the given string. It converts to lowercase, replaces spaces/underscores with hyphens, removes non-alphanumeric characters, and cleans up consecutive hyphens.

func GetRequestIDFromContext

func GetRequestIDFromContext(ctx context.Context) string

GetRequestIDFromContext extracts the request ID from context for log correlation. It reads the canonical ctxutil request-id key, so an id stamped by middleware.LoggingMiddleware (via ctxutil.WithRequestID) is visible here.

func NewID

func NewID() string

NewID returns a freshly minted UUID v7 string. v7 IDs embed a millisecond timestamp, so they sort lexicographically in creation order — which lets later phases paginate by id alone instead of composite cursors.

If the underlying RNG fails (a process-level fault, not a runtime condition on supported platforms), NewID panics.

func NewValidationError

func NewValidationError(field, message string) error

NewValidationError creates a new validation error with field and message.

func NormalizePersonName added in v0.9.0

func NormalizePersonName(raw, fieldName string) (string, error)

NormalizePersonName validates and canonicalizes a person's name, in any script. It applies Unicode NFC, trims ASCII spaces (U+0020) from both ends, and collapses each run of spaces into one; it changes nothing else. Empty or space-only input returns "" and no error: whether a name is required is the caller's decision.

A name may hold only letters and marks (Unicode categories L and M), except those that render as nothing (the Hangul fillers, the combining grapheme joiner, the Khmer inherent vowels, and the variation selectors), and the space, hyphen-minus, apostrophe, right single quotation mark (U+2019), and full stop. Anything else is refused, never stripped: control and format characters (bidi controls and zero-width characters included), other spaces, digits of every script, "<", ">", other punctuation and symbols, and invalid UTF-8. NFC follows the stream-safe format, which inserts U+034F after 30 consecutive combining marks, so a name with more is refused too.

The result must start with a letter or an apostrophe, must not end with a hyphen, must contain a letter, and may be at most MaxPersonNameLength code points long. A refused name returns "" and a *ValidationError for fieldName whose message never includes the input.

func NormalizePhone deprecated

func NormalizePhone(raw, errorField string) (string, error)

NormalizePhone canonicalizes a phone string to E.164. A bare 10-digit number is treated as North American. An input that begins with '+' is preserved verbatim apart from non-digit stripping; anything else is prefixed with '+'.

Returns a ValidationError (wrapping ErrValidation) on empty input or on a result that fails the E.164 regex. The errorField argument is the field name reported in the validation error (e.g. "phone" or "e164") so the caller can shape the error to match its own DTO.

Deprecated: NormalizePhone checks only the shape of E.164, so it accepts numbers no numbering plan allows (000-000-0000, a 7-digit local number, two numbers run together). Use ParsePhone, which validates the number against its region's numbering plan.

func SupersedeCurrentEdge added in v0.12.0

func SupersedeCurrentEdge[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, replacement PT, conds ...EdgeCondition,
) error

SupersedeCurrentEdge is SupersedeEdge for the edge's current row (CurrentEdgePredicate) instead of its active row, so it also acts on an edge after it has ended: supersede an ended edge's closed copy with an open copy (ValidTo nil) to reopen it, or with another closed copy to correct its end. It checks the replacement as SupersedeEdge does, not its times.

A reopened edge is active again, so when another active edge already holds its key under a partial unique index over active rows, the insert fails with an error wrapping ErrDuplicateKey, and the caller must roll back. Everything else (the transaction, the checks, update then insert, no match, the foreign-key note, and concurrency) is SupersedeEdge's.

func SupersedeEdge added in v0.9.0

func SupersedeEdge[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, replacement PT, conds ...EdgeCondition,
) error

SupersedeEdge replaces the active edge id with replacement: it points the edge's superseded_by_id at the replacement, then inserts the replacement. It is how an edge is corrected without updating it in place.

It runs only in the transaction ctx carries, and returns ErrNoTransaction otherwise. It acts only on an active edge (ActiveEdgePredicate) that matches id and every condition; SupersedeCurrentEdge and SuppressCurrentEdge act on an edge after it has ended. Before any SQL runs, it refuses a malformed id or replacement ID with ErrInvalidID, and a condition that is blank, whose parentheses don't balance, or that holds ";", "--", or "/*", with an error wrapping ErrValidation; it refuses a nil replacement, one already superseded or suppressed, and one whose ID is id the same way. When no edge matches, it returns an error wrapping ErrNotFound and inserts nothing.

The replacement's ID is minted before the update (a preset one is kept), and its BeforeCreate hook runs on insert; associations are not saved. Because the update points superseded_by_id at the row inserted next, that column must carry no immediate foreign key to its own table: none, or one declared DEFERRABLE INITIALLY DEFERRED.

On any error the caller must roll back, as Transactor.WithinTx does when its callback returns the error: a failed insert follows a successful update. Under PostgreSQL's READ COMMITTED, of two concurrent calls on one edge exactly one succeeds, because the conditional update re-checks the predicate after waiting for the other's row lock.

func SuppressCurrentEdge added in v0.12.0

func SuppressCurrentEdge[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, conds ...EdgeCondition,
) error

SuppressCurrentEdge is SuppressEdge for the edge's current row (CurrentEdgePredicate), so it takes an edge down whether or not it has ended. It writes only suppressed_at. Everything else (the transaction, the checks, no match, and concurrency) is SuppressEdge's.

func SuppressEdge added in v0.9.0

func SuppressEdge[T any, ID ~string, PT EdgeModel[T, ID]](
	ctx context.Context, id ID, conds ...EdgeCondition,
) error

SuppressEdge takes the active edge id down: it sets its suppressed_at to the context clock's now and writes no other column. verification_status is not touched; VerificationStatusSuppressed is an outcome a writer records on a new row.

It runs only in the transaction ctx carries, and returns ErrNoTransaction otherwise. It acts only on an active edge (ActiveEdgePredicate) that matches id and every condition; SupersedeCurrentEdge and SuppressCurrentEdge act on an edge after it has ended. Before any SQL runs, it refuses a malformed id with ErrInvalidID, and a condition that is blank, whose parentheses don't balance, or that holds ";", "--", or "/*", with an error wrapping ErrValidation. When no edge matches, it returns an error wrapping ErrNotFound and writes nothing.

On any error the caller must roll back, as Transactor.WithinTx does when its callback returns the error. Under PostgreSQL's READ COMMITTED, of two concurrent calls on one edge exactly one succeeds, because the conditional update re-checks the predicate after waiting for the other's row lock.

func ValidateAbbreviation

func ValidateAbbreviation(abbr string) (string, error)

ValidateAbbreviation validates and normalizes a 2-character abbreviation. Returns the normalized uppercase abbreviation.

func ValidateCoordinates

func ValidateCoordinates(lat, lon *float64) error

ValidateCoordinates validates latitude and longitude if provided. Latitude must be between -90 and 90, longitude between -180 and 180. A nil pointer is treated as unset (and therefore valid).

func ValidateExternalSource

func ValidateExternalSource(e *ExternalSource) error

ValidateExternalSource validates the ExternalSource fields against the storage constraints and the dedup-key contract:

  • Provider (when set) must be at most 50 characters.
  • ExternalID (when set) must be at most 500 characters.
  • When Provider is set, ExternalID is required: the two together form the provider dedup key, so a provider without an external identifier cannot be deduplicated.

A nil receiver and a fully-empty source are both valid (user-created entities carry no provenance). Returns a ValidationError wrapping ErrValidation.

func ValidateGeoParams

func ValidateGeoParams(lat, lon, radiusKm float64) error

ValidateGeoParams validates geo query parameters.

func ValidateNonNegative

func ValidateNonNegative(value *int64, fieldName string) error

ValidateNonNegative validates an int64 pointer is non-negative.

func ValidateOptionalURL

func ValidateOptionalURL(urlStr *string, fieldName string) error

ValidateOptionalURL validates an optional URL field. Returns nil if the URL is nil/empty or valid, error if invalid.

func ValidateOptionalUUID

func ValidateOptionalUUID(uuidPtr *string, fieldName string) error

ValidateOptionalUUID validates an optional UUID pointer field. Returns nil if the UUID is nil/empty or valid, validation error if invalid.

func ValidateRequired

func ValidateRequired(value, fieldName string) (string, error)

ValidateRequired trims and validates a required string field. Returns the trimmed value and a validation error if empty.

func ValidateSlug

func ValidateSlug(slug string) (string, error)

ValidateSlug normalizes and validates a slug. Returns the normalized lowercase slug.

func ValidateUUID

func ValidateUUID(id string) error

ValidateUUID checks if the given string is a valid UUID.

func WithClock

func WithClock(ctx context.Context, clk Clock) context.Context

WithClock returns a child context carrying clk.

func WithTx

func WithTx(ctx context.Context, tx *gorm.DB) context.Context

WithTx returns a child context carrying the active GORM transaction handle. Repositories read this via DBFrom so that callers do not need to thread a transactional manager through every method signature.

func WrapDBError

func WrapDBError(err error) error

WrapDBError converts GORM and driver errors to domain errors. It uses typed `errors.As` matching for both the PostgreSQL (pgx) and SQLite drivers, falling back to a string-based match only as a defensive last resort — any string fallback emits a slog.Warn so we can detect when a driver upgrade changes error shapes.

Types

type Auditable

type Auditable interface {
	GetID() string
	TableName() string
}

Auditable indicates a model supports audit logging. Models implementing this interface will have their lifecycle events logged.

type BaseModel

type BaseModel[ID ~string] struct {
	// ID is the UUID primary key, auto-generated on create if empty.
	ID ID `gorm:"type:uuid;primaryKey" json:"id"`

	// CreatedAt is automatically set when the record is created.
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt is automatically updated when the record is modified.
	UpdatedAt time.Time `json:"updated_at"`

	// DeletedAt enables soft-delete functionality - records are filtered by default.
	DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`

	// Metadata allows storing arbitrary JSON data for extensibility.
	Metadata datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"metadata,omitempty"`
}

BaseModel provides common fields for all models in the system. It is generic over a typed ID (any `~string` alias) so that each bounded context can declare its own ID type (e.g. people.PersonID, channels.PhoneID) without losing compile-time safety.

Embed the typed form:

type Person struct {
    models.BaseModel[PersonID]
    GivenName  string
}

PostgreSQL vs SQLite Considerations

This package is designed to work with both PostgreSQL (production) and SQLite (testing). Key compatibility considerations:

## UUID Type

PostgreSQL has native UUID type support, while SQLite stores UUIDs as TEXT. Typed IDs (e.g. PersonID) are string aliases — GORM's reflection sees the underlying string and serializes correctly on both drivers.

## JSONB Type

The datatypes.JSON type handles cross-database JSON storage:

  • PostgreSQL: Uses JSONB column type with indexing support
  • SQLite: Uses TEXT column with JSON stored as string

## Timestamps

GORM's automatic timestamp handling works on both databases.

## Soft Delete Filtering

The gorm.DeletedAt type provides automatic soft-delete filtering on both.

func (*BaseModel[ID]) BeforeCreate

func (b *BaseModel[ID]) BeforeCreate(_ *gorm.DB) error

BeforeCreate is a GORM hook that generates a UUID v7 for the ID field if not already set. v7 IDs are time-ordered; an explicitly-set ID is preserved unchanged so replay tooling can supply its own identifiers.

func (*BaseModel[ID]) GetID

func (b *BaseModel[ID]) GetID() string

GetID returns the model's ID as a string. Satisfies the Auditable interface so audit hooks can log a uniform string identifier across all typed-ID models.

func (*BaseModel[ID]) IsDeleted

func (b *BaseModel[ID]) IsDeleted() bool

IsDeleted returns true if the record has been soft-deleted.

type Clock

type Clock interface {
	Now(ctx context.Context) time.Time
}

Clock abstracts "now" so callers can be given deterministic time.

func ClockFrom

func ClockFrom(ctx context.Context) Clock

ClockFrom returns the Clock attached to ctx, or a real-time default clock when none is attached.

type DBLogger

type DBLogger interface {
	// LogOperation logs a database operation with context.
	LogOperation(ctx context.Context, op DBOperation)
}

DBLogger defines an interface for database operation logging. Implementations can use this for audit trails, metrics, or debugging.

type DBOperation

type DBOperation struct {
	// Timestamp is when the operation occurred (UTC)
	Timestamp time.Time `json:"timestamp"`

	// Type is the operation type: "create", "update", "delete", "query"
	Type string `json:"type"`

	// Model is the model name: "user", "account", "order"
	Model string `json:"model"`

	// ID is the record ID (if applicable)
	ID string `json:"id,omitempty"`

	// Duration is how long the operation took
	DurationMS int64 `json:"duration_ms,omitempty"`

	// RowsAffected is the number of rows affected (for write operations)
	RowsAffected int64 `json:"rows_affected,omitempty"`

	// Error is the error message (if operation failed)
	Error string `json:"error,omitempty"`

	// RequestID is the request ID from context (for correlation)
	RequestID string `json:"request_id,omitempty"`
}

DBOperation represents a database operation for logging.

type Date added in v0.9.0

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date is a calendar date (a year, a month, and a day) with no time of day and no time zone, from 0001-01-01 through 9999-12-31. It maps to a SQL date column and is written as YYYY-MM-DD text, so no database session time zone can move it; text and JSON use the same form. The zero Date is not a date: Value and MarshalText refuse it, so store an optional date as *Date.

A Date from NewDate, ParseDate, or an in-range DateOf is always valid. The fields are exported, so a Date built by hand can name a day that doesn't exist; Value and MarshalText refuse it too.

func DateOf added in v0.9.0

func DateOf(t time.Time) Date

DateOf returns the calendar day of t in UTC. A time outside 0001-01-01 through 9999-12-31 gives a Date that Value and MarshalText refuse. Today's date is DateOf(ClockFrom(ctx).Now(ctx)).

func NewDate added in v0.9.0

func NewDate(year int, month time.Month, day int) (Date, error)

NewDate returns the Date of year, month, and day, or the zero Date and ErrInvalidDate unless they name a real calendar date from 0001-01-01 through 9999-12-31. It never normalizes: February 30 is refused, not moved to March.

func ParseDate added in v0.9.0

func ParseDate(s string) (Date, error)

ParseDate parses s, which must be exactly YYYY-MM-DD: a real calendar date from 0001-01-01 through 9999-12-31, with no surrounding space, sign, time, or zone. Anything else returns the zero Date and ErrInvalidDate, whose text never includes s.

func (Date) After added in v0.9.0

func (d Date) After(other Date) bool

After reports whether d is a later calendar day than other.

func (Date) Before added in v0.9.0

func (d Date) Before(other Date) bool

Before reports whether d is an earlier calendar day than other.

func (Date) GormDataType added in v0.9.0

func (Date) GormDataType() string

GormDataType returns "date", so GORM declares a date column for a Date field (and a nullable one for a *Date field).

func (Date) IsZero added in v0.9.0

func (d Date) IsZero() bool

IsZero reports whether d is the zero Date. encoding/json's omitzero option calls it.

func (Date) MarshalText added in v0.9.0

func (d Date) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler, so JSON writes a Date as the string "YYYY-MM-DD". Like Value, it returns ErrInvalidDate for a Date that is not a real calendar date in range, the zero Date included.

func (*Date) Scan added in v0.9.0

func (d *Date) Scan(src any) error

Scan implements sql.Scanner. It reads a time.Time as that time's own year, month, and day, never converted to another zone first (drivers return a date column as midnight UTC). It reads a string or []byte with ParseDate, using only its first ten bytes when it is longer, because a driver can return timestamp text for a date column. Anything else, nil included, and any date out of range, returns ErrInvalidDate and leaves d unchanged. A NULL belongs in a *Date, which database/sql and GORM set to nil without calling Scan.

func (Date) String added in v0.9.0

func (d Date) String() string

String returns d as YYYY-MM-DD, its fields as they are; the zero Date prints 0000-00-00.

func (*Date) UnmarshalText added in v0.9.0

func (d *Date) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler with ParseDate. On an error it returns ErrInvalidDate and leaves d unchanged.

func (Date) Value added in v0.9.0

func (d Date) Value() (driver.Value, error)

Value implements driver.Valuer. It writes d as YYYY-MM-DD text, which every engine reads as the same day whatever the session time zone, and returns ErrInvalidDate for a Date that is not a real calendar date in range, the zero Date included.

type DefaultDBLogger

type DefaultDBLogger struct{}

DefaultDBLogger forwards DB operations to slog.Default() as a single structured "db_operation" line. The handler installed by the binary (typically observability.Init) controls level filtering, output, and encoding.

func (*DefaultDBLogger) LogOperation

func (l *DefaultDBLogger) LogOperation(ctx context.Context, op DBOperation)

LogOperation logs the database operation through slog.

type EdgeCondition added in v0.9.0

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

EdgeCondition is an extra WHERE fragment that a lifecycle helper ANDs, in parentheses, with the edge id and the helper's predicate (ActiveEdgePredicate, or CurrentEdgePredicate for the current-row helpers), so a condition can only narrow the match. Build it with EdgeWhere.

func EdgeWhere added in v0.9.0

func EdgeWhere(query string, args ...any) EdgeCondition

EdgeWhere returns an EdgeCondition, for example EdgeWhere("owner_id = ?", ownerID). query is SQL written by the caller, never input: one boolean expression whose parentheses balance, with values passed only as args. A helper ANDs it, in parentheses, with the edge id and the helper's predicate (ActiveEdgePredicate, or CurrentEdgePredicate for the current-row helpers), so it can only narrow the match. The helpers refuse, with an error wrapping ErrValidation, a query that is blank, whose parentheses don't balance, or that holds ";", "--", or "/*", because such a fragment could escape the parentheses they add and widen the match.

type EdgeModel added in v0.9.0

type EdgeModel[T any, ID ~string] interface {
	*T
	Edge() *TemporalEdge[ID]
}

EdgeModel is satisfied by a pointer to any model that embeds TemporalEdge[ID]. The lifecycle helpers take it so the edge's ID type is checked at compile time.

type EmailOption added in v0.10.0

type EmailOption func(*emailRules)

EmailOption narrows what NormalizeEmail accepts. Each option refuses one form the broad RFC 5321/5322 set allows; StrictEmail applies them all.

func RejectQuotedLocal added in v0.10.0

func RejectQuotedLocal() EmailOption

RejectQuotedLocal refuses a quoted local part, such as "jane doe"@example.com.

func RejectTrailingDot added in v0.10.0

func RejectTrailingDot() EmailOption

RejectTrailingDot refuses an address that ends in the DNS root dot, such as jane@example.com., instead of dropping the dot.

func RequireDottedDomain added in v0.10.0

func RequireDottedDomain() EmailOption

RequireDottedDomain refuses a single-label domain, such as jane@localhost. An address on the public internet has at least one dot in its domain.

func StrictEmail added in v0.10.0

func StrictEmail() EmailOption

StrictEmail applies RejectQuotedLocal, RejectTrailingDot, and RequireDottedDomain: the shape of an ordinary address on the public internet.

type ExternalSource

type ExternalSource struct {
	// Provider is the external provider name (e.g., "leaguelinq").
	Provider *string `gorm:"size:50;index" json:"provider,omitempty"`

	// ExternalID is the provider-assigned unique identifier used as a dedup key.
	ExternalID *string `gorm:"size:500" json:"external_id,omitempty"`

	// LastSeenAt tracks the last time this entity was observed from the provider.
	LastSeenAt *time.Time `json:"last_seen_at,omitempty"`
}

ExternalSource is an embeddable struct that provides provenance tracking for entities created by external data providers. All fields are optional (pointers) so models can be either user-created (nil provider) or externally-sourced.

Embed anonymously in models so fields are promoted (e.g., game.Provider):

type League struct {
    models.BaseModel
    models.ExternalSource
    Name string `gorm:"size:255;not null" json:"name"`
}

func (*ExternalSource) IsExternal

func (e *ExternalSource) IsExternal() bool

IsExternal returns true if this entity was created by an external provider.

type FixedClock

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

FixedClock is a Clock that always returns a constant time, regardless of the context or the wall clock.

func NewFixedClock

func NewFixedClock(t time.Time) FixedClock

NewFixedClock returns a FixedClock anchored at t.

func (FixedClock) Now

Now returns the anchored time.

type GeoLocatable

type GeoLocatable interface {
	GetLatitude() *float64
	GetLongitude() *float64
}

GeoLocatable indicates a model has latitude/longitude coordinates.

type HookFunc

type HookFunc func(tx *gorm.DB, model any) error

HookFunc is the signature for lifecycle hooks.

type HookOption

type HookOption func(*HookRunner)

HookOption configures a HookRunner.

func WithAfterCreate

func WithAfterCreate(h HookFunc) HookOption

WithAfterCreate adds an AfterCreate hook to the runner.

func WithAfterDelete

func WithAfterDelete(h HookFunc) HookOption

WithAfterDelete adds an AfterDelete hook to the runner.

func WithAfterUpdate

func WithAfterUpdate(h HookFunc) HookOption

WithAfterUpdate adds an AfterUpdate hook to the runner.

type HookRunner

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

HookRunner manages and executes lifecycle hooks. It allows models to run a chain of hooks and optionally add custom logic.

func DefaultHooks

func DefaultHooks() *HookRunner

DefaultHooks returns an empty HookRunner with no pre-registered hooks. Models can use this as a starting point and extend with custom logic via WithAfterCreate, WithAfterUpdate, and WithAfterDelete.

func NewHookRunner

func NewHookRunner(opts ...HookOption) *HookRunner

NewHookRunner creates a HookRunner with the given options.

func (*HookRunner) RunAfterCreate

func (r *HookRunner) RunAfterCreate(tx *gorm.DB, model any) error

RunAfterCreate executes all AfterCreate hooks in order. Returns the first error encountered, or nil if all hooks succeed.

func (*HookRunner) RunAfterDelete

func (r *HookRunner) RunAfterDelete(tx *gorm.DB, model any) error

RunAfterDelete executes all AfterDelete hooks in order. Returns the first error encountered, or nil if all hooks succeed.

func (*HookRunner) RunAfterUpdate

func (r *HookRunner) RunAfterUpdate(tx *gorm.DB, model any) error

RunAfterUpdate executes all AfterUpdate hooks in order. Returns the first error encountered, or nil if all hooks succeed.

type Nameable

type Nameable interface {
	GetName() string
}

Nameable indicates a model has a searchable name field.

type NopDBLogger

type NopDBLogger struct{}

NopDBLogger is a no-op logger for testing or when logging is disabled.

func (*NopDBLogger) LogOperation

func (l *NopDBLogger) LogOperation(_ context.Context, _ DBOperation)

LogOperation does nothing.

type NormalizedEmail

type NormalizedEmail struct {
	// Mailbox is the address mail is delivered to, normalized: the
	// PRECIS-folded local part and the lowercased ASCII (IDN Punycode) domain
	// the input named, before provider domain aliases. It differs from Address
	// only for an aliased domain (jane@googlemail.com, whose Address is
	// jane@gmail.com). Send mail, and match the address a person typed, by
	// Mailbox: an aliased domain need not deliver to the same inbox.
	Mailbox string
	// Address is the canonical per-row form: lowercased ASCII domain (IDN
	// Punycode) with provider domain aliases applied, PRECIS-folded local
	// part. Plus tags are preserved here. Quoted local parts keep their
	// surrounding quotes verbatim.
	Address string
	// Root is the alias-collapsed form: provider rules applied (e.g. plus
	// tag stripped, Gmail dots removed). May equal Address when no rules apply.
	// For quoted local parts, Root equals Address (provider rules are skipped).
	Root string
	// Domain is the ASCII (Punycode) canonical domain, post-aliasing
	// (e.g. googlemail.com → gmail.com).
	Domain string
	// DisplayLocal is the local part as it appeared in the input
	// (post-whitespace-trim, pre-folding). Useful for display.
	DisplayLocal string
	// IsQuoted is true when the local part was a quoted string ("...@...").
	// Quoted local parts are opaque per RFC 5321 §4.1.2 and skip provider rules.
	IsQuoted bool
}

NormalizedEmail is the result of NormalizeEmail. It carries the mailbox the address names (Mailbox), the per-row canonical form (Address) used as the storage key, and the alias-collapsed Root used to group equivalent mailboxes (e.g. Gmail's plus-tags and dot-insensitivity).

func NormalizeEmail

func NormalizeEmail(raw string, opts ...EmailOption) (NormalizedEmail, error)

NormalizeEmail validates an email address and produces its canonical and alias-root forms.

Input is flexible. Surrounding whitespace is trimmed and case is folded, and the wrappers an address is often pasted in are removed: a mailto: scheme, one pair of enclosing angle brackets or quotes (straight or curly), and one trailing comma or semicolon. None of those can be part of a valid address, so removing them never changes the result for one.

With no options it accepts the broad RFC 5321/5322 punctuation set, quoted local parts, a single-label domain, a trailing root dot (dropped), full Unicode local parts via PRECIS (RFC 8265), and internationalized domain names via IDNA (RFC 5891). Options refuse some of those forms; nil options are ignored. A display-name form (Jane <jane@example.com>) and a list of addresses are always refused.

Returns a ValidationError (wrapping ErrValidation) on any parse, length, PRECIS, or IDNA failure, or a form an option refuses. No error includes the input.

type ParsedPhone added in v0.10.0

type ParsedPhone struct {
	// E164 is the canonical form to store and compare, such as +13055550100.
	E164 string

	// International is the standard display form, such as +1 305-555-0100.
	International string

	// RegionCode is the ISO 3166-1 alpha-2 code of the number's region, such
	// as "US"; "001" for a non-geographic number; or empty when the numbering
	// plan doesn't place it in one region.
	RegionCode string

	// CountryCallingCode is the number's country calling code, such as 1.
	CountryCallingCode int

	// NationalNumber is the number without its country calling code, as
	// digits.
	NationalNumber string

	// LineType is the kind of line the numbering plan assigns the number to,
	// or PhoneLineTypeUnknown.
	LineType PhoneLineType
}

ParsedPhone is a phone number ParsePhone accepted, in standard forms.

func ParsePhone added in v0.10.0

func ParsePhone(raw string, opts ...PhoneOption) (ParsedPhone, error)

ParsePhone validates a phone number against its region's numbering plan (libphonenumber's metadata) and returns it in standard forms.

Input is flexible. Before parsing, everything but the digits and the plus signs is dropped (go-sanitize's PhoneNumber): spaces, dashes of any kind, dots, slashes, parentheses, labels such as "Phone:", and URI schemes such as tel:, sms:, and callto:. Digits in any script count, such as full-width or Arabic-Indic ones. An international dialing prefix (00, or 011 in "US") stands for the plus sign when WithDefaultRegion is set, and the trunk 0 a number written with its country code may carry, as in +44 (0)20, is dropped.

The result must be one number of a length its region allows and at most E.164's 15 digits. An extension is refused, because E.164 can't hold one; it is found in the input as written, before its digits could merge into the number's. Options set a default region, require a number in use, or read keypad letters. Nil options are ignored.

Returns a ValidationError (wrapping ErrValidation) on input that is not such a number, and no error includes the input. A default region the metadata doesn't know is ErrUnknownPhoneRegion.

type PhoneLineType added in v0.10.0

type PhoneLineType string

PhoneLineType is the kind of line a numbering plan assigns a phone number to.

const (
	PhoneLineTypeMobile            PhoneLineType = "mobile"
	PhoneLineTypeFixedLine         PhoneLineType = "fixed_line"
	PhoneLineTypeFixedLineOrMobile PhoneLineType = "fixed_line_or_mobile"
	PhoneLineTypeTollFree          PhoneLineType = "toll_free"
	PhoneLineTypePremiumRate       PhoneLineType = "premium_rate"
	PhoneLineTypeSharedCost        PhoneLineType = "shared_cost"
	PhoneLineTypeVOIP              PhoneLineType = "voip"
	PhoneLineTypePersonalNumber    PhoneLineType = "personal_number"
	PhoneLineTypePager             PhoneLineType = "pager"
	PhoneLineTypeUAN               PhoneLineType = "uan"
	PhoneLineTypeVoicemail         PhoneLineType = "voicemail"
	PhoneLineTypeUnknown           PhoneLineType = "unknown"
)

Recognized PhoneLineType values.

type PhoneOption added in v0.10.0

type PhoneOption func(*phoneRules)

PhoneOption adjusts what ParsePhone accepts.

func KeypadLetters added in v0.10.0

func KeypadLetters() PhoneOption

KeypadLetters reads letters as the keypad digits they stand for, as in 1-800-FLOWERS. Without it, letters are dropped with the rest of what isn't a digit, so a lettered number is too short and refused.

func RequireValidNumber added in v0.10.0

func RequireValidNumber() PhoneOption

RequireValidNumber refuses a number outside the ranges its region assigns, such as 000-000-0000 or 123-456-7890. Without it, ParsePhone checks only that the number has a length its region allows, which accepts numbers that are not in use but survives numbering-plan changes the metadata doesn't know yet.

func WithDefaultRegion added in v0.10.0

func WithDefaultRegion(region string) PhoneOption

WithDefaultRegion sets the region, an ISO 3166-1 alpha-2 code such as "US", that a number written without its country code belongs to. It also sets the international dialing prefix ParsePhone recognizes (011 for "US", 00 for "GB"). Without it, a number must start with + and its country code.

type ProviderRule

type ProviderRule struct {
	// Separator is the rune that begins a tag suffix on the local part. Everything
	// from the first occurrence onward is stripped when computing the alias root.
	Separator rune
	// StripDots removes every "." from the local part when computing the alias
	// root. Only Gmail/Googlemail behaves this way.
	StripDots bool
}

ProviderRule describes how a mailbox provider (or class of providers) collapses distinct addresses to the same underlying mailbox. The default rule treats "+" as a tag separator and preserves dots; provider-specific rules override.

Caveats:

  • Outlook's "+" aliasing is config-dependent at the upstream MTA; treating "+" as an alias separator here may collapse rows the provider actually delivers separately. We accept that risk since the result is only used as a queryable alias key — the original address is preserved as the unique row identity.
  • Yahoo historically used "-" as a Disposable Address Plus separator, but that conflicts with legitimate hyphenated local parts (e.g. "mary-anne" would collapse to "mary"). We only honor "+" for Yahoo.
  • FastMail's subdomain alias trick (user@alias.fastmail.com) is not handled; only "+" tagging is collapsed.
  • Yandex delivers a login with dots to the same login with hyphens (alice.the.girl and alice-the-girl); that is not collapsed either.

func LookupProviderRule

func LookupProviderRule(domain string) (canonicalDomain string, rule ProviderRule)

LookupProviderRule resolves a lowercased domain to its canonical form and the provider rule that governs its alias-root computation. Unknown domains return (domain, defaultProviderRule).

type QueryOption

type QueryOption func(*gorm.DB) *gorm.DB

QueryOption is a functional option for customizing database queries. Options are applied in order when building queries.

func FindBySlugOpt

func FindBySlugOpt(slug string) (QueryOption, error)

FindBySlugOpt returns a query option for slug lookup. Returns an error if the slug is empty after normalization.

func FindNearbyOpt

func FindNearbyOpt(lat, lon, radiusKm float64) (QueryOption, error)

FindNearbyOpt returns a query option for bounding box geo queries. Validates coordinates and calculates the bounding box.

func SearchByNameOpt

func SearchByNameOpt(query string) QueryOption

SearchByNameOpt returns a query option for case-insensitive name search. If the query is empty, returns a no-op option.

func WithCondition

func WithCondition(query any, args ...any) QueryOption

WithCondition adds a custom WHERE condition to the query. This allows for arbitrary filtering without predefined methods.

Example:

cities, err := repo.FindAll(ctx, WithCondition("population > ?", 1000000))

func WithIncludeDeleted

func WithIncludeDeleted(include bool) QueryOption

WithIncludeDeleted includes soft-deleted records in the query results.

func WithLimit

func WithLimit(limit int) QueryOption

WithLimit sets the maximum number of records to return.

func WithOffset

func WithOffset(offset int) QueryOption

WithOffset sets the number of records to skip before returning results.

func WithOrderBy

func WithOrderBy(field string, desc bool) QueryOption

WithOrderBy adds an ordering clause to the query. The desc parameter determines if the order is descending (true) or ascending (false).

Example:

states, err := repo.FindAll(ctx, WithOrderBy("name", false)) // ORDER BY name ASC
cities, err := repo.FindAll(ctx, WithOrderBy("created_at", true)) // ORDER BY created_at DESC

func WithPreload

func WithPreload(association string, args ...any) QueryOption

WithPreload eagerly loads the specified association. Multiple WithPreload options can be chained to load multiple associations.

Example:

cities, err := repo.FindAll(ctx, WithPreload("State"), WithPreload("Neighborhoods"))

func WithSelect

func WithSelect(fields ...string) QueryOption

WithSelect specifies which fields to retrieve. By default, all fields are selected.

Example:

states, err := repo.FindAll(ctx, WithSelect("id", "name"))

type Repository

type Repository[T any, ID ~string] struct {
	// contains filtered or unexported fields
}

Repository provides generic CRUD operations for models. It is doubly generic — over the entity type T and over the entity's typed ID — so per-context repositories inherit fully-typed CRUD without per-entity shim methods. The active database handle is read from ctx via DBFrom, so a repository call made inside Transactor.WithinTx automatically picks up the transaction.

A repository may be configured with a separate read replica (see NewRepositoryWithReadWrite): read methods then target the replica while write methods target the primary. Reads issued inside an active transaction still use the transaction's connection (the primary), preserving read-your-writes consistency. When no replica is configured, reads and writes share one handle.

func NewRepository

func NewRepository[T any, ID ~string](db *gorm.DB) *Repository[T, ID]

NewRepository creates a new generic repository instance bound to db. Reads and writes share the single connection.

func NewRepositoryWithReadWrite added in v0.1.4

func NewRepositoryWithReadWrite[T any, ID ~string](writeDB, readDB *gorm.DB) *Repository[T, ID]

NewRepositoryWithReadWrite creates a repository that routes writes to writeDB and reads to readDB (a read replica). Reads made inside an active transaction still use the transaction's connection, so they observe uncommitted writes. A nil readDB falls back to writeDB, making this equivalent to NewRepository.

func (*Repository[T, ID]) Count

func (r *Repository[T, ID]) Count(ctx context.Context, opts ...QueryOption) (int64, error)

Count returns the number of records matching the query options.

func (*Repository[T, ID]) Create

func (r *Repository[T, ID]) Create(ctx context.Context, entity *T) error

Create inserts a new record into the database.

func (*Repository[T, ID]) DB

func (r *Repository[T, ID]) DB() *gorm.DB

DB returns the bound primary/write database handle. Repositories that need direct GORM access (custom joins, raw SQL) can use this. Prefer DBFrom(ctx, r.DB()) so that an active transaction is picked up.

func (*Repository[T, ID]) Delete

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

Delete soft-deletes a record by its typed ID.

func (*Repository[T, ID]) Exists

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

Exists checks if a record with the given ID exists.

func (*Repository[T, ID]) Find

func (r *Repository[T, ID]) Find(ctx context.Context, id ID, opts ...QueryOption) (*T, error)

Find retrieves a record by its typed UUID. Validates the ID format.

func (*Repository[T, ID]) FindAll

func (r *Repository[T, ID]) FindAll(ctx context.Context, opts ...QueryOption) ([]T, error)

FindAll retrieves all records matching the query options.

func (*Repository[T, ID]) FindOne

func (r *Repository[T, ID]) FindOne(ctx context.Context, opts ...QueryOption) (*T, error)

FindOne retrieves a single record matching the query options.

func (*Repository[T, ID]) HardDelete

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

HardDelete permanently removes a record from the database. Use with caution — this operation is irreversible.

func (*Repository[T, ID]) ReadDB added in v0.1.4

func (r *Repository[T, ID]) ReadDB() *gorm.DB

ReadDB returns the read database handle (the read replica when configured, otherwise the primary). Prefer DBFrom(ctx, r.ReadDB()) so that an active transaction is picked up and observes uncommitted writes.

func (*Repository[T, ID]) Restore

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

Restore un-deletes a soft-deleted record.

func (*Repository[T, ID]) Update

func (r *Repository[T, ID]) Update(ctx context.Context, entity *T) error

Update saves changes to an existing record.

type SimulatedClock added in v0.5.0

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

SimulatedClock is a Clock whose current time can be advanced or repositioned by the caller, making it suitable for deterministic tests of time-dependent behavior such as retries, backoff, scheduling, leases, and expiry. Where FixedClock reports a constant instant, a SimulatedClock lets a test move time forward explicitly without ever touching the wall clock, so elapsed-time paths become reproducible and instantaneous.

A SimulatedClock is safe for concurrent use by multiple goroutines.

func NewSimulatedClock added in v0.5.0

func NewSimulatedClock(t time.Time) *SimulatedClock

NewSimulatedClock returns a SimulatedClock whose current time starts at t.

func (*SimulatedClock) Advance added in v0.5.0

func (c *SimulatedClock) Advance(d time.Duration) time.Time

Advance moves the clock forward by d and returns the resulting current time. Advancing by a non-negative duration never moves the clock backwards; to reposition the clock to an arbitrary earlier or later instant, use Set.

func (*SimulatedClock) Now added in v0.5.0

Now returns the clock's current simulated time. The context is ignored; it is accepted only to satisfy the Clock interface.

func (*SimulatedClock) Set added in v0.5.0

func (c *SimulatedClock) Set(t time.Time)

Set replaces the clock's current time with t, which may be earlier or later than the time it currently reports.

type Sluggable

type Sluggable interface {
	GetSlug() string
}

Sluggable indicates a model has a URL slug field.

type TemporalEdge

type TemporalEdge[ID ~string] struct {
	// ID is the UUID v7 primary key, minted on create when empty.
	ID ID `gorm:"type:uuid;primaryKey" json:"id"`

	// ValidFrom is the real-world start of the relationship. It is never
	// auto-defaulted — a zero value signals a writer defect.
	ValidFrom time.Time `json:"valid_from"`

	// ValidTo is the real-world end; nil means the edge is still active.
	ValidTo *time.Time `json:"valid_to,omitempty"`

	// RecordedAt is the system time the edge was written; auto-defaulted to
	// the context clock's now when zero.
	RecordedAt time.Time `json:"recorded_at"`

	// EventTime is the source-asserted real-world event time; nil when the
	// source publishes none.
	EventTime *time.Time `json:"event_time,omitempty"`

	// SupersededByID points to the row that replaces this one: a correction
	// (SupersedeEdge) or a closed copy that records the edge's end (EndEdge,
	// EndEdgeAt, EndEdgeAtWith).
	SupersededByID *ID `gorm:"type:uuid" json:"superseded_by_id,omitempty"`

	// SuppressedAt is set by SuppressEdge when the edge is taken down.
	SuppressedAt *time.Time `json:"suppressed_at,omitempty"`

	// Source is the human-readable adapter/source name.
	Source string `json:"source"`

	// ByteHash is the SHA-256 of what the edge derives from: the source bytes
	// (or byte range) for a fetched fact, or the normalized value for one
	// entered or proven first-hand. It may be empty when a hash would reveal
	// the value.
	ByteHash string `json:"byte_hash"`

	// RuleVersion is the version of the derivation rule that produced the edge.
	RuleVersion string `json:"rule_version"`

	// PipelineVersionHash is sha256(adapter_version‖rule_version‖fixture_version).
	PipelineVersionHash string `json:"pipeline_version_hash"`

	// Confidence is the source-published confidence; nil means not set, which
	// is distinct from a real 0.0 confidence.
	Confidence *float64 `json:"confidence,omitempty"`

	// VerificationStatus defaults to VerificationStatusUnverified when written
	// empty.
	VerificationStatus string `json:"verification_status"`

	// CreatedAt is the row insert time; equals RecordedAt unless backdated by
	// replay tooling. Auto-defaulted to the context clock's now when zero.
	CreatedAt time.Time `json:"created_at"`
}

TemporalEdge is the substrate for time-bounded relationships. Embed the typed form in any edge model (ownership, lien, mailing intent, communication, agent decision). It carries real-world validity, system time, source event time, append-only correction fields, and inline provenance.

TemporalEdge is generic over its own ID type so each edge model gets a distinct typed ID and a typed SupersededByID self-reference:

type PartyPhone struct {
    models.TemporalEdge[PartyPhoneID]
    PersonID people.PersonID
    PhoneID  PhoneID
}

TemporalEdge does NOT embed BaseModel — entities and relationships are independent substrates. Corrections are append-only (SupersededByID, SuppressedAt), so it has no soft-delete and no metadata blob.

Change an edge's lifecycle only with the lifecycle helpers (SupersedeEdge, EndEdge, EndEdgeAt, EndEdgeAtWith, SuppressEdge, and, after an edge has ended, SupersedeCurrentEdge and SuppressCurrentEdge), never by updating its columns.

func (*TemporalEdge[ID]) BeforeCreate

func (e *TemporalEdge[ID]) BeforeCreate(tx *gorm.DB) error

BeforeCreate is the GORM hook that mints the ID and applies defaults. An explicitly-set ID, RecordedAt, or CreatedAt is preserved so replay tooling can supply its own. ValidFrom is never defaulted.

func (*TemporalEdge[ID]) Edge added in v0.9.0

func (e *TemporalEdge[ID]) Edge() *TemporalEdge[ID]

Edge returns e. A model that embeds TemporalEdge inherits it, which lets the generic lifecycle helpers reach the edge fields of any such model.

type Transactor

type Transactor interface {
	WithinTx(ctx context.Context, fn func(ctx context.Context) error) error
}

Transactor runs fn inside a database transaction. The ctx passed to fn carries the transaction handle, which Repository.* methods read via DBFrom. Nested calls to WithinTx use GORM savepoints, so services can compose without coordinating who owns the outer transaction.

func NewTransactor

func NewTransactor(db *gorm.DB) Transactor

NewTransactor returns a Transactor backed by the given write database. When the ctx passed to WithinTx already carries a transaction, GORM creates a savepoint instead of starting a new top-level transaction.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError wraps ErrValidation with a specific message.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error returns the formatted validation error message.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the underlying sentinel error for errors.Is() support.

Jump to

Keyboard shortcuts

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