Skip to content

Composite key cursor pagination is broken #1209

@jacob-pro

Description

@jacob-pro

Description

The SQL generated by the Cursor struct when using composite keys is incorrect and leads to missed results when paginating. The problem is that the WHERE clause is incorrect, it can only currently work if it just so happens that your two columns naturally followed the exact same ordering.

Example

Lets say you have the following table:

ID Category
1 B
2 B
3 A
4 C
5 A
6 A
7 C
8 B
9 A

Now lets say you want to paginate by category, category isn't unique so in order to page you need to combine with the ID column into a unique composite key.

The SQL to fetch the first page would look like:

Lets query the first 3 results:

SELECT * FROM example
ORDER BY category ASC, id ASC
LIMIT 3

Which returns:

ID Category
3 A
5 A
6 A

Now we want to get the next page, according to the current implementation this creates a query like:

SELECT * FROM example
WHERE category > 'A' AND id > 6
ORDER BY category ASC, id ASC
LIMIT 3

But this is wrong - we would end up only getting two more results, missing out many inbetween

ID Category
8 B
7 C

We need to actually have a query like:

SELECT * FROM example
WHERE (category = 'A' and id > 6) OR category > 'A'
ORDER BY category ASC, id ASC
LIMIT 3

which produces:

ID Category
9 A
1 B
2 B

Three Columns

Lets say you have 3 columns "x", "y", "z", then the WHERE clause needs to look like:

WHERE ("x"= X AND "y" = Y AND "z" > Z) OR ("x" = X AND "y" > Y) OR "x" > X

Versions

Present in master

Related To

@tyt2y3 @billy1624 @Sytten @ikrivosheev

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions