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

097 Feb 20: Add demo flag in table for mock data #824

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

Conversation

HarshP4585
Copy link
Collaborator

@HarshP4585 HarshP4585 commented Feb 20, 2025

Describe your changes

  • Added is_demo flag in tables for mock data

Issue number

  • NA

Please ensure all items are checked off before requesting a review:

  • I deployed the code locally.
  • I have performed a self-review of my code.
  • I have included the issue # in the PR.
  • I have labelled the PR correctly.
  • The issue I am working on is assigned to me.
  • I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
  • I made sure font sizes, color choices etc are all referenced from the theme.
  • My PR is granular and targeted to one specific feature.
  • I took a screenshot or a video and attached to this PR if there is a UI change.

Summary by CodeRabbit

  • New Features

    • Introduced a demo marker across multiple records to distinguish demonstration data.
  • Refactor

    • Standardized data insertion with automatic inclusion of the demo flag.
    • Streamlined the demo data cleanup process, ensuring consistent removal across related records.
  • Chore

    • Updated sample user data by removing outdated entries.

These changes improve data consistency and simplify the management of demo versus production records.

@HarshP4585 HarshP4585 added the backend Backend related tasks/issues label Feb 20, 2025
@HarshP4585 HarshP4585 self-assigned this Feb 20, 2025
Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Walkthrough

The pull request introduces a new boolean column is_demo across multiple SQL tables to flag demo records and updates SQL command strings accordingly. The changes modify the insertion logic in the driver file to append a demo flag value and refactor the deletion process to loop over tables and call a consolidated utility function for removing demo data. Additionally, several legacy utility functions have been removed and some mock user entries are commented out.

Changes

File / Group Change Summary
SQL_Commands.sql Added a new column is_demo BOOLEAN to the tables: roles, users, projects, vendors, assessments, controlcategories, controls, subcontrols, projectrisks, vendorrisks, vendors_projects, projectscopes, topics, subtopics, questions, and files. Modified the PRIMARY KEY of vendors_projects to include is_demo.
Servers/driver/autoDriver.driver.ts Updated insertQuery statements for multiple entities to include is_demo and modified the generateValuesString functions to append a demo value ('1'). Refactored deleteMockData to loop through table names and call a unified deletion function.
Servers/mocks/users.data.ts Commented out the user entries for "Cathy", "David", and "Eva" from the returned data array.
Servers/utils/autoDriver.util.ts Removed several utility functions (checkTableExists, createTable, deleteExistingData, dropTable, and checkDataExists). Introduced a new function deleteDEMOData to delete demo data from a specified table with special handling when the table is "vendors".

Sequence Diagram(s)

sequenceDiagram
    participant D as autoDriver.driver.ts
    participant U as autoDriver.util.ts
    D->>D: deleteMockData()
    loop For each table in demo deletion list
        D->>U: deleteDEMOData(tableName)
        alt tableName is "vendors"
            U->>U: Retrieve vendor IDs where is_demo = true
            U->>U: Delete matching entries from vendors_projects
        end
        U->>U: Delete entries where is_demo is true in table
    end
    D->>D: Complete deletion process
Loading

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • MuhammadKhalilzadeh

Poem

I'm a little bunny hopping by,
Adding is_demo with a gleam in my eye,
Tables get a flag so clear,
In SQL land, there's cheer,
Code now dances with a fresh supply!
🐇💻 Enjoy the changes, oh my!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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
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 comments (2)
Servers/driver/autoDriver.driver.ts (1)

41-345: 🛠️ Refactor suggestion

Use boolean values for is_demo flag.

The insert queries use string '1' for the is_demo flag instead of proper boolean values. This could cause type mismatches with the database schema.

Replace all occurrences of '1' with true in the generateValuesString functions. Example:

-        '1'
+        true
SQL_Commands.sql (1)

1-208: 🛠️ Refactor suggestion

Enhance database schema for demo data.

Consider the following improvements:

  1. Add default value for is_demo column
  2. Add index for performance optimization
  3. Include migration strategy for existing data

