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: implement QueryResult properly #19

Merged
merged 4 commits into from
Jun 13, 2024
Merged

feat: implement QueryResult properly #19

merged 4 commits into from
Jun 13, 2024

Conversation

EmilyMatt
Copy link
Contributor

@EmilyMatt EmilyMatt commented Jun 10, 2024

Some functionality was missing, also renamed from FalkorResponse to QueryResult and created a type alias to maintain BC

Summary by CodeRabbit

  • New Features

    • Added methods to retrieve specific statistics from query results, such as labels added, nodes created, properties set, etc.
    • Introduced a method to check if a query was executed from cache.
    • Introduced a method to retrieve the internal execution time of a query.
  • Refactor

    • Renamed FalkorResponse to QueryResult for consistency across modules.
    • Updated method signatures and return types to use QueryResult instead of FalkorResponse.

@EmilyMatt EmilyMatt added enhancement New feature or request rust Pull requests that update Rust code labels Jun 10, 2024
@EmilyMatt EmilyMatt requested a review from AviAvni June 10, 2024 15:25
@EmilyMatt EmilyMatt self-assigned this Jun 10, 2024
Copy link

coderabbitai bot commented Jun 10, 2024

Walkthrough

The changes introduce a new error variant StatisticNotFound to handle missing statistics in query results and rename FalkorResponse to QueryResult across multiple files for consistency. Methods have also been updated to return QueryResult instead of FalkorResponse, along with new methods for retrieving specific query execution statistics.

Changes

File/Path Change Summary
src/error/mod.rs Added StatisticNotFound variant to FalkorDBError enum.
src/graph/blocking.rs Updated method return types to QueryResult and removed import of ConstraintType.
src/graph/query_builder.rs Renamed return types and method signatures from FalkorResponse to QueryResult.
src/lib.rs Renamed FalkorResponse to QueryResult and added deprecation warning for FalkorResponse.
src/response/mod.rs Renamed FalkorResponse to QueryResult, added StatisticType enum, and new methods for statistics.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FalkorDB
    participant QueryEngine

    User->>FalkorDB: Execute query
    FalkorDB->>QueryEngine: Process query
    QueryEngine->>FalkorDB: Return QueryResult
    FalkorDB->>User: Return QueryResult with statistics
    Note over User, FalkorDB: If statistic not found, return StatisticNotFound error
Loading

Poem

In the land of Falkor's database,
A change has brought a smoother pace,
QueryResults now take the throne,
No more responses all alone.

Statistics gather, errors found,
New methods make the queries sound.
With every tweak, our system grows,
In the garden of code, it brightly glows! 🌷📚


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

@EmilyMatt EmilyMatt linked an issue Jun 10, 2024 that may be closed by this pull request
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: 2

Outside diff range and nitpick comments (2)
src/graph/blocking.rs (2)

117-121: Update the documentation to reflect the new return type.

The documentation for the query method still mentions FalkorResultSet which seems to be a leftover from the previous implementation. Please update it to LazyResultSet to match the new method signature.


137-137: Ensure consistency in documentation.

The documentation for the ro_query method does not specify the return type in the description. It would be beneficial for clarity to include that it returns a QueryBuilder object configured for a read-only query that will yield a QueryResult<LazyResultSet>.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between dabb41f and c53438c.

Files selected for processing (5)
  • src/error/mod.rs (1 hunks)
  • src/graph/blocking.rs (10 hunks)
  • src/graph/query_builder.rs (7 hunks)
  • src/lib.rs (2 hunks)
  • src/response/mod.rs (5 hunks)
Additional comments not posted (9)
src/lib.rs (2)

29-31: The deprecation notice is clear and provides a helpful migration path for users. Ensure that all documentation and examples in the repository are updated to reflect this change.


48-48: Exporting QueryResult here is consistent with the changes across the project. This centralizes the import paths for users, simplifying the usage of QueryResult across different modules.

src/error/mod.rs (1)

115-117: Adding the StatisticNotFound error variant is appropriate for handling cases where a requested statistic is not found. This aligns with the new functionalities related to statistics retrieval in QueryResult.

src/response/mod.rs (3)

18-44: The StatisticType enum is well-defined with clear serialization values for each statistic type. This will facilitate easy parsing and usage in logging or reporting features.


48-48: The QueryResult struct is well-structured to encapsulate the header, data, and statistics of a query response. This struct will centralize response handling and improve the maintainability of the code.


Line range hint 57-159: The methods for retrieving various statistics are correctly implemented using the get_statistics helper method. This approach reduces code duplication and enhances readability. Ensure that the error handling is robust, especially for parsing operations.

src/graph/query_builder.rs (2)

Line range hint 107-146: The updates to QueryBuilder to return QueryResult instead of FalkorResponse are consistent with the overall PR objectives. The handling of different response sizes with appropriate error messages is a good practice. Ensure that the error messages are clear and provide enough context for debugging.


Line range hint 294-313: The updates to ProcedureQueryBuilder to return QueryResult are well-implemented. The use of FalkorParsable for parsing the response ensures that the type constraints and parsing logic are centralized, which is beneficial for maintenance and consistency.

src/graph/blocking.rs (1)

277-278: Good use of type alias for clarity.

The method list_constraints correctly uses the QueryResult type in its signature, aligning with the rest of the changes in this PR. This is a good practice for maintaining consistency across the API.

src/graph/blocking.rs Outdated Show resolved Hide resolved
@EmilyMatt EmilyMatt marked this pull request as draft June 13, 2024 07:18
@EmilyMatt EmilyMatt marked this pull request as ready for review June 13, 2024 09:29
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

Outside diff range and nitpick comments (2)
src/graph/blocking.rs (2)

133-137: Refactor to ensure the documentation is updated to reflect the new return type.

The comment on line 133 still mentions FalkorResultSet which should be updated to QueryResult<LazyResultSet> to reflect the changes in the code and maintain consistency.


Line range hint 223-257: Review the string construction for security and performance.

The method create_index constructs a query string dynamically which could be prone to injection if not properly sanitized. Ensure that properties and options are properly escaped or use parameterized queries if possible. Additionally, consider optimizing string operations for better performance.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c53438c and c3c6b58.

Files selected for processing (5)
  • src/error/mod.rs (1 hunks)
  • src/graph/blocking.rs (8 hunks)
  • src/graph/query_builder.rs (9 hunks)
  • src/lib.rs (1 hunks)
  • src/response/mod.rs (3 hunks)
Additional comments not posted (9)
src/lib.rs (1)

37-37: The export of QueryResult here is well-placed, ensuring it's accessible where needed. Good job maintaining clean and clear module exports.

src/error/mod.rs (1)

115-117: Adding the StatisticNotFound error variant is a good approach to handle missing statistics in QueryResult. This should help in providing more descriptive error handling throughout the application.

src/response/mod.rs (1)

18-44: The introduction of StatisticType enum is a structured way to handle different statistics types. Using strum for serialization simplifies the conversion to and from strings, which is beneficial for logging and messaging.

src/graph/query_builder.rs (2)

Line range hint 115-158: The update to the QueryBuilder to return QueryResult instead of FalkorResponse aligns with the PR's objectives of standardizing the return types across the application. The handling of different response lengths is robust, ensuring that each scenario is catered to appropriately.


Line range hint 310-372: The ProcedureQueryBuilder's handling of QueryResult for FalkorIndex and Constraint is well-executed. The detailed error handling for different array sizes in the response is a good practice, ensuring that the function behaves predictably under different conditions.

src/graph/blocking.rs (4)

153-153: Ensure the new QueryBuilder return type is correctly integrated across all usages.

The change from FalkorResponse to QueryResult in the ro_query function aligns with the overall PR objectives and improves consistency across the API.


197-198: Consider refactoring to reduce redundancy in index-related methods.

This comment is a continuation of the previous suggestion to refactor repeated code patterns in index-related methods. Consider creating a private helper method to construct these query strings to reduce redundancy and improve maintainability.


309-310: Validate the integration of QueryResult in constraint-related methods.

The update to return QueryResult in list_constraints method is in line with the PR's goals of enhancing API consistency and handling query results more effectively.


275-275: Verify the correct handling of index types in the drop_index method.

Verification successful

The ast-grep search results indicate that there is a match statement handling different index types within src/graph/blocking.rs. Specifically, it handles IndexType::Range, IndexType::Vector, and IndexType::Fulltext. We need to verify that this match statement is part of the drop_index method and that the method uses it correctly.

