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

feat(mongox): fix pagination #47

Merged
merged 2 commits into from
Aug 9, 2024
Merged

feat(mongox): fix pagination #47

merged 2 commits into from
Aug 9, 2024

Conversation

pyshx
Copy link
Collaborator

@pyshx pyshx commented Aug 9, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced pagination functionality with improved filter handling and sorting mechanisms.
    • Introduced a new method for retrieving documents based on cursor parameters.
  • Bug Fixes

    • Optimized pagination flow to ensure correct application of filters and sorting.
  • Tests

    • Added comprehensive test cases for validating cursor-based pagination scenarios.

@pyshx pyshx requested a review from rot1024 as a code owner August 9, 2024 10:01
Copy link

coderabbitai bot commented Aug 9, 2024

Walkthrough

The updates to the mongox/pagination.go file enhance pagination logic by refining filter handling and cursor management. A new helper function improves modularity, while tests for cursor-based pagination expand coverage and assert the correctness of various scenarios. Collectively, these changes bolster the clarity, functionality, and reliability of the pagination feature.

Changes

Files Change Summary
mongox/pagination.go Refactored Paginate and pageFilter methods for improved filter handling and sorting logic. Introduced getCursorDocument to enhance modularity. Adjusted cursor handling to use After and Before parameters.
mongox/pagination_test.go Added TestClientCollection_DetailedPagination to validate various cursor-based pagination scenarios, ensuring robustness through comprehensive test coverage.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Collection
    participant Database

    Client->>Collection: Request Paginate
    Collection->>Collection: Generate Filters
    Collection->>Collection: Determine Sort Order
    Collection->>Database: Execute Query with Filters and Sort
    Database-->>Collection: Return Paginated Results
    Collection-->>Client: Send Paginated Data
Loading

🐇 In fields so green, I hop and play,
With filters and sorts, we pave the way.
Pagination's dance is a joyful surprise,
Through data we leap, oh how time flies!
With tests all around, our code shines bright,
Hooray for the changes that feel just right! 🥕


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 586dfb9 and a124646.

Files selected for processing (2)
  • mongox/pagination.go (4 hunks)
  • mongox/pagination_test.go (1 hunks)
Additional comments not posted (7)
mongox/pagination.go (6)

20-24: Ensure error handling is comprehensive.

The error handling for the pageFilter method call looks good. Ensure that all potential errors are covered and that the context is appropriately used for error reporting.


30-37: Clarify sort key and order logic.

The logic for determining the sortKey and sortOrder is clear and handles the Reverted flag well. Ensure that this logic aligns with the expected behavior of the pagination feature.


71-71: Ensure cursor swap logic is correct.

The logic for swapping startCursor and endCursor when reversing items is correct. Ensure that this behavior is intended and tested.


237-299: Review pageFilter logic for correctness.

The pageFilter method has been updated to return a bson.M type, improving type safety. The logic for constructing the filter based on the cursor and sort order is sound. Ensure that the filter logic aligns with the expected pagination behavior.


301-307: Review new helper function getCursorDocument.

The getCursorDocument function encapsulates the logic for retrieving a document based on the cursor. This improves modularity and readability. Ensure that error handling covers all potential failure points.


39-41: Verify cursor handling logic.

The logic for reversing the sort order when p.Cursor.Last is present is correct. Verify that this logic is consistent with the rest of the pagination implementation.

Verification successful

Cursor handling logic is consistent.

The logic for reversing the sort order when p.Cursor.Last is present is consistently applied across the pagination implementation in mongox/pagination.go. This includes reversing the sort order, reversing items, and determining pagination limits. The handling of p.Cursor.Last is coherent with the intended pagination behavior.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify cursor handling logic consistency in the codebase.

# Test: Search for references to `p.Cursor.Last`. Expect: Consistent handling of cursor logic.
rg --type go 'p\.Cursor\.Last'

Length of output: 516


Script:

#!/bin/bash
# Extract more context around each occurrence of `p.Cursor.Last` to verify the logic.
rg --type go 'p\.Cursor\.Last' -A 3 -B 3

Length of output: 1956

mongox/pagination_test.go (1)

341-433: Comprehensive test coverage for pagination.

The TestClientCollection_DetailedPagination function provides extensive test coverage for various cursor-based pagination scenarios. The use of seeded data and multiple test cases ensures robustness. Ensure that the test cases cover all edge cases and expected behaviors.

Comment on lines +43 to +49
findOpts := options.Find().
SetSort(bson.D{{Key: sortKey, Value: sortOrder}, {Key: idKey, Value: sortOrder}}).
SetLimit(limit(*p))

if p.Offset != nil {
findOpts.SetSkip(p.Offset.Offset)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize find options configuration.

The findOpts configuration correctly sets sorting and limit options. Consider consolidating the logic for setting options to enhance readability and maintainability.

- findOpts := options.Find().
- 	SetSort(bson.D{{Key: sortKey, Value: sortOrder}, {Key: idKey, Value: sortOrder}}).
- 	SetLimit(limit(*p))
+ findOpts := options.Find().
+ 	SetSort(bson.D{{Key: sortKey, Value: sortOrder}, {Key: idKey, Value: sortOrder}}).
+ 	SetLimit(limit(*p))

if p.Offset != nil {
	findOpts.SetSkip(p.Offset.Offset)
}

Committable suggestion was skipped due to low confidence.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a124646 and 6328ffb.

Files selected for processing (1)
  • mongox/pagination.go (6 hunks)
Additional comments not posted (3)
mongox/pagination.go (3)

20-24: Approve the use of pageFilter.

The use of c.pageFilter improves type safety and clarity in filter handling.


43-49: Optimize find options configuration.

The findOpts configuration correctly sets sorting and limit options. Consider consolidating the logic for setting options to enhance readability and maintainability.


273-279: Approve the addition of getCursorDocument.

The function encapsulates cursor retrieval logic, enhancing modularity and readability.

Comment on lines +209 to +270
func (c *Collection) pageFilter(ctx context.Context, p usecasex.Pagination, s *usecasex.Sort) (bson.M, error) {
if p.Cursor == nil {
return nil, nil
}

var filter bson.M
sortKey := idKey
sortOrder := 1

if s != nil && s.Key != "" {
sortKey = s.Key
if s.Reverted {
sortOrder = -1
}
}

var cursor *usecasex.Cursor
var op string
var cur *usecasex.Cursor

if p.Cursor.First != nil {
if p.Cursor.After != nil {
cursor = p.Cursor.After
op = "$gt"
cur = p.Cursor.After
} else if p.Cursor.Last != nil {
} else if p.Cursor.Before != nil {
cursor = p.Cursor.Before
op = "$lt"
cur = p.Cursor.Before
} else {
return nil, errors.New("neither first nor last are set")
}
if cur == nil {
return nil, nil
}

var sortKey *string
if s != nil {
sortKey = &s.Key
}
var paginationFilter bson.M
if sortKey == nil || *sortKey == "" {
paginationFilter = bson.M{idKey: bson.M{op: *cur}}
} else {
var cursorDoc bson.M
if err := c.collection.FindOne(ctx, bson.M{idKey: *cur}).Decode(&cursorDoc); err != nil {
return nil, fmt.Errorf("failed to find cursor element")
}

if cursorDoc[*sortKey] == nil {
return nil, fmt.Errorf("invalied sort key")
if cursor != nil {
cursorDoc, err := c.getCursorDocument(ctx, *cursor)
if err != nil {
return nil, err
}

paginationFilter = bson.M{
filter = bson.M{
"$or": []bson.M{
{*sortKey: bson.M{op: cursorDoc[*sortKey]}},
{sortKey: bson.M{op: cursorDoc[sortKey]}},
{
*sortKey: cursorDoc[*sortKey],
idKey: bson.M{op: *cur},
sortKey: cursorDoc[sortKey],
idKey: bson.M{op: cursorDoc[idKey]},
},
},
}

if sortOrder == -1 {
if op == "$gt" {
op = "$lt"
} else {
op = "$gt"
}
filter = bson.M{
"$or": []bson.M{
{sortKey: bson.M{op: cursorDoc[sortKey]}},
{
sortKey: cursorDoc[sortKey],
idKey: bson.M{op: cursorDoc[idKey]},
},
},
}
}
}

return paginationFilter, nil
return filter, nil
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize duplicated filter logic for reversed sort order.

The logic for creating the filter when the sort order is reversed is duplicated. Consider refactoring to reduce redundancy.

if cursor != nil {
    cursorDoc, err := c.getCursorDocument(ctx, *cursor)
    if err != nil {
        return nil, err
    }

    op1, op2 := op, "$lt"
    if sortOrder == -1 {
        op1, op2 = "$lt", "$gt"
    }

    filter = bson.M{
        "$or": []bson.M{
            {sortKey: bson.M{op1: cursorDoc[sortKey]}},
            {
                sortKey: cursorDoc[sortKey],
                idKey:   bson.M{op2: cursorDoc[idKey]},
            },
        },
    }
}

@pyshx pyshx merged commit e67ae6c into main Aug 9, 2024
2 checks passed
@pyshx pyshx deleted the fix/pagination-behaviour branch August 9, 2024 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant