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): sql playground #2714

Merged
merged 14 commits into from
Nov 22, 2024
Merged

feat(torii): sql playground #2714

merged 14 commits into from
Nov 22, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Nov 22, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a SQL playground interface allowing users to write and execute SQL queries in real-time with enhanced UI and code editing capabilities.
    • Added a new method to handle incoming requests, streamlining the request management process.
  • Bug Fixes

    • Improved error handling for SQL query execution with user-friendly alerts and better support for various data types.

Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

Ohayo, sensei! The changes in this pull request enhance the SqlHandler struct by adding two new asynchronous methods: serve_playground, which serves a static HTML page, and handle_request, which centralizes request handling logic. Additionally, a new HTML file, sql-playground.html, is created to provide a user interface for executing SQL queries using React and Monaco Editor. This interface includes features like query editing, syntax highlighting, and responsive design.

Changes

File Path Change Summary
crates/torii/server/src/handlers/sql.rs - Added method: async fn serve_playground(&self) -> Response<Body>
- Added method: async fn handle_request(&self, req: Request<Body>) -> Response<Body>
- Modified handle method to call handle_request for streamlined request handling.
crates/torii/server/static/sql-playground.html - New HTML file created for SQL playground interface using React and Monaco Editor, with query editor and results display.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SqlHandler
    participant Playground

    Client->>SqlHandler: GET /sql-playground
    SqlHandler->>Playground: serve_playground()
    Playground-->>SqlHandler: HTML Response
    SqlHandler-->>Client: 200 OK with HTML
Loading
sequenceDiagram
    participant Client
    participant SqlHandler

    Client->>SqlHandler: Request (GET or Query)
    SqlHandler->>SqlHandler: handle_request(req)
    alt If GET and empty query
        SqlHandler->>SqlHandler: serve_playground()
    else If Query
        SqlHandler->>SqlHandler: extract_query()
        alt If successful
            SqlHandler->>SqlHandler: execute_query(query)
        else
            SqlHandler->>SqlHandler: serve_playground()
        end
    end
    SqlHandler-->>Client: Response
Loading

Possibly related PRs

  • feat(torii): sql proxy endpoint for querying #2706: The changes in this PR introduce a SQL proxy endpoint that handles SQL queries, which is directly related to the enhancements made in the SqlHandler struct in the main PR, as both involve SQL query handling and response generation.

Suggested reviewers

  • glihm

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a9eb280 and d3dbc5b.

📒 Files selected for processing (1)
  • crates/torii/server/static/sql-playground.html (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/server/static/sql-playground.html

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

🧹 Outside diff range and nitpick comments (2)
crates/torii/server/src/handlers/sql.rs (1)

Line range hint 24-24: Critical: SQL Injection Risk in Query Execution!

Ohayo sensei! The execute_query method directly executes user input as SQL queries without proper sanitization or validation. This is a critical security vulnerability that could lead to SQL injection attacks.

Consider these security improvements:

  1. Implement a SQL query validator/sanitizer
  2. Use parameterized queries where possible
  3. Add a whitelist of allowed SQL operations
  4. Implement query timeout mechanism

Would you like me to provide an implementation with these security measures?

crates/torii/server/static/sql-playground.html (1)

95-95: Unused reference monacoRef

Ohayo, sensei! The monacoRef reference is assigned but never used, which can be removed to clean up the code.

Apply this diff to remove monacoRef:

-            const monacoRef = useRef(null);

And remove the assignment:

-                monacoRef.current = monaco;

Also applies to: 277-277

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b55f1fc and 831a649.

📒 Files selected for processing (2)
  • crates/torii/server/src/handlers/sql.rs (3 hunks)
  • crates/torii/server/static/sql-playground.html (1 hunks)
🔇 Additional comments (1)
crates/torii/server/src/handlers/sql.rs (1)

152-152: Verify SQL endpoint path handling, sensei!

The implementation looks good, but let's verify that all SQL-related paths are properly handled.

✅ Verification successful

SQL endpoint path handling is properly implemented, sensei!

The implementation in sql.rs shows that:

  • The handler correctly checks for /sql path prefix in should_handle
  • Path handling is properly implemented with both GET and POST methods
  • The handler serves SQL playground for empty GET requests
  • Query parameter handling is properly implemented for both methods
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other SQL endpoint handlers that might conflict
rg -l "starts_with\(\"/sql\"\)" --type rust

# Search for SQL route definitions
rg "route.*sql" --type rust

Length of output: 113


Script:

#!/bin/bash
# Let's check the SQL handler implementation to verify path handling
ast-grep --pattern 'impl SqlHandler {
  $$$
  async fn handle_request($$$) {
    $$$
  }
  $$$
}'

