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 : introduce criteriagroup for searching #1605

Merged
merged 1 commit into from
Dec 28, 2024
Merged

Conversation

rajadilipkolli
Copy link
Owner

@rajadilipkolli rajadilipkolli commented Dec 28, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced search functionality with support for complex query criteria
    • Added ability to combine search criteria using logical operators (AND/OR)
    • Introduced more flexible search request handling
  • Improvements

    • Updated search specification builder to support advanced querying
    • Improved type conversion and criteria validation
    • Enhanced JSON serialization for search criteria
  • Tests

    • Added new test cases for advanced search scenarios
    • Implemented comprehensive testing for new search functionality
  • Chores

    • Updated Spring Boot parent version from 3.4.1 to 3.4.0

Copy link
Contributor

coderabbitai bot commented Dec 28, 2024

Walkthrough

This pull request introduces a comprehensive enhancement to the keyset pagination and query specification system. The changes focus on creating a more flexible and robust search criteria mechanism by introducing an ISearchCriteria interface, a new CriteriaGroup class, and modifying existing classes to support complex, nested query logic. The modifications allow for more advanced query construction, supporting logical grouping of search criteria with AND/OR operators, and improve the overall extensibility of the search functionality.

Changes

File Change Summary
pom.xml Downgraded Spring Boot parent version from 3.4.1 to 3.4.0
model/query/CriteriaGroup.java New class implementing ISearchCriteria for logical grouping of search criteria
model/query/ISearchCriteria.java New interface with Jackson annotations for polymorphic serialization
model/query/SearchCriteria.java Updated to implement ISearchCriteria, added toSpecification() method
model/query/SearchRequest.java Updated to use List<ISearchCriteria> instead of List<SearchCriteria>
services/EntitySpecification.java Refactored to work with ISearchCriteria and CriteriaGroup
test/CriteriaGroupTest.java New test class for JSON serialization of CriteriaGroup
test/EntitySpecificationTest.java Updated to use CriteriaGroup in test scenarios
test/AnimalControllerIT.java Added test for complex AND/OR criteria group search

Sequence Diagram

sequenceDiagram
    participant Client
    participant SearchRequest
    participant EntitySpecification
    participant CriteriaGroup
    participant SearchCriteria

    Client->>SearchRequest: Create with search criteria
    SearchRequest->>EntitySpecification: Build specification
    EntitySpecification->>CriteriaGroup: Process criteria group
    CriteriaGroup->>SearchCriteria: Convert individual criteria
    SearchCriteria-->>EntitySpecification: Generate predicates
    EntitySpecification-->>Client: Return filtered results
Loading

Possibly related PRs

Suggested labels

component: keyset-pagination-data-jpa

Poem

🐰 Hop, hop, through queries we dance,
Criteria grouped with logical stance,
AND and OR, our new delight,
Searching data with rabbit might!
Flexibility springs, our code takes flight! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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>, please review it.
    • 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 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 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 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. (Beta)
  • @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.

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.

@rajadilipkolli rajadilipkolli self-assigned this Dec 28, 2024
@github-actions github-actions bot added type: dependency-upgrade Pull requests that update a dependency file component: keyset-pagination-data-jpa labels Dec 28, 2024
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: 2

🧹 Nitpick comments (7)
jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/services/EntitySpecification.java (2)

22-28: Consider returning a typed specification.
The specificationBuilder method currently returns a raw Specification, potentially sacrificing type safety. Using Specification<T> instead of an unparameterized type strengthens compile-time checks and improves readability.

- public Specification specificationBuilder(List<ISearchCriteria> searchCriteriaList, Class<T> entityClass) {
+ public Specification<T> specificationBuilder(List<ISearchCriteria> searchCriteriaList, Class<T> entityClass) {

50-53: Simple and effective validation.
Throwing an IllegalArgumentException for invalid fields is straightforward. Optionally, you may wish to include the entity class name in the error message for more context.

- throw new IllegalArgumentException("Invalid field: " + fieldName);
+ throw new IllegalArgumentException("Invalid field '" + fieldName + "' in entity " + entityClass.getName());
jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/model/query/CriteriaGroupTest.java (1)

1-33: Solid JSON serialization test.
This test verifies basic serialization correctly. Consider adding further test cases for multiple nested criteria or different operators to ensure comprehensive coverage.

jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/CriteriaGroup.java (2)

13-16: Avoid silent failures in the constructor.
If either the operator or criteriaList is null, the subsequent usage (e.g., in toSpecification()) could fail. Consider throwing an IllegalArgumentException or similar if invalid arguments are provided.


22-25: Consider stricter immutability.
The setter pattern is acceptable, but for a domain object representing criteria, immutability can reduce bug surfaces. An alternative would be to create new instances whenever the operator or criteria list changes.

jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/repository/EntitySpecificationTest.java (1)

169-176: Comprehensive AND-criteria test.
These assertions confirm that the query logic for two SearchCriteria objects joined by AND returns exactly one matching animal. This validates proper integration with CriteriaGroup. To further improve test coverage, consider adding edge cases where the criteria list is empty or partially null.

jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/web/controllers/AnimalControllerIT.java (1)

477-477: Optional: unify JSON request structure.
Including "type": "criteria" might be helpful for clarity, but ensure consistent usage throughout the test suite so future maintainers easily recognize the format.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 314c1b9 and 22b0d44.

📒 Files selected for processing (9)
  • jpa/keyset-pagination/boot-data-window-pagination/pom.xml (1 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/CriteriaGroup.java (1 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/ISearchCriteria.java (1 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/SearchCriteria.java (2 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/SearchRequest.java (1 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/services/EntitySpecification.java (2 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/model/query/CriteriaGroupTest.java (1 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/repository/EntitySpecificationTest.java (2 hunks)
  • jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/web/controllers/AnimalControllerIT.java (2 hunks)
🧰 Additional context used
📓 Learnings (1)
jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/services/EntitySpecification.java (1)
Learnt from: rajadilipkolli
PR: rajadilipkolli/my-spring-boot-experiments#1544
File: jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/services/EntitySpecification.java:29-38
Timestamp: 2024-12-03T09:06:24.894Z
Learning: In `EntitySpecification.specificationBuilder()` method within `EntitySpecification.java`, the `searchCriteriaList` is validated through `SearchCriteria`, ensuring it cannot be null or empty. Therefore, additional null or empty checks in `specificationBuilder()` are unnecessary.
🔇 Additional comments (13)
jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/services/EntitySpecification.java (3)

3-4: Imports look fine.
No issues spotted in these import statements.


31-36: Metadata validation logic appears consistent with retrieved learnings.
As per previous learnings, the searchCriteriaList validation is already handled, so additional null/empty checks are unnecessary. No issues found here.


40-45: Be mindful of nested CriteriaGroups.
This recursive approach processes nested groups effectively. However, if CriteriaGroup objects end up referencing each other in a loop, there’s a potential for infinite recursion. Consider implementing cycle checks if cyclical references are possible.

jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/SearchCriteria.java (3)

3-18: Interface implementation and imports look good.
Implementing ISearchCriteria<T> and these imports are aligned with the new design.


63-136: Extensive operator handling in toSpecification().
The switch statement covers a wide range of operators thoroughly. The fallback to default throwing an IllegalArgumentException is good defensive coding.


138-167: Robust type conversion logic.
The convertToType method supports many common types. The exception thrown on invalid/unrecognized types is appropriate.

jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/ISearchCriteria.java (1)

1-20: New interface for polymorphic search criteria.
This JSON-annotated interface nicely supports both CriteriaGroup and SearchCriteria.

jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/SearchRequest.java (1)

8-8: Flexibility improvement with List<ISearchCriteria>.
Switching to the interface-based list broadens applicability for future custom criteria. The constructor’s null checks are thoughtful.

Also applies to: 16-16, 21-21, 25-25

jpa/keyset-pagination/boot-data-window-pagination/src/main/java/com/example/keysetpagination/model/query/CriteriaGroup.java (2)

8-9: Clarify defaults or constraints for operator and criteriaList.
Currently, if a new CriteriaGroup is created without initializing the operator or criteriaList, it may produce unexpected behavior in toSpecification(). Consider adding validations or defaults (e.g., a default operator or an empty list) to avoid potential null pointer issues.


31-34: Validate non-empty criteriaList.
When empty, toSpecification() could lead to an IndexOutOfBoundsException. Consider returning a Specification that always evaluates to true/false for an empty list, or handle it gracefully.

jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/repository/EntitySpecificationTest.java (1)

9-9: Good usage of CriteriaGroup import.
Importing CriteriaGroup helps unify the testing of combined search criteria.

jpa/keyset-pagination/boot-data-window-pagination/src/test/java/com/example/keysetpagination/web/controllers/AnimalControllerIT.java (1)

585-634: Excellent complex query testing.
This test correctly verifies nested grouping (AND containing an OR group). It ensures that combining CriteriaGroup objects works end-to-end through the controller layer. If possible, add a negative test scenario (e.g., a habitat that doesn't exist) to confirm no records are returned.

jpa/keyset-pagination/boot-data-window-pagination/pom.xml (1)

10-10: Verify Maven dependency compatibility after version downgrade.
Downgrading from 3.4.1 to 3.4.0 may affect plugin or transitive dependencies. Ensure that no feature from 3.4.1 is required elsewhere.

✅ Verification successful

Let me analyze the version usage in the codebase to verify the impact of downgrading from 3.4.1 to 3.4.0.


Let me check the dependencies and configuration in the specific project to understand the impact.


Spring Boot 3.4.0 version is compatible with project dependencies

The downgrade from 3.4.1 to 3.4.0 is safe for the following reasons:

  • The project uses standard Spring Boot starters (web, data-jpa, actuator, etc.) which are compatible across minor versions
  • Third-party dependency versions used (springdoc-openapi 2.7.0, datasource-micrometer-boot 1.0.6) work with both Spring Boot 3.4.0 and 3.4.1
  • No usage of features specific to 3.4.1 was found in the codebase
  • The project includes Spring Milestones repository, indicating it's prepared for milestone/RC versions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the codebase for explicit references to Spring Boot version 3.4.1 or features introduced after 3.4.0
rg "3.4.1"

Length of output: 66506


Script:

#!/bin/bash
# Check for any Spring Boot version references in pom.xml files
rg -t xml "<version>3\.4\." -g "pom.xml"

# Check for any Spring Boot parent version references
rg -t xml "<spring.boot.version>3\.4\." -g "pom.xml"
rg -t xml "<spring-boot.version>3\.4\." -g "pom.xml"

# Check the parent pom if it exists
fd "^parent.pom.xml$" --exec cat {}

Length of output: 2736


Script:

#!/bin/bash
# Check the full pom.xml content of the project
cat jpa/keyset-pagination/boot-data-window-pagination/pom.xml

# Check for any Spring Boot specific imports or configurations
rg -t java "org.springframework.boot" jpa/keyset-pagination/boot-data-window-pagination/

Length of output: 19229

Comment on lines +169 to +182
private Predicate combinePredicates(
List<Object> values,
Function<Object, Predicate> predicateFunction,
BiFunction<Predicate, Predicate, Predicate> combiner) {
if (values.size() == 1) {
return predicateFunction.apply(values.getFirst());
}
return values.stream()
.map(predicateFunction)
.reduce(combiner::apply)
.orElseThrow(() -> new IllegalArgumentException(
String.format("No predicates could be generated from values: %s", values)));
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Likely bug in single-value predicate creation.
Line 174 uses values.getFirst(), but List in Java has no getFirst() method. This should be values.get(0) unless a custom List implementation provides it. This can cause a runtime error.

- return predicateFunction.apply(values.getFirst());
+ return predicateFunction.apply(values.get(0));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private Predicate combinePredicates(
List<Object> values,
Function<Object, Predicate> predicateFunction,
BiFunction<Predicate, Predicate, Predicate> combiner) {
if (values.size() == 1) {
return predicateFunction.apply(values.getFirst());
}
return values.stream()
.map(predicateFunction)
.reduce(combiner::apply)
.orElseThrow(() -> new IllegalArgumentException(
String.format("No predicates could be generated from values: %s", values)));
}
private Predicate combinePredicates(
List<Object> values,
Function<Object, Predicate> predicateFunction,
BiFunction<Predicate, Predicate, Predicate> combiner) {
if (values.size() == 1) {
return predicateFunction.apply(values.get(0));
}
return values.stream()
.map(predicateFunction)
.reduce(combiner::apply)
.orElseThrow(() -> new IllegalArgumentException(
String.format("No predicates could be generated from values: %s", values)));
}

Comment on lines +36 to +52
@Override
public Specification<?> toSpecification() {
List<Specification> specs =
criteriaList.stream().map(ISearchCriteria::toSpecification).toList();

Specification result = specs.getFirst();
for (int i = 1; i < specs.size(); i++) {
if (getOperator() == QueryOperator.AND) {
result = result.and(specs.get(i));
} else if (getOperator() == QueryOperator.OR) {
result = result.or(specs.get(i));
} else {
throw new UnsupportedOperationException("Operator not supported in group: " + operator);
}
}
return result;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent possible IndexOutOfBoundsException in specs.getFirst().

  1. If criteriaList is empty, then specs is empty too, and specs.getFirst() is not a standard Java List method unless you rely on a specific library extension. Double-check the utility used here.
  2. If specs is from a standard List, you probably need specs.get(0) instead.
  3. Consider returning a no-op specification when empty instead of throwing a runtime error.
- Specification result = specs.getFirst();
+ if (specs.isEmpty()) {
+     return (root, query, cb) -> cb.conjunction();
+ }
+ Specification result = specs.get(0);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public Specification<?> toSpecification() {
List<Specification> specs =
criteriaList.stream().map(ISearchCriteria::toSpecification).toList();
Specification result = specs.getFirst();
for (int i = 1; i < specs.size(); i++) {
if (getOperator() == QueryOperator.AND) {
result = result.and(specs.get(i));
} else if (getOperator() == QueryOperator.OR) {
result = result.or(specs.get(i));
} else {
throw new UnsupportedOperationException("Operator not supported in group: " + operator);
}
}
return result;
}
@Override
public Specification<?> toSpecification() {
List<Specification> specs =
criteriaList.stream().map(ISearchCriteria::toSpecification).toList();
if (specs.isEmpty()) {
return (root, query, cb) -> cb.conjunction();
}
Specification result = specs.get(0);
for (int i = 1; i < specs.size(); i++) {
if (getOperator() == QueryOperator.AND) {
result = result.and(specs.get(i));
} else if (getOperator() == QueryOperator.OR) {
result = result.or(specs.get(i));
} else {
throw new UnsupportedOperationException("Operator not supported in group: " + operator);
}
}
return result;
}

@rajadilipkolli rajadilipkolli merged commit 40f6b30 into main Dec 28, 2024
8 of 9 checks passed
@rajadilipkolli rajadilipkolli deleted the windows-group branch December 28, 2024 12:25
Copy link

Qodana Community for JVM

102 new problems were found

Inspection name Severity Problems
Unchecked warning 🔶 Warning 36
@NotNull/@Nullable problems 🔶 Warning 30
'equals()' method which does not check class of parameter 🔶 Warning 21
Nullability and data flow problems 🔶 Warning 3
Field can be local 🔶 Warning 3
Declaration has problems in Javadoc references 🔶 Warning 2
AutoCloseable used without 'try'-with-resources 🔶 Warning 1
Class is exposed outside of its visibility scope 🔶 Warning 1
Default annotation parameter value 🔶 Warning 1
Javadoc declaration problems 🔶 Warning 1
Mismatched query and update of collection 🔶 Warning 1
Optional.get() is called without isPresent() check 🔶 Warning 1
Commented out code ◽️ Notice 1

☁️ View the detailed Qodana report

Contact Qodana team

Contact us at [email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant