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

[WEB-2809] chore: changed the soft deletion logic #6171

Merged
merged 1 commit into from
Dec 9, 2024

Conversation

NarayanBavisetti
Copy link
Collaborator

@NarayanBavisetti NarayanBavisetti commented Dec 9, 2024

Description

  • Implemented soft deletion logic ensuring related objects with on_delete=models.CASCADE are soft-deleted in alignment with the primary object.

Type of Change

  • Code refactoring

References

WEB-2809

Summary by CodeRabbit

  • New Features

    • Enhanced filtering capabilities for issue retrieval based on updated_at.
    • Improved error handling for missing issues and validation checks in API endpoints.
  • Bug Fixes

    • Streamlined handling of empty issue IDs in the IssueListEndpoint.
  • Refactor

    • Simplified query logic and refined related object deletion processes.
  • Chores

    • Removed unused imports to streamline module dependencies.

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Walkthrough

The changes in this pull request involve modifications to several files, primarily focusing on the apiserver/plane/app/views/issue/base.py, apiserver/plane/bgtasks/deletion_task.py, and apiserver/plane/db/models/__init__.py. Key updates include the removal of unused imports, enhancements to the get method for filtering issue IDs, and refinements in the soft deletion logic for related objects. The overall structure of the API and its endpoints remains intact, with an emphasis on clarity and maintainability.

Changes

File Path Change Summary
apiserver/plane/app/views/issue/base.py Removed unused imports; streamlined get method in IssueListEndpoint for filtering issue_ids; minor adjustments in IssueViewSet methods for clarity.
apiserver/plane/bgtasks/deletion_task.py Updated soft_delete_related_objects function with a new docstring, refined logic for handling related fields, and improved error handling for soft deletion.
apiserver/plane/db/models/__init__.py Removed multiple import statements to simplify module dependencies, indicating a restructuring of model organization.

Possibly related PRs

Suggested labels

🔄migrations

Suggested reviewers

  • pablohashescobar

Poem

🐰 In the code where bunnies play,
Imports gone, they hopped away.
Issues filtered, soft delete,
Logic clearer, oh what a treat!
With every change, we cheer and say,
"Hooray for code, hip-hip-hooray!"


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.

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

🧹 Outside diff range and nitpick comments (4)
apiserver/plane/bgtasks/deletion_task.py (4)

15-17: Enhance the docstring with detailed information

The docstring for soft_delete_related_objects is minimal. Providing more details about the function's purpose, parameters, and behavior would improve code readability and maintainability.

Consider expanding the docstring as follows:

def soft_delete_related_objects(app_label, model_name, instance_pk, using=None):
    """
    Soft delete a model instance and its related objects recursively.

    Args:
        app_label (str): The app label of the model.
        model_name (str): The name of the model class.
        instance_pk (int): The primary key of the instance to soft delete.
        using (str, optional): The database alias to use. Defaults to None.

    Returns:
        None
    """

21-21: Line exceeds maximum length (95 > 88 characters)

The comment on line 21 exceeds the recommended maximum line length of 88 characters, which may affect readability. Consider splitting the comment into multiple lines.

Apply this diff to fix the line length:

-    # Get the instance using all_objects to ensure we can get even if it's already soft deleted
+    # Get the instance using all_objects to ensure we can get even if it's already
+    # soft deleted
🧰 Tools
🪛 Ruff (0.8.0)

21-21: Line too long (95 > 88)

(E501)


100-100: Use logging instead of print statements for error handling

Using print statements for logging errors is not recommended in production code. Consider using Python's built-in logging module to handle logging more appropriately.

To address this, first import the logging module and set up a logger at the top of the file:

import logging

logger = logging.getLogger(__name__)

Then, replace the print statement with a logging call:

-        print(f"Error handling relation {related_name}: {str(e)}")
+        logger.error(f"Error handling relation {related_name}: {str(e)}")

71-83: Refactor duplicated code into a helper function

The code for soft-deleting related objects and recursively calling soft_delete_related_objects is duplicated in lines 71-83 and 88-98. Refactoring this into a helper function will reduce code duplication and improve maintainability.

Consider adding a helper function:

def soft_delete_and_recurse(related_obj, using=None):
    if hasattr(related_obj, "deleted_at") and not related_obj.deleted_at:
        related_obj.deleted_at = timezone.now()
        related_obj.save()
        # Recursively handle related objects
        soft_delete_related_objects(
            related_obj._meta.app_label,
            related_obj._meta.model_name,
            related_obj.pk,
            using,
        )

Then, replace the duplicated code with calls to this helper function:

First occurrence (lines 71-83):

-            if related_obj:
-                if hasattr(related_obj, "deleted_at"):
-                    if not related_obj.deleted_at:
-                        related_obj.deleted_at = timezone.now()
-                        related_obj.save()
-                        # Recursively handle related objects
-                        soft_delete_related_objects(
-                            related_obj._meta.app_label,
-                            related_obj._meta.model_name,
-                            related_obj.pk,
-                            using,
-                        )
+            if related_obj:
+                soft_delete_and_recurse(related_obj, using)

Second occurrence (lines 88-98):

-        for related_obj in related_queryset:
-            if hasattr(related_obj, "deleted_at"):
-                if not related_obj.deleted_at:
-                    related_obj.deleted_at = timezone.now()
-                    related_obj.save()
-                    # Recursively handle related objects
-                    soft_delete_related_objects(
-                        related_obj._meta.app_label,
-                        related_obj._meta.model_name,
-                        related_obj.pk,
-                        using,
-                    )
+        for related_obj in related_queryset:
+            soft_delete_and_recurse(related_obj, using)

Also applies to: 88-98

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a85e592 and 71b5ce6.

📒 Files selected for processing (3)
  • apiserver/plane/app/views/issue/base.py (0 hunks)
  • apiserver/plane/bgtasks/deletion_task.py (1 hunks)
  • apiserver/plane/db/models/__init__.py (0 hunks)
💤 Files with no reviewable changes (2)
  • apiserver/plane/app/views/issue/base.py
  • apiserver/plane/db/models/init.py
🧰 Additional context used
🪛 Ruff (0.8.0)
apiserver/plane/bgtasks/deletion_task.py

21-21: Line too long (95 > 88)

(E501)

@sriramveeraghanta sriramveeraghanta merged commit ff8bbed into preview Dec 9, 2024
12 of 14 checks passed
@sriramveeraghanta sriramveeraghanta deleted the chore/soft-deletion-task branch December 9, 2024 14:59
nishantPFM pushed a commit to Pocket-Fm/plane that referenced this pull request Dec 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants