Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugfix: reorder paginated queries #348

Merged
merged 2 commits into from
Mar 7, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions storage/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,13 @@ func (c *StorageClient) withTotalCount(ctx context.Context, sql string, args ...
if len(args) < 2 {
return nil, fmt.Errorf("list queries must have at least two params (limit and offset)")
}
rows, err := c.db.Query(
ctx,
sql,
args...,
)
if err != nil {
return nil, err
}

// A note on ordering: We query the totalCount before querying for the rows in order to
// avoid deadlocks. The row returned by the totalCount query is Scan-ed immediately
// and thus the underlying db connection is also released. However, the `rows` are
// `Scan`-ed in the calling function, which means that the underlying db connection is
// held (and unavailable to other goroutines) in the meantime.
limit := args[len(args)-2]
args[len(args)-2] = maxTotalCount + 1 // limit
Andrew7234 marked this conversation as resolved.
Show resolved Hide resolved
if err := c.db.QueryRow(
ctx,
Expand All @@ -133,6 +131,16 @@ func (c *StorageClient) withTotalCount(ctx context.Context, sql string, args ...
return nil, wrapError(err)
}

args[len(args)-2] = limit
rows, err := c.db.Query(
ctx,
sql,
args...,
)
if err != nil {
return nil, err
}

clipped := totalCount == maxTotalCount+1
Andrew7234 marked this conversation as resolved.
Show resolved Hide resolved
if clipped {
totalCount = maxTotalCount
Expand Down