Skip to content

refactor(proxy): change database driver packages to optional peer dependency#2388

Open
jiashengguo wants to merge 1 commit intodevfrom
jiasheng-proxy
Open

refactor(proxy): change database driver packages to optional peer dependency#2388
jiashengguo wants to merge 1 commit intodevfrom
jiasheng-proxy

Conversation

@jiashengguo
Copy link
Member

@jiashengguo jiashengguo commented Feb 20, 2026

Summary by CodeRabbit

  • Chores
    • Database drivers for PostgreSQL, MySQL, and SQLite are now optional dependencies. Install only those you need.
    • Enhanced error messages provide installation guidance for missing database drivers when required.

@claude
Copy link
Contributor

claude bot commented Feb 20, 2026

Claude finished @jiashengguo's task —— View job


PR Review Analysis

I've completed my analysis of the refactor to make database driver packages optional peer dependencies.

Todo List:

  • Read and analyze package.json changes
  • Review proxy.ts implementation changes
  • Check for potential runtime issues with optional dependencies
  • Evaluate error handling and user experience
  • Assess security implications
  • Review performance considerations
  • Provide comprehensive feedback and recommendations

Summary of Changes

package.json: Added pg, better-sqlite3, and mysql2 as optional peer dependencies with peerDependenciesMeta
proxy.ts: Enhanced dynamic import handling with proper error messages for missing database drivers

Code Review Feedback

Strengths

  1. Proper Peer Dependency Configuration (packages/cli/package.json:74-88):

    • Correctly declares database drivers as peer dependencies
    • Uses peerDependenciesMeta with "optional": true for all three drivers
    • Follows npm best practices for optional peer dependencies
  2. Excellent Error Handling (packages/cli/src/actions/proxy.ts:144-149, 167-170, 183-186):

    • Each database driver import is wrapped in try-catch blocks
    • Clear, actionable error messages guide users on installation
    • Consistent error message format across all database providers
  3. Type Safety Maintained:

    • Import types are properly declared and used conditionally
    • No runtime type issues with dynamic imports

⚠️ Areas for Improvement

  1. Error Message Consistency (packages/cli/src/actions/proxy.ts:148, 169, 185):

    • The installation commands could be more specific about package manager choice
    • Consider mentioning the specific package manager used by the project (pnpm) or provide alternatives
  2. Missing MySQL Type Import (packages/cli/src/actions/proxy.ts:21):

    • The MySQL type import createPool as MysqlCreatePool is imported but the actual import uses the default export name
    • Consider consistency with how other imports are handled

🔍 Potential Issues

  1. Runtime Dependency Resolution:

    • No issues found - the dynamic imports correctly handle missing dependencies
    • Error messages are clear and help users resolve the issue
  2. Security Considerations:

    • No security concerns identified
    • Database URL redaction is properly implemented (packages/cli/src/actions/proxy.ts:124-138)
  3. Performance Impact:

    • Dynamic imports are only executed when needed, so no performance degradation
    • Error handling doesn't introduce significant overhead

💡 Recommendations

  1. Enhanced Error Messages:

    // Consider updating error messages to be more specific about package managers
    throw new CliError(
        `Package "better-sqlite3" is required for SQLite support. Please install it with: pnpm add better-sqlite3 (or npm install better-sqlite3)`
    );
  2. Consider Adding Runtime Checks:

    • The current implementation is solid, but you might consider adding a utility function to check for available database drivers at startup

📋 Test Coverage

  • The changes should be covered by existing tests for the proxy functionality
  • Consider adding specific tests for the error cases when database drivers are missing

Overall Assessment

This is a well-executed refactor that properly handles optional database driver dependencies. The implementation follows best practices for optional peer dependencies and provides excellent user experience with clear error messages. The code is maintainable, secure, and performant.

Recommendation: ✅ Approve - This PR successfully achieves its goal of making database drivers optional while maintaining good error handling and user experience.


@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 20, 2026

📝 Walkthrough

Walkthrough

The pull request refactors database driver dependencies in the CLI package from required runtime dependencies to optional peer dependencies, with corresponding updates to dynamically import these drivers at runtime using proper error handling.

Changes

