Skip to content

Commit 56dcf40

Browse files
committed
PrepareRaw to paginate raw SQL queries
1 parent a17f20f commit 56dcf40

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

page.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,26 @@ func (p Paginator[T]) PrepareQuery(q sq.SelectBuilder, page *Page) ([]T, sq.Sele
199199
return make([]T, 0, limit+1), q
200200
}
201201

202+
func (p Paginator[T]) PrepareRaw(q string, args []any, page *Page) ([]T, string, []any) {
203+
limit, offset := page.Limit(), page.Offset()
204+
205+
q = q + " ORDER BY " + strings.Join(p.getOrder(page), ", ")
206+
q = q + " LIMIT @limit OFFSET @offset"
207+
208+
for i, arg := range args {
209+
if existing, ok := arg.(pgx.NamedArgs); ok {
210+
existing["limit"] = limit + 1
211+
existing["offset"] = offset
212+
break
213+
}
214+
if i == len(args)-1 {
215+
args = append(args, pgx.NamedArgs{"limit": limit + 1, "offset": offset})
216+
}
217+
}
218+
219+
return make([]T, 0, limit+1), q, args
220+
}
221+
202222
// PrepareResult prepares the paginated result. If the number of rows is n+1:
203223
// - it removes the last element, returning n elements
204224
// - it sets more to true in the page object

0 commit comments

Comments
 (0)