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-sqlite): primitive upgrades towards bigger types #2931

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

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Jan 20, 2025

#2925 this updates torii to support new less strict upgrades for primitives

Summary by CodeRabbit

  • New Features

    • Enhanced database schema upgrade capabilities.
    • Introduced a method to determine type compatibility for upgrades in the Primitive enum.
  • Improvements

    • Added advanced logic for managing SQLite schema modifications.
    • Implemented safer column type transition mechanisms.

Copy link

coderabbitai bot commented Jan 20, 2025

Walkthrough

Ohayo, sensei! The changes enhance the SQLite database schema upgrade mechanism by introducing a new modify_column closure that addresses SQLite's limitations on direct column alterations. This involves creating a temporary column, copying data, dropping the original column, and renaming the temporary column. Additionally, a new can_upgrade_to method is added to the Primitive struct to determine type upgrade compatibility, which is integrated into the column modification logic to ensure safe and controlled schema transitions.

Changes

File Change Summary
crates/torii/sqlite/src/lib.rs - Added modify_column closure for column modification workaround
- Enhanced schema upgrade logic with type compatibility checks
crates/dojo/types/src/primitive.rs - Added pub fn can_upgrade_to(&self, other: &Primitive) -> bool method in Primitive enum for type upgrade compatibility

Sequence Diagram

sequenceDiagram
    participant Schema as Database Schema
    participant Modifier as Column Modifier
    participant Primitive as Type Checker

    Primitive->>Primitive: can_upgrade_to()
    alt Upgrade Possible
        Modifier->>Schema: Create Temporary Column
        Modifier->>Schema: Copy Data
        Modifier->>Schema: Drop Original Column
        Modifier->>Schema: Rename Temporary Column
    else Upgrade Not Possible
        Primitive-->>Modifier: Return Error
    end
Loading

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

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

🧹 Nitpick comments (1)
crates/torii/sqlite/src/lib.rs (1)

957-977: Ohayo, sensei! Enhance error handling for invalid primitive type upgrades.

The error message in lines 967-971 could be more informative to aid debugging:

return Err(anyhow::anyhow!(
    "Invalid primitive type upgrade from {:?} to {:?}",
    old_primitive,
    p
));

Consider including additional context or guidance on how to resolve the error. Additionally, logging the error might help in monitoring and troubleshooting.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2dd3ead and 0792db5.

📒 Files selected for processing (1)
  • crates/torii/sqlite/src/lib.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (1)
crates/torii/sqlite/src/lib.rs (1)

983-1020: Ohayo, sensei! The can_upgrade_to method correctly implements type upgrade logic.

The implementation accurately defines the permissible upgrades between primitive types, ensuring data integrity during schema migrations.

Comment on lines 850 to 863
let mut modify_column = |name: &str, sql_type: &str, sql_value: &str| {
// SQLite doesn't support ALTER COLUMN directly, so we need to:
// 1. Create a new temporary column
// 2. Copy the data
// 3. Drop the old column
// 4. Rename the temporary column
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] ADD COLUMN [tmp_{name}] {sql_type}"));
alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));
alter_table_queries.push(format!("ALTER TABLE [{table_id}] DROP COLUMN [{name}]"));
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] RENAME COLUMN [tmp_{name}] TO [{name}]"));
};

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! Address potential SQL injection vulnerability in modify_column.

In the modify_column closure, the sql_value is directly interpolated into the SQL statement without parameterization:

alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));

This approach might expose the code to SQL injection attacks if sql_value contains malicious input. It's essential to use parameterized queries or ensure that sql_value is properly sanitized before use.

Apply this diff to fix the issue by using parameterized queries:

- alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));
+ alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = ?"));
+ // Ensure to pass `sql_value` as a parameter when executing the query.

@Larkooo Larkooo changed the title refactor(torii): primitive upgrades towards bigger types feat(torii-sqlite): primitive upgrades towards bigger types Jan 20, 2025
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

🧹 Nitpick comments (1)
crates/torii/sqlite/src/lib.rs (1)

958-979: Enhance error message and add logging for upgrades.

The error message could be more descriptive, and successful upgrades should be logged for better observability.

