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(torii-core): add indices to speed up queries #2824

Merged
merged 2 commits into from
Dec 20, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Dec 19, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced database schema with new indices for improved query performance on internal_entity_id, internal_event_message_id, and other key columns.
    • Added indices to the entities and event_messages_historical tables for faster data retrieval.
  • Bug Fixes

    • Improved error handling and result propagation during database operations.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

Ohayo, sensei! The pull request introduces performance-enhancing database indices for the Torii core SQL module. Two primary files are modified: the Rust source code in crates/torii/core/src/sql/mod.rs and a SQL migration file crates/torii/migrations/20241219104134_indices.sql. The changes focus on adding strategic indices to the entities and event_messages_historical tables, which will optimize query performance by enabling faster data retrieval for specific columns.

Changes

File Change Summary
crates/torii/core/src/sql/mod.rs Updated build_model_query and add_columns_recursive methods to support index creation for internal_entity_id and internal_event_message_id columns.
crates/torii/migrations/20241219104134_indices.sql Added 5 new indices:
- idx_entities_updated_at on entities.updated_at
- 4 indices on event_messages_historical table for id, keys, event_id, and executed_at columns.

Sequence Diagram

sequenceDiagram
    participant SQL as SQL Migration
    participant Core as Torii Core
    SQL->>Core: Define new indices
    Core->>Core: Conditionally create indices during schema upgrade
    Core-->>SQL: Apply indices to database schema
Loading

Possibly Related PRs

Suggested Reviewers

  • glihm

Sensei, the indices are ready to boost our query performance! Ohayo! 🚀🔍


🪧 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 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

🧹 Nitpick comments (2)
crates/torii/core/src/sql/mod.rs (2)

769-776: Ohayo! Good addition of indices on foreign key columns, sensei!

Adding indices on foreign key columns internal_entity_id and internal_event_message_id is a good practice as it will improve JOIN performance. Consider combining these indices since they're often used together in queries.

Consider creating a composite index:

-        indices.push(format!(
-            "CREATE INDEX IF NOT EXISTS [idx_{table_id}_internal_entity_id] ON [{table_id}] \
-             ([internal_entity_id]);"
-        ));
-        indices.push(format!(
-            "CREATE INDEX IF NOT EXISTS [idx_{table_id}_internal_event_message_id] ON [{table_id}] \
-             ([internal_event_message_id]);"
-        ));
+        indices.push(format!(
+            "CREATE INDEX IF NOT EXISTS [idx_{table_id}_internal_ids] ON [{table_id}] \
+             ([internal_entity_id], [internal_event_message_id]);"
+        ));

769-776: Consider monitoring index usage and performance impact

While these indices will improve query performance, they also:

  1. Increase storage space requirements
  2. Add overhead to write operations
  3. Need maintenance (rebuilding/reindexing)

Consider implementing monitoring to track:

  • Index usage statistics
  • Query performance improvements
  • Write operation impact
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2f00ed and 6eacca8.

📒 Files selected for processing (2)
  • crates/torii/core/src/sql/mod.rs (1 hunks)
  • crates/torii/migrations/20241219104134_indices.sql (1 hunks)
🔇 Additional comments (1)
crates/torii/migrations/20241219104134_indices.sql (1)

1-9: Ohayo, sensei! The indices look well-structured.

The indices are appropriately named and placed on columns that are likely used in WHERE clauses or JOINs. This should improve query performance for operations involving these columns.

Let's verify if these columns are indeed frequently used in queries:

✅ Verification successful

Ohayo, sensei! The indices are well-justified by the codebase usage.

The evidence from the codebase strongly supports the need for these indices:

  • updated_at: Used in WHERE clauses for querying entities by timestamp (found in crates/torii/grpc/src/server/mod.rs)
  • keys: Extensively used in WHERE clauses with REGEXP for filtering (found in multiple files, e.g., crates/torii/grpc/src/server/mod.rs)
  • event_id: Used in ORDER BY clauses for sorting results (found in multiple queries across grpc/src/server/mod.rs and core/src/model.rs)
  • executed_at: Part of the core schema and used in historical tracking

The indices will improve query performance for these frequently used columns in WHERE clauses, JOIN conditions, and ORDER BY operations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for SQL queries using these columns
rg -i "where.*updated_at|join.*updated_at" --type rust
rg -i "where.*event_id|join.*event_id" --type rust
rg -i "where.*executed_at|join.*executed_at" --type rust
rg -i "where.*keys|join.*keys" --type rust

Length of output: 1001


Script:

#!/bin/bash
# Let's check for any other potential usages of these columns in SQL queries
# that might not be in WHERE/JOIN clauses

# Search for any SQL-like usage of these columns
rg -i "updated_at|event_id|executed_at|keys" --type sql -A 3 -B 3
rg -i "select.*updated_at|select.*event_id|select.*executed_at|select.*keys" --type rust
rg -i "order by.*updated_at|order by.*event_id|order by.*executed_at|order by.*keys" --type rust

# Also check table definitions to understand the role of these columns
rg -i "create table.*entities|create table.*event_messages_historical" --type sql -A 10

Length of output: 27217

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

🧹 Nitpick comments (1)
crates/torii/core/src/sql/mod.rs (1)

769-776: Ohayo, sensei! The indices look good and will improve query performance!

The addition of indices on internal_entity_id and internal_event_message_id columns is a solid performance optimization. These indices will significantly speed up lookups and joins involving these columns.

A few positive observations:

  • Using IF NOT EXISTS prevents errors on repeated executions
  • Index naming follows best practices
  • The indices are properly scoped to their respective tables

For optimal performance, consider monitoring the usage patterns of these indices once they're in production. Tools like EXPLAIN QUERY PLAN can help verify that the indices are being utilized effectively.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6eacca8 and 6226343.

📒 Files selected for processing (1)
  • crates/torii/core/src/sql/mod.rs (1 hunks)

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