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 updated at field in top level toriii query #2807

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

edisontim
Copy link
Collaborator

@edisontim edisontim commented Dec 13, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new field internal_updated_at for tracking updates in the Query message.
    • Enhanced query capabilities to filter results based on the internal_updated_at timestamp.
  • Bug Fixes

    • Improved methods in the DojoWorld struct to consistently utilize the internal_updated_at parameter for better entity retrieval.
  • Documentation

    • Updated method signatures to reflect the addition of the internal_updated_at parameter across various functions.

Copy link

coderabbitai bot commented Dec 13, 2024

Walkthrough

Ohayo, sensei! This pull request introduces modifications across several files to enhance the handling of an internal_updated_at timestamp. The build_sql_query function in model.rs now accepts this new parameter to filter SQL results. Additionally, the Query message in types.proto and the Query struct in mod.rs have been updated to include this field. Various methods in the DojoWorld struct have also been modified to incorporate the internal_updated_at parameter, ensuring consistent usage throughout the entity retrieval process.

Changes

File Path Change Summary
crates/torii/core/src/model.rs - Method signature updated: build_sql_query now includes internal_updated_at: u64.
- Logic modified to append a conditional clause for internal_updated_at in SQL query generation.
crates/torii/grpc/proto/types.proto - Field added: uint64 internal_updated_at = 7; in Query message.
crates/torii/grpc/src/server/mod.rs - Multiple method signatures updated to include internal_updated_at: u64 in DojoWorld struct methods.
- Updated entities_all, fetch_entities, query_by_*, and retrieve_entities methods to utilize the new parameter.
crates/torii/grpc/src/types/mod.rs - Field added: pub internal_updated_at: u64 in Query struct.
- Updated From<Query> for proto::types::Query implementation to include internal_updated_at.
crates/torii/grpc/src/server/tests/entities_test.rs - Updated test_entities_queries to include an additional argument 0 in the query_by_keys method call.

Possibly related PRs

Suggested reviewers

  • Larkooo

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. This feature will be included in our Pro Plan when released.


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. (Experiment)
  • @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: 1

🧹 Outside diff range and nitpick comments (1)
crates/torii/core/src/model.rs (1)

Line range hint 176-189: Ohayo, sensei! Potential inefficiency in internal_updated_at clause construction.

The internal_updated_at_clause vector is initialized even if internal_updated_at is zero. Consider initializing it only when internal_updated_at > 0 to optimize performance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e8f254 and 7602646.

📒 Files selected for processing (4)
  • crates/torii/core/src/model.rs (5 hunks)
  • crates/torii/grpc/proto/types.proto (1 hunks)
  • crates/torii/grpc/src/server/mod.rs (17 hunks)
  • crates/torii/grpc/src/types/mod.rs (2 hunks)
🔇 Additional comments (12)
crates/torii/grpc/src/server/mod.rs (7)

Line range hint 232-244: Ohayo, sensei! Verify consistent propagation of internal_updated_at parameter.

The entities_all function now includes the internal_updated_at parameter. Please ensure that this parameter is consistently passed to all internal function calls within entities_all, such as query_by_hashed_keys, to maintain proper filtering based on the update timestamp.


271-271: Ohayo, sensei! Confirm usage of internal_updated_at in fetch_entities.

The fetch_entities function now includes the internal_updated_at parameter. Please verify that this parameter is utilized within the function, particularly when constructing queries, to ensure entities are filtered correctly.


Line range hint 438-519: Ohayo, sensei! Ensure internal_updated_at is passed to fetch_entities correctly.

In the query_by_hashed_keys function, the new internal_updated_at parameter is added. Please verify that this parameter is correctly passed to the fetch_entities function to maintain consistency in entity filtering.


Line range hint 537-666: Ohayo, sensei! Check internal update timestamp handling in query_by_keys.

The query_by_keys function now includes internal_updated_at. Ensure that this parameter affects the query as intended and that it is passed correctly to any subsequent functions or query constructions.


Line range hint 778-812: Ohayo, sensei! Validate internal_updated_at implementation in query_by_member.

Please ensure that the internal_updated_at parameter is correctly utilized within the query_by_member function, especially when building and executing queries.


Line range hint 883-1052: Ohayo, sensei! Review internal_updated_at handling in query_by_composite.

In the query_by_composite function, the internal_updated_at parameter is introduced. Please confirm that it is correctly integrated into the query logic and that it properly filters entities based on the update timestamp.


