Skip to content

feat: add sql script#32

Merged
hexqi merged 4 commits intoopentiny:mainfrom
lu-yg:feat/migration
Aug 4, 2025
Merged

feat: add sql script#32
hexqi merged 4 commits intoopentiny:mainfrom
lu-yg:feat/migration

Conversation

@lu-yg
Copy link
Contributor

@lu-yg lu-yg commented Jul 25, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced a command-line SQL data migration tool with detailed logging and support for multiple database tables.
    • Added a structured logging utility for improved command-line output clarity.
    • Added a new script to run database migrations easily from the command line.
  • Chores

    • Added a new dependency to support MySQL database operations.
    • Updated npm scripts for easier execution of migration tasks.

@coderabbitai
Copy link

coderabbitai bot commented Jul 25, 2025

Walkthrough

A new SQL data migration utility was introduced, including a comprehensive script for migrating data between MySQL databases with transformation logic for various tables. Supporting this, a structured Logger class was added for consistent logging. The package.json was updated to add the mysql2 dependency and new npm scripts for running the migration.

Changes

Cohort / File(s) Change Summary
Package configuration - package.json
Added "sql" npm script, updated "clean" script for JSON syntax, and added "mysql2" dependency.
Logging utility - scripts/logger.mjs
Introduced Logger class with methods for info, warn, error, and success logs; uses picocolors for color-coded output.
SQL migration script - scripts/sqlScript.mjs
Added SqlScript class implementing data migration for many tables with transformation functions, batch inserts, connection pooling, and detailed logging.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NpmScript
    participant SqlScript
    participant Logger
    participant SourceDB
    participant TargetDB

    User->>NpmScript: Run "npm run sql"
    NpmScript->>SqlScript: Execute sqlScript.mjs
    SqlScript->>SourceDB: Connect to source DB
    SqlScript->>TargetDB: Connect to target DB
    loop For each table
        SqlScript->>SourceDB: Fetch rows from source table
        SqlScript->>SqlScript: Transform rows
        SqlScript->>TargetDB: Batch insert into target table
        SqlScript->>Logger: Log progress
    end
    SqlScript->>Logger: Log migration completion
    SqlScript->>SourceDB: Close connection
    SqlScript->>TargetDB: Close connection
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

In tunnels deep where data flows,
The rabbit hops where SQL grows.
With Logger bright and scripts anew,
It migrates tables, old to new.
A whiskered cheer for code so neat,
🐇—migration magic can't be beat!

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

🧹 Nitpick comments (2)
scripts/sqlScript.mjs (2)

52-53: Use strict equality operators

Replace loose equality (==) with strict equality (===) for better type safety.

-      if (rows.length == 0) {
+      if (rows.length === 0) {
-    if (data.length == 0) {
+    if (data.length === 0) {

Also applies to: 83-84


120-124: Extract repeated null handling to a helper function

The pattern item.field == null ? "1" : item.field is repeated many times. Consider extracting it to a helper function for better maintainability.

+// Add this helper function at the top of the class
+function defaultIfNull(value, defaultValue = "1") {
+  return value == null ? defaultValue : value;
+}

// Then in transform functions:
-created_by: item.created_by == null ? "1" : item.created_by,
+created_by: defaultIfNull(item.created_by),

Also applies to: 187-190, 300-303, 337-340, 374-378, 394-397, 409-412, 437-441, 460-463, 509-513, 538-542, 559-562, 575-578

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e31f2f3 and 04bd8aa.

📒 Files selected for processing (3)
  • package.json (2 hunks)
  • scripts/logger.mjs (1 hunks)
  • scripts/sqlScript.mjs (1 hunks)
🔇 Additional comments (6)
scripts/logger.mjs (1)

14-51: Logger implementation looks good!

The Logger class provides a clean, structured approach for console logging with color-coded output. The implementation is well-organized and follows good practices.

package.json (2)

27-28: Script additions look good

The new "sql" script correctly points to the migration script, and the trailing comma addition improves JSON formatting consistency.


69-69: Dependency Verification – mysql2@3.14.2

  • Confirmed that mysql2@3.14.2 is the latest stable release as of July 2025.
  • No known unresolved security vulnerabilities; CVE-2024-21507 and other past issues were patched in earlier 3.x releases.

Changes look safe—approving this dependency update.

scripts/sqlScript.mjs (3)

282-289: Good handling of SQL-incompatible property names

The transform functions correctly handle property names with hyphens (e.g., 'block-category_id') by using computed property access and renaming them to valid SQL identifiers. This prevents SQL syntax errors.

Also applies to: 311-318, 471-478, 483-490


684-687: Important migration conflict warning

Good documentation about potential data conflicts when migrating block groups. This helps prevent data integrity issues.


29-30: Source and target pools use the same database

Both connection pools connect to the same database. If this is intentional for in-place transformation, consider adding a comment. If not, the target database configuration should be different.

Is the intention to transform data within the same database, or should there be separate source and target databases?

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

♻️ Duplicate comments (4)
scripts/sqlScript.mjs (4)

17-37: Critical: Remove hardcoded database credentials

This duplicates a previously identified security issue. The hardcoded database credentials in both nodeConfig and javaConfig pose serious security risks and should be externalized to environment variables.


93-119: Potential SQL injection risk with dynamic table names

This duplicates a previously identified concern about SQL injection risks when dynamically interpolating table and column names, even though parameterized queries are used for values.


595-679: Consider using the established migration pattern for platform data

This duplicates a previously identified inconsistency where the platform method uses raw SQL insertion instead of the established migrateTable pattern used elsewhere in the script.


685-727: Add transaction support for data integrity

This duplicates a previously identified concern about the lack of transaction support, which could leave the database in an inconsistent state if migration fails partway through.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 04bd8aa and c32fcd0.

📒 Files selected for processing (1)
  • scripts/sqlScript.mjs (1 hunks)
🔇 Additional comments (2)
scripts/sqlScript.mjs (2)

43-85: LGTM: Well-structured migration method

The migrateTable method demonstrates good practices with proper connection management, parameterized queries, comprehensive error handling, and resource cleanup in the finally block.


582-584: Verify field mapping in tenant transformation

The field mappings appear to be swapped:

  • name_cn: item.tenant_id (assigning tenant_id to Chinese name)
  • name_en: item.name_cn (assigning Chinese name to English name)

Please verify this is intentional or if the mappings should be corrected.

@hexqi hexqi merged commit 54f1aff into opentiny:main Aug 4, 2025
1 check 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

Comments