where

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package where is the query vocabulary of store: filters, ordering, pagination and the query modifiers, each an Option that a store applies to its query. Fields are the model's public (JSON) names; the store maps them to columns and refuses names it does not know.

posts.List(ctx, where.Eq("status", "published"), where.Order("created_at", true), where.Page(1, 20))

An Option receives the *gorm.DB under construction, which is why gorm appears in its signature: this package is where SQL fragments are made.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidParam reports a bad page, size, order or cursor.
	ErrInvalidParam = errors.New("where: invalid parameter")
	// ErrUnknownField reports a field name the store does not know: in a
	// URL, one without store:"query" (a 400); in the code, one that is no
	// column of the model (a 500).
	ErrUnknownField = q.ErrUnknownField
)

Functions

This section is empty.

Types

type Config

type Config struct {
	Count       bool // Count: report the total
	HasFilter   bool // some WHERE condition was applied
	HasPage     bool // Page, Limit, Offset or Cursor was applied
	HasOrder    bool
	Degenerate  bool // a filter can match nothing (In with no values)
	WithTrashed bool // include soft-deleted rows
	OnlyTrashed bool // only soft-deleted rows
	// Version is the optimistic-lock version an Update or Delete must
	// match; 0 means none.
	Version int
	// Preloads are the relations to load with the rows.
	Preloads []string
	// Cursor and CursorSize are a cursor page request for
	// store.ListWithCursor; FirstPage marks the request for page one.
	Cursor     string
	CursorSize int
	FirstPage  bool
	// Orders are the order clauses, in the order given.
	Orders []orderBy
	// FiltersOnly, set by the store for a count, turns Count into a
	// no-op.
	FiltersOnly bool
	// PageNumber is the 1-based page Page asked for (0 for Offset or
	// cursor pagination); Offset and Limit are the rows to skip and take
	// (Limit 0: the store's default). The store renders them.
	PageNumber, Offset, Limit int
	// FromQuery marks the pagination of FromQuery, read from a URL: the
	// store keeps its size within the policy's max page size. The code's
	// own pagination takes the size it names.
	FromQuery bool
}

Config is what the options of one query declared, read by the store that runs them.

type Option

type Option func(tx *gorm.DB, cfg *Config, fields map[string]string) (*gorm.DB, error)

Option is one part of a query.

func Contains added in v0.2.0

func Contains(field, s string) Option

Contains matches field containing s literally.

Example

Contains, StartsWith and EndsWith match their input literally: a user searching for "50%" does not get a wildcard.

package main

import (
	"github.com/zynthara/chok/store/where"
)

func main() {
	_ = []where.Option{
		where.Contains("title", "50%"),          // title LIKE '%50!%%' ESCAPE '!'
		where.Like("sku", "AB-%"),               // the caller's wildcard
		where.In("status", "draft", "archived"), // status IN (...)
		where.Order("created_at", true),         // newest first
		where.Page(1, 20),
	}
}

func Count added in v0.2.0

func Count() Option

Count asks List to report the total matching rows.

func Cursor added in v0.2.0

func Cursor(c string, size int) Option

Cursor asks for the page of size rows after the opaque cursor c, as returned in a previous page's Cursor ("" for the first page). Only store.ListWithCursor honours it.

func EndsWith added in v0.2.0

func EndsWith(field, s string) Option

EndsWith matches field ending with s literally.

func Eq

func Eq(field string, v any) Option

Eq is field = v. A nil v matches nothing; use Null for IS NULL.

func FromQuery

func FromQuery(q url.Values, allowed map[string]string, strict bool) ([]Option, error)

FromQuery turns a list request's query string into options:

page=2&size=20            Page(2, 20); size alone means page 1
order=created_at:desc     Order, also a comma-separated list
cursor=<token>            Cursor (empty for the first page)
status=draft              Eq; a repeated parameter is In

A request is always paged: without page, size or cursor it is page 1 at the store's default size, and the store keeps every size it reads here within its policy's max page size. An empty value filters nothing, as an empty form field means: status= is no filter, not a match on the empty string. allowed maps the fields the caller may filter and order on to their columns. With strict, a parameter that is neither reserved nor allowed is an error; without it, such parameters are ignored. Every error wraps ErrInvalidParam or ErrUnknownField.

Example

A list request's query string becomes options; the allowed map is the store's query fields, so nothing else reaches the SQL.

package main

import (
	"fmt"
	"net/url"

	"github.com/zynthara/chok/store/where"
)

func main() {
	allowed := map[string]string{"status": "status", "created_at": "created_at"}
	q, _ := url.ParseQuery("status=draft&order=created_at:desc&page=2&size=10")
	opts, err := where.FromQuery(q, allowed, true)
	fmt.Println(len(opts), err)

	_, err = where.FromQuery(url.Values{"author": {"bob"}}, allowed, true)
	fmt.Println(err)
}
Output:
3 <nil>
where: unknown field "author": filter on one of created_at, status

func Gt

func Gt(field string, v any) Option

Gt is field > v.

func Gte

func Gte(field string, v any) Option

Gte is field >= v.

func In added in v0.2.0

func In(field string, values ...any) Option

In is field IN (values...). One slice argument is unwrapped; no values match nothing. More than 500 values is an error (ErrInvalidParam): store.ListIn chunks a larger set.

func Like added in v0.2.0

func Like(field, pattern string) Option

Like is field LIKE pattern, with % and _ as the wildcards the caller wrote; Contains, StartsWith and EndsWith match their input literally instead. Case sensitivity is the dialect's: PostgreSQL compares case, MySQL follows the column collation (case-insensitive by default) and SQLite folds ASCII letters.

func Limit added in v0.2.0

func Limit(n int) Option

Limit caps the rows at n.

func Lt

func Lt(field string, v any) Option

Lt is field < v.

func Lte

func Lte(field string, v any) Option

Lte is field <= v.

func Ne

func Ne(field string, v any) Option

Ne is field <> v.

func NotNull added in v0.2.0

func NotNull(field string) Option

NotNull is field IS NOT NULL.

func Null added in v0.2.0

func Null(field string) Option

Null is field IS NULL.

func Offset added in v0.2.0

func Offset(n int) Option

Offset skips n rows.

func OnlyTrashed added in v0.2.0

func OnlyTrashed() Option

OnlyTrashed matches only soft-deleted rows.

func Order added in v0.2.0

func Order(field string, desc ...bool) Option

Order sorts by field, ascending unless desc is true. Several orders apply in the order given; the store renders them, ending with its own tie-break so pages never overlap.

func Page added in v0.2.0

func Page(page, size int) Option

Page asks for 1-based page of size rows; size 0 takes the store's default page size.

func Preload added in v0.2.0

func Preload(relation string) Option

Preload loads relation, a gorm association of the model ("Author", a path such as "Comments.Author", or "*" for every direct association), with the rows. An association whose model has an owner is fenced the way a store of that model would fence it: the caller's rows only.

func StartsWith added in v0.2.0

func StartsWith(field, s string) Option

StartsWith matches field starting with s literally.

func Version added in v0.2.0

func Version(v int) Option

Version makes an Update or Delete apply only while the row is still at version v; otherwise it fails with a version conflict.

func WithTrashed added in v0.2.0

func WithTrashed() Option

WithTrashed includes soft-deleted rows.

Jump to

Keyboard shortcuts

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