gormx

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package gormx translates database errors into the application's error vocabulary, and provides the query scopes every repository needs.

The translation is the valuable half. A driver error reaching a handler has two failure modes, and both are real: it is rendered as a 500 when it was actually a duplicate name the user can fix, and its text — containing the constraint name, the table and sometimes the value — is sent to the client.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply(db *gorm.DB, scopes ...Scope) *gorm.DB

Apply runs scopes against a query.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is GORM's not-found.

func Translate

func Translate(err error, entity string) error

Translate maps a database error to an *errs.Error, with the original kept as the cause so the log still has everything.

entity names the thing being operated on, for the message: "product", not "ProductModel" and not "catalog_products".

Types

type Scope

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

Scope is a composable query fragment.

func ForUpdate

func ForUpdate() Scope

ForUpdate takes a row lock for the rest of the transaction.

Use it for read-modify-write on a counter, a quota or an allocation. The alternative — read, decide, write — is a lost update under any concurrency at all, and the window is wide enough to hit in practice.

func Order

func Order(clause string) Scope

Order sorts by a column YOU name in code. Not for request input.

func Paginate

func Paginate(q pagination.Query) Scope

Paginate applies LIMIT, OFFSET and ORDER BY from a parsed page request.

The ORDER BY is only safe because pagination.Query.Sort is restricted to an allow-list at parse time. Never hand this a sort key straight off a request.

func Preload

func Preload(assoc string, args ...any) Scope

Preload eager-loads an association.

Reach for it whenever a list handler reads an association per row. That pattern — the N+1 — is the single most common performance defect in this kind of service, and it never shows up in development, where the list has four rows.

func Where

func Where(query any, args ...any) Scope

Where is a plain condition as a scope.

Jump to

Keyboard shortcuts

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