Skip to content

Conversation

@fogelito
Copy link
Contributor

@fogelito fogelito commented Jun 30, 2025

Summary by CodeRabbit

  • Refactor

    • Streamlined pagination and ordering logic for database queries to provide consistent behavior with cursors and custom order attributes.
  • Bug Fixes

    • Enforced unique ordering attributes in queries to prevent duplicate results.
    • Added validation to ensure all necessary cursor values are present during pagination.
  • Chores

    • Removed unused code and improved internal logic for enhanced performance and clarity.
  • Tests

    • Added tests verifying multi-attribute ordering and cursor-based pagination for accurate sorting and result retrieval.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 30, 2025

"""

Walkthrough

The changes refactor the cursor-based pagination and ordering logic in the MariaDB and Postgres database adapters, simplifying and unifying the construction of pagination WHERE clauses. The main Database class is updated to set a default cursor direction, ensure unique ordering by appending a sequence attribute if necessary, and validate cursor completeness. Additionally, new tests verify multi-attribute ordering and cursor pagination behavior.

Changes

File(s) Change Summary
src/Database/Adapter/MariaDB.php Refactored find method: removed unused imports and flags, unified pagination WHERE clause construction by accumulating conditions for all order attributes, removed special cases and fallback ordering.
src/Database/Adapter/Postgres.php Refactored find method: removed unused imports and special cases, introduced uniform pagination WHERE clause construction with combined conditions for order attributes, simplified order direction handling.
src/Database/Database.php Added default cursor direction handling, enforced unique ordering by appending $sequence if missing, validated cursor completeness with exception throwing, and added OrderException import.
tests/e2e/Adapter/Scopes/DocumentTests.php Extended testFindOrderByCursorAfter to test multi-attribute ordering and cursor pagination, including assertions on returned documents and cursor behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Database
    participant Adapter

    Client->>Database: find(collection, queries, forPermission)
    Database->>Database: Set default cursor direction if not provided
    Database->>Database: Ensure unique order attribute (append $sequence if missing)
    Database->>Database: Validate cursor completeness (throw OrderException if missing)
    Database->>Adapter: find(..., cursorDirection, ...)
    Adapter->>Adapter: Build uniform pagination WHERE clause based on order attributes and cursor
    Adapter-->>Database: Return results
    Database-->>Client: Return results
Loading

Poem

In the warren of code, the queries hop,
Pagination logic gets a tidy mop.
No more tangled branches, just a single flow,
Cursors and orders now simply go.
With sequence and order, results align,
A rabbit’s delight—database refined! 🐇✨
"""


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f73b597 and 376f0e9.

📒 Files selected for processing (1)
  • tests/e2e/Adapter/Scopes/DocumentTests.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/e2e/Adapter/Scopes/DocumentTests.php
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Adapter Tests (SharedTables/Postgres)
  • GitHub Check: Adapter Tests (SharedTables/SQLite)
  • GitHub Check: Adapter Tests (MySQL)
  • GitHub Check: Adapter Tests (SharedTables/MySQL)
  • GitHub Check: Adapter Tests (Mirror)
  • GitHub Check: Adapter Tests (SharedTables/MariaDB)
  • GitHub Check: Adapter Tests (SQLite)
  • GitHub Check: Adapter Tests (MariaDB)
  • GitHub Check: Adapter Tests (Pool)
  • GitHub Check: Adapter Tests (Postgres)
  • GitHub Check: Unit Test
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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
Contributor

@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.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7dff6b6 and 3dcc906.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • src/Database/Adapter/MariaDB.php (2 hunks)
  • src/Database/Adapter/Postgres.php (1 hunks)
  • src/Database/Database.php (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/Database/Adapter/MariaDB.php (6)
src/Database/Adapter/SQL.php (2)
  • getInternalKeyForAttribute (1712-1724)
  • getSQLOperator (1432-1458)
src/Database/Adapter.php (2)
  • filter (1105-1114)
  • quote (447-447)
src/Database/Database.php (1)
  • Database (35-6790)
src/Database/Adapter/Postgres.php (1)
  • quote (2007-2010)
src/Database/Adapter/Pool.php (1)
  • quote (118-121)
src/Database/Query.php (1)
  • Query (8-730)
src/Database/Database.php (2)
src/Database/Exception.php (1)
  • Exception (7-21)
src/Database/Document.php (1)
  • getAttribute (212-219)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup & Build Docker Image
🔇 Additional comments (7)
src/Database/Database.php (5)

16-16: LGTM: Necessary import for cursor validation.

The OrderException import is correctly added to support the new cursor validation logic introduced in the find method.


6018-6019: LGTM: Appropriate default cursor direction.

Setting Database::CURSOR_AFTER as the default cursor direction when none is provided ensures consistent pagination behavior and centralizes the default logic in the main Database class rather than leaving it to individual adapters.


6020-6029: LGTM: Essential unique ordering enforcement.

This logic ensures that pagination results have deterministic ordering by requiring either $id or $sequence in the order attributes. Appending $sequence when no unique attribute is present is a solid approach that guarantees consistent pagination behavior across different queries.


6031-6040: LGTM: Robust cursor validation.

The validation ensures that the cursor document contains non-null values for all order attributes, which is essential for accurate cursor-based pagination. The use of OrderException with both a descriptive message and the specific attribute name provides good debugging information.

The logic correctly handles the case where $sequence might be dynamically added to the order attributes, ensuring the cursor validation is comprehensive.


6108-6108: LGTM: Explicit cursor direction parameter.

Passing the cursor direction explicitly to the adapter method call ensures that the centralized logic in the Database class takes precedence over any adapter-specific defaults, which aligns with the overall refactoring goals mentioned in the summary.

src/Database/Adapter/MariaDB.php (1)

1519-1568: Well-implemented cursor pagination logic.

The refactored cursor pagination implementation correctly:

  • Handles multiple order attributes with proper equality conditions for preceding attributes
  • Reverses sort direction appropriately for CURSOR_BEFORE
  • Builds the WHERE clause with proper OR conditions for cursor-based pagination
  • Uses parameterized queries with unique bind names to prevent conflicts

This unified approach simplifies the logic and makes it more maintainable.

src/Database/Adapter/Postgres.php (1)

1401-1450: Consistent cursor pagination implementation across adapters.

The Postgres adapter implementation correctly mirrors the MariaDB approach, ensuring consistent behavior across different database backends. The cursor pagination logic properly handles:

  • Multiple order attributes with appropriate conditions
  • Direction reversal for CURSOR_BEFORE
  • Proper parameter binding with unique names
  • Postgres-specific quoting

This unified approach improves code maintainability and reduces the likelihood of adapter-specific bugs.

Copy link
Contributor

@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.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0e71cd and f73b597.

📒 Files selected for processing (2)
  • src/Database/Adapter/MariaDB.php (1 hunks)
  • tests/e2e/Adapter/Scopes/DocumentTests.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Database/Adapter/MariaDB.php
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: ArnabChatterjee20k
PR: utopia-php/database#613
File: src/Database/Adapter/Postgres.php:1254-1319
Timestamp: 2025-07-01T11:31:37.438Z
Learning: In PostgreSQL adapter methods like getUpsertStatement, complexity for database-specific SQL generation is acceptable when the main business logic is properly separated in the parent SQL adapter class, following the adapter pattern where each database adapter handles its own SQL syntax requirements.
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Adapter Tests (Postgres)
  • GitHub Check: Adapter Tests (Pool)
  • GitHub Check: Adapter Tests (SharedTables/MariaDB)
  • GitHub Check: Adapter Tests (SharedTables/Postgres)
  • GitHub Check: Adapter Tests (SharedTables/SQLite)
  • GitHub Check: Adapter Tests (SharedTables/MySQL)
  • GitHub Check: Adapter Tests (MariaDB)
  • GitHub Check: Adapter Tests (Mirror)
  • GitHub Check: Adapter Tests (MySQL)
  • GitHub Check: Adapter Tests (SQLite)
  • GitHub Check: Unit Test
🔇 Additional comments (1)
tests/e2e/Adapter/Scopes/DocumentTests.php (1)

1904-1951: Well-structured test for multi-attribute ordering and cursor pagination.

This test effectively validates:

  • Multi-attribute ordering (year ascending, then price ascending) works correctly
  • The expected sort order of movies is maintained
  • Cursor pagination (cursorAfter) functions properly with multi-attribute ordering
  • The correct subset of documents is returned after a cursor position

The test coverage aligns well with the cursor pagination refactoring mentioned in the PR objectives and provides good validation for the enhanced cursor logic.

@abnegate abnegate merged commit eb2f759 into main Jul 2, 2025
15 checks passed
@abnegate abnegate deleted the fix-cursor branch July 2, 2025 16:37
@coderabbitai coderabbitai bot mentioned this pull request Jul 6, 2025
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.

3 participants