To ensure the match statement is within the drop_index method and verify the method's handling of index types, we need to gather the relevant method implementation.


The previous script did not produce any output, indicating that it did not find the drop_index method with the provided pattern. To adjust our approach, we will search for the method name itself and then inspect its implementation.


The drop_index method has been located, and part of its implementation has been extracted. The method includes a match statement handling different index types. To ensure the correct handling of index types, we need to review the complete implementation of the method.


The complete implementation of the drop_index method has been extracted. The method includes a match statement that handles different index types (IndexType::Range, IndexType::Vector, and IndexType::Fulltext) and constructs the appropriate query string for dropping the index.

  • The match statement correctly maps each IndexType to its corresponding string representation.
  • The constructed query string uses this mapping to drop the index for the specified entity type and properties.

This confirms that the drop_index method correctly handles the different index types.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the index types are handled correctly in the `drop_index` method.

# Test: Search for the handling of different index types in the method. Expect: Proper handling of each index type.
ast-grep --lang rust --pattern 'match $$_ { IndexType::Range => "", IndexType::Vector => "VECTOR", IndexType::Fulltext => "FULLTEXT" }' src/graph/blocking.rs

Length of output: 473



Script:

#!/bin/bash
# Description: Verify that the match statement handling index types is within the `drop_index` method and check the method's overall handling of index types.

# Search for the `drop_index` method implementation in the `src/graph/blocking.rs` file.
ast-grep --lang rust --pattern 'fn drop_index($_) -> $_ { $$$ }' src/graph/blocking.rs

Length of output: 88



Script:

#!/bin/bash
# Description: Locate the `drop_index` method and verify its handling of index types.

# Search for the `drop_index` method by name in the `src/graph/blocking.rs` file.
rg 'fn drop_index' src/graph/blocking.rs

# Extract the implementation of the `drop_index` method to verify the handling of index types.
rg -A 20 'fn drop_index' src/graph/blocking.rs

Length of output: 889



Script:

#!/bin/bash
# Description: Extract the complete implementation of the `drop_index` method to verify the handling of index types.

# Extract the remaining part of the `drop_index` method to fully understand its implementation.
rg -A 50 'fn drop_index' src/graph/blocking.rs

Length of output: 2049

src/response/mod.rs Outdated Show resolved Hide resolved
src/response/mod.rs Show resolved Hide resolved
AviAvni
AviAvni previously approved these changes Jun 13, 2024
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: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c3c6b58 and 845f4cc.

Files selected for processing (2)
  • src/graph/blocking.rs (11 hunks)
  • src/response/mod.rs (3 hunks)
Additional comments not posted (2)
src/response/mod.rs (1)

18-44: The StatisticType enum is well implemented with clear serialization for each type.

src/graph/blocking.rs (1)

133-137: The updated return types in query and ro_query methods to QueryResult<LazyResultSet> align well with the rest of the changes in the PR. Ensure all dependent code is updated to handle the new return type.

Also applies to: 153-153

src/response/mod.rs Show resolved Hide resolved
src/graph/blocking.rs Show resolved Hide resolved
@EmilyMatt EmilyMatt merged commit 4bb0967 into main Jun 13, 2024
6 checks passed
@EmilyMatt EmilyMatt deleted the query_result branch June 13, 2024 12:52
@github-actions github-actions bot mentioned this pull request Jun 13, 2024
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: 2

Outside diff range and nitpick comments (1)
src/graph/blocking.rs (1)

Line range hint 429-457: The test cases for creating, listing, and dropping indices are comprehensive and ensure that the index management functionality works as expected. However, consider adding additional tests for error scenarios, such as attempting to create or drop an index that does not exist.

Would you like me to help by adding these test cases?

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c3c6b58 and c10910e.

Files selected for processing (2)
  • src/graph/blocking.rs (11 hunks)
  • src/response/mod.rs (3 hunks)
Additional comments not posted (5)
src/response/mod.rs (3)

18-44: The enum StatisticType is well-defined with clear serialization for each type. This structure will facilitate easy mapping from string values to enum types, which is beneficial for parsing statistics from responses.


