Skip to content

[#514] Preserve SleekDB criteria state across paginator count#515

Merged
armanist merged 3 commits into
softberg:masterfrom
armanist:issue/514-sleekdb-paginator-state
May 13, 2026
Merged

[#514] Preserve SleekDB criteria state across paginator count#515
armanist merged 3 commits into
softberg:masterfrom
armanist:issue/514-sleekdb-paginator-state

Conversation

@armanist
Copy link
Copy Markdown
Member

@armanist armanist commented May 13, 2026

Fixes #514

Summary by CodeRabbit

  • Bug Fixes

    • Fixed a regression in pagination where applied query criteria could be inadvertently cleared before a subsequent paginated data fetch on the same model instance.
  • Tests

    • Added comprehensive unit test coverage to verify that query criteria persist correctly and reliably across pagination operations, including tests for chained and grouped criteria scenarios.

Review Change Stack

@armanist armanist added the bug Something isn't working label May 13, 2026
@armanist armanist added this to the 3.0.0 milestone May 13, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 49b60554-68f9-46b4-bd47-48171ce4ccd8

📥 Commits

Reviewing files that changed from the base of the PR and between 432b88d and 65516e5.

📒 Files selected for processing (2)
  • src/Paginator/Adapters/ModelPaginator.php
  • tests/Unit/Database/Adapters/Sleekdb/Statements/ResultSleekTest.php

📝 Walkthrough

Walkthrough

This PR fixes a SleekDB paginator regression where calling count() would reset the query builder state, causing subsequent paginated fetches on the same model to lose applied criteria. The fix clones the model before counting to isolate the total calculation from the original query state.

Changes

SleekDB Criteria Preservation in Pagination

Layer / File(s) Summary
ModelPaginator cloned counting to preserve builder state
src/Paginator/Adapters/ModelPaginator.php, CHANGELOG.md
ModelPaginator::__construct() now clones the model and builder before computing $total via a new getCountFromClonedModel() helper, preventing the count operation from resetting criteria that are later used by data(). Imports ModelException and updates docblocks. Regression fix documented in changelog.
Test validation of criteria persistence
tests/Unit/Database/Adapters/Sleekdb/Statements/ResultSleekTest.php
Adds three unit tests validating that criteria remain intact: after criteria()->count()->orderBy()->get(), after criteria()->orderBy()->paginate(), and across grouped criterias in both paginate()->total() and paginate()->data() calls. Imports TestEventModel for test data.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • charoyan88
  • hatik92
  • Arno2005
  • andrey-smaelov

Poem

🐰 A paginator's count once broke the state,
Criteria lost, the data came too late—
Now cloned builders keep the filters tight,
Pagination flows with filters in sight! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Preserve SleekDB criteria state across paginator count' accurately summarizes the main fix: preventing criteria loss when SleekDB's paginator calls count().
Linked Issues check ✅ Passed The PR addresses all key objectives from issue #514: modifying count logic to preserve criteria state in paginator, adding unit tests for filtered queries with paginate()+data(), and covering grouped criteria scenarios.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the SleekDB paginator criteria state issue: test coverage, changelog entry, and the ModelPaginator helper method.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@armanist armanist requested a review from andrey-smaelov May 13, 2026 08:43
@codecov
Copy link
Copy Markdown

codecov Bot commented May 13, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.87%. Comparing base (47b3301) to head (65516e5).

Additional details and impacted files
@@            Coverage Diff            @@
##             master     #515   +/-   ##
=========================================
  Coverage     90.87%   90.87%           
- Complexity     3069     3070    +1     
=========================================
  Files           263      263           
  Lines          8096     8100    +4     
=========================================
+ Hits           7357     7361    +4     
  Misses          739      739           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 432b88d79d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/Database/Adapters/Sleekdb/Statements/Result.php Outdated
Copy link
Copy Markdown

@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.

🧹 Nitpick comments (2)
src/Database/Adapters/Sleekdb/Statements/Result.php (1)

131-135: ⚡ Quick win

Consider adding an explanatory comment for the cloning approach.

The cloning strategy differs from the try/finally pattern used in get(), findOne(), findOneBy(), and first(). Adding a brief inline comment explaining why cloning is necessary here (to preserve criteria state for subsequent operations like pagination) would help future maintainers understand the design decision.

📝 Suggested comment addition
 public function count(): int
 {
+    // Clone to preserve original criteria state for subsequent operations (e.g., paginate()->data())
+    // Nulling queryBuilder ensures getBuilder() reconstructs a fresh builder with preserved criteria
     $counter = clone $this;
     $counter->queryBuilder = null;
     $counter->builderPrepared = false;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Database/Adapters/Sleekdb/Statements/Result.php` around lines 131 - 135,
Add a brief inline comment above the cloning block that explains why clone $this
is used instead of the try/finally pattern: note that cloning preserves the
original Result instance's query/criteria state while allowing
$counter->queryBuilder = null and $counter->builderPrepared = false to be
modified for a count operation via
fetchFilteredResultsFromBuilder($counter->getBuilder()), which avoids altering
state needed by methods like get(), findOne(), findOneBy(), and first() (use the
symbols clone $this, $counter, fetchFilteredResultsFromBuilder, get, findOne,
findOneBy, first in the comment).
tests/Unit/Database/Adapters/Sleekdb/Statements/ResultSleekTest.php (1)

90-119: ⚡ Quick win

Consider adding test coverage for grouped OR criteria.

The tests validate that basic criteria() chains are preserved across count() and paginate() workflows. However, the PR objectives specifically mention testing "grouped OR criteria via criterias([...], [...]) to ensure filters persist and no stale builder side effects occur."

Adding a test case that uses criterias() with multiple grouped conditions would provide more comprehensive validation of the fix.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/Unit/Database/Adapters/Sleekdb/Statements/ResultSleekTest.php` around
lines 90 - 119, Add a test that exercises grouped OR criteria using the
criterias([...], [...]) API and asserts those grouped filters persist across
count() and paginate() calls: instantiate the model (e.g., TestEventModel or
SleekDbal), apply criterias with two grouped condition arrays (one group AND,
the other OR), call count() and then paginate() (or get()) and assert the
returned count and paginated results match the expected filtered set and
ordering (use criterias, count, paginate, orderBy, get and
model/TestEventModel/SleekDbal to locate where to add the test).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/Database/Adapters/Sleekdb/Statements/Result.php`:
- Around line 131-135: Add a brief inline comment above the cloning block that
explains why clone $this is used instead of the try/finally pattern: note that
cloning preserves the original Result instance's query/criteria state while
allowing $counter->queryBuilder = null and $counter->builderPrepared = false to
be modified for a count operation via
fetchFilteredResultsFromBuilder($counter->getBuilder()), which avoids altering
state needed by methods like get(), findOne(), findOneBy(), and first() (use the
symbols clone $this, $counter, fetchFilteredResultsFromBuilder, get, findOne,
findOneBy, first in the comment).

In `@tests/Unit/Database/Adapters/Sleekdb/Statements/ResultSleekTest.php`:
- Around line 90-119: Add a test that exercises grouped OR criteria using the
criterias([...], [...]) API and asserts those grouped filters persist across
count() and paginate() calls: instantiate the model (e.g., TestEventModel or
SleekDbal), apply criterias with two grouped condition arrays (one group AND,
the other OR), call count() and then paginate() (or get()) and assert the
returned count and paginated results match the expected filtered set and
ordering (use criterias, count, paginate, orderBy, get and
model/TestEventModel/SleekDbal to locate where to add the test).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ac83240b-0fbf-4f7e-83ae-9bffa4ead722

📥 Commits

Reviewing files that changed from the base of the PR and between 47b3301 and 432b88d.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • src/Database/Adapters/Sleekdb/Statements/Result.php
  • tests/Unit/Database/Adapters/Sleekdb/Statements/ResultSleekTest.php

@armanist armanist merged commit ac34323 into softberg:master May 13, 2026
7 checks passed
@armanist armanist deleted the issue/514-sleekdb-paginator-state branch May 13, 2026 11:14
@armanist armanist restored the issue/514-sleekdb-paginator-state branch May 13, 2026 11:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SleekDB paginator drops query criteria after count() due to builder reset in #508

2 participants