# Also check for any route registration or path handling in the main server setup
rg -A 5 "Router::new\(\).*sql" --type rust

Length of output: 144


Script:

#!/bin/bash
# Let's check the entire SQL handler file content
cat crates/torii/server/src/handlers/sql.rs

# Also check for router setup in main.rs or lib.rs
fd -e rs "main|lib" -X cat

Length of output: 102409

crates/torii/server/src/handlers/sql.rs Show resolved Hide resolved
crates/torii/server/src/handlers/sql.rs Outdated Show resolved Hide resolved
Comment on lines 304 to 308
React.createElement(Button, {
variant: 'outline',
onClick: () => copyToClipboard(query)
}, copied ? '✓ Copied!' : 'Copy')
]),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Undefined function copyToClipboard

Ohayo, sensei! The function copyToClipboard is called but not defined, which will cause a runtime error when attempting to copy the query.

To fix this issue, define the copyToClipboard function.

crates/torii/server/static/sql-playground.html Outdated Show resolved Hide resolved
crates/torii/server/static/sql-playground.html Outdated Show resolved Hide resolved
crates/torii/server/static/sql-playground.html Outdated Show resolved Hide resolved
Copy link

codecov bot commented Nov 22, 2024

Codecov Report

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

Project coverage is 56.23%. Comparing base (b55f1fc) to head (d3dbc5b).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/server/src/handlers/sql.rs 0.00% 31 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2714      +/-   ##
==========================================
+ Coverage   56.16%   56.23%   +0.07%     
==========================================
  Files         414      415       +1     
  Lines       52965    53206     +241     
==========================================
+ Hits        29747    29921     +174     
- Misses      23218    23285      +67     

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


🚨 Try these New Features:

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

152-152: Ohayo! Consider adding error handling wrapper, sensei!

The direct delegation to handle_request could benefit from a top-level error handling wrapper to ensure consistent error responses:

-self.handle_request(req).await
+match self.handle_request(req).await {
+    response if response.status().is_success() => response,
+    response => {
+        tracing::error!("SQL handler error: {:?}", response.status());
+        response
+    }
+}
crates/torii/server/static/sql-playground.html (3)

7-11: Consider production-ready setup for external dependencies

Ohayo, sensei! While the current setup works, consider these production improvements:

  1. Pin versions for all dependencies (currently only Monaco Editor is pinned)
  2. Bundle TailwindCSS instead of using CDN for production
  3. Consider self-hosting these dependencies for better reliability and performance

105-233: Enhance SQL autocompletion suggestions