48-48: The transformation of FalkorResponse to QueryResult and the addition of methods to fetch various statistics are well-implemented. The methods are clear and use generics effectively to fetch typed statistics.


104-163: The methods for retrieving specific statistics like get_labels_added, get_nodes_created, etc., are concise and make good use of the get_statistics method. This reusability reduces code duplication and enhances maintainability.

src/graph/blocking.rs (2)

Line range hint 133-153: The update to use QueryResult in methods like query and ro_query aligns with the renaming and refactoring across the project. This consistency in using QueryResult enhances the clarity and maintainability of the codebase.


Line range hint 197-310: The methods list_indices, create_index, drop_index, and list_constraints have been updated to return QueryResult. This change is consistent with the overall PR objectives and improves the type safety and clarity of the method return values.

Comment on lines +83 to +102
fn get_statistics<S>(
&self,
stat_type: StatisticType,
) -> Option<S>
where
S: FromStr,
{
for stat in self.stats.iter() {
if stat.contains(Into::<&'static str>::into(stat_type)) {
// Splits the statistic string by ': ', then retrieves and parses the statistic value.
return stat
.split(": ")
.nth(1)
.and_then(|stat_value| stat_value.split(' ').next())
.and_then(|res| res.parse().ok());
}
}

None
}
Copy link

Choose a reason for hiding this comment

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

The get_statistics method efficiently parses statistics from a string format. The use of generics and the FromStr trait ensures flexibility and type safety. However, consider adding error logging or a debug statement for cases where parsing fails, to aid in debugging and maintainability.

+                .and_then(|res| res.parse().ok())
+                .or_else(|| {
+                    log::debug!("Failed to parse statistic value: {}", stat);
+                    None
+                });
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
fn get_statistics<S>(
&self,
stat_type: StatisticType,
) -> Option<S>
where
S: FromStr,
{
for stat in self.stats.iter() {
if stat.contains(Into::<&'static str>::into(stat_type)) {
// Splits the statistic string by ': ', then retrieves and parses the statistic value.
return stat
.split(": ")
.nth(1)
.and_then(|stat_value| stat_value.split(' ').next())
.and_then(|res| res.parse().ok());
}
}
None
}
// Splits the statistic string by ': ', then retrieves and parses the statistic value.
return stat
.split(": ")
.nth(1)
.and_then(|stat_value| stat_value.split(' ').next())
.and_then(|res| res.parse().ok())
.or_else(|| {
log::debug!("Failed to parse statistic value: {}", stat);
None
});

Comment on lines +166 to +214
#[cfg(test)]
mod tests {
use crate::test_utils::open_test_graph;

#[test]
fn test_get_statistics() {
let mut graph = open_test_graph("imdb_stats_test");
{
let query_result = graph
.inner
.query("CREATE (a:new_node { new_property: 1})-[b:new_relationship]->(a)")
.execute()
.expect("Could not run query");

assert!(query_result.get_internal_execution_time().is_some());
assert_eq!(query_result.get_nodes_created(), Some(1));
assert_eq!(query_result.get_relationship_created(), Some(1));
assert_eq!(query_result.get_properties_set(), Some(1));
}
{
let query_result = graph
.inner
.query(
"MATCH (a:new_node { new_property: 1})-[b:new_relationship]->(a) DELETE b, a",
)
.execute()
.expect("Could not run query");
assert_eq!(query_result.get_nodes_deleted(), Some(1));
assert_eq!(query_result.get_relationship_deleted(), Some(1));
}

{
let query_result = graph
.inner
.query("UNWIND range(0, 1000) AS x RETURN x")
.execute()
.expect("Could not run query");
assert_eq!(query_result.get_cached_execution(), Some(false));
}

{
let query_result = graph
.inner
.query("UNWIND range(0, 1000) AS x RETURN x")
.execute()
.expect("Could not run query");
assert_eq!(query_result.get_cached_execution(), Some(true));
}
}
Copy link

Choose a reason for hiding this comment

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

The test cases are well-organized and cover a variety of scenarios, ensuring that the QueryResult methods function as expected. Consider adding a test case to verify the behavior when no statistics are available, to ensure that the methods handle empty or incorrect stats gracefully.

Would you like me to help by adding this test case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request rust Pull requests that update Rust code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement QueryResult functionallity that was missing
2 participants