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] Seed process not working #8422

Merged
merged 3 commits into from
Oct 14, 2024
Merged

[Fix] Seed process not working #8422

merged 3 commits into from
Oct 14, 2024

Conversation

samuelmbabhazi
Copy link
Contributor

@samuelmbabhazi samuelmbabhazi commented Oct 14, 2024

PR

Please note: we will close your PR without comment if you do not check the boxes above and provide ALL requested information.


Summary by CodeRabbit

  • New Features

    • Enhanced SQL query generation for MySQL compatibility by replacing double quotes with backticks.
    • Implemented batch insertion for goal KPIs to improve performance and reduce deadlocks.
    • Improved project creation and member assignment processes with additional logic and database compatibility.
  • Bug Fixes

    • Added console warnings for missing organization contacts during project creation.
  • Documentation

    • Updated function signatures to reflect new parameters and logic changes.

@samuelmbabhazi samuelmbabhazi self-assigned this Oct 14, 2024
@samuelmbabhazi samuelmbabhazi marked this pull request as ready for review October 14, 2024 16:55
Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

The changes in this pull request involve modifications to several functions across different files to enhance SQL query handling and improve database operations. Key updates include the addition of MySQL-specific syntax handling in the replacePlaceholders function, the introduction of batch processing in the insertRandomGoalKpiInBatches function for improved KPI insertion, and updates to project creation and member assignment functions to accommodate different database types, particularly MySQL. These changes aim to enhance performance, reliability, and compatibility across various database systems.

Changes

File Path Change Summary
packages/core/src/core/utils.ts Modified replacePlaceholders to handle MySQL-specific syntax by replacing double quotes with backticks.
packages/core/src/goal-kpi/goal-kpi.seed.ts Updated createDefaultGoalKpi to call insertRandomGoalKpiInBatches, which includes batch processing for KPI insertion. New function signature includes batchSize.
packages/core/src/organization-project/organization-project.seed.ts Enhanced createDefaultOrganizationProjects and createRandomOrganizationProjects with better handling of organization contacts. Updated seedProjectMembersCount to support MySQL-specific SQL syntax.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant Database

    User->>API: Request to create default KPI
    API->>Database: Call insertRandomGoalKpiInBatches with batchSize
    Database-->>API: Return inserted KPIs
    API-->>User: Respond with success

    User->>API: Request to create organization projects
    API->>Database: Call createDefaultOrganizationProjects
    Database-->>API: Return created projects
    API-->>User: Respond with success
Loading

🐇 In the garden, where data flows,
A rabbit hops where the SQL grows.
With backticks for MySQL's grace,
And batches to keep up the pace.
Projects bloom, KPIs align,
In CodeRabbit's world, all works fine! 🌼


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 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.

@samuelmbabhazi
Copy link
Contributor Author

Capture d’écran du 2024-10-14 18-49-42

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

🧹 Outside diff range and nitpick comments (6)
packages/core/src/core/utils.ts (2)

Line range hint 720-732: Refactor replacePlaceholders for improved clarity and maintainability

While the function works as intended, its structure could be improved for better readability and maintainability. Consider the following suggestions:

  1. Add a function-level comment explaining its purpose and parameters.
  2. Use a switch statement instead of multiple if conditions for different database types.
  3. Separate the placeholder replacement logic from the MySQL-specific quoting logic.

Here's a suggested refactoring:

/**
 * Adjusts SQL query placeholders and quoting based on the database type.
 * @param query - The original SQL query
 * @param dbType - The type of the database
 * @returns The adjusted SQL query
 */
export function replacePlaceholders(query: string, dbType: DatabaseTypeEnum): string {
    switch (dbType) {
        case DatabaseTypeEnum.sqlite:
        case DatabaseTypeEnum.betterSqlite3:
            return query.replace(/\$\d+/g, '?');
        case DatabaseTypeEnum.mysql:
            return query.replace(/\$\d+/g, '?').replace(/"/g, '`');
        default:
            return query;
    }
}

This refactoring improves readability and makes it easier to add support for additional database types in the future.


Line range hint 720-732: Consider broader refactoring for database-type handling consistency

The replacePlaceholders function is part of a larger set of database-related utility functions in this file. To improve overall code consistency and maintainability, consider the following suggestions:

  1. Create a common pattern for handling different database types across all relevant functions.
  2. Consider extracting database-specific logic into separate helper functions or a dedicated module.
  3. Ensure consistent error handling and edge case management across all database-related functions.

Here's an example of how you might start this refactoring:

  1. Create a new file database-utils.ts with specific helpers for each database type.
  2. In utils.ts, use these helpers to simplify the logic:
import { adjustQueryForSQLite, adjustQueryForMySQL } from './database-utils';

export function replacePlaceholders(query: string, dbType: DatabaseTypeEnum): string {
    switch (dbType) {
        case DatabaseTypeEnum.sqlite:
        case DatabaseTypeEnum.betterSqlite3:
            return adjustQueryForSQLite(query);
        case DatabaseTypeEnum.mysql:
            return adjustQueryForMySQL(query);
        default:
            return query;
    }
}

This approach would make it easier to maintain database-specific logic and ensure consistency across the codebase.

packages/core/src/goal-kpi/goal-kpi.seed.ts (2)

31-31: Consider making batchSize a constant or configuration

The hardcoded value 100 for batchSize could be defined as a constant or retrieved from a configuration to enhance maintainability and readability.

Apply this diff to define BATCH_SIZE as a constant:

+const BATCH_SIZE = 100;
...

-return insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);
+return insertRandomGoalKpiInBatches(dataSource, goalKpis, BATCH_SIZE);

34-50: Rename function for clarity

The function name insertRandomGoalKpiInBatches might be misleading since it doesn't generate random GoalKPIs but inserts provided ones. Consider renaming it to insertGoalKpisInBatches to improve clarity.

Apply this diff to rename the function:

-const insertRandomGoalKpiInBatches = async (
+const insertGoalKpisInBatches = async (
    dataSource: DataSource,
    goalKpis: GoalKPI[],
    batchSize: number
): Promise<GoalKPI[]> => {
...
}

...

-return insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);
+return insertGoalKpisInBatches(dataSource, goalKpis, 100);
packages/core/src/organization-project/organization-project.seed.ts (2)

Line range hint 235-238: Ensure consistent function declaration style

The seedProjectMembersCount function has been changed from an exported constant assigned to an anonymous function to an exported named async function. For consistency and readability, consider using the same function declaration style throughout the codebase. Most functions in this file are declared using export const functionName = async () => {} syntax.


Line range hint 269-301: Consider using QueryBuilder to construct database-agnostic queries

Using raw SQL queries with database-specific syntax can introduce maintenance challenges and increase the potential for errors. Consider utilizing TypeORM's QueryBuilder to construct the update statements. This approach abstracts away database-specific syntax differences, enhances readability, and improves maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ad84931 and 088315d.

📒 Files selected for processing (3)
  • packages/core/src/core/utils.ts (1 hunks)
  • packages/core/src/goal-kpi/goal-kpi.seed.ts (1 hunks)
  • packages/core/src/organization-project/organization-project.seed.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
packages/core/src/core/utils.ts (2)

Line range hint 1-732: Overall assessment: Positive changes with room for further improvements

The changes to the replacePlaceholders function improve MySQL compatibility, which is a valuable addition. However, this review has identified several areas for potential improvement:

  1. The immediate changes could be refactored for better clarity and maintainability.
  2. There's an opportunity for a broader refactoring to improve consistency in handling different database types across the file.
  3. Consider extracting database-specific logic into separate helper functions or a dedicated module.

These improvements would enhance the overall quality, maintainability, and extensibility of the codebase. While the current changes are approved, I recommend considering these suggestions for future iterations.


728-732: Enhance MySQL compatibility with backtick quoting

The addition of MySQL-specific handling for identifier quoting is a good improvement. It ensures that column and table names are properly escaped in MySQL queries, preventing potential syntax errors.

However, there are a couple of points to consider:

  1. The condition [DatabaseTypeEnum.mysql].includes(dbType) can be simplified to dbType === DatabaseTypeEnum.mysql.
  2. This change might affect existing queries that rely on double quotes for string literals.

To ensure this change doesn't introduce unintended side effects, please run the following verification script:

This script will help identify any potential conflicts or issues that might arise from this change across the codebase.

packages/core/src/organization-project/organization-project.seed.ts (1)

272-285: ⚠️ Potential issue

Verify the database type comparison for accurate condition checking

In the condition if (dataSource.options.type === DatabaseTypeEnum.mysql), ensure that dataSource.options.type and DatabaseTypeEnum.mysql are of compatible types and values. TypeORM's dataSource.options.type is typically a string (e.g., 'mysql'), so confirm that DatabaseTypeEnum.mysql matches this string value to prevent incorrect query execution.

To verify the values, you can log them:

console.log('dataSource.options.type:', dataSource.options.type);
console.log('DatabaseTypeEnum.mysql:', DatabaseTypeEnum.mysql);

Alternatively, run the following script to check the value of DatabaseTypeEnum.mysql:

@@ -27,12 +27,25 @@ export const createDefaultGoalKpi = async (
goalKpis.push(goalKpi);
});
});
return await insertRandomGoalKpi(dataSource, goalKpis);
// Insert in batches to prevent deadlocks
return await insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unnecessary await in return statement

In an async function, using return await is redundant because the returned promise will be awaited automatically. You can simplify the code by removing the await.

Apply this diff to simplify the return statement:

-return await insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);
+return insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);
📝 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
return await insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);
return insertRandomGoalKpiInBatches(dataSource, goalKpis, 100);

