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

fix: fixed material generation and database connection for components #1152

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

Ljhhhhhh
Copy link

@Ljhhhhhh Ljhhhhhh commented Feb 27, 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

  • Refactor
    • Adjusted internal processing of material components for clearer, more consistent ordering.
    • Streamlined database interactions by updating table references, query structures, and parameter names to enhance component management.

…t libraries

- Add support for TinyVue and Element Plus component libraries in material generation
- Update database connection script with new table and column names
- Modify component insertion logic to match new database schema
- Add version and script details for third-party component libraries
Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

Walkthrough

The changes involve two files. In scripts/buildMaterials.mjs, the destructuring of the npm object is repositioned to occur before assigning appInfo.materialHistory.components, ensuring the values are available for constructing the mapItem object. In scripts/connection.mjs, several database-related modifications were applied. These include updating the table name references, renaming methods (with the old relationMaterialHistory now becoming relationMaterialBlockHistory and a new relationMaterialHistory method added with a deprecation notice), and revising parameters and SQL queries in the insertComponent and initDB functions.

Changes

File(s) Summary
scripts/buildMaterials.mjs Moved the destructuring assignment for the npm object (extracting packageName, version, and exportName) before the assignment to appInfo.materialHistory.components. Removed a redundant extraction to streamline the usage in the later construction of the mapItem object.
scripts/connection.mjs Updated the database layer by changing the table name from 'user_components' to 't_component' and the material history ID from 639 to 1. Renamed relationMaterialHistory to relationMaterialBlockHistory (with a new relationMaterialHistory added that issues a deprecation notice). Also, updated parameter names and SQL queries in both insertComponent and initDB methods.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Build Process
    participant GC as generateComponents
    Caller->>GC: Initiate component generation
    GC->>GC: Destructure npm object (packageName, version, exportName)
    GC->>GC: Assign appInfo.materialHistory.components
    GC->>GC: Construct mapItem using the destructured values
    GC-->>Caller: Return processed components
Loading
sequenceDiagram
    participant App as Application
    participant Conn as MysqlConnection
    participant DB as Database

    App->>Conn: Call relationMaterialBlockHistory(id)
    Conn->>DB: Execute SQL query on "r_material_history_component"
    DB-->>Conn: Return result
    Conn-->>App: Return data

    App->>Conn: Call new relationMaterialHistory(id)
    Conn->>DB: Execute updated SQL query (with deprecation notice)
    DB-->>Conn: Return result
    Conn-->>App: Return data
Loading

Possibly related PRs

Suggested labels

bug, refactor-main

Suggested reviewers

  • rhlin
  • hexqi

Poem

Hop, hop along the code lane,
A bunny tweaks with a happy gain.
Destructuring in place, so neat and right,
Database queries now in clear sight.
With each line and SQL spark,
We celebrate changes from dawn till dark! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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.
  • @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.

@github-actions github-actions bot added the bug Something isn't working label Feb 27, 2025
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: 3

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

205-208: Provide concrete deprecation timeline and usage details.
Using @deprecated is a good start, but consider documenting the removal version or guiding developers how to migrate to the newer relationMaterialHistory method. This ensures a clear path forward.


301-308: Hard-coded defaults might limit flexibility.
The new fields (component_metadata, library_id, tenant_id, renter_id, site_id, created_by, last_updated_by) default to null or 1. If multiple tenants or sites exist, these static values may cause conflicts.

Do you want to parameterize these fields or load them from environment variables for increased flexibility?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 36a2b5e and 67760dc.

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

153-154: Destructuring logic looks solid.
Extracting package, version, and exportName from npm early on prevents undefined errors and maintains readability. The fallback to {} ensures safe defaults if npm is missing.

scripts/connection.mjs (1)

18-20: Verify references after renaming table and altering history ID.
Renaming the table to 't_component' and resetting materialHistoryId to 1 could potentially break references in other parts of the code if they rely on the old table name or on the previous history ID.

Would you like me to generate a script to find any remaining references to the old table name or history ID?

@@ -335,7 +359,7 @@ class MysqlConnection {
* @param {object} component 组件数据
*/
initDB(component) {
const selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE component = '${component.component}'`
const selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE name_en = '${component.component}'`
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

Mismatch between “name_en” and “component.component”.
The query filters on name_en, yet we're passing the property component.component. If component.component doesn’t match the stored name_en, the lookup will fail.

Apply this diff to maintain consistency with the actual stored column and data:

- const selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE name_en = '${component.component}'`
+ const selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE component = '${component.component}'`
📝 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 selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE name_en = '${component.component}'`
const selectSqlContent = `SELECT * FROM ${this.config.database}.${componentsTableName} WHERE component = '${component.component}'`

Comment on lines +340 to +343
const sqlContent = `INSERT INTO ${componentsTableName} (version, name, name_en, icon, description, doc_url,
screenshot, tags, keywords, dev_mode, npm, \`group\`, \`category\`, priority, snippets,
schema_fragment, configure, \`public\`, framework, isOfficial, isDefault, tiny_reserved,
tenant, createdBy, updatedBy) VALUES ${values}`.replace(/\n/g, '')
schema_fragment, configure, \`public\`, framework, is_official, is_default, tiny_reserved,component_metadata,
library_id, tenant_id, renter_id, site_id, created_by, last_updated_by) VALUES ${values}`.replace(/\n/g, '')
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

Schema mismatch for “name_en” and “component_metadata”.
This insert statement references name_en and component_metadata, but the table definition does not declare a name_en column. This will fail unless the table schema is updated accordingly.

A possible fix in your CREATE TABLE statement might be:

  CREATE TABLE t_component (
    ...
+   name_en varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
    component_metadata longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
    ...
  );

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

Comment on lines +219 to +232
/**
* 新建的组件关联物料资产包
* @param {number} id 新建的组件id
*/
relationMaterialHistory(id) {
const uniqSql = `SELECT * FROM \`r_material_history_component\` WHERE \`material_history_id\`=${materialHistoryId} AND \`component_id\`=${id}`
this.query(uniqSql).then((result) => {
if (!result.length) {
const sqlContent = `INSERT INTO \`r_material_history_component\` (\`material_history_id\`, \`component_id\`) VALUES (${materialHistoryId}, ${id})`
this.query(sqlContent)
}
})
}

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

Use parameterized queries to prevent SQL injection.
Directly concatenating id into the SQL statement may be risky if the value is not guaranteed to be an integer. Parameterized queries will secure this method and help avoid potential injection vulnerabilities.

Possible fix using placeholders (for example in MySQL Node libraries):

- const uniqSql = `SELECT * FROM \`r_material_history_component\` WHERE \`material_history_id\`=${materialHistoryId} AND \`component_id\`=${id}`
- ...
- const sqlContent = `INSERT INTO \`r_material_history_component\` (\`material_history_id\`, \`component_id\`) VALUES (${materialHistoryId}, ${id})`
+ const uniqSql = 'SELECT * FROM `r_material_history_component` WHERE `material_history_id` = ? AND `component_id` = ?'
+ ...
+ const sqlContent = 'INSERT INTO `r_material_history_component` (`material_history_id`, `component_id`) VALUES (?, ?)'
...

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant