perf(pagination): split list queries into first-page and after-cursor variants

This commit is contained in:
kk10
2026-10-10 10:51:50 +03:00
parent a288193cda
commit c8470beeee
6 changed files with 202 additions and 90 deletions
+64 -15
View File
@@ -116,7 +116,7 @@ func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (boo
return exists, err
}
const listChats = `-- name: ListChats :many
const listChatsAfter = `-- name: ListChatsAfter :many
SELECT
c.id, c.title, c.created_at,
ARRAY(
@@ -127,33 +127,30 @@ SELECT
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1
AND (
$2::timestamptz IS NULL
OR (c.created_at, c.id) > (
$2::timestamptz,
$3::uuid
)
AND (c.created_at, c.id) > (
$2::timestamptz,
$3::uuid
)
ORDER BY c.created_at, c.id
LIMIT $4
`
type ListChatsParams struct {
type ListChatsAfterParams struct {
UserID uuid.UUID
AfterCreatedAt *time.Time
AfterID *uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
Lim int32
}
type ListChatsRow struct {
type ListChatsAfterRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
rows, err := q.db.Query(ctx, listChats,
func (q *Queries) ListChatsAfter(ctx context.Context, arg ListChatsAfterParams) ([]ListChatsAfterRow, error) {
rows, err := q.db.Query(ctx, listChatsAfter,
arg.UserID,
arg.AfterCreatedAt,
arg.AfterID,
@@ -163,9 +160,61 @@ func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListCha
return nil, err
}
defer rows.Close()
items := []ListChatsRow{}
items := []ListChatsAfterRow{}
for rows.Next() {
var i ListChatsRow
var i ListChatsAfterRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listChatsFirstPage = `-- name: ListChatsFirstPage :many
SELECT
c.id, c.title, c.created_at,
ARRAY(
SELECT cm.user_id FROM chat_members cm
WHERE cm.chat_id = c.id
ORDER BY cm.user_id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1
ORDER BY c.created_at, c.id
LIMIT $2
`
type ListChatsFirstPageParams struct {
UserID uuid.UUID
Lim int32
}
type ListChatsFirstPageRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsFirstPage(ctx context.Context, arg ListChatsFirstPageParams) ([]ListChatsFirstPageRow, error) {
rows, err := q.db.Query(ctx, listChatsFirstPage, arg.UserID, arg.Lim)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsFirstPageRow{}
for rows.Next() {
var i ListChatsFirstPageRow
if err := rows.Scan(
&i.ID,
&i.Title,