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

refactor: member clauses handle struct fields & operators & recursive #2420

Merged
merged 9 commits into from
Sep 16, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Sep 12, 2024

this PR reworks member clauses and composite clauses

  • member clauses should be able to handle deep model fields. Like "x" in a Vec2 of a Position model. we should be able to filter on X by giving "vec.x" on the member clause
  • composite clauses should be recursive and be able to filter on multiple inner composite clauses
  • OR and AND operators should be able to work correctly

Summary by CodeRabbit

  • New Features

    • Enhanced SQL query construction for improved performance and flexibility.
    • Introduced a new method for building composite clauses.
  • Bug Fixes

    • Streamlined query handling to reduce potential errors, ensuring consistent retrieval of results.
  • Refactor

    • Modularized clause-building logic for better readability and maintainability.
    • Improved clarity in the SQL query construction process.

Copy link

coderabbitai bot commented Sep 12, 2024

Walkthrough

Ohayo, sensei! The changes involve significant modifications to the DojoWorld implementation in the mod.rs file, focusing on SQL query handling and composite clause construction. A new method, build_composite_clause, has been introduced to streamline the construction of SQL clauses, while the query_by_composite function has been updated for improved clarity. Additionally, the handling of SQL result counts has been refined to ensure consistent retrieval of results, enhancing the overall structure and readability of the code.

Changes

Files Change Summary
crates/torii/grpc/src/server/mod.rs - Modified: pub(crate) async fn query_by_composite(...) in impl DojoWorld.
- Added: fn build_composite_clause(...) in impl DojoWorld.
- Enhanced SQL query handling and clause construction logic.

Possibly related PRs


Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2aad21e and 09e1a16.

Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (7 hunks)
Files skipped from review as they are similar to previous changes (1)
  • crates/torii/grpc/src/server/mod.rs

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 generate interesting stats about this repository and render them as a table.
    -- @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 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

@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: 0

Outside diff range and nitpick comments (1)
crates/torii/grpc/src/server/mod.rs (1)

Line range hint 578-766: Ohayo sensei! The changes look great, just a minor suggestion.

The refactoring to use build_composite_clause method for constructing the SQL query is a significant improvement in terms of code readability and maintainability. The consistent usage of fetch_one and the improved approach to binding values are also positive changes.

To further improve the code, consider extracting the logic for mapping the database entities to proto::types::Entity into a separate method. This will make the query_by_composite method more focused and easier to understand.

For example:

fn map_db_entities_to_proto_entities(
    db_entities: &Vec<(String, String)>,
    table: &str,
    entity_relation_column: &str,
    pool: &Pool<Sqlite>,
) -> Result<Vec<proto::types::Entity>, Error> {
    // ...
}

Then, in query_by_composite:

let entities = map_db_entities_to_proto_entities(
    &db_entities,
    table,
    entity_relation_column,
    &self.pool,
).await?;
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 28baa66 and 133fd3a.

Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (11 hunks)

Copy link

codecov bot commented Sep 12, 2024

Codecov Report

Attention: Patch coverage is 0% with 103 lines in your changes missing coverage. Please review.

Project coverage is 68.01%. Comparing base (f4e15f1) to head (09e1a16).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/grpc/src/server/mod.rs 0.00% 103 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2420      +/-   ##
==========================================
- Coverage   68.04%   68.01%   -0.04%     
==========================================
  Files         364      364              
  Lines       47871    47892      +21     
==========================================
- Hits        32573    32572       -1     
- Misses      15298    15320      +22     

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

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: 0

Outside diff range and nitpick comments (2)
crates/torii/grpc/src/server/mod.rs (2)

527-528: Ohayo sensei! Consider simplifying the code.

The code can be simplified by using fetch_one instead of fetch_optional and handling the RowNotFound error. Something like this:

let models_str = sqlx::query_scalar(&models_query)
    .fetch_one(&self.pool) 
    .await
    .map_err(|e| match e {
        sqlx::Error::RowNotFound => QueryError::NotFound,
        _ => e.into(),
    })?;

955-1051: Ohayo sensei! The new build_composite_clause function looks great.

The function is well-structured and handles all clause types correctly. Recursively processing nested composite clauses is a nice touch. Using bind variables is also a good security practice.

Just one small nitpick - consider renaming is_or to is_disjunction or is_disjunctive to be more explicit.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 71a0073 and e5500f3.

Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (7 hunks)
Additional comments not posted (3)
crates/torii/grpc/src/server/mod.rs (3)

44-44: LGTM!

The import statement is correct and necessary.


543-550: Looks good to me, sensei!

The parsing of the member clause correctly handles both top-level and nested fields. The use of $ as a separator and external_ prefix for the column name follows the established conventions.


Line range hint 586-596: Ohayo! The changes look great.

Extracting the clause building logic into build_composite_clause improves code organization and readability. Using DISTINCT in the count query is also a good catch to avoid duplicate counts.

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: 0

Outside diff range and nitpick comments (2)
crates/torii/grpc/src/server/mod.rs (2)

Line range hint 586-669: Ohayo sensei! The changes to use the build_composite_clause function look great!

The build_composite_clause function nicely encapsulates the logic for generating the SQL clauses and bind values for the composite clause query. This makes the query_by_composite function much cleaner and easier to read.

One minor nitpick: Consider using if let instead of match for the models_str variable since you only care about the Some case:

-        let models_str: Option<String> =
-            sqlx::query_scalar(&models_query).fetch_optional(&self.pool).await?;
-        if models_str.is_none() {
+        if let Some(models_str) = sqlx::query_scalar(&models_query).fetch_optional(&self.pool).await? {
+            let model_ids = models_str
+                .split(',')
+                .map(Felt::from_str)
+                .collect::<Result<Vec<_>, _>>()
+                .map_err(ParseError::FromStr)?;
+            let schemas =
+                self.model_cache.models(&model_ids).await?.into_iter().map(|m| m.schema).collect();
+            ...
+        } else {
             return Ok((Vec::new(), 0));
         }
-
-        let models_str = models_str.unwrap();

955-1051: Ohayo sensei! The new build_composite_clause function looks great!

The function correctly generates the SQL clauses and bind values for composite clauses, handling all the different clause types and recursively handling nested composite clauses.

One minor nitpick: Consider using String::new() instead of String::from("") for empty strings. For example:

-    let having_clause = if !having_clauses.is_empty() {
-        format!("HAVING {}", having_clauses.join(if is_or { " OR " } else { " AND " }))
-    } else {
-        String::from("")
+        String::new()
     };

This is a bit more idiomatic and avoids an unnecessary allocation.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e5500f3 and bf507d9.

Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (7 hunks)

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: 0

Outside diff range and nitpick comments (1)
crates/torii/grpc/src/server/mod.rs (1)

Line range hint 586-669: Ohayo sensei! The changes to query_by_composite look great!

The refactor to use the new build_composite_clause function improves the modularity and readability of the code by extracting the composite clause building logic into a separate function. 👍

To further improve readability, consider extracting the count query and main query into separate functions. This will make the query_by_composite function more focused and easier to understand.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bf507d9 and 2aad21e.

Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (7 hunks)
Additional comments not posted (1)
crates/torii/grpc/src/server/mod.rs (1)

955-1050: Ohayo sensei! The new build_composite_clause function looks fantastic!

The function correctly handles the different types of clauses (hashed keys, keys, member, and nested composite) and generates the appropriate SQL clauses and bind values. The recursive handling of nested composite clauses is a great feature that allows for complex queries.

The use of the build_keys_pattern function to generate the keys pattern for keys clauses, the ComparisonOperator enum to map the comparison operator for member clauses, and the Primitive type to convert the member clause value to a SQL value are all excellent choices that make the code more robust and maintainable.

Overall, this is a well-designed and implemented function that greatly improves the composite clause handling in the codebase. Great job! 🙌

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Nice to have this recursively.

@glihm glihm merged commit 09203e8 into dojoengine:main Sep 16, 2024
13 of 15 checks passed
@kariy kariy mentioned this pull request Sep 19, 2024
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.

2 participants