Apply these changes to the schema:

 ALTER TABLE roles ADD COLUMN is_demo BOOLEAN DEFAULT false;
+CREATE INDEX idx_roles_is_demo ON roles(is_demo);
 
 ALTER TABLE users ADD COLUMN is_demo BOOLEAN DEFAULT false;
+CREATE INDEX idx_users_is_demo ON users(is_demo);
 
 -- Repeat for other tables

Also, consider adding a migration script to handle existing data:

-- Set is_demo = false for existing records
UPDATE roles SET is_demo = false WHERE is_demo IS NULL;
UPDATE users SET is_demo = false WHERE is_demo IS NULL;
-- Repeat for other tables
🧹 Nitpick comments (1)
Servers/mocks/users.data.ts (1)

27-59: Remove commented-out code.

Instead of keeping commented-out mock user entries, they should be removed entirely. If needed, these entries can be retrieved from version control history.

Apply this diff to clean up the code:

-    // {
-    //   id: 3,
-    //   name: "Cathy",
-    //   surname: "Brown",
-    //   email: "[email protected]",
-    //   password_hash:
-    //     "$2b$10$7qXYDROKyGgH3lpWL0dJR.dRN1T0AvG.J7EmZHF9iVqptQWAWHq.a",
-    //   role: role3, // Editor
-    //   created_at: new Date("2024-03-10"),
-    //   last_login: new Date("2024-09-28"),
-    // },
-    // {
-    //   id: 4,
-    //   name: "David",
-    //   surname: "Wilson",
-    //   email: "[email protected]",
-    //   password_hash:
-    //     "$2b$10$7yo46.rtqbrn4fxxLENu5eqfvfi8pYXm00sceVM3Ash7PlZuGONOa",
-    //   role: role4, // Auditor
-    //   created_at: new Date("2024-04-05"),
-    //   last_login: new Date("2024-09-30"),
-    // },
-    // {
-    //   id: 5,
-    //   name: "Eva",
-    //   surname: "Clark",
-    //   email: "[email protected]",
-    //   password_hash:
-    //     "$2b$10$3T5VhzKdBpUPXqHuiKZXJusPdR7k.SmwRbl3fopf4XEJhMfgyYSOO",
-    //   role: role2, // Reviewer
-    //   created_at: new Date("2024-05-20"),
-    //   last_login: new Date("2024-09-18"),
-    // },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3bc53d0 and c5c3ef9.

📒 Files selected for processing (4)
  • SQL_Commands.sql (10 hunks)
  • Servers/driver/autoDriver.driver.ts (12 hunks)
  • Servers/mocks/users.data.ts (1 hunks)
  • Servers/utils/autoDriver.util.ts (1 hunks)

Comment on lines +8 to 16
export async function deleteDEMOData(tablename: string) {
if (tablename === "vendors") {
const result = await pool.query(`SELECT id FROM vendors WHERE is_demo;`)
await Promise.all(result.rows.map(async r => {
await pool.query(`DELETE FROM vendors_projects WHERE vendor_id = ${r.id}`)
}))
}
await pool.query(`DELETE FROM ${tablename} WHERE is_demo;`)
}
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

Fix SQL injection vulnerability and add error handling.

The function has several issues that need to be addressed:

  1. SQL injection vulnerability in the vendor ID interpolation
  2. Missing error handling for database operations
  3. No transaction management for cascading deletes

Apply this diff to fix the issues:

 export async function deleteDEMOData(tablename: string) {
+  const client = await pool.connect();
+  try {
+    await client.query('BEGIN');
     if (tablename === "vendors") {
-      const result = await pool.query(`SELECT id FROM vendors WHERE is_demo;`)
+      const result = await client.query(`SELECT id FROM vendors WHERE is_demo;`);
       await Promise.all(result.rows.map(async r => {
-        await pool.query(`DELETE FROM vendors_projects WHERE vendor_id = ${r.id}`)
+        await client.query(`DELETE FROM vendors_projects WHERE vendor_id = $1`, [r.id]);
       }))
     }
-    await pool.query(`DELETE FROM ${tablename} WHERE is_demo;`)
+    await client.query(`DELETE FROM $1 WHERE is_demo;`, [tablename]);
+    await client.query('COMMIT');
+  } catch (error) {
+    await client.query('ROLLBACK');
+    throw new Error(`Failed to delete demo data from ${tablename}: ${error.message}`);
+  } finally {
+    client.release();
+  }
 }

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

Comment on lines 563 to 576
export async function deleteMockData() {
const projects = await getDEMOProjects()
for (let project of projects) {
await deleteProjectByIdQuery(project.id)
};
await deleteExistingData("vendors", "vendor_name");
await deleteExistingData("users", "name");
// await deleteExistingData("roles", "name");
// const projects = await getDEMOProjects()
// for (let project of projects) {
// await deleteProjectByIdQuery(project.id)
// };
// await deleteExistingData("vendors", "vendor_name");
// await deleteExistingData("users", "name");
// // await deleteExistingData("roles", "name");

for (let table of ["questions", "subtopics", "topics", "projectscopes", "projectrisks", "vendorrisks",
"subcontrols", "controls", "controlcategories", "assessments", "vendors", "projects", "users"]) {
await deleteDEMOData(table)
}
}
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

Improve demo data deletion logic.

The function has several issues:

  1. Commented code should be removed
  2. Table names are hardcoded and could be out of sync with schema
  3. No error handling for failed deletions

Apply this diff to improve the code:

 export async function deleteMockData() {
-  // const projects = await getDEMOProjects()
-  // for (let project of projects) {
-  //   await deleteProjectByIdQuery(project.id)
-  // };
-  // await deleteExistingData("vendors", "vendor_name");
-  // await deleteExistingData("users", "name");
-  // // await deleteExistingData("roles", "name");
-
-  for (let table of ["questions", "subtopics", "topics", "projectscopes", "projectrisks", "vendorrisks",
-    "subcontrols", "controls", "controlcategories", "assessments", "vendors", "projects", "users"]) {
-    await deleteDEMOData(table)
+  const tables = [
+    "questions", "subtopics", "topics", "projectscopes",
+    "projectrisks", "vendorrisks", "subcontrols", "controls",
+    "controlcategories", "assessments", "vendors", "projects", "users"
+  ];
+  
+  for (const table of tables) {
+    try {
+      await deleteDEMOData(table);
+    } catch (error) {
+      console.error(`Failed to delete demo data from ${table}:`, error);
+      throw error;
+    }
   }
 }
📝 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
export async function deleteMockData() {
const projects = await getDEMOProjects()
for (let project of projects) {
await deleteProjectByIdQuery(project.id)
};
await deleteExistingData("vendors", "vendor_name");
await deleteExistingData("users", "name");
// await deleteExistingData("roles", "name");
// const projects = await getDEMOProjects()
// for (let project of projects) {
// await deleteProjectByIdQuery(project.id)
// };
// await deleteExistingData("vendors", "vendor_name");
// await deleteExistingData("users", "name");
// // await deleteExistingData("roles", "name");
for (let table of ["questions", "subtopics", "topics", "projectscopes", "projectrisks", "vendorrisks",
"subcontrols", "controls", "controlcategories", "assessments", "vendors", "projects", "users"]) {
await deleteDEMOData(table)
}
}
export async function deleteMockData() {
const tables = [
"questions", "subtopics", "topics", "projectscopes",
"projectrisks", "vendorrisks", "subcontrols", "controls",
"controlcategories", "assessments", "vendors", "projects", "users"
];
for (const table of tables) {
try {
await deleteDEMOData(table);
} catch (error) {
console.error(`Failed to delete demo data from ${table}:`, error);
throw error;
}
}
}

@MuhammadKhalilzadeh
Copy link
Collaborator

@HarshP4585
There conflicts here that you'll need to fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend Backend related tasks/issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants