rails_cursor_pagination 0.1.3
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/CHANGELOG.md +42 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +380 -0
- data/lib/rails_cursor_pagination.rb +172 -0
- data/lib/rails_cursor_pagination/configuration.rb +30 -0
- data/lib/rails_cursor_pagination/paginator.rb +464 -0
- data/lib/rails_cursor_pagination/version.rb +5 -0
- metadata +71 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: ff75c17ca149149eba59773520bc6690c7f0c5a86066d3783f68314e03a58e8e
|
4
|
+
data.tar.gz: bb0a908d6a7c204da69851ac3bb83dad64d829dc9f0ac955d33c5164231fb0e7
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 5bfc9913cb0232569b0ca322e0b50dbf6a591f79ef7c97baf1dd3fd1850e5875163fa9468d91532a576b4e3bd36126a39ec835f531b6a4d29b308acaebcbaf2b
|
7
|
+
data.tar.gz: 4f4624b26ce65bd8a70f18602931b5d5a2209ce9b912babed5bba534bfffeef06da0fbd287461a4aa5cc58bc18e6217c8ba7232e6fc71ba4ba3f369125514fcb
|
data/CHANGELOG.md
ADDED
@@ -0,0 +1,42 @@
|
|
1
|
+
# Changelog
|
2
|
+
|
3
|
+
All notable changes to this project will be documented in this file.
|
4
|
+
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
6
|
+
|
7
|
+
## [Unreleased]
|
8
|
+
|
9
|
+
These are the latest changes on the project's `master` branch that have not yet been released.
|
10
|
+
|
11
|
+
<!---
|
12
|
+
If you submit a pull request for this gem, please add a summary of your changes here.
|
13
|
+
This will ensure that they're also mentioned in the next release description.
|
14
|
+
Follow the same format as previous releases by categorizing your feature into "Added", "Changed", "Deprecated", "Removed", "Fixed", or "Security".
|
15
|
+
--->
|
16
|
+
|
17
|
+
## [0.1.3] - 2021-03-17
|
18
|
+
|
19
|
+
### Changed
|
20
|
+
- Make the gem publicly available via github.com/xing/rails_cursor_pagination and release it to Rubygems.org
|
21
|
+
- Reference changelog file in the gemspec instead of the general releases Github tab
|
22
|
+
|
23
|
+
### Removed
|
24
|
+
- Remove bulk from release: The previous gem releases contained files like the content of the `bin` folder or the Gemfile used for testing. Since this is not useful for gem users, adjust the gemspec file accordingly.
|
25
|
+
|
26
|
+
## [0.1.2] - 2021-02-04
|
27
|
+
|
28
|
+
### Fixed
|
29
|
+
- Pagination for relations in which a custom `SELECT` does not contain cursor-relevant fields like `:id` or the field specified via `order_by`
|
30
|
+
|
31
|
+
## [0.1.1] - 2021-01-21
|
32
|
+
|
33
|
+
### Added
|
34
|
+
- Add support for handling `nil` for `order` and `order_by` values as if they were not passed
|
35
|
+
|
36
|
+
### Fixed
|
37
|
+
- Pagination for relations that use a custom `SELECT`
|
38
|
+
|
39
|
+
## [0.1.0-pre] - 2021-01-12
|
40
|
+
|
41
|
+
### Add
|
42
|
+
- First version of the gem, including pagination, custom ordering by column and sort-order.
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mail@nicolasfricke.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2020 XING GmbH & Co. KG
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,380 @@
|
|
1
|
+
# RailsCursorPagination
|
2
|
+
|
3
|
+
This library allows to paginate through an `ActiveRecord` relation using cursor pagination.
|
4
|
+
It also supports ordering by any column on the relation in either ascending or descending order.
|
5
|
+
|
6
|
+
Cursor pagination allows to paginate results and gracefully deal with deletions / additions on previous pages.
|
7
|
+
Where a regular limit / offset pagination would jump in results if a record on a previous page gets deleted or added while requesting the next page, cursor pagination just returns the records following the one identified in the request.
|
8
|
+
|
9
|
+
To learn more about cursor pagination, check out the _"How does it work?"_ section below.
|
10
|
+
|
11
|
+
## Installation
|
12
|
+
|
13
|
+
Add this line to your application's Gemfile:
|
14
|
+
|
15
|
+
```ruby
|
16
|
+
gem 'rails_cursor_pagination'
|
17
|
+
```
|
18
|
+
|
19
|
+
And then execute:
|
20
|
+
|
21
|
+
```sh
|
22
|
+
$ bundle install
|
23
|
+
```
|
24
|
+
|
25
|
+
Or install it yourself as:
|
26
|
+
|
27
|
+
```sh
|
28
|
+
$ gem install rails_cursor_pagination
|
29
|
+
```
|
30
|
+
|
31
|
+
## Usage
|
32
|
+
|
33
|
+
Using it is very straight forward by just interfacing with the `RailsCursorPagination::Paginator` class.
|
34
|
+
|
35
|
+
Let's assume we have an `ActiveRecord` model called `Post` of which we want to fetch some data and then paginate through it.
|
36
|
+
Therefore, we first apply our scopes, `where` clauses or other functionality as usual:
|
37
|
+
|
38
|
+
```ruby
|
39
|
+
posts = Post.where(author: 'Jane')
|
40
|
+
```
|
41
|
+
|
42
|
+
And then we pass these posts to our paginator to fetch the first response page:
|
43
|
+
|
44
|
+
```ruby
|
45
|
+
RailsCursorPagination::Paginator.new(posts).fetch(with_total: true)
|
46
|
+
```
|
47
|
+
|
48
|
+
This will return a data structure similar to the following:
|
49
|
+
```
|
50
|
+
{
|
51
|
+
total: 42,
|
52
|
+
page_info: {
|
53
|
+
has_previous_page: false,
|
54
|
+
has_next_page: true,
|
55
|
+
start_cursor: "MQ==",
|
56
|
+
end_cursor: "MTA="
|
57
|
+
},
|
58
|
+
page: [
|
59
|
+
{ cursor: "MQ==", data: #<Post:0x00007fd7071b2ea8 @id=1> },
|
60
|
+
{ cursor: "Mg==", data: #<Post:0x00007fd7071bb738 @id=2> },
|
61
|
+
...,
|
62
|
+
{ cursor: "MTA=", data: #<Post:0x00007fd707238260 @id=10> }
|
63
|
+
]
|
64
|
+
}
|
65
|
+
```
|
66
|
+
|
67
|
+
Note that any ordering of the relation at this stage will be ignored by the gem.
|
68
|
+
Take a look at the next section _"Ordering"_ to see how you can have an order different than ascending IDs.
|
69
|
+
Read the _"The passed relation"_ to learn more about the relation that can be passed to the paginator.
|
70
|
+
|
71
|
+
As you saw in the request, `with_total` is an option.
|
72
|
+
If omitted, or set to `false`, the resulting hash will lack the `:total` key, but this will also cause one DB query less.
|
73
|
+
It is therefore recommended to only pass `with_total: true` when requested by the user.
|
74
|
+
So in the next examples we will also leave it away.
|
75
|
+
|
76
|
+
To then get the next result page, you simply need to pass the last cursor of the returned page item via:
|
77
|
+
|
78
|
+
```ruby
|
79
|
+
RailsCursorPagination::Paginator
|
80
|
+
.new(posts, after: 'MTA=')
|
81
|
+
.fetch
|
82
|
+
```
|
83
|
+
|
84
|
+
This will then fetch the next result page.
|
85
|
+
You can also just as easily paginate to previous pages by using `before` instead of `after` and using the first cursor of the current page.
|
86
|
+
|
87
|
+
```ruby
|
88
|
+
RailsCursorPagination::Paginator
|
89
|
+
.new(posts, before: "MTE=")
|
90
|
+
.fetch
|
91
|
+
```
|
92
|
+
|
93
|
+
By default, this will always return up to 10 results.
|
94
|
+
But you can also specify how many records should be returned.
|
95
|
+
You can pass `first: 2` to get the very first 2 records of the relation:
|
96
|
+
|
97
|
+
```ruby
|
98
|
+
RailsCursorPagination::Paginator
|
99
|
+
.new(posts, first: 2)
|
100
|
+
.fetch
|
101
|
+
```
|
102
|
+
|
103
|
+
Then, you can also combine `first` with `after` to get the first X records after a given one:
|
104
|
+
|
105
|
+
```ruby
|
106
|
+
RailsCursorPagination::Paginator
|
107
|
+
.new(posts, first: 2, after: 'MTA=')
|
108
|
+
.fetch
|
109
|
+
```
|
110
|
+
|
111
|
+
Or you can combine `before` with `last` to get the last X records before a given one:
|
112
|
+
|
113
|
+
```ruby
|
114
|
+
RailsCursorPagination::Paginator
|
115
|
+
.new(posts, last: 2, before: 'MTA=')
|
116
|
+
.fetch
|
117
|
+
```
|
118
|
+
|
119
|
+
### Ordering
|
120
|
+
|
121
|
+
As said, this gem ignores any previous ordering added to the passed relation.
|
122
|
+
But you can still paginate through relations with an order different than by ascending IDs.
|
123
|
+
|
124
|
+
### The `order` parameter
|
125
|
+
|
126
|
+
The first option you can pass is the `order` parameter.
|
127
|
+
It allows you to order the relation in reverse, descending.
|
128
|
+
|
129
|
+
```ruby
|
130
|
+
RailsCursorPagination::Paginator
|
131
|
+
.new(posts, order: :desc)
|
132
|
+
.fetch
|
133
|
+
```
|
134
|
+
|
135
|
+
The default is `:asc`, therefore this doesn't need to be passed.
|
136
|
+
|
137
|
+
### The `order_by` parameter
|
138
|
+
|
139
|
+
However, you can also specify a different column to order the results by.
|
140
|
+
Therefore, the `order_by` parameter needs to be passed.
|
141
|
+
|
142
|
+
```ruby
|
143
|
+
RailsCursorPagination::Paginator
|
144
|
+
.new(posts, order_by: :author)
|
145
|
+
.fetch
|
146
|
+
```
|
147
|
+
|
148
|
+
This will now order the records ascending by the `:author` field.
|
149
|
+
You can also combine the two:
|
150
|
+
|
151
|
+
```ruby
|
152
|
+
RailsCursorPagination::Paginator
|
153
|
+
.new(posts, order_by: :author, order: :desc)
|
154
|
+
.fetch
|
155
|
+
```
|
156
|
+
|
157
|
+
This will then sort the results by the author field in a descending order.
|
158
|
+
Of course, this can both be combined with `first`, `last`, `before`, and `after`.
|
159
|
+
|
160
|
+
**Important:**
|
161
|
+
If your app regularly orders by another column, you might want to add a database index for this.
|
162
|
+
Say that your order column is `author` then your index should be on `CONCAT(author, '-', id)`.
|
163
|
+
|
164
|
+
Please take a look at the _"How does it work?"_ to find out more why this is necessary.
|
165
|
+
|
166
|
+
### Configuration options
|
167
|
+
|
168
|
+
You can also change the default page size to a value that better fits the needs of your application.
|
169
|
+
So if a user doesn't request a given `first` or `last` value, the default amount of records is being returned.
|
170
|
+
|
171
|
+
To change the default, simply add an initializer to your app that does the following:
|
172
|
+
|
173
|
+
```ruby
|
174
|
+
RailsCursorPagination.configure do |config|
|
175
|
+
config.default_page_size = 50
|
176
|
+
end
|
177
|
+
```
|
178
|
+
|
179
|
+
This would set the default page size to 50.
|
180
|
+
|
181
|
+
### The passed relation
|
182
|
+
|
183
|
+
The relation passed to the `RailsCursorPagination::Paginator` needs to be an instance of an `ActiveRecord::Relation`.
|
184
|
+
So if you e.g. have a `Post` model that inherits from `ActiveRecord::Base`, you can initialize your paginator like this:
|
185
|
+
|
186
|
+
```ruby
|
187
|
+
RailsCursorPagination::Paginator
|
188
|
+
.new(Post.all)
|
189
|
+
```
|
190
|
+
|
191
|
+
This would then paginate over all post records in your database.
|
192
|
+
|
193
|
+
#### Limiting the paginated records
|
194
|
+
|
195
|
+
As shown above, you can also apply `.where` clauses to filter your records before pagination:
|
196
|
+
|
197
|
+
```ruby
|
198
|
+
RailsCursorPagination::Paginator
|
199
|
+
.new(Post.where(author: 'Jane'))
|
200
|
+
```
|
201
|
+
|
202
|
+
This would only paginate over Jane's records.
|
203
|
+
|
204
|
+
#### Limiting the queried fields
|
205
|
+
|
206
|
+
You can also use `.select` to limit the fields that are requested from the database.
|
207
|
+
If, for example, your post contains a very big `content` field that you don't want to return on the paginated index endpoint, you can select to only get the fields relevant to you:
|
208
|
+
|
209
|
+
```ruby
|
210
|
+
RailsCursorPagination::Paginator
|
211
|
+
.new(Post.select(:id, :author))
|
212
|
+
```
|
213
|
+
|
214
|
+
One important thing to note is that the ID of the record _will always be returned_, whether you selected it or not.
|
215
|
+
This is due to how the cursor is generated.
|
216
|
+
It requires the record's ID to always be present.
|
217
|
+
Therefore, even if it is not selected by you, it will be added to the query.
|
218
|
+
|
219
|
+
The same goes for any field that is specified via `order_by:`, this field is also required for building the cursor and will therefore automatically be requested from the database.
|
220
|
+
|
221
|
+
## How does it work?
|
222
|
+
|
223
|
+
The _cursor_ that we use for the `before` or `after` query encodes a value that uniquely identifies a given row _for the requested order_.
|
224
|
+
Then, based on this cursor, you can request the _"`n` **first** records **after** the cursor"_ (forward-pagination) or the _"`n` **last** records **before** the cursor"_ (backward-pagination).
|
225
|
+
|
226
|
+
As an example, assume we have a table called "posts" with this data:
|
227
|
+
|
228
|
+
| id | author |
|
229
|
+
|----|--------|
|
230
|
+
| 1 | Jane |
|
231
|
+
| 2 | John |
|
232
|
+
| 3 | John |
|
233
|
+
| 4 | Jane |
|
234
|
+
| 5 | Jane |
|
235
|
+
| 6 | John |
|
236
|
+
| 7 | John |
|
237
|
+
|
238
|
+
Now if we make a basic request without any `first`/`after`, `last`/`before`, custom `order` or `order_by` column, this will just request the first page of this relation.
|
239
|
+
|
240
|
+
```ruby
|
241
|
+
RailsCursorPagination::Paginator
|
242
|
+
.new(relation)
|
243
|
+
.fetch
|
244
|
+
```
|
245
|
+
|
246
|
+
Assume that our default page size here is 2 and we would get a query like this:
|
247
|
+
|
248
|
+
```sql
|
249
|
+
SELECT *
|
250
|
+
FROM "posts"
|
251
|
+
ORDER BY "posts"."id" ASC
|
252
|
+
LIMIT 2
|
253
|
+
```
|
254
|
+
|
255
|
+
This will return the first page of results, containing post #1 and #2.
|
256
|
+
Since no custom order is defined, each item in the returned collection will have a cursor that only encodes the record's ID.
|
257
|
+
|
258
|
+
If we want to now request the next page, we can pass in the cursor of record #2 which would be `"Mg=="`.
|
259
|
+
So now we can request the next page by calling:
|
260
|
+
|
261
|
+
```ruby
|
262
|
+
RailsCursorPagination::Paginator
|
263
|
+
.new(relation, first: 2, after: "Mg==")
|
264
|
+
.fetch
|
265
|
+
```
|
266
|
+
|
267
|
+
And this will decode the given cursor and issue a query like:
|
268
|
+
|
269
|
+
```sql
|
270
|
+
SELECT *
|
271
|
+
FROM "posts"
|
272
|
+
WHERE "posts"."id" > 2
|
273
|
+
ORDER BY "posts"."id" ASC
|
274
|
+
LIMIT 2
|
275
|
+
```
|
276
|
+
|
277
|
+
Which would return posts #3 and #4.
|
278
|
+
If we now want to paginate back, we can request the posts that came before the first post, whose cursor would be `"Mw=="`:
|
279
|
+
|
280
|
+
```ruby
|
281
|
+
RailsCursorPagination::Paginator
|
282
|
+
.new(relation, last: 2, before: "Mw==")
|
283
|
+
.fetch
|
284
|
+
```
|
285
|
+
|
286
|
+
Since we now paginate backward, the resulting SQL query needs to be flipped around to get the last two records that have an ID smaller than the given one:
|
287
|
+
|
288
|
+
```sql
|
289
|
+
SELECT *
|
290
|
+
FROM "posts"
|
291
|
+
WHERE "posts"."id" < 3
|
292
|
+
ORDER BY "posts"."id" DESC
|
293
|
+
LIMIT 2
|
294
|
+
```
|
295
|
+
|
296
|
+
This would return posts #2 and #1.
|
297
|
+
Since we still requested them in ascending order, the result will be reversed before it is returned.
|
298
|
+
|
299
|
+
Now, in case that the user wants to order by a column different than the ID, we require this information in our cursor.
|
300
|
+
Therefore, when requesting the first page like this:
|
301
|
+
|
302
|
+
```ruby
|
303
|
+
RailsCursorPagination::Paginator
|
304
|
+
.new(relation, order_by: :author)
|
305
|
+
.fetch
|
306
|
+
```
|
307
|
+
|
308
|
+
This will issue the following SQL query:
|
309
|
+
|
310
|
+
```sql
|
311
|
+
SELECT *
|
312
|
+
FROM "posts"
|
313
|
+
ORDER BY CONCAT(author, '-', "posts"."id") ASC
|
314
|
+
LIMIT 2
|
315
|
+
```
|
316
|
+
|
317
|
+
As you can see, this will now order by a concatenation of the requested column, a dash `-`, and the ID column.
|
318
|
+
Ordering only the author is not enough since we cannot know if the custom column only has unique values.
|
319
|
+
And we need to guarantee the correct order of ambiguous records independent of the direction of ordering.
|
320
|
+
This unique order is the basis of being able to paginate forward and backward repeatedly and getting the correct records.
|
321
|
+
|
322
|
+
The query will then return records #1 and #4.
|
323
|
+
But the cursor for these records will also be different to the previous query where we ordered by ID only.
|
324
|
+
It is important that the cursor encodes all the data we need to uniquely identify a row and filter based upon it.
|
325
|
+
Therefore, we need to encode the same information as we used for the ordering in our SQL query.
|
326
|
+
Hence, the cursor for pagination with a custom column contains a tuple of data, the first record being the custom order column followed by the record's ID.
|
327
|
+
|
328
|
+
Therefore, the cursor of record #4 will encode `['Jane', 4]`, which yields this cursor: `"WyJKYW5lIiw0XQ=="`.
|
329
|
+
|
330
|
+
If we now want to request the next page via:
|
331
|
+
|
332
|
+
```ruby
|
333
|
+
RailsCursorPagination::Paginator
|
334
|
+
.new(relation, order_by: :author, first: 2, after: "WyJKYW5lIiw0XQ==")
|
335
|
+
.fetch
|
336
|
+
```
|
337
|
+
|
338
|
+
We get this SQL query:
|
339
|
+
|
340
|
+
```sql
|
341
|
+
SELECT *
|
342
|
+
FROM "posts"
|
343
|
+
WHERE CONCAT(author, '-', "posts"."id") > 'Jane-4'
|
344
|
+
ORDER BY CONCAT(author, '-', "posts"."id") ASC
|
345
|
+
LIMIT 2
|
346
|
+
```
|
347
|
+
|
348
|
+
You can see how the cursor is being translated into the WHERE clause to uniquely identify the row and properly filter based on this.
|
349
|
+
We will get the records #5 and #2 as response.
|
350
|
+
|
351
|
+
As you can see, when using a custom `order_by`, the concatenation is used for both filtering and ordering.
|
352
|
+
Therefore, it is recommended to add an index for columns that are frequently used for ordering.
|
353
|
+
In our test case we would want to add an index for `CONCAT(author, '-', id)`.
|
354
|
+
|
355
|
+
## Development
|
356
|
+
|
357
|
+
Make sure you have MySQL installed on your machine and create a database with the name `rails_cursor_pagination_testing`.
|
358
|
+
|
359
|
+
After checking out the repo, run `bin/setup` to install dependencies.
|
360
|
+
Then, run `rake spec` to run the tests.
|
361
|
+
You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
362
|
+
|
363
|
+
To install this gem onto your local machine, run `bundle exec rake install`.
|
364
|
+
To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
365
|
+
|
366
|
+
## Contributing
|
367
|
+
|
368
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/xing/rails_cursor_pagination.
|
369
|
+
This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/xing/rails_cursor_pagination/blob/master/CODE_OF_CONDUCT.md).
|
370
|
+
|
371
|
+
If you open a pull request, please make sure to also document your changes in the `CHANGELOG.md`.
|
372
|
+
This way, your change can be properly announced in the next release.
|
373
|
+
|
374
|
+
## License
|
375
|
+
|
376
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
377
|
+
|
378
|
+
## Code of Conduct
|
379
|
+
|
380
|
+
Everyone interacting in the RailsCursorPagination project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/xing/rails_cursor_pagination/blob/master/CODE_OF_CONDUCT.md).
|
@@ -0,0 +1,172 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# This library allows to paginate through a passed relation using a cursor
|
4
|
+
# and first/after or last/before parameters. It also supports ordering by
|
5
|
+
# any column on the relation in either ascending or descending order.
|
6
|
+
#
|
7
|
+
# Cursor pagination allows to paginate results and gracefully deal with
|
8
|
+
# deletions / additions on previous pages. Where a regular limit / offset
|
9
|
+
# pagination would jump in results if a record on a previous page gets deleted
|
10
|
+
# or added while requesting the next page, cursor pagination just returns the
|
11
|
+
# records following the one identified in the request.
|
12
|
+
#
|
13
|
+
# How this works is that it uses a "cursor", which is an encoded value that
|
14
|
+
# uniquely identifies a given row for the requested order. Then, based on
|
15
|
+
# this cursor, you can request the "n FIRST records AFTER the cursor"
|
16
|
+
# (forward-pagination) or the "n LAST records BEFORE the cursor" (backward-
|
17
|
+
# pagination).
|
18
|
+
#
|
19
|
+
# As an example, assume we have a table called "posts" with this data:
|
20
|
+
#
|
21
|
+
# | id | author |
|
22
|
+
# |----|--------|
|
23
|
+
# | 1 | Jane |
|
24
|
+
# | 2 | John |
|
25
|
+
# | 3 | John |
|
26
|
+
# | 4 | Jane |
|
27
|
+
# | 5 | Jane |
|
28
|
+
# | 6 | John |
|
29
|
+
# | 7 | John |
|
30
|
+
#
|
31
|
+
# Now if we make a basic request without any `first`/`after`, `last`/`before`,
|
32
|
+
# custom `order` or `order_by` column, this will just request the first page
|
33
|
+
# of this relation.
|
34
|
+
#
|
35
|
+
# RailsCursorPagination::Paginator
|
36
|
+
# .new(relation)
|
37
|
+
# .fetch
|
38
|
+
#
|
39
|
+
# Assume that our default page size here is 2 and we would get a query like
|
40
|
+
# this:
|
41
|
+
#
|
42
|
+
# SELECT *
|
43
|
+
# FROM "posts"
|
44
|
+
# ORDER BY "posts"."id" ASC
|
45
|
+
# LIMIT 2
|
46
|
+
#
|
47
|
+
# This will return the first page of results, containing post #1 and #2. Since
|
48
|
+
# no custom order is defined, each item in the returned collection will have a
|
49
|
+
# cursor that only encodes the record's ID.
|
50
|
+
#
|
51
|
+
# If we want to now request the next page, we can pass in the cursor of record
|
52
|
+
# #2 which would be "Mg==". So now we can request the next page by calling:
|
53
|
+
#
|
54
|
+
# RailsCursorPagination::Paginator
|
55
|
+
# .new(relation, first: 2, after: "Mg==")
|
56
|
+
# .fetch
|
57
|
+
#
|
58
|
+
# And this will decode the given cursor and issue a query like:
|
59
|
+
#
|
60
|
+
# SELECT *
|
61
|
+
# FROM "posts"
|
62
|
+
# WHERE "posts"."id" > 2
|
63
|
+
# ORDER BY "posts"."id" ASC
|
64
|
+
# LIMIT 2
|
65
|
+
#
|
66
|
+
# Which would return posts #3 and #4. If we now want to paginate back, we can
|
67
|
+
# request the posts that came before the first post, whose cursor would be
|
68
|
+
# "Mw==":
|
69
|
+
#
|
70
|
+
# RailsCursorPagination::Paginator
|
71
|
+
# .new(relation, last: 2, before: "Mw==")
|
72
|
+
# .fetch
|
73
|
+
#
|
74
|
+
# Since we now paginate backward, the resulting SQL query needs to be flipped
|
75
|
+
# around to get the last two records that have an ID smaller than the given
|
76
|
+
# one:
|
77
|
+
#
|
78
|
+
# SELECT *
|
79
|
+
# FROM "posts"
|
80
|
+
# WHERE "posts"."id" < 3
|
81
|
+
# ORDER BY "posts"."id" DESC
|
82
|
+
# LIMIT 2
|
83
|
+
#
|
84
|
+
# This would return posts #2 and #1. Since we still requested them in
|
85
|
+
# ascending order, the result will be reversed before it is returned.
|
86
|
+
#
|
87
|
+
# Now, in case that the user wants to order by a column different than the ID,
|
88
|
+
# we require this information in our cursor. Therefore, when requesting the
|
89
|
+
# first page like this:
|
90
|
+
#
|
91
|
+
# RailsCursorPagination::Paginator
|
92
|
+
# .new(relation, order_by: :author)
|
93
|
+
# .fetch
|
94
|
+
#
|
95
|
+
# This will issue the following SQL query:
|
96
|
+
#
|
97
|
+
# SELECT *
|
98
|
+
# FROM "posts"
|
99
|
+
# ORDER BY CONCAT(author, '-', "posts"."id") ASC
|
100
|
+
# LIMIT 2
|
101
|
+
#
|
102
|
+
# As you can see, this will now order by a concatenation of the requested
|
103
|
+
# column, a dash `-`, and the ID column. Ordering only the author is not
|
104
|
+
# enough since we cannot know if the custom column only has unique values.
|
105
|
+
# And we need to guarantee the correct order of ambiguous records independent
|
106
|
+
# of the direction of ordering. This unique order is the basis of being able
|
107
|
+
# to paginate forward and backward repeatedly and getting the correct records.
|
108
|
+
#
|
109
|
+
# The query will then return records #1 and #4. But the cursor for these
|
110
|
+
# records will also be different to the previous query where we ordered by ID
|
111
|
+
# only. It is important that the cursor encodes all the data we need to
|
112
|
+
# uniquely identify a row and filter based upon it. Therefore, we need to
|
113
|
+
# encode the same information as we used for the ordering in our SQL query.
|
114
|
+
# Hence, the cursor for pagination with a custom column contains a tuple of
|
115
|
+
# data, the first record being the custom order column followed by the
|
116
|
+
# record's ID.
|
117
|
+
#
|
118
|
+
# Therefore, the cursor of record #4 will encode `['Jane', 4]`, which yields
|
119
|
+
# this cursor: "WyJKYW5lIiw0XQ==".
|
120
|
+
#
|
121
|
+
# If we now want to request the next page via:
|
122
|
+
#
|
123
|
+
# RailsCursorPagination::Paginator
|
124
|
+
# .new(relation, order_by: :author, first: 2, after: "WyJKYW5lIiw0XQ==")
|
125
|
+
# .fetch
|
126
|
+
#
|
127
|
+
# We get this SQL query:
|
128
|
+
#
|
129
|
+
# SELECT *
|
130
|
+
# FROM "posts"
|
131
|
+
# WHERE CONCAT(author, '-', "posts"."id") > 'Jane-4'
|
132
|
+
# ORDER BY CONCAT(author, '-', "posts"."id") ASC
|
133
|
+
# LIMIT 2
|
134
|
+
#
|
135
|
+
# You can see how the cursor is being translated into the WHERE clause to
|
136
|
+
# uniquely identify the row and properly filter based on this. We will get
|
137
|
+
# the records #5 and #2 as response.
|
138
|
+
#
|
139
|
+
# As you can see, when using a custom `order_by`, the concatenation is used
|
140
|
+
# for both filtering and ordering. Therefore, it is recommended to add an
|
141
|
+
# index for columns that are frequently used for ordering. In our test case
|
142
|
+
# we would want to add an index for `CONCAT(author, '-', id)`.
|
143
|
+
#
|
144
|
+
module RailsCursorPagination
|
145
|
+
class Error < StandardError; end
|
146
|
+
|
147
|
+
require_relative 'rails_cursor_pagination/version'
|
148
|
+
|
149
|
+
require_relative 'rails_cursor_pagination/configuration'
|
150
|
+
|
151
|
+
require_relative 'rails_cursor_pagination/paginator'
|
152
|
+
|
153
|
+
class << self
|
154
|
+
# Allows to configure this gem. Currently supported configuration values
|
155
|
+
# are:
|
156
|
+
# * default_page_size - defines how many items are returned when not
|
157
|
+
# passing an explicit `first` or `last` parameter
|
158
|
+
#
|
159
|
+
# Usage:
|
160
|
+
#
|
161
|
+
# RailsCursorPagination.configure do |config|
|
162
|
+
# config.default_page_size = 42
|
163
|
+
# end
|
164
|
+
#
|
165
|
+
# @yield [config] Yields a block to configure the gem as explained above
|
166
|
+
# @yieldparam config [RailsCursorPagination::Configuration]
|
167
|
+
# Configuration instance that can be used to set up this gem
|
168
|
+
def configure(&_block)
|
169
|
+
yield(Configuration.instance)
|
170
|
+
end
|
171
|
+
end
|
172
|
+
end
|
@@ -0,0 +1,30 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'singleton'
|
4
|
+
|
5
|
+
module RailsCursorPagination
|
6
|
+
# Configuration class to set the default gem settings. Accessible via
|
7
|
+
# `RailsCursorPagination.configure`.
|
8
|
+
#
|
9
|
+
# Usage:
|
10
|
+
#
|
11
|
+
# RailsCursorPagination.configure do |config|
|
12
|
+
# config.default_page_size = 42
|
13
|
+
# end
|
14
|
+
#
|
15
|
+
class Configuration
|
16
|
+
include Singleton
|
17
|
+
|
18
|
+
attr_accessor :default_page_size
|
19
|
+
|
20
|
+
# Ensure the default values are set on first initialization
|
21
|
+
def initialize
|
22
|
+
reset!
|
23
|
+
end
|
24
|
+
|
25
|
+
# Reset all values to their defaults
|
26
|
+
def reset!
|
27
|
+
@default_page_size = 10
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
@@ -0,0 +1,464 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module RailsCursorPagination
|
4
|
+
# Use this Paginator class to effortlessly paginate through ActiveRecord
|
5
|
+
# relations using cursor pagination. For more details on how this works,
|
6
|
+
# read the top-level documentation of the `RailsCursorPagination` module.
|
7
|
+
#
|
8
|
+
# Usage:
|
9
|
+
# RailsCursorPagination::Paginator
|
10
|
+
# .new(relation, order_by: :author, first: 2, after: "WyJKYW5lIiw0XQ==")
|
11
|
+
# .fetch
|
12
|
+
#
|
13
|
+
class Paginator
|
14
|
+
# Generic error that gets raised when invalid parameters are passed to the
|
15
|
+
# Paginator initializer
|
16
|
+
class ParameterError < Error; end
|
17
|
+
|
18
|
+
# Error that gets raised if a cursor given as `before` or `after` parameter
|
19
|
+
# cannot be properly parsed
|
20
|
+
class InvalidCursorError < ParameterError; end
|
21
|
+
|
22
|
+
# Create a new instance of the `RailsCursorPagination::Paginator`
|
23
|
+
#
|
24
|
+
# @param relation [ActiveRecord::Relation]
|
25
|
+
# Relation that will be paginated.
|
26
|
+
# @param first [Integer, nil]
|
27
|
+
# Number of records to return in a forward pagination. Can be combined
|
28
|
+
# with `after`.
|
29
|
+
# @param after [String, nil]
|
30
|
+
# Cursor to paginate forward from. Can be combined with `first`.
|
31
|
+
# @param last [Integer, nil]
|
32
|
+
# Number of records to return. Must be used together with `before`.
|
33
|
+
# @param before [String, nil]
|
34
|
+
# Cursor to paginate upto (excluding). Can be combined with `last`.
|
35
|
+
# @param order_by [Symbol, String, nil]
|
36
|
+
# Column to order by. If none is provided, will default to ID column.
|
37
|
+
# NOTE: this will cause an SQL `CONCAT` query. Therefore, you might want
|
38
|
+
# to add an index to your database: `CONCAT(<order_by_field>, '-', id)`
|
39
|
+
# @param order [Symbol, nil]
|
40
|
+
# Ordering to apply, either `:asc` or `:desc`. Defaults to `:asc`.
|
41
|
+
#
|
42
|
+
# @raise [RailsCursorPagination::Paginator::ParameterError]
|
43
|
+
# If any parameter is not valid
|
44
|
+
def initialize(relation, first: nil, after: nil, last: nil, before: nil,
|
45
|
+
order_by: nil, order: nil)
|
46
|
+
order_by ||= :id
|
47
|
+
order ||= :asc
|
48
|
+
|
49
|
+
ensure_valid_params!(relation, first, after, last, before, order)
|
50
|
+
|
51
|
+
@order_field = order_by
|
52
|
+
@order_direction = order
|
53
|
+
@relation = relation
|
54
|
+
|
55
|
+
@cursor = before || after
|
56
|
+
@is_forward_pagination = before.blank?
|
57
|
+
|
58
|
+
@page_size =
|
59
|
+
first ||
|
60
|
+
last ||
|
61
|
+
RailsCursorPagination::Configuration.instance.default_page_size
|
62
|
+
|
63
|
+
@memos = {}
|
64
|
+
end
|
65
|
+
|
66
|
+
# Get the paginated result, including the actual `page` with its data items
|
67
|
+
# and cursors as well as some meta data in `page_info` and an optional
|
68
|
+
# `total` of records across all pages.
|
69
|
+
#
|
70
|
+
# @param with_total [TrueClass, FalseClass]
|
71
|
+
# @return [Hash] with keys :page, :page_info, and optional :total
|
72
|
+
def fetch(with_total: false)
|
73
|
+
{
|
74
|
+
**(with_total ? { total: total } : {}),
|
75
|
+
page_info: page_info,
|
76
|
+
page: page
|
77
|
+
}
|
78
|
+
end
|
79
|
+
|
80
|
+
private
|
81
|
+
|
82
|
+
# Ensure that the parameters of this service are valid. Otherwise raise
|
83
|
+
# a `RailsCursorPagination::Paginator::ParameterError`.
|
84
|
+
#
|
85
|
+
# @param relation [ActiveRecord::Relation]
|
86
|
+
# Relation that will be paginated.
|
87
|
+
# @param first [Integer, nil]
|
88
|
+
# Optional, must be positive, cannot be combined with `last`
|
89
|
+
# @param after [String, nil]
|
90
|
+
# Optional, cannot be combined with `before`
|
91
|
+
# @param last [Integer, nil]
|
92
|
+
# Optional, must be positive, requires `before`, cannot be combined
|
93
|
+
# with `first`
|
94
|
+
# @param before [String, nil]
|
95
|
+
# Optional, cannot be combined with `after`
|
96
|
+
# @param order [Symbol]
|
97
|
+
# Optional, must be :asc or :desc
|
98
|
+
#
|
99
|
+
# @raise [RailsCursorPagination::Paginator::ParameterError]
|
100
|
+
# If any parameter is not valid
|
101
|
+
def ensure_valid_params!(relation, first, after, last, before, order)
|
102
|
+
unless relation.is_a?(ActiveRecord::Relation)
|
103
|
+
raise ParameterError,
|
104
|
+
'The first argument must be an ActiveRecord::Relation, but was '\
|
105
|
+
"the #{relation.class} `#{relation.inspect}`"
|
106
|
+
end
|
107
|
+
unless %i[asc desc].include?(order)
|
108
|
+
raise ParameterError,
|
109
|
+
"`order` must be either :asc or :desc, but was `#{order}`"
|
110
|
+
end
|
111
|
+
if first.present? && last.present?
|
112
|
+
raise ParameterError, '`first` cannot be combined with `last`'
|
113
|
+
end
|
114
|
+
if before.present? && after.present?
|
115
|
+
raise ParameterError, '`before` cannot be combined with `after`'
|
116
|
+
end
|
117
|
+
if last.present? && before.blank?
|
118
|
+
raise ParameterError, '`last` must be combined with `before`'
|
119
|
+
end
|
120
|
+
if first.present? && first.negative?
|
121
|
+
raise ParameterError, "`first` cannot be negative, but was `#{first}`"
|
122
|
+
end
|
123
|
+
if last.present? && last.negative?
|
124
|
+
raise ParameterError, "`last` cannot be negative, but was `#{last}`"
|
125
|
+
end
|
126
|
+
|
127
|
+
true
|
128
|
+
end
|
129
|
+
|
130
|
+
# Get meta information about the current page
|
131
|
+
#
|
132
|
+
# @return [Hash]
|
133
|
+
def page_info
|
134
|
+
{
|
135
|
+
has_previous_page: previous_page?,
|
136
|
+
has_next_page: next_page?,
|
137
|
+
start_cursor: start_cursor,
|
138
|
+
end_cursor: end_cursor
|
139
|
+
}
|
140
|
+
end
|
141
|
+
|
142
|
+
# Get the records for the given page along with their cursors
|
143
|
+
#
|
144
|
+
# @return [Array<Hash>] List of hashes, each with a `cursor` and `data`
|
145
|
+
def page
|
146
|
+
records.map do |item|
|
147
|
+
{
|
148
|
+
cursor: cursor_for_record(item),
|
149
|
+
data: item
|
150
|
+
}
|
151
|
+
end
|
152
|
+
end
|
153
|
+
|
154
|
+
# Get the total number of records in the given relation
|
155
|
+
#
|
156
|
+
# @return [Integer]
|
157
|
+
def total
|
158
|
+
memoize(:total) { @relation.size }
|
159
|
+
end
|
160
|
+
|
161
|
+
# Check if the pagination direction is forward
|
162
|
+
#
|
163
|
+
# @return [TrueClass, FalseClass]
|
164
|
+
def paginate_forward?
|
165
|
+
@is_forward_pagination
|
166
|
+
end
|
167
|
+
|
168
|
+
# Check if the user requested to order on a field different than the ID. If
|
169
|
+
# a different field was requested, we have to change our pagination logic to
|
170
|
+
# accommodate for this.
|
171
|
+
#
|
172
|
+
# @return [TrueClass, FalseClass]
|
173
|
+
def custom_order_field?
|
174
|
+
@order_field.downcase.to_sym != :id
|
175
|
+
end
|
176
|
+
|
177
|
+
# Check if there is a page before the current one.
|
178
|
+
#
|
179
|
+
# @return [TrueClass, FalseClass]
|
180
|
+
def previous_page?
|
181
|
+
if paginate_forward?
|
182
|
+
# When paginating forward, we can only have a previous page if we were
|
183
|
+
# provided with a cursor and there were records discarded after applying
|
184
|
+
# this filter. These records would have to be on previous pages.
|
185
|
+
@cursor.present? && filtered_and_sorted_relation.size < total
|
186
|
+
else
|
187
|
+
# When paginating backwards, if we managed to load one more record than
|
188
|
+
# requested, this record will be available on the previous page.
|
189
|
+
@page_size < limited_relation_plus_one.size
|
190
|
+
end
|
191
|
+
end
|
192
|
+
|
193
|
+
# Check if there is another page after the current one.
|
194
|
+
#
|
195
|
+
# @return [TrueClass, FalseClass]
|
196
|
+
def next_page?
|
197
|
+
if paginate_forward?
|
198
|
+
# When paginating forward, if we managed to load one more record than
|
199
|
+
# requested, this record will be available on the next page.
|
200
|
+
@page_size < limited_relation_plus_one.size
|
201
|
+
else
|
202
|
+
# When paginating backward, if applying our cursor reduced the number
|
203
|
+
# records returned, we know that the missing records will be on
|
204
|
+
# subsequent pages.
|
205
|
+
filtered_and_sorted_relation.size < total
|
206
|
+
end
|
207
|
+
end
|
208
|
+
|
209
|
+
# Load the correct records and return them in the right order
|
210
|
+
#
|
211
|
+
# @return [Array<ActiveRecord>]
|
212
|
+
def records
|
213
|
+
records = limited_relation_plus_one.first(@page_size)
|
214
|
+
|
215
|
+
paginate_forward? ? records : records.reverse
|
216
|
+
end
|
217
|
+
|
218
|
+
# Apply limit to filtered and sorted relation that contains one item more
|
219
|
+
# than the user-requested page size. This is useful for determining if there
|
220
|
+
# is an additional page available without having to do a separate DB query.
|
221
|
+
#
|
222
|
+
# @return [ActiveRecord::Relation]
|
223
|
+
def limited_relation_plus_one
|
224
|
+
memoize :limited_relation_plus_one do
|
225
|
+
filtered_and_sorted_relation.limit(@page_size + 1)
|
226
|
+
end
|
227
|
+
end
|
228
|
+
|
229
|
+
# Cursor of the first record on the current page
|
230
|
+
#
|
231
|
+
# @return [String, nil]
|
232
|
+
def start_cursor
|
233
|
+
return if page.empty?
|
234
|
+
|
235
|
+
page.first[:cursor]
|
236
|
+
end
|
237
|
+
|
238
|
+
# Cursor of the last record on the current page
|
239
|
+
#
|
240
|
+
# @return [String, nil]
|
241
|
+
def end_cursor
|
242
|
+
return if page.empty?
|
243
|
+
|
244
|
+
page.last[:cursor]
|
245
|
+
end
|
246
|
+
|
247
|
+
# Get the order we need to apply to our SQL query. In case we are paginating
|
248
|
+
# backwards, this has to be the inverse of what the user requested, since
|
249
|
+
# our database can only apply the limit to following records. In the case of
|
250
|
+
# backward pagination, we then reverse the order of the loaded records again
|
251
|
+
# in `#records` to return them in the right order to the user.
|
252
|
+
#
|
253
|
+
# Examples:
|
254
|
+
# - first 2 after 4 ascending
|
255
|
+
# -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2
|
256
|
+
# - first 2 after 4 descending ^ as requested
|
257
|
+
# -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2
|
258
|
+
# but: ^ as requested
|
259
|
+
# - last 2 before 4 ascending
|
260
|
+
# -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2
|
261
|
+
# - last 2 before 4 descending ^ reversed
|
262
|
+
# -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2
|
263
|
+
# ^ reversed
|
264
|
+
#
|
265
|
+
# @return [Symbol] Either :asc or :desc
|
266
|
+
def pagination_sorting
|
267
|
+
return @order_direction if paginate_forward?
|
268
|
+
|
269
|
+
@order_direction == :asc ? :desc : :asc
|
270
|
+
end
|
271
|
+
|
272
|
+
# Get the right operator to use in the SQL WHERE clause for filtering based
|
273
|
+
# on the given cursor. This is dependent on the requested order and
|
274
|
+
# pagination direction.
|
275
|
+
#
|
276
|
+
# If we paginate forward and want ascending records, or if we paginate
|
277
|
+
# backward and want descending records we need records that have a higher
|
278
|
+
# value than our cursor.
|
279
|
+
#
|
280
|
+
# On the contrary, if we paginate forward but want descending records, or
|
281
|
+
# if we paginate backwards and want ascending records, we need them to have
|
282
|
+
# lower values than our cursor.
|
283
|
+
#
|
284
|
+
# Examples:
|
285
|
+
# - first 2 after 4 ascending
|
286
|
+
# -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2
|
287
|
+
# - last 2 before 4 descending ^ records with higher value than cursor
|
288
|
+
# -> SELECT * FROM table WHERE id > 4 ODER BY id ASC LIMIT 2
|
289
|
+
# but: ^ records with higher value than cursor
|
290
|
+
# - first 2 after 4 descending
|
291
|
+
# -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2
|
292
|
+
# - last 2 before 4 ascending ^ records with lower value than cursor
|
293
|
+
# -> SELECT * FROM table WHERE id < 4 ODER BY id DESC LIMIT 2
|
294
|
+
# ^ records with lower value than cursor
|
295
|
+
#
|
296
|
+
# @return [String] either '<' or '>'
|
297
|
+
def filter_operator
|
298
|
+
if paginate_forward?
|
299
|
+
@order_direction == :asc ? '>' : '<'
|
300
|
+
else
|
301
|
+
@order_direction == :asc ? '<' : '>'
|
302
|
+
end
|
303
|
+
end
|
304
|
+
|
305
|
+
# The value our relation is filtered by. This is either just the cursor's ID
|
306
|
+
# if we use the default order, or it is the combination of the custom order
|
307
|
+
# field's value and its ID, joined by a dash.
|
308
|
+
#
|
309
|
+
# @return [Integer, String]
|
310
|
+
def filter_value
|
311
|
+
return decoded_cursor_id unless custom_order_field?
|
312
|
+
|
313
|
+
"#{decoded_cursor_field}-#{decoded_cursor_id}"
|
314
|
+
end
|
315
|
+
|
316
|
+
# Generate a cursor for the given record and ordering field. The cursor
|
317
|
+
# encodes all the data required to then paginate based on it with the given
|
318
|
+
# ordering field.
|
319
|
+
#
|
320
|
+
# If we only order by ID, the cursor doesn't need to include any other data.
|
321
|
+
# But if we order by any other field, the cursor needs to include both the
|
322
|
+
# value from this other field as well as the records ID to resolve the order
|
323
|
+
# of duplicates in the non-ID field.
|
324
|
+
#
|
325
|
+
# @param record [ActiveRecord] Model instance for which we want the cursor
|
326
|
+
# @return [String]
|
327
|
+
def cursor_for_record(record)
|
328
|
+
unencoded_cursor =
|
329
|
+
if custom_order_field?
|
330
|
+
[record[@order_field], record.id]
|
331
|
+
else
|
332
|
+
record.id
|
333
|
+
end
|
334
|
+
|
335
|
+
Base64.strict_encode64(unencoded_cursor.to_json)
|
336
|
+
end
|
337
|
+
|
338
|
+
# Decode the provided cursor. Either just returns the cursor's ID or in case
|
339
|
+
# of pagination on any other field, returns a tuple of first the cursor
|
340
|
+
# record's other field's value followed by its ID.
|
341
|
+
#
|
342
|
+
# @return [Integer, Array]
|
343
|
+
def decoded_cursor
|
344
|
+
memoize(:decoded_cursor) { JSON.parse(Base64.strict_decode64(@cursor)) }
|
345
|
+
rescue ArgumentError, JSON::ParserError
|
346
|
+
raise InvalidCursorError,
|
347
|
+
"The given cursor `#{@cursor.inspect}` could not be decoded"
|
348
|
+
end
|
349
|
+
|
350
|
+
# Return the ID of the cursor's record. In case we use an ordering by ID,
|
351
|
+
# this is all the data the cursor encodes. Otherwise, it's the second
|
352
|
+
# element of the tuple encoded by the cursor.
|
353
|
+
#
|
354
|
+
# @return [Integer]
|
355
|
+
def decoded_cursor_id
|
356
|
+
return decoded_cursor unless decoded_cursor.is_a? Array
|
357
|
+
|
358
|
+
decoded_cursor.last
|
359
|
+
end
|
360
|
+
|
361
|
+
# Return the value of the cursor's record's custom order field. Only exists
|
362
|
+
# if the cursor was generated by a query with a custom order field.
|
363
|
+
# Otherwise the cursor would only encode the ID and not be an array.
|
364
|
+
|
365
|
+
# @raise [InvalidCursorError] in case the cursor is not a tuple
|
366
|
+
# @return [Object]
|
367
|
+
def decoded_cursor_field
|
368
|
+
unless decoded_cursor.is_a? Array
|
369
|
+
raise InvalidCursorError,
|
370
|
+
"The given cursor `#{@cursor}` was decoded as "\
|
371
|
+
"`#{decoded_cursor.inspect}` but could not be parsed"
|
372
|
+
end
|
373
|
+
|
374
|
+
decoded_cursor.first
|
375
|
+
end
|
376
|
+
|
377
|
+
# The SQL identifier of the column we need to consider for both ordering and
|
378
|
+
# filtering.
|
379
|
+
#
|
380
|
+
# In case we have a custom field order, this is a concatenation
|
381
|
+
# of the custom order field and the ID column joined by a dash. This is to
|
382
|
+
# ensure uniqueness of records even if they might have duplicates in the
|
383
|
+
# custom order field. If we don't have a custom order, it just returns a
|
384
|
+
# reference to the table's ID column.
|
385
|
+
#
|
386
|
+
# This uses the fully qualified and escaped reference to the ID column to
|
387
|
+
# prevent ambiguity in case of a query that uses JOINs and therefore might
|
388
|
+
# have multiple ID columns.
|
389
|
+
#
|
390
|
+
# @return [String]
|
391
|
+
def sql_column
|
392
|
+
memoize :sql_column do
|
393
|
+
escaped_table_name = @relation.quoted_table_name
|
394
|
+
escaped_id_column = @relation.connection.quote_column_name(:id)
|
395
|
+
|
396
|
+
id_column = "#{escaped_table_name}.#{escaped_id_column}"
|
397
|
+
|
398
|
+
sql =
|
399
|
+
if custom_order_field?
|
400
|
+
"CONCAT(#{@order_field}, '-', #{id_column})"
|
401
|
+
else
|
402
|
+
id_column
|
403
|
+
end
|
404
|
+
|
405
|
+
Arel.sql(sql)
|
406
|
+
end
|
407
|
+
end
|
408
|
+
|
409
|
+
# Ensure that the relation has the ID column and any potential `order_by`
|
410
|
+
# column selected. These are required to generate the record's cursor and
|
411
|
+
# therefore it's crucial that they are part of the selected fields.
|
412
|
+
#
|
413
|
+
# @return [ActiveRecord::Relation]
|
414
|
+
def relation_with_cursor_fields
|
415
|
+
return @relation if @relation.select_values.blank?
|
416
|
+
|
417
|
+
relation = @relation
|
418
|
+
|
419
|
+
unless @relation.select_values.include?(:id)
|
420
|
+
relation = relation.select(:id)
|
421
|
+
end
|
422
|
+
|
423
|
+
if custom_order_field? && !@relation.select_values.include?(@order_field)
|
424
|
+
relation = relation.select(@order_field)
|
425
|
+
end
|
426
|
+
|
427
|
+
relation
|
428
|
+
end
|
429
|
+
|
430
|
+
# The given relation with the right ordering applied. Takes custom order
|
431
|
+
# columns as well as custom direction and pagination into account.
|
432
|
+
#
|
433
|
+
# @return [ActiveRecord::Relation]
|
434
|
+
def sorted_relation
|
435
|
+
relation_with_cursor_fields
|
436
|
+
.reorder(sql_column => pagination_sorting.upcase)
|
437
|
+
end
|
438
|
+
|
439
|
+
# Applies the filtering based on the provided cursor and order column to the
|
440
|
+
# sorted relation.
|
441
|
+
#
|
442
|
+
# @return [ActiveRecord::Relation]
|
443
|
+
def filtered_and_sorted_relation
|
444
|
+
memoize :filtered_and_sorted_relation do
|
445
|
+
next sorted_relation if @cursor.blank?
|
446
|
+
|
447
|
+
sorted_relation.where "#{sql_column} #{filter_operator} ?", filter_value
|
448
|
+
end
|
449
|
+
end
|
450
|
+
|
451
|
+
# Ensures that given block is only executed exactly once and on subsequent
|
452
|
+
# calls returns result from first execution. Useful for memoizing methods.
|
453
|
+
#
|
454
|
+
# @param key [Symbol]
|
455
|
+
# Name or unique identifier of the method that is being memoized
|
456
|
+
# @yieldreturn [Object]
|
457
|
+
# @return [Object] Whatever the block returns
|
458
|
+
def memoize(key, &_block)
|
459
|
+
return @memos[key] if @memos.key?(key)
|
460
|
+
|
461
|
+
@memos[key] = yield
|
462
|
+
end
|
463
|
+
end
|
464
|
+
end
|
metadata
ADDED
@@ -0,0 +1,71 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: rails_cursor_pagination
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.3
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Nicolas Fricke
|
8
|
+
autorequire:
|
9
|
+
bindir: bin
|
10
|
+
cert_chain: []
|
11
|
+
date: 2021-03-17 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: activerecord
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - ">="
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '5.0'
|
20
|
+
type: :runtime
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - ">="
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '5.0'
|
27
|
+
description: This library is an implementation of cursor pagination for ActiveRecord
|
28
|
+
relations. Where a regular limit & offset pagination has issues with items that
|
29
|
+
are being deleted from or added to the collection on previous pages, cursor pagination
|
30
|
+
will continue to offer a stable set regardless of changes to the base relation.
|
31
|
+
email:
|
32
|
+
- mail@nicolasfricke.com
|
33
|
+
executables: []
|
34
|
+
extensions: []
|
35
|
+
extra_rdoc_files: []
|
36
|
+
files:
|
37
|
+
- CHANGELOG.md
|
38
|
+
- CODE_OF_CONDUCT.md
|
39
|
+
- LICENSE.txt
|
40
|
+
- README.md
|
41
|
+
- lib/rails_cursor_pagination.rb
|
42
|
+
- lib/rails_cursor_pagination/configuration.rb
|
43
|
+
- lib/rails_cursor_pagination/paginator.rb
|
44
|
+
- lib/rails_cursor_pagination/version.rb
|
45
|
+
homepage: https://github.com/xing/rails_cursor_pagination
|
46
|
+
licenses:
|
47
|
+
- MIT
|
48
|
+
metadata:
|
49
|
+
homepage_uri: https://github.com/xing/rails_cursor_pagination
|
50
|
+
source_code_uri: https://github.com/xing/rails_cursor_pagination
|
51
|
+
changelog_uri: https://github.com/xing/rails_cursor_pagination/blob/master/CHANGELOG.md
|
52
|
+
post_install_message:
|
53
|
+
rdoc_options: []
|
54
|
+
require_paths:
|
55
|
+
- lib
|
56
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
57
|
+
requirements:
|
58
|
+
- - ">="
|
59
|
+
- !ruby/object:Gem::Version
|
60
|
+
version: 2.5.0
|
61
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
62
|
+
requirements:
|
63
|
+
- - ">="
|
64
|
+
- !ruby/object:Gem::Version
|
65
|
+
version: '0'
|
66
|
+
requirements: []
|
67
|
+
rubygems_version: 3.1.4
|
68
|
+
signing_key:
|
69
|
+
specification_version: 4
|
70
|
+
summary: Add cursor pagination to your ActiveRecord backed application.
|
71
|
+
test_files: []
|