Merge 'translate: implement Sequence opcode and fix sort order' from Preston Thorpe

This PR implements the `Sequence` and `SequenceTest` opcodes, although
does not yet add plumbing to emit the latter.
SQLite has two distinct mechanisms that determine the final row order
with aggregates:
Traversal order of GROUP BY, and ORDER BY tiebreaking. When ORDER BY
contains only aggregate expressions and/or constants, SQLite has no
extra tiebreak key, but when ORDER BY mixes aggregate and non-aggregate
terms, SQLite adds an implicit, stable row `sequence` so “ties” respect
the input order.
This PR also fixes an issue with a query like the following:
```sql
SELECT u.first_name, COUNT(*) AS c
FROM users u
JOIN orders o ON o.user_id = u.id
GROUP BY u.first_name
ORDER BY c DESC;
```
Because ORDER BY has only an aggregate (COUNT(*) DESC) and no non-
aggregate terms, SQLite traverses the group key (u.first_name) in DESC
order in this case, so ties on c naturally appear with group keys in
descending order.
Previously tursodb would return the group key sorted in ASC order,
because it was used in all cases as the default

Closes #3287
This commit is contained in:
Jussi Saurio
2025-09-24 08:38:08 +03:00
committed by GitHub
12 changed files with 305 additions and 58 deletions

View File

@@ -326,3 +326,23 @@ sneakers|sneakers|sneakers
boots|boots|boots
coat|coat|coat
accessories|accessories|accessories}
# make sure we return the group by key sorted DESC when the order by has only an aggregate term
do_execsql_test proper-sort-order {
SELECT u.first_name, COUNT(*) AS c
FROM users u
JOIN products p ON p.id = u.id
GROUP BY u.first_name
ORDER BY c DESC;
} {Travis|1
Tommy|1
Rachel|1
Nicholas|1
Matthew|1
Jennifer|1
Jamie|1
Edward|1
Daniel|1
Cindy|1
Aimee|1}