Comment on lines +44 to +47
await dataSource.transaction(async (manager) => {
await manager.save(batch);
});
insertedGoalKpis.push(...batch);
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 returned entities from save method to capture generated values

When saving entities using manager.save(batch), the method returns the saved entities, including any generated values like IDs or timestamps. Currently, you're adding the original batch to insertedGoalKpis, which might miss these updates. Capture the returned entities instead.

Apply this diff to collect the saved entities:

 await dataSource.transaction(async (manager) => {
-    await manager.save(batch);
+    const savedBatch = await manager.save(batch);
+    insertedGoalKpis.push(...savedBatch);
 });
-insertedGoalKpis.push(...batch);
📝 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
await dataSource.transaction(async (manager) => {
await manager.save(batch);
});
insertedGoalKpis.push(...batch);
await dataSource.transaction(async (manager) => {
const savedBatch = await manager.save(batch);
insertedGoalKpis.push(...savedBatch);
});

Copy link

nx-cloud bot commented Oct 14, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit 088315d. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


🟥 Failed Commands
nx serve api -c=production --prod

Sent with 💌 from NxCloud.

@evereq evereq merged commit cb03af4 into develop Oct 14, 2024
19 of 20 checks passed
@evereq evereq deleted the fix/8414-seed-process branch October 14, 2024 19:08
evereq added a commit that referenced this pull request Oct 14, 2024
* feat: #8386 global logging API middleware

* fix: #8386 save API response into DB

* fix: store missing user id to the tabele

* fix: favorite entity type use global entity enum

* fix: #8386 api call log module middleware routes

* fix: improvement suggested by CodeRabbit

* fix: #8386 recursively process nested objects and arrays

* fix: updated logger

* feat(ActivityLog): Optimize beforeEntityCreate and beforeEntityUpdate methods

- Centralized serialization logic for SQLite databases into a single method `serializeDataForSQLite`.
- Refactored `beforeEntityCreate` and `beforeEntityUpdate` methods to delegate serialization logic to the new method.

* fix(cspell): typo spelling :-)

* fix: no need to store empty object into DB

* fix(api-call-log): correct middleware configuration for time tracking routes

- Replaced the unsupported regular expression pattern in route paths with the correct wildcard pattern ('/timesheet/*') in the `ApiCallLogMiddleware`.

* feat: login components to handle workspace login and navigation

* fix:  rename `_errorHandlingService` to `errorHandlingService` and update type annotations in `NgxLoginComponent` constructor and `tap` callback.

* resolves #8379 by fixing late desktop theme listener setup

* fix: login components to handle workspace navigation and state

* fix: #8386 updated call log middleware

* fix: #8386 added http method transformer pipe

* fix: ensure robust extraction of token from authorization header

* fix: optimize code based on coderabbitai suggestion

* fix: apply filters on logging API

* refactor: time tracker component to combine conditions for retrieving remote log and handle API request

* feat: add two function calls to updateTaskStatus and updateOrganizationTeamEmployee on silent restart

* fix: improve ActorTypeTransformerPipe for integer storage

* feat: add missing `version` property to timer objects in SequenceQueue and TimeTrackerComponent.

* fix: optimize code based on coderabbitai suggestion

* fix: optimize code based on coderabbitai suggestion

* [Fix] View and Resource Links Activity Logs (#8409)

* fix: organization sprint update activity log

* feat: task view activity log

* feat: resource link activity log

* fix: removed unecessary js-docs

* fix: use global base entity enum

* fix: CodeRabbit suggestions

* fix: CodeRabbit suggestions

---------

Co-authored-by: Ruslan Konviser <evereq@gmail.com>

* [Feat] Selector update persistence electron side (#8421)

* feat: create electron selector service

* feat: electronService with selectorElectronService in client-selector, note, project-selector, task-selector, and team-selector components

* fix: rename 'refresh' method to 'clear' in client-selector, project-selector, task-selector, and team-selector components

* feat: add conditional check for `this.useStore` in `clear()` method of ClientSelector, ProjectSelector, TaskSelector, and TeamSelector components.

* [Fix] Seed process not working (#8422)

* [Fix] Seed process not working

* [Fix] Seed process not working

* chore: windows builds

---------

Co-authored-by: Rahul R. <rahulrathore576@gmail.com>
Co-authored-by: GloireMutaliko21 <mufunyig@gmail.com>
Co-authored-by: Kifungo A <45813955+adkif@users.noreply.github.com>
Co-authored-by: Gloire Mutaliko (Salva) <86450367+GloireMutaliko21@users.noreply.github.com>
Co-authored-by: samuel mbabhazi <111171386+samuelmbabhazi@users.noreply.github.com>
@samuelmbabhazi samuelmbabhazi linked an issue Oct 15, 2024 that may be closed by this pull request
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.

[Fix] Seed process not working
2 participants