keyset

package
v0.23.0-beta.6 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0, BSD-3-Clause, MIT Imports: 19 Imported by: 0

Documentation

Overview

Package keyset is the keyset pager of Nanostack DB (ADR 0001, ADR 0027).

A Key reads one ordering column from a scanned row and compares that column with a cursor value. An Order is a total ordering: the requested sort keys, then a unique tiebreak. Order.Seek turns a cursor into the predicate for the rows after it, Order.Trim cuts a page fetched with LIMIT limit+1 and gives the next cursor, and Page runs the count and the page through db/query.

The package takes the executor as a parameter (query.Executor). It never reads a transaction from a context: the caller resolves it.

Page runs on PostgreSQL, MySQL, MariaDB and SQLite with one contract: the same rows, every walk complete (no row skipped, no row repeated), and the same cursor tokens. Order and matching follow the column's collation. Page reads the dialect from its source and writes that dialect's SQL:

  • NULLs sort last when ascending and first when descending, unless a key asks for NullsFirst or NullsLast. MySQL and SQLite get an explicit placement only for a nullable key whose placement differs from their default, so a NOT NULL key stays a plain "col ASC" that an index serves.
  • The seek is a row value on PostgreSQL and SQLite when every key is NOT NULL and has one direction, and no key is an enum on SQLite (SQLite orders an enum through a CASE). The seek is the expanded form otherwise. MySQL always gets the expanded form: it does not range-scan a row value.
  • Each codec refuses a cursor value that the dialect's column cannot hold with search.ErrInvalidCursor, before any statement runs. A key whose column type the dialect lacks is ErrDialect.
  • A key must match how the column stores and compares its values: see LocalTimeKey for SQLite time text, and EnumKey for collations. A page that ends on its own cursor row is ErrNoProgress, never a page that a client would follow without end.

Order.Seek and Order.OrderBy write PostgreSQL SQL, for a db/postgres statement that does not fit Page.

A cursor is position, not authority: see db/search.Cursor.

Computed keys

A computed key (IntExprKey, FloatExprKey, TimeExprKey, StringExprKey and their Nullable forms) orders on an expression, not on a column: for example a correlated count of a widget's requests, or the time of its last request.

The first argument is the key's name: its name in the cursor signature and its select alias. It must be a row.field alias that matches ^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$, for example "widget_row.request_count" for the RequestCount field of a WidgetRow, or the constructor panics. The scan maps only this form to a field. The name must not be the name of another key of the search (OrderOf returns an error) or the alias of a selected column (Page returns an error).

Page selects each computed key of the order AS its name (Order.Projections), so the scan fills the field that the next cursor reads. To fill the field on every order, put Key.Projection in the columns of the page: Page does not select it twice. A hand-written query that uses Order.OrderBy or Order.Seek selects Order.Projections itself. Select a computed value only through Key.Projection or Order.Projections, never with your own AS.

An expression can be NULL even when it reads only NOT NULL columns: a scalar subquery that finds no row, such as the MAX of a widget with no requests. A non-nullable form reads NULL as the zero value of its type (0, the zero time.Time, the empty string): it wraps the expression in COALESCE, so the order, the seek and the field always agree. Use the Nullable form (with a pointer field) when NULL must sort apart from the zero value.

The integer, float and time forms cast the expression to the SQL type of their cursor value, so the order, the seek and the select share one type and the scan always fits the field. The statement's dialect selects the cast when it is serialized:

           integer   float             time
PostgreSQL bigint    double precision  timestamp with time zone
MySQL      SIGNED    DOUBLE            (ErrDialect)
SQLite     INTEGER   REAL              (ErrDialect)

PostgreSQL drops a cast to the type the expression already has. The text forms do not cast: a cast to text would change the order of a citext or collated expression. The time forms are PostgreSQL only, as TimeKey is: MySQL and SQLite have no timestamp with time zone, so a page with a time computed key and a source of another dialect is ErrDialect.

The expression is SQL of the page's dialect: build a subquery with the SELECT of the dialect package of the page's source.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDialect reports a source that is not a table or join of db/postgres,
	// db/mysql or db/sqlite, or a key whose column type the source's dialect
	// lacks (TimeKey and InetKey off PostgreSQL, MySQLTimestampKey and
	// MariaDBTimestampKey off MySQL, RealKey on SQLite, a computed key off
	// PostgreSQL). Page reports it before any statement runs. It is a
	// programming error, not a client error.
	ErrDialect = errors.New("keyset: the dialect does not support this source or key")

	// ErrNoProgress reports a page after a cursor whose last row is the cursor
	// row: the seek matched the row it starts after, and the next cursor would
	// repeat the page without end. The key does not match how the column
	// stores or compares its values (for example a SQLite time written in
	// another text form). Run returns it in place of the page. It is a
	// programming or data error, not a client error. It does not see a cycle
	// longer than one page, nor a skipped row.
	ErrNoProgress = errors.New("keyset: the page ends on its own cursor row")

	// ErrPageSourceMissing reports a page that runs without From.
	ErrPageSourceMissing = errors.New("keyset: paginated query has no FROM")

	// ErrPageOrderConflict reports a page that has both OrderBy and Keyset: a
	// keyset owns the whole ordering.
	ErrPageOrderConflict = errors.New("keyset: paginated query has both OrderBy and Keyset")
)

Functions

This section is empty.

Types

type Key

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

Key is one column of a keyset ordering over scanned rows of T: the column or computed expression to order and compare on, and how to read its value from a row.

Build keys with the typed constructors (StringKey, UUIDKey, InetKey, EnumKey, TimeKey, LocalTimeKey, MySQLTimestampKey, MariaDBTimestampKey, IntKey, FloatKey, RealKey, the computed keys IntExprKey, FloatExprKey, TimeExprKey and StringExprKey, and their Nullable forms) so the cursor value and the SQL literal share one type. A constructor refuses a cursor value its column cannot hold with search.ErrInvalidCursor, before any query runs. What a column can hold depends on the dialect, so the check runs when Page knows the dialect of its source.

A key takes the column of any dialect package: the column types of db/postgres, db/mysql and db/sqlite are the same types.

func EnumKey

func EnumKey[T any](column jet.ColumnString, enumType string, labels []string, value func(T) string) Key[T]

EnumKey orders on a NOT NULL enum column, in the declaration order of its labels. labels lists them in that order: a cursor that carries any other value is refused before the database sees it.

On PostgreSQL the cursor value is cast to enumType, the enum's SQL type name, because PostgreSQL orders an enum by declaration order and refuses to compare it with text. enumType is written into the SQL as raw text, so it must match ^[a-z_][a-z0-9_.]*$ (for example "order_status" or "public.order_status"). EnumKey panics otherwise.

On MySQL and MariaDB, ORDER BY uses the ENUM column itself, which sorts by the label's index, so labels must be the column's labels in the order of its definition. The seek is an IN list of the labels after the cursor's label, because MySQL compares an ENUM with a string as text. The empty string, the value MySQL stores for an invalid label (index 0), sorts before every label and is a valid cursor value.

On SQLite the column is text. ORDER BY maps each label to its position with a CASE, and the seek is the same IN list as on MySQL. Both compare the bytes (as BLOB), whatever the column's collation, so a value matches a label only when it is exactly that label. On a NOCASE column, 'ACTIVE' is not the label "active". A value that is not a label sorts before every label, as on MySQL, and all such values tie. The seek is never a row value, because the column's own order is text order.

A text column that holds enum-like values and sorts as text is a StringKey.

func FloatExprKey

func FloatExprKey[T any](name string, expression jet.FloatExpression, value func(T) float64) Key[T]

FloatExprKey orders on a double precision expression. It reads NULL as 0. See IntExprKey.

func FloatKey

func FloatKey[T any](column jet.ColumnFloat, value func(T) float64) Key[T]

FloatKey orders on a NOT NULL double precision column. It does not fit numeric or decimal, where float64 rounding would repeat a row forever, nor real (MySQL FLOAT), which takes RealKey.

NaN and the infinities round-trip exactly on PostgreSQL, which orders them above every number. MySQL's DOUBLE holds none of them, and SQLite stores NaN as NULL, so a cursor that carries one is refused there with search.ErrInvalidCursor.

func InetKey

func InetKey[T any](column jet.ColumnString, value func(T) string) Key[T]

InetKey orders on a NOT NULL PostgreSQL inet column, read as its text form. PostgreSQL refuses to compare inet with text, so the cursor value is cast to inet. A value that is not an address or a network, or an address with an IPv6 zone (fe80::1%eth0), which inet cannot hold, is refused before the cast. MySQL and SQLite have no inet type: Page returns ErrDialect.

func IntExprKey

func IntExprKey[T any](name string, expression jet.IntegerExpression, value func(T) int64) Key[T]

IntExprKey orders on an integer expression, for example a correlated COUNT of a row's children. It reads NULL as 0 (see the package doc, Computed keys).

func IntKey

func IntKey[T any](column jet.ColumnInteger, value func(T) int64) Key[T]

IntKey orders on a NOT NULL integer column.

func LocalTimeKey

func LocalTimeKey[T any](column jet.ColumnTimestamp, value func(T) time.Time) Key[T]

LocalTimeKey orders on a NOT NULL timestamp without time zone: a PostgreSQL timestamp, a MySQL DATETIME, or a SQLite DATETIME column. The value is the wall clock, read as if it were UTC, so the cursor cannot shift it.

On MySQL a cursor value outside the DATETIME range (1000-01-01 to 9999-12-31) is search.ErrInvalidCursor, and the literal is the wall clock as text, so the driver's loc setting cannot shift it. The zero date '0000-00-00 00:00:00', which MySQL stores when sql_mode allows it, reads as time.Time{} with parseTime=true. It sorts before every date, and it is a valid cursor value. A MySQL TIMESTAMP column takes MySQLTimestampKey.

SQLite has no time type: the column holds text and compares as text. By default the literal is the cursor's time in the form in which the driver writes a time.Time, "2006-01-02 15:04:05.999999999-07:00", with a +00:00 offset. So every row must be written through the driver, as a time.Time in UTC. A value that SQL writes (CURRENT_TIMESTAMP, datetime('now'), strftime, a text literal) or another client writes has another text form: a walk then skips the rows that tie with the cursor row, or repeats them without end. A column that SQL fills takes SQLiteLayout with its text form. No layout fits a column that holds both forms. The text sorts in time order for four-digit years only, so a cursor value outside the years 0000 to 9999 is search.ErrInvalidCursor.

func MariaDBTimestampKey

func MariaDBTimestampKey[T any](column jet.ColumnTimestamp, value func(T) time.Time) Key[T]

MariaDBTimestampKey orders on a NOT NULL TIMESTAMP column of MariaDB 11.5 or later on a 64-bit build, which holds 1970-01-01 00:00:01 to 2106-02-07 06:28:15 UTC. It is MySQLTimestampKey with that range.

func MySQLTimestampKey

func MySQLTimestampKey[T any](column jet.ColumnTimestamp, value func(T) time.Time) Key[T]

MySQLTimestampKey orders on a NOT NULL MySQL TIMESTAMP column, or a MariaDB TIMESTAMP before MariaDB 11.5. A cursor value outside the TIMESTAMP range (1970-01-01 00:00:01 to 2038-01-19 03:14:07) is search.ErrInvalidCursor, except the zero date, as in LocalTimeKey. MySQL reads and compares a TIMESTAMP in the session time zone, and the range is checked in UTC, so run the session in UTC: in a zone with daylight saving time, the repeated hour maps two instants to one wall clock, and a walk through it can skip or repeat rows. PostgreSQL and SQLite have no such type: Page returns ErrDialect.

func NullableEnumKey

func NullableEnumKey[T any](column jet.ColumnString, enumType string, labels []string, value func(T) *string) Key[T]

NullableEnumKey orders on a nullable enum column. enumType is checked as in EnumKey.

func NullableFloatExprKey

func NullableFloatExprKey[T any](name string, expression jet.FloatExpression, value func(T) *float64) Key[T]

NullableFloatExprKey orders on a double precision expression that can be NULL, for example an AVG over no rows.

func NullableFloatKey

func NullableFloatKey[T any](column jet.ColumnFloat, value func(T) *float64) Key[T]

NullableFloatKey orders on a nullable double precision column.

func NullableInetKey

func NullableInetKey[T any](column jet.ColumnString, value func(T) *string) Key[T]

NullableInetKey orders on a nullable inet column.

func NullableIntExprKey

func NullableIntExprKey[T any](name string, expression jet.IntegerExpression, value func(T) *int64) Key[T]

NullableIntExprKey orders on an integer expression that can be NULL, with NULLs placed as the key says (NullsFirst, NullsLast). See IntExprKey.

func NullableIntKey

func NullableIntKey[T any](column jet.ColumnInteger, value func(T) *int64) Key[T]

NullableIntKey orders on a nullable integer column.

func NullableLocalTimeKey

func NullableLocalTimeKey[T any](column jet.ColumnTimestamp, value func(T) *time.Time) Key[T]

NullableLocalTimeKey orders on a nullable timestamp without time zone.

func NullableMariaDBTimestampKey

func NullableMariaDBTimestampKey[T any](column jet.ColumnTimestamp, value func(T) *time.Time) Key[T]

NullableMariaDBTimestampKey orders on a nullable MariaDB 11.5 TIMESTAMP column.

func NullableMySQLTimestampKey

func NullableMySQLTimestampKey[T any](column jet.ColumnTimestamp, value func(T) *time.Time) Key[T]

NullableMySQLTimestampKey orders on a nullable MySQL TIMESTAMP column.

func NullableRealKey

func NullableRealKey[T any](column jet.ColumnFloat, value func(T) *float32) Key[T]

NullableRealKey orders on a nullable real column.

func NullableStringExprKey

func NullableStringExprKey[T any](name string, expression jet.StringExpression, value func(T) *string) Key[T]

NullableStringExprKey orders on a text expression that can be NULL. See IntExprKey.

func NullableStringKey

func NullableStringKey[T any](column jet.ColumnString, value func(T) *string) Key[T]

NullableStringKey orders on a nullable text column.

func NullableTimeExprKey

func NullableTimeExprKey[T any](
	name string, expression jet.TimestampzExpression, value func(T) *time.Time,
) Key[T]

NullableTimeExprKey orders on a timestamptz expression that can be NULL, for example the MAX of a widget with no requests.

func NullableTimeKey

func NullableTimeKey[T any](column jet.ColumnTimestampz, value func(T) *time.Time) Key[T]

NullableTimeKey orders on a nullable timestamptz column.

func NullableUUIDKey

func NullableUUIDKey[T any](column jet.ColumnString, value func(T) *uuid.UUID) Key[T]

NullableUUIDKey orders on a nullable uuid column.

func RealKey

func RealKey[T any](column jet.ColumnFloat, value func(T) float32) Key[T]

RealKey orders on a NOT NULL single-precision column: a PostgreSQL real or a MySQL FLOAT. A real compared with a double literal is promoted, and 0.1 stored as real is not 0.1 as double, so the boundary row would match itself and repeat. The key compares as real: with a cast on PostgreSQL, and with the float64 of the float32 value on MySQL, which equals the promoted column value. It refuses a finite cursor value outside real's range with ErrInvalidCursor: the conversion to float32 would turn it into an infinity, and the page would jump to the end. NaN and the infinities follow FloatKey's rules per dialect.

SQLite REAL is a double, which a float32 cursor cannot hold exactly: Page returns ErrDialect there. Use FloatKey on SQLite.

func StringExprKey

func StringExprKey[T any](name string, expression jet.StringExpression, value func(T) string) Key[T]

StringExprKey orders on a text expression. It reads NULL as the empty string. See IntExprKey.

func StringKey

func StringKey[T any](column jet.ColumnString, value func(T) string) Key[T]

StringKey orders on a NOT NULL text column. The order and the matching follow the column's collation.

func TimeExprKey

func TimeExprKey[T any](name string, expression jet.TimestampzExpression, value func(T) time.Time) Key[T]

TimeExprKey orders on a timestamptz expression. It reads NULL as the zero time.Time (0001-01-01 UTC). See IntExprKey.

It is PostgreSQL only, as TimeKey is: MySQL and SQLite have no timestamp with time zone, so Page returns ErrDialect there.

func TimeKey

func TimeKey[T any](column jet.ColumnTimestampz, value func(T) time.Time) Key[T]

TimeKey orders on a NOT NULL PostgreSQL timestamptz column. MySQL and SQLite have no such type (their generated models map timestamp and datetime columns to a timestamp without time zone): Page returns ErrDialect there. Use LocalTimeKey or MySQLTimestampKey.

func UUIDKey

func UUIDKey[T any](column jet.ColumnString, value func(T) uuid.UUID) Key[T]

UUIDKey orders on a NOT NULL uuid column. A cursor value that does not parse as a UUID is refused before the database sees it.

On PostgreSQL the column is a uuid and the literal is cast to uuid. On MySQL (CHAR(36)) and SQLite (TEXT) the column holds the lower-case canonical text form, which sorts as the uuid does, and the literal is that text.

func (Key[T]) NullsFirst

func (k Key[T]) NullsFirst() Key[T]

NullsFirst returns the key with NULLs sorted before every value, in both directions. Use it when the API promises a placement that must not flip with the direction. PostgreSQL needs a matching index (... NULLS FIRST) to serve it without a sort.

func (Key[T]) NullsLast

func (k Key[T]) NullsLast() Key[T]

NullsLast returns the key with NULLs sorted after every value, in both directions, for example "unlicensed organizations last".

func (Key[T]) Projection

func (k Key[T]) Projection() jet.Projection

Projection returns the expression of a computed key AS its name, and nil for a column key. Put it in the columns of a page to fill the row field on every order, not only when the order uses the key: Page does not select it twice.

func (Key[T]) SQLiteLayout

func (k Key[T]) SQLiteLayout(layout string) Key[T]

SQLiteLayout returns the key with the SQLite literal written in layout, the Go time layout of the column's stored text. Use "2006-01-02 15:04:05" for a column filled by CURRENT_TIMESTAMP or datetime('now'). Every row of the column must hold exactly that form. A cursor value that the layout cannot write exactly (a fraction that it drops) is search.ErrInvalidCursor on SQLite. The layout must start with "2006-01-02 15:04:05" or "2006-01-02T15:04:05", so that the text sorts in time order.

It applies to LocalTimeKey and NullableLocalTimeKey, and panics on any other key. The layout comes from code, never from a request.

type Order

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

Order is a total keyset ordering over rows of T: the requested sort keys, then a unique tiebreak. The tiebreak is unique, so every row has exactly one position. A cursor (the last row's values) splits the result into the rows before it and the rows after it, with no skip and no repeat, however rows are inserted or deleted between pages.

Build one with OrderOf and give it to PageBuilder.Keyset. A repository whose query does not fit PageBuilder uses OrderBy, Seek and Trim directly.

Seek and OrderBy write PostgreSQL SQL. Use them only in a db/postgres statement. PageBuilder reads the dialect of its source (db/postgres, db/mysql or db/sqlite) and writes that dialect's SQL, so one Order runs on any of them.

func OrderOf

func OrderOf[S ~string, T any](
	sorts []search.Sort[S], keys map[S]Key[T], tiebreak Key[T], more ...Key[T],
) (Order[T], error)

OrderOf builds the keyset ordering of a search: the requested sorts, then the tiebreak keys.

A requested sort absent from keys is search.ErrUnknownSort, naming it: ordering by another column than the client asked answers another question. A search resolves its documented default to a key before it calls OrderOf.

The tiebreak keys together must be unique and NOT NULL within the rows the search can return, normally the primary key. A table with a composite key passes every key column that the search scope does not already fix, for example the member id for a search scoped to one organization, or both columns otherwise. The tiebreak sorts in the direction of the last requested sort (ascending when there is none), so a composite index on (sort, id) serves the query in one scan. A column requested twice keeps its first position, and a tiebreak column that was requested is not repeated.

Two different keys of one name, for example a computed key named after the tiebreak column, are an error, whatever the request sorts on: one would silently replace the other in the order and in the cursor.

func (Order[T]) Cursor

func (o Order[T]) Cursor(row T) (string, error)

Cursor encodes the position of row, the last row of a page.

func (Order[T]) OrderBy

func (o Order[T]) OrderBy() []jet.OrderByClause

OrderBy returns the ORDER BY clauses, tiebreak included, in PostgreSQL SQL: use them only in a db/postgres statement. Page writes the clauses of its source's dialect itself. The PostgreSQL defaults apply to NULLs, unless a key asks for NullsFirst or NullsLast: last when ascending, first when descending. Seek relies on exactly that placement.

func (Order[T]) Projections

func (o Order[T]) Projections() jet.ProjectionList

Projections returns the computed keys of the ordering, each selected AS its name (Key.Projection), so the scan fills the row field that the cursor reads. It is empty when every key is a column. PageBuilder adds them to the page itself. A hand-written query that orders or seeks with this ordering adds them to its select list, and must not select another column with the alias of a computed key.

func (Order[T]) Seek

func (o Order[T]) Seek(cursor string) (jet.BoolExpression, error)

Seek returns the predicate that selects the rows strictly after cursor in this ordering, or nil for an empty cursor. A cursor issued for another ordering, or one that does not decode, is search.ErrInvalidCursor. The predicate is PostgreSQL SQL: use it only in a db/postgres statement. Page writes the seek of its source's dialect itself.

func (Order[T]) Signature

func (o Order[T]) Signature() string

Signature identifies the ordering, for example "widgets.created_at:DESC,widgets.id:DESC". Cursors embed it.

func (Order[T]) Trim

func (o Order[T]) Trim(rows []T, limit int) ([]T, string, error)

Trim cuts rows fetched with LIMIT limit+1 down to one page. When the extra row is present, it returns the cursor of the page's last row. Otherwise the page is the end, and the cursor is empty.

type PageBuilder

type PageBuilder[T, R any] struct {
	// contains filtered or unexported fields
}

PageBuilder runs the count-then-page pair behind a search.Result.

Every paginated search has the same shape: count the matches, take one page of rows in some order, map them, and assemble a search.Result. Only the filter and the sort keys change per entity. PageBuilder owns the rest.

order, err := keyset.OrderOf(input.Sort, map[workspace.SortField]keyset.Key[model.Workspaces]{
	workspace.SortFieldCreatedAt: keyset.TimeKey(table.Workspaces.CreatedAt,
		func(m model.Workspaces) time.Time { return m.CreatedAt }),
}, keyset.StringKey(table.Workspaces.ID, func(m model.Workspaces) string { return m.ID }))
if err != nil {
	return search.Result[workspace.Workspace]{}, err
}
return keyset.Page(db, toDomain, table.Workspaces.AllColumns).
	From(table.Workspaces).
	Where(table.Workspaces.OrganizationID.EQ(jet.String(organizationID))).
	RequireWhere().
	Keyset(order).
	Run(ctx, input.Pagination)

func Page

func Page[T, R any](db query.Executor, mapFunc func(T) R, columns ...jet.Projection) *PageBuilder[T, R]

Page starts a paginated query that returns rows of T mapped to R. db is the executor of both statements: a *sql.DB, a *sql.Tx, or the transaction the caller took from its context. Page never reads a transaction itself.

Both type parameters are inferred from mapFunc. It comes before the columns because they are variadic.

func PageOf

func PageOf[T, R any](
	db query.Executor, mapPage func(context.Context, []T) ([]R, error), columns ...jet.Projection,
) *PageBuilder[T, R]

PageOf is Page with a mapper that reads the whole page at once, for example to load the children of the page's rows in one statement. The mapper gets the rows of the page only, never the extra row that tells whether another page follows. A nil result is an empty page.

func (*PageBuilder[T, R]) From

func (b *PageBuilder[T, R]) From(source Source) *PageBuilder[T, R]

From sets the table or join to select from. It is required.

func (*PageBuilder[T, R]) Keyset

func (b *PageBuilder[T, R]) Keyset(order Order[T]) *PageBuilder[T, R]

Keyset orders the page by a total keyset ordering built with OrderOf, and enables cursor pagination: Run accepts Pagination.Cursor and fills Result.NextCursor.

T must scan one SQL row into one value. Run fetches limit+1 rows and reads the next cursor from the last kept one. So a destination that groups rows (a model with a nested slice of joined children), or a join that repeats a parent, would cut pages short and end the walk early. Page the parent rows flat, then load the children of the page in a second statement (PageOf).

The page selects the computed keys of the ordering (Order.Projections) after the columns of Page, so the scan fills the row fields that the next cursor reads. The count does not select them. To fill a computed field on every order, put Key.Projection in the columns: the page then does not select it twice. Another column with the alias of a computed key is an error, before any statement runs. The time computed keys are PostgreSQL only: on MySQL and SQLite they are ErrDialect.

func (*PageBuilder[T, R]) OrderBy

func (b *PageBuilder[T, R]) OrderBy(clauses ...jet.OrderByClause) *PageBuilder[T, R]

OrderBy appends ordering to an offset page. The count ignores it. A keyset owns the whole ordering, so OrderBy and Keyset together are ErrPageOrderConflict.

func (*PageBuilder[T, R]) RequireWhere

func (b *PageBuilder[T, R]) RequireWhere() *PageBuilder[T, R]

RequireWhere is search mode: Run refuses a nil Where with search.ErrUnscoped, so a search whose scope came out empty can never run as "select everything".

func (*PageBuilder[T, R]) Run

func (b *PageBuilder[T, R]) Run(ctx context.Context, page search.Pagination) (search.Result[R], error)

Run counts the matches and reads one page.

The count runs first. When it is zero, the page query does not run. Total always counts every match of the filter, not the page and not only the rows after a cursor.

With a Keyset, the page starts after Pagination.Cursor when one is given, and NextCursor is set whenever another row follows the page, in offset mode too, so a client can move from offsets to cursors at any page. A cursor with an offset is search.ErrCursorWithOffset, and a cursor that does not belong to this ordering is search.ErrInvalidCursor. Without a Keyset, a cursor is search.ErrInvalidCursor.

A page after a cursor that ends on the cursor row is ErrNoProgress, so a client that follows NextCursor cannot loop on one page.

Run checks the cursor with Pagination.Validate. It does not check the limit: a search checks it with search.CheckPage before it builds the page.

func (*PageBuilder[T, R]) Where

func (b *PageBuilder[T, R]) Where(condition jet.BoolExpression) *PageBuilder[T, R]

Where filters both the count and the page. nil selects everything, unless RequireWhere is set.

type Source

type Source = any

Source is the table or join a page reads: a ReadableTable of db/postgres, db/mysql or db/sqlite. The dialect packages have no common table interface (INNER_JOIN returns a different type in each), so Run resolves Source with a type switch, and writes the SQL of that dialect. Any other value is ErrDialect.

Jump to

Keyboard shortcuts

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