Skip to content

Pagination ​

Introduction ​

Listing records a page at a time is one of the most common database tasks. @plinthjs/database offers three styles, each returning a small paginator object you can inspect or send straight back as JSON:

  • paginate() counts the whole result set, so it can tell you the total and the last page. Use it when you show page numbers.
  • simplePaginate() never counts. It only knows whether another page follows. Use it for "Previous / Next" links on large tables.
  • cursorPaginate() pages by position instead of by offset. It is stable while rows are inserted or deleted and stays fast on deep pages. Use it for feeds and infinite scroll.

The examples assume this setup:

ts
import { sqliteConnection, paginate, simplePaginate } from '@plinthjs/database'

const db = sqliteConnection()
await db.statement('create table posts (id integer primary key, title text, score integer)')
await db
  .table('posts')
  .insert(Array.from({ length: 7 }, (_, i) => ({ title: `P${i + 1}`, score: i % 3 })))

Paginating with page numbers ​

paginate(query, page = 1, perPage = 15) takes a query builder and returns a LengthAwarePaginator. It runs one count and one windowed select, each against a clone of your query, so the query you pass in is untouched. A query with groupBy() is counted by group (through a wrapping subquery), so total() is the number of groups.

ts
const page = await paginate(db.table('posts').orderBy('id'), 2, 3)

page.items() // => rows 4, 5 and 6
page.total() // => 7
page.perPage() // => 3
page.currentPage() // => 2
page.lastPage() // => 3
page.hasMorePages() // => true
page.onFirstPage() // => false
page.firstItem() // => 4 (1-based position of the first row on this page)
page.lastItem() // => 6

lastPage() is never below 1, and firstItem() and lastItem() are null when the page has no rows.

Always add an orderBy() so the pages are consistent between requests. Constraints, joins and ordering you put on the query are all respected.

The JSON shape ​

A paginator has a toJSON() method, so JSON.stringify(page) (and returning it from a controller as JSON) produces:

json
{
  "data": [
    { "id": 4, "title": "P4", "score": 0 },
    { "id": 5, "title": "P5", "score": 1 },
    { "id": 6, "title": "P6", "score": 2 }
  ],
  "total": 7,
  "per_page": 3,
  "current_page": 2,
  "last_page": 3,
  "from": 4,
  "to": 6,
  "path": null,
  "first_page_url": null,
  "last_page_url": null,
  "next_page_url": null,
  "prev_page_url": null
}

For an empty result you get data: [], total: 0, last_page: 1, and from and to of null. The URL keys are null until you give the paginator a path; see below.

Page URLs ​

Pass path, pageName and query as a fourth argument (options) to fill the URL keys and use the URL helpers:

ts
const page = await paginate(db.table('posts').orderBy('id'), 2, 3, {
  path: '/posts', // the base path or absolute URL
  pageName: 'page', // the query parameter that carries the page number (the default)
  query: { sort: 'new' }, // kept on every link; undefined and null values are dropped
})

page.url(3) // => '/posts?sort=new&page=3'
page.nextPageUrl() // => '/posts?sort=new&page=3'
page.previousPageUrl() // => '/posts?sort=new&page=1'
page.path() // => '/posts'
page.links() // => [{ url, label: 'Previous', page: 1, active: false }, { label: '1', ... }, ..., { label: 'Next', ... }]

links() returns the entries to render a pager: a previous arrow, the page numbers (the first, the last and a window around the current page, with '...' gaps that have a null url) and a next arrow. Every helper returns null without a path, and nextPageUrl() and previousPageUrl() return null at the ends. toJSON() then includes path, first_page_url, last_page_url, next_page_url and prev_page_url. simplePaginate() accepts the same options and offers url(), nextPageUrl(), previousPageUrl(), path() and a two-entry links(); its JSON gains path, first_page_url, next_page_url and prev_page_url.

Simple pagination ​

simplePaginate(query, page = 1, perPage = 15, options) skips the count(). It asks for one row more than a page holds, uses the extra row to learn whether another page exists, and trims it off. That makes it cheaper on big tables, at the cost of not knowing the total.

ts
const page = await simplePaginate(db.table('posts').orderBy('id'), 3, 3)

page.items() // => [{ id: 7, ... }]
page.hasMorePages() // => false
page.onFirstPage() // => false
page.currentPage() // => 3
page.perPage() // => 3

JSON.stringify(page)
// => {"data":[{"id":7,"title":"P7","score":0}],"per_page":3,"current_page":3,
//     "path":null,"first_page_url":null,"next_page_url":null,"prev_page_url":null}

Cursor pagination ​

cursorPaginate(perPage = 15, cursor?) is a method on the query builder. Instead of an offset it uses the values of the ordering columns of the last row you returned, so the next page is "everything after that row". The query needs at least one column-based orderBy(); without one it throws.

ts
const first = await db.table('posts').orderBy('id').cursorPaginate(3)

first.items() // => rows 1, 2 and 3
first.hasMorePages() // => true
first.nextCursor() // => a Cursor
first.previousCursor() // => null (this is the first page)

nextCursor() and previousCursor() return Cursor objects. Call encode() to get an opaque, URL-safe string that you can put in a query string, and pass that string (or the Cursor itself) back as the second argument to fetch the next page.

ts
const token = first.nextCursor()!.encode() // => 'eyJpZCI6MywiX3BvaW50c1RvTmV4dEl0ZW1zIjp0cnVlfQ'

const second = await db.table('posts').orderBy('id').cursorPaginate(3, token)
second.items() // => rows 4, 5 and 6

const third = await db.table('posts').orderBy('id').cursorPaginate(3, second.nextCursor())
third.items() // => row 7
third.hasMorePages() // => false
third.nextCursor() // => null

To go backwards, pass previousCursor() the same way. The page comes back in its natural order:

ts
const back = await db.table('posts').orderBy('id').cursorPaginate(3, third.previousCursor())
back.items() // => rows 4, 5 and 6

Cursor pagination works with several ordering columns. Include a unique column such as id last so that rows with equal values keep a stable order:

ts
const page = await db.table('posts').orderBy('score').orderBy('id').cursorPaginate(3)
page.items().map((row) => row.id) // => [1, 4, 7]

Pass null, undefined or an empty string for the first page. A cursor string that cannot be decoded (tampered with, truncated) throws an InvalidCursorError instead of quietly returning the first page, so catch it where you read the request and answer with a 400. Cursor.decode(token) does the same decoding and throws; Cursor.fromEncoded(token) returns null for an invalid string if you prefer to handle that yourself.

The JSON shape ​

json
{
  "data": [{ "id": 4, "title": "P4", "score": 0 }],
  "per_page": 3,
  "next_cursor": "eyJpZCI6NiwiX3BvaW50c1RvTmV4dEl0ZW1zIjp0cnVlfQ",
  "prev_cursor": "eyJpZCI6NCwiX3BvaW50c1RvTmV4dEl0ZW1zIjpmYWxzZX0"
}

There are no page numbers or totals; clients just follow next_cursor and prev_cursor. A cursor is null when there is no page in that direction.

WARNING

A cursor encodes the values of the ordering columns as readable base64 JSON. It is opaque to clients but not secret or signed, so do not rely on it to hide data.

Choosing between them ​

MethodCounts rowsJump to a pageStable under insertsCost on deep pages
paginate()yesyesnogrows with offset
simplePaginate()noyesnogrows with offset
cursorPaginate()nonoyesconstant

Paginating a request ​

The paginators do not read the request for you; you pass the page number and size in. A typical handler reads them from the query string, clamps them, and returns the paginator as JSON:

ts
const page = Math.max(1, Number(request.query('page') ?? 1))
const perPage = Math.min(100, Number(request.query('per_page') ?? 15))

const posts = await paginate(db.table('posts').orderBy('id'), page, perPage)
return Response.json(posts.toJSON())

See Requests and Responses for reading input and returning JSON.

Paginating models ​

paginate() and simplePaginate() here return plain rows. With the ORM, the model and its builders have their own paginate(page, perPage, options) and simplePaginate(...) that return paginators of model instances (scopes, soft deletes and eager loads applied): User.where('active', true).orderBy('id').paginate(2, 15, { path: '/users' }). See ORM Getting Started.

Gotchas ​

  • paginate() and simplePaginate() are standalone functions that take a query builder. Only cursorPaginate() is a builder method.
  • The paginators only know your path; they do not read the request. Pass the current path (and the query parameters to keep) in options when you want links.
  • Cursor pagination on a column that can be null or that is not unique may skip or repeat rows. Order by a unique column last.

Released under the MIT License.