Skip to content

Commit 3e72c6a

Browse files
authored
Merge pull request #196 from barweiss/fix-presto-limit-and-offset-order
Fix #195 the order of LIMIT and OFFSET clauses when using the Presto flavor
2 parents 87b9c12 + baa3920 commit 3e72c6a

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

select.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,7 @@ func (sb *SelectBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{
457457
buf.WriteLeadingString("LIMIT ")
458458
buf.WriteString(sb.limitVar)
459459
}
460-
case PostgreSQL, Presto:
460+
case PostgreSQL:
461461
if len(sb.limitVar) > 0 {
462462
buf.WriteLeadingString("LIMIT ")
463463
buf.WriteString(sb.limitVar)
@@ -467,6 +467,20 @@ func (sb *SelectBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{
467467
buf.WriteLeadingString("OFFSET ")
468468
buf.WriteString(sb.offsetVar)
469469
}
470+
case Presto:
471+
// There might be a hidden constraint in Presto requiring offset to be set before limit.
472+
// The select statement documentation (https://prestodb.io/docs/current/sql/select.html)
473+
// puts offset before limit, and Trino, which is based on Presto, seems
474+
// to require this specific order.
475+
if len(sb.offsetVar) > 0 {
476+
buf.WriteLeadingString("OFFSET ")
477+
buf.WriteString(sb.offsetVar)
478+
}
479+
480+
if len(sb.limitVar) > 0 {
481+
buf.WriteLeadingString("LIMIT ")
482+
buf.WriteString(sb.limitVar)
483+
}
470484

471485
case SQLServer:
472486
// If ORDER BY is not set, sort column #1 by default.

select_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,9 +229,9 @@ func ExampleSelectBuilder_limit_offset() {
229229
// Presto
230230
// #1: SELECT * FROM user
231231
// #2: SELECT * FROM user OFFSET ?
232-
// #3: SELECT * FROM user LIMIT ? OFFSET ?
232+
// #3: SELECT * FROM user OFFSET ? LIMIT ?
233233
// #4: SELECT * FROM user LIMIT ?
234-
// #5: SELECT * FROM user ORDER BY id LIMIT ? OFFSET ?
234+
// #5: SELECT * FROM user ORDER BY id OFFSET ? LIMIT ?
235235
//
236236
// Oracle
237237
// #1: SELECT * FROM user

0 commit comments

Comments
 (0)