Database: Pagination
Introduction
Returning an entire table in one response is fine for a dozen rows and untenable for a million. A paginator reads the page from the request, fetches only the rows for that page, and builds the links to the surrounding pages. It works on the query builder, models, and search results without extra setup.
dust-framework offers three shapes:
paginatecounts every matching row and returns numbered page links.simple_paginateskips the count and returns previous and next links only.cursor_paginateresumes after the last row you saw, without an offset.
Each paginator serializes to JSON with the page's items under data, so you can return it directly from an API handler. In a view, loop over its links array. In a feed, read next_page_url and request it for the next page.
Basic usage
Choosing a strategy
| Strategy | Counts all rows | Cost of a deep page | Stable while rows are inserted | Links | Best for |
|---|---|---|---|---|---|
paginate |
Yes, with a second query | Scans and discards every skipped row | No, rows can shift between pages | Numbered pages | Admin tables and search results with page numbers |
simple_paginate |
No | Scans and discards every skipped row | No | Previous and next | Large lists that only need "older" and "newer" |
cursor_paginate |
No | Seeks straight to the next row | Yes | Previous and next | Feeds, infinite scroll, and very large tables |
Start with paginate: the page numbers and total are what most interfaces need. Switch to simple_paginate when the count query is the expensive part, and to cursor_paginate when the list is a feed or the table is large.
Paginating query results
To paginate a query, call paginate with the number of items you want per page. dust-framework calculates the limit and offset from the request's page query parameter. Always include an explicit order_by clause so rows stay on consistent pages across requests. For example, this handler returns 15 subscribers per page as JSON:
use dust::db;use dust::pagination::Paginator;use dust::prelude::*;use serde::Serialize;#[derive(db::FromRow, Serialize)]pub struct Subscriber { id: i64, email: String,}pub async fn index() -> dust::Result<Json<Paginator<Subscriber>>> { let subscribers = db::table("subscribers") .order_by("email") .paginate::<Subscriber>(15) .await?; Ok(Json(subscribers))}In addition to returning a Paginator as JSON or passing it to a view, you may inspect the paginator directly in Rust to access the current page's records, totals, and navigation URLs (check out Paginator methods for the full list):
let subscribers = db::table("subscribers").order_by("email").paginate::<Subscriber>(15).await?;for subscriber in subscribers.items() { println!("{}", subscriber.email);}let page = subscribers.current_page();let total = subscribers.total();let next_url = subscribers.next_page_url();Because paginate computes total page counts, it executes a second query to count all matching rows. If your UI only needs "Previous" and "Next" links, use simple_paginate instead. It skips the count query on large tables and returns a SimplePaginator:
let subscribers = db::table("subscribers") .order_by("id") .simple_paginate::<Subscriber>(15) .await?;Paginating models
You may also paginate model queries directly without specifying a row type, because the query is already typed to the model:
use dust::model::model;use dust::pagination::Paginator;use dust::prelude::*;use dust::time::Timestamp;#[model]pub struct Post { pub id: i64, pub title: String, pub published: bool, pub created_at: Timestamp,}pub async fn index() -> dust::Result<Json<Paginator<Post>>> { let posts = Post::query() .filter(Post::published.eq(true)) .order_by(Post::created_at.desc()) .paginate(15) .await?; Ok(Json(posts))}Paginated model queries eager-load any relationships passed to with, like get. If you want to transform each model before returning the paginator, such as into a smaller response struct, call map:
#[derive(Serialize)]pub struct PostSummary { id: i64, title: String,}let posts = Post::query() .order_by(Post::id.desc()) .paginate(15) .await? .map(|post| PostSummary { id: post.id, title: post.title });Cursor pagination
Offset-based pagination (paginate and simple_paginate) skips rows with a SQL OFFSET clause. On deep pages, the database still has to scan and discard every skipped row, and if new records are inserted while a user is paging through results, rows shift downward and may appear twice across adjacent pages.
cursor_paginate avoids both issues by encoding the ordered column values of the last row into an opaque cursor query parameter so the next request resumes directly after that row. It returns a CursorPaginator:
let posts = Post::query() .order_by(Post::created_at.desc()) .order_by(Post::id.desc()) .cursor_paginate(15) .await?;For example, on page 500, paginate forces the database to scan and discard 7,485 rows:
SELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT 15 OFFSET 7485By contrast, cursor_paginate queries directly for rows after the previous page's cursor, taking advantage of an index on the ordered columns. It fetches one extra row to determine whether another page exists:
SELECT * FROM postsWHERE created_at < ? OR (created_at = ? AND id < ?)ORDER BY created_at DESC, id DESCLIMIT 16We recommend cursor pagination for feeds, infinite scroll, and large tables. Because cursor pagination only provides previous and next links, use paginate when your UI requires numbered page links.
Order by a combination of columns that uniquely identifies every row, such as a timestamp followed by the primary key. Model queries without an order_by default to ordering by their primary key. Ordered columns must be non-nullable, and db::table queries must select them so the paginator can construct the cursor from the final row.
Edge cases
Paginators are forgiving with request input:
- A missing
page, a non-number such as?page=abc, or a number below 1 all mean page 1. - A page beyond the last one returns an empty
dataarray withfromandtoset tonull; the surrounding links are still valid, so the user can navigate back. - An empty result set makes a numbered paginator report
total = 0andlast_page = 1, so it still renders one page link. per_pageis at least 1: passing 0 behaves like 1. There is no upper cap, so clamp a page size that comes from the request (for example, to 100) rather than passing it through.
Two rules keep pages consistent:
- Always order by something unique. With
order_by("created_at")alone, rows that share a timestamp can swap between pages. Add the primary key as a tie-breaker:.order_by(Post::created_at.desc()).order_by(Post::id.desc()). - Cursor columns must be non-nullable and selected. A
db::tablecursor query has to select the columns it orders by, because the paginator builds the next cursor from the last row. Nullable columns cannot form a stable cursor.
paginate runs a count query and a page query as two statements, so a write between them can make total disagree with the page you fetched. That is expected without a transaction; the links remain usable.
Paginator methods
Every paginator (Paginator, SimplePaginator, and CursorPaginator) provides these methods:
| Method | Description |
|---|---|
items(), into_items() |
Returns a slice (&[T]) or owned Vec<T> of the items on the current page. |
per_page() |
Returns the number of items per page. |
has_more_pages() |
Returns whether another page follows the current page. |
previous_page_url(), next_page_url() |
Returns the URL for the previous or next page, or None at either end. |
map(f) |
Transforms each item on the current page using the closure f. |
with_query_string(), appends(query), with_path(path) |
Customizes the generated pagination URLs. |
Offset-based paginators (Paginator and SimplePaginator) also provide:
| Method | Description |
|---|---|
current_page() |
Returns the current 1-based page number. |
url(page) |
Generates the URL for a given page number. |
Paginator (returned by paginate) adds methods based on the total row count:
| Method | Description |
|---|---|
total() |
Returns the total number of matching rows across all pages. |
last_page() |
Returns the page number of the final page. |
on_each_side(count) |
Sets how many page links appear on each side of the current page in links. |
CursorPaginator (returned by cursor_paginate) adds cursor helpers:
| Method | Description |
|---|---|
previous_cursor(), next_cursor() |
Returns the encoded cursor for the previous or next page, or None at either end. |
on_first_page() |
Returns whether the current page is the first page. |
Customizing pagination URLs
By default, pagination URLs inherit the current request path and append only the page parameter, such as https://example.com/users?page=2. Other query parameters are omitted, so navigating to page 2 drops active search or sort filters. Call with_query_string to preserve the entire query string:
let users = User::query().order_by(User::name).paginate(15).await?.with_query_string();To preserve only specific parameters, pass them to appends. It accepts key-value pairs such as [("view", "grid")] or a serializable struct such as your query filters, omitting None fields. Using #[dust::query] ensures an invalid bookmark parameter such as ?sort=bogus is ignored instead of failing the page:
use dust::pagination::Paginator;use dust::prelude::*;use serde::Serialize;#[dust::query]#[derive(Serialize)]pub struct Filters { #[validate(max_length(100))] search: Option<String>, #[validate(one_of("name", "newest"))] sort: Option<String>,}pub async fn index(Query(filters): Query<Filters>) -> dust::Result<Json<Paginator<User>>> { let users = User::query() .filter(filters.search.as_ref().map(|term| User::name.contains(term))) .order_by(User::name) .paginate(15) .await? .appends(&filters); Ok(Json(users))}To build page URLs from another path, such as https://example.com/admin/users?page=2, call with_path:
let users = User::query().order_by(User::name).paginate(15).await?.with_path("/admin/users");Multiple paginators per page
When rendering multiple paginated lists on the same page, assign each one a distinct query parameter with page_name, or cursor_name for cursor pagination, and call with_query_string so paginating one list preserves the other's position:
let users = User::query() .order_by(User::name) .paginate(15) .page_name("users") .await? .with_query_string();let posts = Post::query() .order_by(Post::id.desc()) .paginate(15) .page_name("posts") .await? .with_query_string();Fetching a specific page
By default, paginators read the page number or cursor from the request's query string. When the page comes from somewhere else, such as a JSON request body, pass it explicitly with page (or cursor for cursor pagination). Both accept an Option, falling back to the request query string when given None:
use dust::pagination::Paginator;use dust::prelude::*;#[dust::input]pub struct Search { page: Option<u64>,}pub async fn search(Json(search): Json<Search>) -> dust::Result<Json<Paginator<User>>> { let users = User::query().order_by(User::id).paginate(15).page(search.page).await?; Ok(Json(users))}Manually creating a paginator
Sometimes items come from a source outside the query builder, such as raw SQL or an external API. Fetch one page of items yourself, then construct a Paginator from the page's items, total count, page size, and current page. pagination::current_page reads the current page number from the request query string:
use dust::db;use dust::pagination::{self, Paginator};use dust::prelude::*;pub async fn index() -> dust::Result<Json<Paginator<Subscriber>>> { let page = pagination::current_page(); let offset = (page - 1) * 15; let subscribers = db::query!( "SELECT id, email FROM subscribers ORDER BY id LIMIT 15 OFFSET {offset}" ) .select_as::<Subscriber>() .await?; let total = db::query!("SELECT COUNT(*) FROM subscribers") .scalar::<i64>() .await? .unwrap_or(0); Ok(Json(Paginator::new(subscribers, total as u64, 15, page)))}Displaying pagination results
Converting results to JSON
Paginators implement Serialize, encoding items under data alongside pagination metadata and URLs. Return a paginator directly with Json; page 2 of paginate(15) serializes as follows:
{ "current_page": 2, "data": [{ "id": 16, "name": "Taylor" }], "first_page_url": "https://example.com/users?page=1", "from": 16, "last_page": 3, "last_page_url": "https://example.com/users?page=3", "links": [ { "url": "https://example.com/users?page=1", "label": "« Previous", "page": 1, "active": false }, { "url": "https://example.com/users?page=1", "label": "1", "page": 1, "active": false }, { "url": "https://example.com/users?page=2", "label": "2", "page": 2, "active": true }, { "url": "https://example.com/users?page=3", "label": "3", "page": 3, "active": false }, { "url": "https://example.com/users?page=3", "label": "Next »", "page": 3, "active": false } ], "next_page_url": "https://example.com/users?page=3", "path": "https://example.com/users", "per_page": 15, "prev_page_url": "https://example.com/users?page=1", "to": 30, "total": 45}When there are many pages, links includes the first two pages, three pages on each side of the current page, and the last two pages, inserting { "url": null, "label": "...", "active": false } entries for any omitted gaps. Call on_each_side on the paginator to adjust how many pages appear on each side of the current page:
let users = User::query() .order_by(User::name) .paginate(15) .await? .on_each_side(1);For example, on page 10 of 20 with on_each_side(1), the links array produces entries for 1, 2, ..., 9, 10, 11, ..., 19, and 20:
[ { "url": "https://example.com/users?page=9", "label": "« Previous", "page": 9, "active": false }, { "url": "https://example.com/users?page=1", "label": "1", "page": 1, "active": false }, { "url": "https://example.com/users?page=2", "label": "2", "page": 2, "active": false }, { "url": null, "label": "...", "active": false }, { "url": "https://example.com/users?page=9", "label": "9", "page": 9, "active": false }, { "url": "https://example.com/users?page=10", "label": "10", "page": 10, "active": true }, { "url": "https://example.com/users?page=11", "label": "11", "page": 11, "active": false }, { "url": null, "label": "...", "active": false }, { "url": "https://example.com/users?page=19", "label": "19", "page": 19, "active": false }, { "url": "https://example.com/users?page=20", "label": "20", "page": 20, "active": false }, { "url": "https://example.com/users?page=11", "label": "Next »", "page": 11, "active": false }]SimplePaginator omits last_page, last_page_url, links, and total from its JSON output. CursorPaginator serializes data, path, per_page, next_cursor, next_page_url, prev_cursor, and prev_page_url.
Rendering links in views
In a view, pass the paginator in your template data, such as data! { users }, then loop over its links array. Mark each label with the safe filter so the HTML entities in "Previous" and "Next" render properly:
<nav> {% for link in users.links %} {% if link.url %} <a href="{{ link.url }}" {% if link.active %}aria-current="page"{% endif %} >{{ link.label | safe }}</a> {% else %} <span>{{ link.label | safe }}</span> {% endif %} {% endfor %}</nav>When multiple views render pagination links, you can extract this markup into a template macro:
<!-- resources/views/components/pagination.html -->{% macro pagination(paginator) %} <nav> {% for link in paginator.links %} {% if link.url %} <a href="{{ link.url }}" {% if link.active %}aria-current="page"{% endif %} >{{ link.label | safe }}</a> {% else %} <span>{{ link.label | safe }}</span> {% endif %} {% endfor %} </nav>{% endmacro %}Then import and call the macro from any view:
{% from "components.pagination" import pagination %}{{ pagination(users) }}If the page is rendered by a browser-side client instead, return the paginator as JSON and build the navigation from links. Each label contains HTML entities (« and »), so insert it as HTML rather than as plain text.
Infinite scroll
A feed reads better as one growing list than as numbered pages. Pair it with cursor_paginate, so each request resumes exactly after the row the reader last saw, without counting or skipping rows. The endpoint returns the paginator as JSON:
use dust::pagination::CursorPaginator;use dust::prelude::*;use crate::models::Post;pub async fn index() -> dust::Result<Json<CursorPaginator<Post>>> { let posts = Post::query() .order_by(Post::created_at.desc()) .order_by(Post::id.desc()) .cursor_paginate(15) .await?; Ok(Json(posts))}Render the first page in the view and keep its next_page_url on a "Load more" button:
<div id="posts"> {% for post in posts.data %} <article>{{ post.title }}</article> {% endfor %}</div>{% if posts.next_page_url %} <button id="more" data-next="{{ posts.next_page_url }}">Load more</button>{% endif %}The client requests that URL as-is, appends the returned items, and replaces the button's URL with the new next_page_url until there is none:
<script> const button = document.querySelector("#more"); button?.addEventListener("click", async () => { button.disabled = true; const response = await fetch(button.dataset.next, { headers: { Accept: "application/json" }, }); const page = await response.json(); for (const post of page.data) { const article = document.createElement("article"); article.textContent = post.title; document.querySelector("#posts").append(article); } if (page.next_page_url) { button.dataset.next = page.next_page_url; button.disabled = false; } else { button.remove(); } });</script>To load automatically instead of on a click, place an empty element after the list and click the button when an IntersectionObserver sees it:
<div id="sentinel"></div><script> const sentinel = document.querySelector("#sentinel"); new IntersectionObserver(([entry]) => { if (entry.isIntersecting) button?.click(); }).observe(sentinel);</script>Because a cursor page is a stable window rather than a numbered position, a reader who leaves the page open does not see newly inserted posts until they reload. That is usually the right trade-off for a feed; if the interface needs a total and page numbers, use paginate instead.