Cohort / File(s) Summary
Dependency restructuring
packages/cli/package.json
Moved pg, better-sqlite3, and mysql2 from dependencies to peerDependencies with optional: true flags, reducing direct runtime coupling.
Dynamic import pattern
packages/cli/src/actions/proxy.ts
Made createDialect asynchronous; replaced static imports with dynamic imports for all three database drivers, adding validation and user-friendly error messages for missing optional dependencies.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Our hopping code grows lean and light,
With databases now optionally in sight,
No bundled weight, just what we need,
Each driver loads on eager deed,
A flexible leap through code so clean! 🌱

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: converting database driver packages (better-sqlite3, mysql2, pg) from required dependencies to optional peer dependencies in the proxy module.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jiasheng-proxy

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/cli/package.json`:
- Line 93: The file ends with a closing brace '}' but lacks a trailing newline;
update the packages/cli package.json by adding a single newline character after
the final '}' so the file ends with a POSIX-compliant trailing newline.

In `@packages/cli/src/actions/proxy.ts`:
- Around line 143-150: The catch blocks for dynamic imports (the SQLite import
assigning to SQLite: typeof BetterSqlite3 and the similar pg and mysql2 import
blocks) currently swallow all errors and always surface a "package missing"
CliError; change each catch to capture the error (e.g., catch (err)) and inspect
err.code (or err.message) — if it indicates module-not-found
(ERR_MODULE_NOT_FOUND / MODULE_NOT_FOUND) then throw the existing CliError
telling the user to install the package, otherwise rethrow the original error or
wrap it in a CliError that includes the original error message so native
addon/ABI failures are not misreported as "not installed". Ensure this change is
applied to the better-sqlite3, pg, and mysql2 dynamic import blocks.

"node": ">=20"
}
}
} No newline at end of file
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 | 🟡 Minor

Missing trailing newline at end of file.

POSIX convention and most linter/formatter configs expect a trailing newline. This appears to have been removed.

Fix

Ensure the file ends with a newline character after the closing }.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/package.json` at line 93, The file ends with a closing brace '}'
but lacks a trailing newline; update the packages/cli package.json by adding a
single newline character after the final '}' so the file ends with a
POSIX-compliant trailing newline.

Comment on lines +143 to +150
let SQLite: typeof BetterSqlite3;
try {
SQLite = (await import('better-sqlite3')).default;
} catch {
throw new CliError(
`Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`,
);
}
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 | 🟡 Minor

Catch-all hides real errors (e.g., native binary ABI mismatch).

The bare catch block assumes any import failure means the package is missing. For better-sqlite3 in particular, a common failure mode is a native addon compilation/ABI mismatch — the package is installed but fails to load. The current error message would mislead the user into re-installing a package that's already present.

The same pattern applies to the pg (lines 167-171) and mysql2 (lines 183-187) catch blocks, though native addon issues are less common there.

Proposed fix: inspect the error code before assuming "not installed"
             try {
                 SQLite = (await import('better-sqlite3')).default;
-            } catch {
-                throw new CliError(
-                    `Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`,
-                );
+            } catch (err: any) {
+                if (err?.code === 'ERR_MODULE_NOT_FOUND' || err?.code === 'MODULE_NOT_FOUND') {
+                    throw new CliError(
+                        `Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`,
+                    );
+                }
+                throw new CliError(
+                    `Failed to load "better-sqlite3": ${err instanceof Error ? err.message : String(err)}`,
+                );
             }

Apply the same pattern to the pg and mysql2 blocks.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/actions/proxy.ts` around lines 143 - 150, The catch blocks
for dynamic imports (the SQLite import assigning to SQLite: typeof BetterSqlite3
and the similar pg and mysql2 import blocks) currently swallow all errors and
always surface a "package missing" CliError; change each catch to capture the
error (e.g., catch (err)) and inspect err.code (or err.message) — if it
indicates module-not-found (ERR_MODULE_NOT_FOUND / MODULE_NOT_FOUND) then throw
the existing CliError telling the user to install the package, otherwise rethrow
the original error or wrap it in a CliError that includes the original error
message so native addon/ABI failures are not misreported as "not installed".
Ensure this change is applied to the better-sqlite3, pg, and mysql2 dynamic
import blocks.

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

Comments