Ohayo, sensei! Consider these improvements to the SQL suggestions:

  1. Add missing common SQL keywords (HAVING, DISTINCT, etc.)
  2. Add documentation for all SQL functions like you did for COUNT
  3. Consider fetching table suggestions dynamically from the backend
 const suggestions = [
+    {
+        label: 'HAVING',
+        kind: monaco.languages.CompletionItemKind.Keyword,
+        insertText: 'HAVING',
+        detail: 'SQL Keyword',
+        documentation: 'Filter grouped rows'
+    },
+    {
+        label: 'DISTINCT',
+        kind: monaco.languages.CompletionItemKind.Keyword,
+        insertText: 'DISTINCT',
+        detail: 'SQL Keyword',
+        documentation: 'Return unique values'
+    },
     // ... existing suggestions ...
     {
         label: 'SUM',
         kind: monaco.languages.CompletionItemKind.Function,
         insertText: 'SUM($0)',
         insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
-        detail: 'SQL Function'
+        detail: 'SQL Function',
+        documentation: 'Calculate the sum of values'
     },
     {
         label: 'AVG',
         kind: monaco.languages.CompletionItemKind.Function,
         insertText: 'AVG($0)',
         insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
-        detail: 'SQL Function'
+        detail: 'SQL Function',
+        documentation: 'Calculate the average of values'
     },

377-411: Enhance results table functionality

Ohayo, sensei! Consider adding these features to improve the results display:

  1. Pagination for large result sets
  2. Column sorting
  3. Cell content truncation with expandable view
 React.createElement('table', { className: 'min-w-full divide-y divide-zinc-800' }, [
     React.createElement('thead', { className: 'bg-zinc-900' },
         React.createElement('tr', {},
             Object.keys(response[0]).map(header =>
                 React.createElement('th', {
                     key: header,
-                    className: 'px-6 py-3 text-left text-xs font-medium text-zinc-400 uppercase tracking-wider'
+                    className: 'px-6 py-3 text-left text-xs font-medium text-zinc-400 uppercase tracking-wider cursor-pointer hover:text-white',
+                    onClick: () => handleSort(header)
                 }, header)
             )
         )
     ),
     React.createElement('tbody', { className: 'divide-y divide-zinc-800' },
-        response.map((row, rowIndex) =>
+        paginatedResults.map((row, rowIndex) =>
             React.createElement('tr', {
                 key: rowIndex,
                 className: rowIndex % 2 === 0 ? 'bg-zinc-900' : 'bg-zinc-900/50'
             },
                 Object.values(row).map((value, colIndex) =>
                     React.createElement('td', {
                         key: colIndex,
-                        className: 'px-6 py-4 whitespace-nowrap text-sm text-zinc-300 font-mono'
+                        className: 'px-6 py-4 text-sm text-zinc-300 font-mono',
+                        title: String(value)
                     },
                         value === null ?
                             React.createElement('span', { className: 'text-zinc-500 italic' }, 'NULL') :
                             typeof value === 'object' ?
-                                JSON.stringify(value) :
-                                String(value)
+                                truncateText(JSON.stringify(value), 100) :
+                                truncateText(String(value), 100)
                     )
                 )
             )
         )
     )
 ])
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 831a649 and 1f6c270.

📒 Files selected for processing (2)
  • crates/torii/server/src/handlers/sql.rs (3 hunks)
  • crates/torii/server/static/sql-playground.html (1 hunks)
🔇 Additional comments (4)
crates/torii/server/src/handlers/sql.rs (4)

7-7: Previous comment about include_str import is still valid, sensei!


122-131: Previous security improvement suggestions are still valid, sensei!


133-142: Previous suggestions about error handling and security measures are still valid, sensei!


134-134: ⚠️ Potential issue

Ohayo! Let's handle the unwrap_or_default more safely, sensei!

The current implementation might panic if the URI is malformed. Consider using a more defensive approach:

-if req.method() == Method::GET && req.uri().query().unwrap_or_default().is_empty() {
+if req.method() == Method::GET && req.uri().query().map(|q| q.is_empty()).unwrap_or(true) {

Likely invalid or redundant comment.

Comment on lines 330 to 427
return React.createElement('div', { className: 'min-h-screen bg-black text-white p-4' },
React.createElement('div', { className: 'max-w-8xl mx-auto' }, [
React.createElement('div', { className: 'mb-6', key: 'header' }, [
React.createElement('div', { className: 'flex items-center gap-2 mb-1' }, [
React.createElement('h1', { className: 'text-2xl font-bold text-white' }, 'Torii SQL Playground'),
React.createElement('span', { className: 'px-2 py-1 rounded-full bg-zinc-800 text-xs text-zinc-400' }, 'BETA')
]),
React.createElement('p', { className: 'text-zinc-400' }, 'Write and execute SQL queries in real-time')
]),
React.createElement('div', { className: 'grid grid-cols-1 lg:grid-cols-2 gap-6', key: 'content' }, [
// Query Editor Panel
React.createElement(Card, { key: 'editor', className: 'flex flex-col h-[75vh]' }, [
React.createElement('div', { className: 'p-4 border-b border-zinc-800 flex items-center justify-between' }, [
React.createElement('h2', { className: 'text-lg font-semibold text-white' }, 'Query Editor'),
React.createElement(Button, {
variant: 'outline',
onClick: () => copyToClipboard(query)
}, copied ? '✓ Copied!' : 'Copy')
]),
React.createElement('div', { className: 'flex-1 relative' },
React.createElement('div', {
id: 'monaco-editor',
className: 'absolute inset-0'
})
),
React.createElement('div', { className: 'p-4 border-t border-zinc-800' },
React.createElement(Button, {
onClick: executeQuery,
disabled: loading,
className: 'w-full'
}, loading ? '⟳ Executing...' : '▶ Run Query')
)
]),

// Results Panel updates...
React.createElement(Card, { key: 'results', className: 'flex flex-col h-[75vh]' }, [
React.createElement('div', { className: 'p-4 border-b border-zinc-800 flex items-center justify-between' }, [
React.createElement('h2', { className: 'text-lg font-semibold text-white' }, 'Results'),
response && React.createElement(Button, {
variant: 'outline',
onClick: downloadResults
}, '⇩ Download JSON')
]),
React.createElement('div', { className: 'flex-1 p-4 overflow-auto' }, [
error && React.createElement(Alert, { variant: 'destructive' },
'⚠ ' + error
),
response && response.length > 0 && React.createElement('div', { className: 'overflow-x-auto' },
React.createElement('table', { className: 'min-w-full divide-y divide-zinc-800' }, [
React.createElement('thead', { className: 'bg-zinc-900' },
React.createElement('tr', {},
Object.keys(response[0]).map(header =>
React.createElement('th', {
key: header,
className: 'px-6 py-3 text-left text-xs font-medium text-zinc-400 uppercase tracking-wider'
}, header)
)
)
),
React.createElement('tbody', { className: 'divide-y divide-zinc-800' },
response.map((row, rowIndex) =>
React.createElement('tr', {
key: rowIndex,
className: rowIndex % 2 === 0 ? 'bg-zinc-900' : 'bg-zinc-900/50'
},
Object.values(row).map((value, colIndex) =>
React.createElement('td', {
key: colIndex,
className: 'px-6 py-4 whitespace-nowrap text-sm text-zinc-300 font-mono'
},
value === null ?
React.createElement('span', { className: 'text-zinc-500 italic' }, 'NULL') :
typeof value === 'object' ?
JSON.stringify(value) :
String(value)
)
)
)
)
)
])
),
(!response || response.length === 0) && !error && !loading && React.createElement('div', {
className: 'flex flex-col items-center justify-center h-full text-zinc-500'
}, [
React.createElement('p', { className: 'text-lg font-medium' }, 'No Results Yet'),
React.createElement('p', { className: 'text-sm' }, 'Execute a query to see results here')
])
]),
response && React.createElement('div', { className: 'p-4 border-t border-zinc-800 bg-zinc-900' },
React.createElement('p', { className: 'text-sm text-zinc-400' },
`Showing ${response.length} row${response.length !== 1 ? 's' : ''}`
)
)
])
])
])
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add accessibility support

Ohayo, sensei! The interface needs accessibility improvements:

  1. Add ARIA labels and roles
  2. Implement keyboard navigation
  3. Add screen reader support
 return React.createElement('div', { className: 'min-h-screen bg-black text-white p-4' },
-    React.createElement('div', { className: 'max-w-8xl mx-auto' }, [
+    React.createElement('div', { 
+        className: 'max-w-8xl mx-auto',
+        role: 'main',
+        'aria-label': 'SQL Playground'
+    }, [
         React.createElement('div', { className: 'mb-6', key: 'header' }, [
             React.createElement('div', { className: 'flex items-center gap-2 mb-1' }, [
-                React.createElement('h1', { className: 'text-2xl font-bold text-white' }, 'Torii SQL Playground'),
+                React.createElement('h1', { 
+                    className: 'text-2xl font-bold text-white',
+                    role: 'heading',
+                    'aria-level': '1'
+                }, 'Torii SQL Playground'),

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 288 to 304
const executeQuery = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('/sql?' + new URLSearchParams({ query }));
if (!response.ok) {
throw new Error(`Query failed: ${response.statusText}`);
}
const data = await response.json();
setResponse(data);
} catch (error) {
setError(error.message);
setResponse(null);
} finally {
setLoading(false);
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve query execution robustness

Ohayo, sensei! Consider enhancing the query execution with:

  1. Timeout handling for long-running queries
  2. Query size validation
  3. Rate limiting feedback
 const executeQuery = async () => {
     setLoading(true);
     setError(null);
     try {
+        if (query.length > 10000) {
+            throw new Error('Query too large. Please limit to 10000 characters.');
+        }
+        const controller = new AbortController();
+        const timeoutId = setTimeout(() => controller.abort(), 30000);
         const response = await fetch('/sql?' + new URLSearchParams({ query }), {
+            signal: controller.signal
         });
+        clearTimeout(timeoutId);
         if (!response.ok) {
+            const errorData = await response.json();
+            if (response.status === 429) {
+                throw new Error('Rate limit exceeded. Please wait before trying again.');
+            }
             throw new Error(`Query failed: ${response.statusText}`);
         }
         const data = await response.json();
         setResponse(data);
     } catch (error) {
+        if (error.name === 'AbortError') {
+            setError('Query timed out. Please try a simpler query.');
+        } else {
             setError(error.message);
+        }
         setResponse(null);
     } finally {
         setLoading(false);
     }
 };
📝 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
const executeQuery = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('/sql?' + new URLSearchParams({ query }));
if (!response.ok) {
throw new Error(`Query failed: ${response.statusText}`);
}
const data = await response.json();
setResponse(data);
} catch (error) {
setError(error.message);
setResponse(null);
} finally {
setLoading(false);
}
};
const executeQuery = async () => {
setLoading(true);
setError(null);
try {
if (query.length > 10000) {
throw new Error('Query too large. Please limit to 10000 characters.');
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000);
const response = await fetch('/sql?' + new URLSearchParams({ query }), {
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorData = await response.json();
if (response.status === 429) {
throw new Error('Rate limit exceeded. Please wait before trying again.');
}
throw new Error(`Query failed: ${response.statusText}`);
}
const data = await response.json();
setResponse(data);
} catch (error) {
if (error.name === 'AbortError') {
setError('Query timed out. Please try a simpler query.');
} else {
setError(error.message);
}
setResponse(null);
} finally {
setLoading(false);
}
};

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/server/src/handlers/sql.rs (1)

52-70: Ohayo sensei! Let's improve the type handling maintainability!

The fallback type handling logic is quite complex and would benefit from being extracted into a separate method with proper documentation explaining the type conversion strategy.

Consider this refactor:

+ /// Attempts to convert a SQL value to a JSON value using various type conversions
+ /// in a specific order: i64 -> f64 -> bool -> String -> BLOB(base64)
+ fn convert_sql_value(&self, row: &sqlx::Row, i: usize) -> serde_json::Value {
+     if let Ok(val) = row.try_get::<i64, _>(i) {
+         serde_json::Value::Number(val.into())
+     } else if let Ok(val) = row.try_get::<f64, _>(i) {
+         serde_json::json!(val)
+     } else if let Ok(val) = row.try_get::<bool, _>(i) {
+         serde_json::Value::Bool(val)
+     } else if let Ok(val) = row.try_get::<String, _>(i) {
+         serde_json::Value::String(val)
+     } else {
+         let val = row.get::<Option<Vec<u8>>, _>(i);
+         val.map_or(serde_json::Value::Null, |bytes| {
+             serde_json::Value::String(STANDARD.encode(bytes))
+         })
+     }
+ }

- _ => {
-     // Try different types in order
-     if let Ok(val) = row.try_get::<i64, _>(i) {
-         serde_json::Value::Number(val.into())
-     } else if let Ok(val) = row.try_get::<f64, _>(i) {
-         // Handle floating point numbers
-         serde_json::json!(val)
-     } else if let Ok(val) = row.try_get::<bool, _>(i) {
-         serde_json::Value::Bool(val)
-     } else if let Ok(val) = row.try_get::<String, _>(i) {
-         serde_json::Value::String(val)
-     } else {
-         // Handle or fallback to BLOB as base64
-         let val = row.get::<Option<Vec<u8>>, _>(i);
-         val.map_or(serde_json::Value::Null, |bytes| {
-             serde_json::Value::String(STANDARD.encode(bytes))
-         })
-     }
- },
+ _ => self.convert_sql_value(row, i),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1f6c270 and 9b7b380.

📒 Files selected for processing (1)
  • crates/torii/server/src/handlers/sql.rs (5 hunks)
🔇 Additional comments (2)
crates/torii/server/src/handlers/sql.rs (2)

168-168: Ohayo sensei! The handler implementation looks good!

The delegation to handle_request is clean and follows good separation of concerns.


149-158: ⚠️ Potential issue

Ohayo sensei! The error handling needs improvement!

The current implementation falls back to serving the playground on query extraction errors, which could mask important issues from clients.

Consider this enhanced implementation:

 async fn handle_request(&self, req: Request<Body>) -> Response<Body> {
     if req.method() == Method::GET && req.uri().query().unwrap_or_default().is_empty() {
         self.serve_playground().await
     } else {
         match self.extract_query(req).await {
             Ok(query) => self.execute_query(query).await,
-            Err(_) => self.serve_playground().await,
+            Err(response) => response,  // Return the actual error response
         }
     }
 }

Likely invalid or redundant comment.

Comment on lines +138 to +147
async fn serve_playground(&self) -> Response<Body> {
let html = include_str!("../../static/sql-playground.html");

Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, "text/html")
.header("Access-Control-Allow-Origin", "*")
.body(Body::from(html))
.unwrap()
}
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! Let's enhance the playground security!

The playground serving implementation needs some security improvements:

  1. Using unwrap() could cause panics
  2. The Access-Control-Allow-Origin: * header is too permissive
  3. Missing important security headers (CSP, X-Content-Type-Options)

Consider this safer implementation:

 async fn serve_playground(&self) -> Response<Body> {
     let html = include_str!("../../static/sql-playground.html");
 
-    Response::builder()
-        .status(StatusCode::OK)
-        .header(CONTENT_TYPE, "text/html")
-        .header("Access-Control-Allow-Origin", "*")
-        .body(Body::from(html))
-        .unwrap()
+    Response::builder()
+        .status(StatusCode::OK)
+        .header(CONTENT_TYPE, "text/html")
+        .header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';")
+        .header("X-Content-Type-Options", "nosniff")
+        .body(Body::from(html))
+        .unwrap_or_else(|e| {
+            Response::builder()
+                .status(StatusCode::INTERNAL_SERVER_ERROR)
+                .body(Body::from(format!("Failed to serve playground: {}", e)))
+                .unwrap_or_default()
+        })

Committable suggestion skipped: line range outside the PR's diff.

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/server/src/handlers/sql.rs (1)

Line range hint 33-70: Ohayo sensei! Nice type handling implementation!

The enhanced type conversion logic is well-structured with proper fallbacks. Consider extracting the type conversion logic into a separate method for better maintainability.

impl SqlHandler {
+    fn convert_column_value(&self, row: &sqlx::sqlite::SqliteRow, i: usize, column: &sqlx::sqlite::SqliteColumn) -> serde_json::Value {
+        match column.type_info().name() {
+            "TEXT" => row.get::<Option<String>, _>(i)
+                .map_or(serde_json::Value::Null, serde_json::Value::String),
+            // ... rest of the type conversion logic ...
+        }
+    }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9e7a872 and 50f7c56.

📒 Files selected for processing (1)
  • crates/torii/server/src/handlers/sql.rs (5 hunks)
🔇 Additional comments (1)
crates/torii/server/src/handlers/sql.rs (1)

168-168: Ohayo! Clean implementation, sensei!

Good job delegating to the new handle_request method. This improves code organization and separation of concerns.

Comment on lines +149 to +158
async fn handle_request(&self, req: Request<Body>) -> Response<Body> {
if req.method() == Method::GET && req.uri().query().unwrap_or_default().is_empty() {
self.serve_playground().await
} else {
match self.extract_query(req).await {
Ok(query) => self.execute_query(query).await,
Err(_) => self.serve_playground().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! Let's enhance the request validation, sensei!

The current implementation has two areas for improvement:

  1. Falling back to playground on query extraction error masks potential issues
  2. Missing input validation before query execution

Consider this enhanced implementation:

 async fn handle_request(&self, req: Request<Body>) -> Response<Body> {
     if req.method() == Method::GET && req.uri().query().unwrap_or_default().is_empty() {
         self.serve_playground().await
     } else {
         match self.extract_query(req).await {
             Ok(query) => {
+                // Validate query before execution
+                if query.trim().is_empty() {
+                    return Response::builder()
+                        .status(StatusCode::BAD_REQUEST)
+                        .body(Body::from("Empty query"))
+                        .unwrap_or_default();
+                }
                 self.execute_query(query).await
             }
-            Err(_) => self.serve_playground().await,
+            Err(e) => e,  // Return the actual error for better visibility
         }
     }
 }
📝 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
async fn handle_request(&self, req: Request<Body>) -> Response<Body> {
if req.method() == Method::GET && req.uri().query().unwrap_or_default().is_empty() {
self.serve_playground().await
} else {
match self.extract_query(req).await {
Ok(query) => self.execute_query(query).await,
Err(_) => self.serve_playground().await,
}
}
}
async fn handle_request(&self, req: Request<Body>) -> Response<Body> {
if req.method() == Method::GET && req.uri().query().unwrap_or_default().is_empty() {
self.serve_playground().await
} else {
match self.extract_query(req).await {
Ok(query) => {
// Validate query before execution
if query.trim().is_empty() {
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("Empty query"))
.unwrap_or_default();
}
self.execute_query(query).await
}
Err(e) => e, // Return the actual error for better visibility
}
}
}

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.

That's fire @Larkooo!

Suggestion, we may have a toggle to display the JSON or the result as table. Like so, someone that tries to execute some code on the JSON can see the JSON instead of having to download it.

@glihm glihm merged commit da52a06 into dojoengine:main Nov 22, 2024
13 of 14 checks passed
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