Skip to content

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

Closed
Ljhhhhhh wants to merge 6 commits intoopentiny:developfrom
Ljhhhhhh:develop
Closed

fix: fixed material generation and database connection for components#1152
Ljhhhhhh wants to merge 6 commits intoopentiny:developfrom
Ljhhhhhh:develop

Conversation

@Ljhhhhhh
Copy link
Contributor

@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.
    • Improved error handling for internationalization properties to prevent potential null reference errors.
    • Enhanced state handling by explicitly managing different types and ensuring robustness in getter computations.
    • Simplified assignment of state variables in the VariableConfigurator for improved clarity.
    • Introduced fallback mechanisms for property assignments in app state to accommodate different naming conventions.

…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
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

Walkthrough

The changes involve multiple 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, including updating 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. Additionally, in packages/toolbars/generate-code/src/Main.vue, error handling for the i18n property within the metaData object was introduced.

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.
packages/toolbars/generate-code/src/Main.vue Introduced error handling for the i18n property within the metaData object, ensuring it is initialized as an empty object if undefined, preventing potential null reference errors.

Possibly related PRs

  • fix: update splitMaterial and buildMaterials path #1094: The changes in the main PR regarding the generateComponents function's destructuring assignment are related to the enhancements made in the error handling of the same function in the retrieved PR, as both modifications directly affect the logic within scripts/buildMaterials.mjs.
  • Fix split materials,Complete the npm information of the component.json file #1154: The changes in the main PR, which involve repositioning the destructuring assignment of the npm object in the generateComponents function, are related to the retrieved PR that enhances the npm field in the splitMaterials function by completing its information, as both modifications focus on the handling of the npm object.
  • fix: fixed material generation and database connection for components #1151: The changes in the main PR are directly related to the same generateComponents function in scripts/buildMaterials.mjs, where the destructuring assignment for the npm object is repositioned, similar to the modifications in the retrieved PR that also involve the same function and variables.

Suggested labels

refactor-main

Suggested reviewers

  • hexqi
  • chilingling

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! 🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/canvas/render/src/application-function/global-state.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/packages/canvas".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "packages/canvas/.eslintrc.cjs » @vue/eslint-config-typescript".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ab1c1b and 27b4320.

📒 Files selected for processing (3)
  • packages/canvas/render/src/application-function/global-state.ts (1 hunks)
  • packages/configurator/src/variable-configurator/VariableConfigurator.vue (1 hunks)
  • packages/plugins/materials/src/composable/useResource.js (1 hunks)
🔇 Additional comments (3)
packages/configurator/src/variable-configurator/VariableConfigurator.vue (1)

507-519: Good simplification to avoid incorrect store visualization.

The change properly simplifies store variable handling by only displaying store IDs rather than attempting to show their nested properties. The commented code and added note clearly explain that store processing has been moved to global-state.ts, which aligns with the overall architecture improvements.

packages/plugins/materials/src/composable/useResource.js (1)

146-147: Improved property access with fallback for naming convention differences.

This change enhances the flexibility of property assignments by supporting both camelCase and snake_case naming conventions in the API response. This is a good defensive programming approach to handle potential inconsistencies in the API data format.

packages/canvas/render/src/application-function/global-state.ts (1)

16-52: Excellent enhancement for robust state handling.

This refactoring significantly improves how different types of state are handled:

  1. Properly handles array states while preserving their structure
  2. Adds robust error handling for getter computation failures
  3. Correctly processes primitive values and null states
  4. Uses appropriate type checking before operations

The code is well-structured with clear logical separation between different state types and getter handling scenarios. This change will prevent runtime errors when working with varied state structures.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

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.

Ljhhhhhh and others added 4 commits March 6, 2025 15:38
- 重构 global-state.ts 中的状态处理,支持数组和对象类型的状态计算
- 修改 VariableConfigurator.vue 中的变量加载方式
- 更新 useResource 中的应用状态获取逻辑,增加兼容性
@chilingling
Copy link
Member

chilingling commented Mar 11, 2025

这里的 commit 跟 #1207 的 commit 有重复,需要分离一下 @Ljhhhhhh

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


The commit here is repeated with the commit of #1208, so it needs to be separated.

@Ljhhhhhh Ljhhhhhh closed this Mar 11, 2025
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.

3 participants