Apply this diff to improve the error handling and add logging:

                     if old_primitive.can_upgrade_to(p) {
+                        tracing::info!(
+                            "Upgrading column {} from {:?} to {:?}",
+                            column_name, old_primitive, p
+                        );
                         modify_column(
                             alter_table_queries,
                             &column_name,
                             p.to_sql_type().as_ref(),
                             p.to_sql_value().as_ref(),
                         );
                     } else {
                         return Err(anyhow::anyhow!(
-                            "Invalid primitive type upgrade from {:?} to {:?}",
+                            "Invalid primitive type upgrade for column '{}': cannot upgrade from {:?} to {:?}. Please check the upgrade compatibility rules.",
+                            column_name,
                             old_primitive,
                             p
                         ));
                     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0792db5 and f2affb6.

📒 Files selected for processing (2)
  • crates/dojo/types/src/primitive.rs (1 hunks)
  • crates/torii/sqlite/src/lib.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: ensure-wasm
  • GitHub Check: docs
  • GitHub Check: build
🔇 Additional comments (1)
crates/dojo/types/src/primitive.rs (1)

407-441: Ohayo, sensei! Add test coverage for the new can_upgrade_to method.

The new method defines critical upgrade paths for primitive types but lacks test coverage to ensure the upgrade rules are working as expected.

Would you like me to generate comprehensive test cases covering all upgrade paths?

(U8(_), U16(_) | U32(_) | USize(_) | U64(_) | U128(_) | Felt252(_)) => true,
(U16(_), U32(_) | USize(_) | U64(_) | U128(_) | Felt252(_)) => true,
(U32(_), USize(_) | U64(_) | U128(_) | Felt252(_)) => true,
(USize(_), U32(_) | U64(_) | U128(_) | Felt252(_)) => true,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Verify USize upgrade path to prevent data loss.

The USize type can upgrade to U32 which might cause data loss on 64-bit systems where usize is 64 bits.

Apply this diff to fix the upgrade path:

-            (USize(_), U32(_) | U64(_) | U128(_) | Felt252(_)) => true,
+            (USize(_), U64(_) | U128(_) | Felt252(_)) => true,
📝 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
(USize(_), U32(_) | U64(_) | U128(_) | Felt252(_)) => true,
(USize(_), U64(_) | U128(_) | Felt252(_)) => true,

Comment on lines +850 to +863
let modify_column =
|alter_table_queries: &mut Vec<String>, name: &str, sql_type: &str, sql_value: &str| {
// SQLite doesn't support ALTER COLUMN directly, so we need to:
// 1. Create a new temporary column
// 2. Copy the data
// 3. Drop the old column
// 4. Rename the temporary column
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] ADD COLUMN [tmp_{name}] {sql_type}"));
alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));
alter_table_queries.push(format!("ALTER TABLE [{table_id}] DROP COLUMN [{name}]"));
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] RENAME COLUMN [tmp_{name}] TO [{name}]"));
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure atomic operations with transaction handling.

The column modification process involves multiple SQL operations that should be atomic to prevent data corruption if any step fails.

Wrap the operations in a transaction by adding these queries at the start and end:

+            alter_table_queries.push("BEGIN TRANSACTION;".to_string());
             alter_table_queries
                 .push(format!("ALTER TABLE [{table_id}] ADD COLUMN [tmp_{name}] {sql_type}"));
             alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));
             alter_table_queries.push(format!("ALTER TABLE [{table_id}] DROP COLUMN [{name}]"));
             alter_table_queries
                 .push(format!("ALTER TABLE [{table_id}] RENAME COLUMN [tmp_{name}] TO [{name}]"));
+            alter_table_queries.push("COMMIT;".to_string());

Also, add error handling:

+            alter_table_queries.push("ROLLBACK;".to_string());
📝 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
let modify_column =
|alter_table_queries: &mut Vec<String>, name: &str, sql_type: &str, sql_value: &str| {
// SQLite doesn't support ALTER COLUMN directly, so we need to:
// 1. Create a new temporary column
// 2. Copy the data
// 3. Drop the old column
// 4. Rename the temporary column
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] ADD COLUMN [tmp_{name}] {sql_type}"));
alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));
alter_table_queries.push(format!("ALTER TABLE [{table_id}] DROP COLUMN [{name}]"));
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] RENAME COLUMN [tmp_{name}] TO [{name}]"));
};
let modify_column =
|alter_table_queries: &mut Vec<String>, name: &str, sql_type: &str, sql_value: &str| {
// SQLite doesn't support ALTER COLUMN directly, so we need to:
// 1. Create a new temporary column
// 2. Copy the data
// 3. Drop the old column
// 4. Rename the temporary column
alter_table_queries.push("BEGIN TRANSACTION;".to_string());
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] ADD COLUMN [tmp_{name}] {sql_type}"));
alter_table_queries.push(format!("UPDATE [{table_id}] SET [tmp_{name}] = {sql_value}"));
alter_table_queries.push(format!("ALTER TABLE [{table_id}] DROP COLUMN [{name}]"));
alter_table_queries
.push(format!("ALTER TABLE [{table_id}] RENAME COLUMN [tmp_{name}] TO [{name}]"));
alter_table_queries.push("COMMIT;".to_string());
alter_table_queries.push("ROLLBACK;".to_string());
};

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.

Working fine, thank you @Larkooo! Waiting some confirmations from @remybar on the #2925 and will merge.

// Felt252 and address types
(Felt252(_), ClassHash(_) | ContractAddress(_)) => true,
(ClassHash(_), Felt252(_) | ContractAddress(_)) => true,
(ContractAddress(_), Felt252(_) | ClassHash(_)) => true,
Copy link
Collaborator

Choose a reason for hiding this comment

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

We're missing EthAddress, not sure at which point it's relevant for now and may be supported later.

(U8(_), U16(_) | U32(_) | USize(_) | U64(_) | U128(_) | Felt252(_)) => true,
(U16(_), U32(_) | USize(_) | U64(_) | U128(_) | Felt252(_)) => true,
(U32(_), USize(_) | U64(_) | U128(_) | Felt252(_)) => true,
(USize(_), U32(_) | U64(_) | U128(_) | Felt252(_)) => true,
Copy link
Collaborator

Choose a reason for hiding this comment

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

I've left a comment here #2925 (comment), I think having usize non-changeable would make more sense at the cairo level (for Torii, it's way less relevant, but it is to match the cairo rules).

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