Line range hint 1052-1121: Ohayo, sensei! Ensure internal_updated_at is passed and utilized in retrieve_entities.

The retrieve_entities function now accepts the internal_updated_at parameter. Verify that this parameter is consistently passed to the appropriate functions and that it effectively influences the entity retrieval based on the update timestamp.

crates/torii/grpc/proto/types.proto (1)

79-79: Ohayo, sensei! Confirm field numbering for internal_updated_at.

The new field internal_updated_at is added with field number 7. Ensure that this field number does not collide with any existing or reserved field numbers, and that the addition maintains backward compatibility.

crates/torii/grpc/src/types/mod.rs (2)

109-109: Ohayo, sensei! Adding internal_updated_at to Query struct looks good.

The inclusion of internal_updated_at in the Query struct aligns with the protocol buffer definition and ensures consistency between client and server.


275-275: Ohayo, sensei! Verify internal_updated_at field mapping in From<Query>.

Ensure that the internal_updated_at field is correctly mapped in the From<Query> implementation to prevent any serialization issues.

crates/torii/core/src/model.rs (2)

127-127: Ohayo, sensei! Addition of internal_updated_at parameter to build_sql_query.

The new parameter allows filtering based on update timestamps, enhancing query capabilities.


207-218: Ohayo, sensei! Correct conditional inclusion of internal_updated_at in WHERE clause.

The logic to append the internal_updated_at conditions to the WHERE clause is correctly handled, ensuring proper SQL query construction.

Comment on lines 360 to 364
internal_updated_at,
)?;

let rows = sqlx::query(&entity_query).bind(models_str).fetch_all(&mut *tx).await?;
let query = sqlx::query(&entity_query).bind(models_str);
let rows = query.fetch_all(&mut *tx).await?;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ohayo, sensei! Missing binding for internal_updated_at in the SQL query.

While internal_updated_at is used within the build_sql_query function to build the SQL query, it appears that in lines 363-364, internal_updated_at is not bound to the query. This may lead to incorrect query results.

Please bind internal_updated_at to the query to ensure proper functionality.

Apply this diff to fix the issue:

-                let query = sqlx::query(&entity_query).bind(models_str);
+                let query = sqlx::query(&entity_query).bind(models_str).bind(internal_updated_at);
📝 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
internal_updated_at,
)?;
let rows = sqlx::query(&entity_query).bind(models_str).fetch_all(&mut *tx).await?;
let query = sqlx::query(&entity_query).bind(models_str);
let rows = query.fetch_all(&mut *tx).await?;
internal_updated_at,
)?;
let query = sqlx::query(&entity_query).bind(models_str).bind(internal_updated_at);
let rows = query.fetch_all(&mut *tx).await?;

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 (4)
crates/torii/grpc/src/server/mod.rs (1)

Line range hint 332-361: Ohayo, sensei! Consider optimizing model cache access.

The code fetches models from cache in a loop, which could be optimized by fetching all required models at once and caching them locally.

Consider refactoring to batch the model cache access:

-let schemas = self
-    .model_cache
-    .models(&model_ids)
-    .await?
-    .into_iter()
-    .map(|m| m.schema)
-    .collect::<Vec<_>>();
+// Fetch all models at once at the beginning
+let model_cache = self.model_cache.models(&all_model_ids).await?;
+let model_map: HashMap<_, _> = model_cache.into_iter().map(|m| (m.id, m.schema)).collect();
crates/torii/grpc/src/server/tests/entities_test.rs (1)

146-146: LGTM! Test updated for the new internal_updated_at parameter.

The test now includes the new timestamp parameter with a value of 0, which effectively disables timestamp filtering. This provides good coverage for the base case.

Consider adding additional test cases with non-zero timestamps to verify the filtering behavior.

crates/torii/core/src/model.rs (2)

Line range hint 177-190: Consider optimizing the vector capacity initialization.

The internal_updated_at_clause vector's capacity is set to schemas.len(), but it will only be populated if internal_updated_at > 0. Consider moving the initialization inside the condition to avoid unnecessary allocations.

-    let mut internal_updated_at_clause = Vec::with_capacity(schemas.len());
     // Process each model schema
     for model in schemas {
         let model_table = model.name();
         joins.push(format!(
             "LEFT JOIN [{model_table}] ON {table_name}.id = \
              [{model_table}].{entity_relation_column}",
         ));
 
+        let mut internal_updated_at_clause = if internal_updated_at > 0 {
+            Vec::with_capacity(schemas.len())
+        } else {
+            Vec::new()
+        };
         if internal_updated_at > 0 {
             internal_updated_at_clause
                 .push(format!("[{model_table}].internal_updated_at > {}", internal_updated_at));
         }

517-517: LGTM! Test updated with the new parameter.

The test case has been updated to include the new internal_updated_at parameter with a value of 0.

Consider adding test cases with non-zero timestamps to verify the filtering behavior, similar to the suggestion for the integration test.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4fa9955 and 04b2764.

📒 Files selected for processing (3)
  • crates/torii/core/src/model.rs (6 hunks)
  • crates/torii/grpc/src/server/mod.rs (18 hunks)
  • crates/torii/grpc/src/server/tests/entities_test.rs (1 hunks)
🔇 Additional comments (3)
crates/torii/grpc/src/server/mod.rs (1)

364-365: ⚠️ Potential issue

Ohayo, sensei! Missing binding for internal_updated_at in the SQL query.

The SQL query is built with internal_updated_at parameter but it's not bound to the query execution. This could lead to incorrect filtering of results.

Apply this diff to fix the issue:

-let query = sqlx::query(&entity_query).bind(models_str);
+let query = sqlx::query(&entity_query).bind(models_str).bind(internal_updated_at);
crates/torii/core/src/model.rs (2)

Line range hint 119-128: LGTM! Function signature updated appropriately.

Ohayo! The new internal_updated_at parameter is well-placed and the clippy attribute is maintained correctly.


208-219: LGTM! SQL query construction handles timestamp filtering correctly.

The implementation properly handles both cases:

  1. When there's no existing WHERE clause
  2. When there's an existing WHERE clause that needs to be extended

Copy link

codecov bot commented Dec 13, 2024

Codecov Report

Attention: Patch coverage is 34.21053% with 25 lines in your changes missing coverage. Please review.

Project coverage is 55.71%. Comparing base (4e8f254) to head (04b2764).

Files with missing lines Patch % Lines
crates/torii/grpc/src/server/mod.rs 31.57% 13 Missing ⚠️
crates/torii/core/src/model.rs 38.88% 11 Missing ⚠️
crates/torii/grpc/src/types/mod.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2807      +/-   ##
==========================================
- Coverage   55.74%   55.71%   -0.03%     
==========================================
  Files         439      439              
  Lines       55613    55649      +36     
==========================================
+ Hits        31001    31007       +6     
- Misses      24612    24642      +30     

☔ 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 (1)
crates/torii/grpc/src/server/mod.rs (1)

365-374: Ohayo, sensei! Consider optimizing timestamp binding.

The timestamp is being bound multiple times (once per schema) which is redundant since it's the same value. Consider binding it only once and reusing the parameter in the SQL query.

-            if internal_updated_at > 0 {
-                for _ in 0..schemas.len() {
-                    query = query.bind(
-                        DateTime::<Utc>::from_timestamp(internal_updated_at as i64, 0)
-                            .ok_or_else(|| Error::from(QueryError::UnsupportedQuery))?
-                            .to_rfc3339(),
-                    );
-                }
-            }
+            if internal_updated_at > 0 {
+                query = query.bind(
+                    DateTime::<Utc>::from_timestamp(internal_updated_at as i64, 0)
+                        .ok_or_else(|| Error::from(QueryError::UnsupportedQuery))?
+                        .to_rfc3339(),
+                );
+            }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 04b2764 and 85df91a.

📒 Files selected for processing (2)
  • crates/torii/core/src/model.rs (6 hunks)
  • crates/torii/grpc/src/server/mod.rs (19 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/core/src/model.rs
🔇 Additional comments (2)
crates/torii/grpc/src/server/mod.rs (2)

233-233: Ohayo, sensei! Parameter propagation looks good!

The internal_updated_at parameter is consistently propagated through all query methods, maintaining a clean and uniform interface.

Also applies to: 245-245, 273-273, 362-362, 449-449, 548-548, 722-722, 823-823, 1063-1063, 1087-1087, 1102-1102, 1117-1117, 1132-1132


362-362: Ohayo, sensei! Previous binding issue has been resolved.

The timestamp binding issue mentioned in the past review has been properly addressed. The internal_updated_at parameter is now correctly passed to build_sql_query and bound to the query.

Also applies to: 365-365

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.

1 participant