Skip to content

Conversation

@numbpill3d
Copy link
Owner

@numbpill3d numbpill3d commented Jun 8, 2025

Summary

  • use execute_sql RPC for initializing DB tables
  • adjust migration scripts to call RPC instead of .query
  • add missing server/models/Item.js

Testing

  • npm test (fails: fetch errors and module issues)

https://chatgpt.com/codex/tasks/task_e_68450e64dd24832f8bd07252b8d015db

Summary by Sourcery

Refactor DB setup and migration scripts to invoke SQL via the execute_sql RPC and add the missing Item model alias.

Enhancements:

  • Refactor database initialization and migration scripts to use the execute_sql RPC for running SQL statements instead of direct query calls.

Chores:

  • Add missing server/models/Item.js alias for ScrapyardItem.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jun 8, 2025

Reviewer's Guide

This PR refactors all direct SQL execution calls to a unified RPC endpoint and adds a missing model alias.

Sequence Diagram: Database Query Execution via RPC

sequenceDiagram
  participant ClientCode as "Application Code (e.g., Migrations, DB Init)"
  participant SupabaseAdminSDK as "Supabase Admin SDK"
  participant SupabasePlatform as "Supabase Platform"

  ClientCode->>+SupabaseAdminSDK: call rpc("execute_sql", { sql: "DDL/DML..." })
  SupabaseAdminSDK->>+SupabasePlatform: Forward execute_sql RPC request
  SupabasePlatform-->>-SupabaseAdminSDK: RPC response (data/error)
  SupabaseAdminSDK-->>-ClientCode: Return response
Loading

Class Diagram: New server/models/Item.js Alias

classDiagram
  direction LR
  namespace server.models {
    class Item {
      <<JavaScript Module>>
      + require('./ScrapyardItem')
    }
    class ScrapyardItem {
      // Existing model
    }
  }
  server.models.Item ..> server.models.ScrapyardItem : "aliases/exports"
Loading

File-Level Changes

Change Details Files
Refactor table creation to use execute_sql RPC
  • Swap supabaseAdmin.query calls for supabaseAdmin.rpc('execute_sql', {sql})
  • Apply this change across all migration scripts and the database initializer
scripts/migrations/create-forum-tables.js
scripts/migrations/create-streetpass-table.js
scripts/migrations/create-wir-transactions-table.js
server/utils/database.js
Add missing Item model alias
  • Introduce server/models/Item.js exporting the ScrapyardItem model
server/models/Item.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

CREATE INDEX idx_forum_threads_created_at ON forum_threads(created_at);
CREATE INDEX idx_forum_threads_updated_at ON forum_threads(updated_at);
`);
`
Copy link
Contributor

Choose a reason for hiding this comment

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

Security Concern: SQL Injection Risk

The use of raw SQL queries (execute_sql) with template literals can potentially expose the application to SQL injection attacks if not properly sanitized or parameterized. Although this script is likely run in a controlled migration environment, it's a good practice to avoid forming SQL commands directly from input variables or using parameterized queries or stored procedures to mitigate such risks.

Recommendation:
Consider using parameterized queries or stored procedures to enhance security, especially if any part of the SQL command can be influenced by external input in future modifications.

Comment on lines +21 to 25
await supabaseAdmin.rpc('execute_sql', {
sql: `
CREATE TABLE market_wir_transactions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
Copy link
Contributor

Choose a reason for hiding this comment

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

Potential SQL Injection and Dependency on uuid_generate_v4()

The SQL query for creating the table is embedded directly in the code and executed without explicit sanitization or parameterization, which could expose the system to SQL injection vulnerabilities. Additionally, the use of uuid_generate_v4() as a default value assumes that this function is available in the database, which might not be the case in all environments.

Recommendation:

  • Use parameterized queries or stored procedures to avoid SQL injection.
  • Ensure that uuid_generate_v4() is available in your database setup or provide an alternative method for generating UUIDs.

`
});

console.log('market_wir_transactions table created successfully!');
Copy link
Contributor

Choose a reason for hiding this comment

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

Lack of Verification After Table Creation

The script logs a success message after executing the table creation command but does not verify whether the table and indexes were actually created. This could lead to situations where the script reports success, but the operation failed due to underlying SQL errors or permission issues.

Recommendation:

  • Implement checks to verify the successful creation of the table and indexes. This could involve querying the database to confirm the existence of the table and indexes after the creation commands have been executed.

Comment on lines 80 to 87

if (error && error.code === '42P01') { // Table doesn't exist
console.log('Creating users table...');
await supabaseAdmin.query(`
await supabaseAdmin.rpc('execute_sql', {
sql: `
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
username TEXT UNIQUE NOT NULL,
Copy link
Contributor

Choose a reason for hiding this comment

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

Potential Issue with UUID Generation

The SQL command for creating the users table assumes the availability of the uuid_generate_v4() function, which is provided by the uuid-ossp extension. This extension is created later in the script (lines 109-111). It's recommended to ensure that the extension is created before any table that requires it to prevent runtime errors during the table creation process.

Suggested Change:
Move the block of code that ensures the uuid-ossp extension exists to a point before any table creation that depends on it. This change would enhance the reliability of the database initialization process.

Comment on lines 161 to 177

if (sessionsError && sessionsError.code === '42P01') { // Table doesn't exist
console.log('Creating sessions table...');
await supabaseAdmin.query(`
await supabaseAdmin.rpc('execute_sql', {
sql: `
CREATE TABLE sessions (
sid varchar NOT NULL PRIMARY KEY,
sess json NOT NULL,
expired timestamp(6) with time zone NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_expired ON sessions(expired);
`);
`
});
}

console.log('Database initialization complete');
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhancement for Session Table Management

The creation of the sessions table includes an index on the expired field, which is excellent for performance when querying or cleaning up expired sessions. However, there is no automated mechanism shown here for handling the cleanup of expired sessions. Over time, without proper cleanup, the sessions table could grow significantly and impact performance.

Suggested Enhancement:
Implement a routine or scheduled task that periodically removes expired sessions from the sessions table. This could be done within this script or as a separate maintenance script, ensuring that the sessions table remains manageable and does not negatively impact database performance.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @numbpill3d - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants