---
url: /runcobo/guide/pagination.md
description: >-
  Turn page and per_page input into safe offsets and limits with
  Runcobo::Pagination.
---

# Pagination

`Runcobo::Pagination` turns a page number and page size into a safe offset and limit. Combine it with a contract for the input and a query that takes `LIMIT` and `OFFSET`:

```sql [db/queries/posts.sql]
-- name: ListPostsPage :many
SELECT id, author_id, title, status FROM posts
ORDER BY id DESC
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
```

```crystal
class PageContract < RequestValidation::Contract
  schema do
    optional :page, Int32
    optional :per_page, Int32
  end
end

class Posts::ListPosts < Blog::BaseAction
  get "/posts"

  call do
    input = validate(PageContract)
    pagination = Runcobo::Pagination.new(input.page, input.per_page)
    posts = store.list_posts_page(row_limit: pagination.per_page, row_offset: pagination.offset.to_i32)
    render_json({
      page:     pagination.page,
      per_page: pagination.per_page,
      posts:    posts.map { |post| {id: post.id, title: post.title} },
    })
  end
end
```

`pagination.offset` is an `Int64`; the generated method takes an `Int32` here, hence `.to_i32`.

## Normalization

Out-of-range values are clamped instead of raising, so a hand-edited URL can't produce a negative offset or an unbounded page:

| Input `page`, `per_page` | `page` | `per_page` | `offset` |
| --- | --- | --- | --- |
| `nil`, `nil` | 1 | 20 | 0 |
| `3`, `10` | 3 | 10 | 20 |
| `0`, `10` | 1 | 10 | 0 |
| `2`, `500` | 2 | 100 | 100 |
| `1`, `0` or negative | 1 | 20 | 0 |

Change the defaults with `default_per_page:` and `max_per_page:`:

```crystal
Runcobo::Pagination.new(input.page, input.per_page, default_per_page: 50, max_per_page: 200)
```

## In-memory lists

`slice` returns the current page of an array:

```crystal
pagination = Runcobo::Pagination.new(2, 10)
pagination.slice((1..35).to_a)   # => [11, 12, ..., 20]
```

::: tip Validate or clamp?
`Pagination` clamps silently. If you'd rather reject bad input with a `422`, add constraints to the contract, e.g. `optional :per_page, Int32, gteq: 1, lteq: 100`.
:::
