Skip to content

Conversation

@ucatbas
Copy link
Contributor

@ucatbas ucatbas commented Aug 26, 2024

  • Removal of associated records before attempting to delete the tenant.
  • Handling scenarios where no tenant is found but related records have been deleted.

Summary by CodeRabbit

  • New Features

    • Enhanced tenant deletion process to ensure all associated records are removed simultaneously, improving data integrity.
    • Introduced a new SQL template for bulk deletion of records linked to a specific tenant.
  • Bug Fixes

    • Improved error handling during tenant deletions to prevent partial deletions and ensure consistent data management.

@ucatbas ucatbas requested a review from tolgaozen August 26, 2024 11:37
@vercel
Copy link

vercel bot commented Aug 26, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
permify ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 27, 2024 10:36am

@coderabbitai
Copy link

coderabbitai bot commented Aug 26, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes involve significant modifications to the DeleteTenant method in both the memory and PostgreSQL implementations of the TenantWriter class. The new implementations ensure that when a tenant is deleted, all associated records in relevant tables are also removed, enhancing data integrity. Additionally, a new SQL template for bulk deletion of tenant-associated records was introduced, improving management capabilities.

Changes

Files Change Summary
internal/storage/memory/tenantWriter.go Updated DeleteTenant method to include checks and deletion operations for associated records in multiple tables.
internal/storage/postgres/tenantWriter.go Refactored DeleteTenant method to use batch operations for deleting tenant and associated records efficiently.
internal/storage/postgres/utils/common.go Introduced a new SQL template DeleteAllByTenantTemplate for bulk deletion of records associated with a tenant.

Poem

🐇 In the meadow where data flows,
A tenant's tale, as everyone knows.
With a hop and a skip, all records are cleared,
No more orphaned bits, all is revered.
Let's dance in the fields of code so bright,
For clean deletions bring pure delight! 🌼✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@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: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b5df684 and a98476d.

Files selected for processing (3)
  • internal/storage/memory/tenantWriter.go (1 hunks)
  • internal/storage/postgres/tenantWriter.go (2 hunks)
  • internal/storage/postgres/utils/common.go (1 hunks)
Additional comments not posted (5)
internal/storage/postgres/tenantWriter.go (4)

72-76: Ensure proper error handling for transaction initiation.

The code correctly handles errors during the transaction initiation.

The code changes are approved.


78-88: Ensure proper error handling for deletion operations.

The code correctly handles errors during the deletion operations and tracks the total number of deleted records.

The code changes are approved.


93-97: Ensure proper error handling for tenant retrieval.

The code correctly handles errors during the tenant retrieval operation.

The code changes are approved.


100-103: Ensure proper error handling for transaction commit.

The code correctly handles errors during the transaction commit operation.

The code changes are approved.

internal/storage/postgres/utils/common.go (1)

43-43: LGTM!

The new SQL template is correctly implemented and enhances the functionality for bulk deletion of tenant-associated records.

The code changes are approved.

Comment on lines 68 to 74
_, err = txn.First(constants.RelationTuplesTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.RelationTuplesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
Copy link

Choose a reason for hiding this comment

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

Fix the logic to handle the absence of records correctly.

The current implementation returns an error if no records are found in the RelationTuplesTable. Instead, it should only return an error if the deletion operation fails.

Apply this diff to fix the logic:

-	_, err = txn.First(constants.RelationTuplesTable, "tenant_id", tenantID)
-	if err != nil {
-		if _, deleteErr := txn.DeleteAll(constants.RelationTuplesTable, "tenant_id", tenantID); deleteErr != nil {
-			return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
-		}
-		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
+	if _, deleteErr := txn.DeleteAll(constants.RelationTuplesTable, "tenant_id", tenantID); deleteErr != nil {
+		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
	}
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
_, err = txn.First(constants.RelationTuplesTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.RelationTuplesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
if _, deleteErr := txn.DeleteAll(constants.RelationTuplesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}

Comment on lines 51 to 58

_, err = txn.First(constants.AttributesTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.AttributesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
Copy link

Choose a reason for hiding this comment

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

Fix the logic to handle the absence of records correctly.

The current implementation returns an error if no records are found in the AttributesTable. Instead, it should only return an error if the deletion operation fails.

Apply this diff to fix the logic:

-	_, err = txn.First(constants.AttributesTable, "tenant_id", tenantID)
-	if err != nil {
-		if _, deleteErr := txn.DeleteAll(constants.AttributesTable, "tenant_id", tenantID); deleteErr != nil {
-			return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
-		}
-		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
+	if _, deleteErr := txn.DeleteAll(constants.AttributesTable, "tenant_id", tenantID); deleteErr != nil {
+		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
	}
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
_, err = txn.First(constants.AttributesTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.AttributesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
if _, deleteErr := txn.DeleteAll(constants.AttributesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}

Comment on lines 60 to 66
_, err = txn.First(constants.BundlesTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.BundlesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
Copy link

Choose a reason for hiding this comment

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

Fix the logic to handle the absence of records correctly.

The current implementation returns an error if no records are found in the BundlesTable. Instead, it should only return an error if the deletion operation fails.

Apply this diff to fix the logic:

-	_, err = txn.First(constants.BundlesTable, "tenant_id", tenantID)
-	if err != nil {
-		if _, deleteErr := txn.DeleteAll(constants.BundlesTable, "tenant_id", tenantID); deleteErr != nil {
-			return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
-		}
-		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
+	if _, deleteErr := txn.DeleteAll(constants.BundlesTable, "tenant_id", tenantID); deleteErr != nil {
+		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
	}
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
_, err = txn.First(constants.BundlesTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.BundlesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
if _, deleteErr := txn.DeleteAll(constants.BundlesTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}

Comment on lines 76 to 82
_, err = txn.First(constants.SchemaDefinitionsTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.SchemaDefinitionsTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
Copy link

Choose a reason for hiding this comment

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

Fix the logic to handle the absence of records correctly.

The current implementation returns an error if no records are found in the SchemaDefinitionsTable. Instead, it should only return an error if the deletion operation fails.

Apply this diff to fix the logic:

-	_, err = txn.First(constants.SchemaDefinitionsTable, "tenant_id", tenantID)
-	if err != nil {
-		if _, deleteErr := txn.DeleteAll(constants.SchemaDefinitionsTable, "tenant_id", tenantID); deleteErr != nil {
-			return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
-		}
-		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
+	if _, deleteErr := txn.DeleteAll(constants.SchemaDefinitionsTable, "tenant_id", tenantID); deleteErr != nil {
+		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
	}
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
_, err = txn.First(constants.SchemaDefinitionsTable, "tenant_id", tenantID)
if err != nil {
if _, deleteErr := txn.DeleteAll(constants.SchemaDefinitionsTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}
if _, deleteErr := txn.DeleteAll(constants.SchemaDefinitionsTable, "tenant_id", tenantID); deleteErr != nil {
return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
}

Copy link

@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: 1

Outside diff range, codebase verification and nitpick comments (1)
internal/storage/postgres/tenantWriter.go (1)

81-89: Ensure Proper Error Handling

The deferred function ensures that the batch result is closed properly. However, consider logging the closeErr for better traceability.

Add logging for closeErr:

	defer func() {
		if closeErr := br.Close(); closeErr != nil {
			if err == nil {
				err = closeErr
			}
+			slog.ErrorContext(ctx, "error closing batch result", slog.Any("error", closeErr))
		}
	}()
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a98476d and eca2763.

Files selected for processing (1)
  • internal/storage/postgres/tenantWriter.go (2 hunks)
Additional comments not posted (2)
internal/storage/postgres/tenantWriter.go (2)

72-79: Efficient Batch Deletion

The batch deletion of tenant-related records from multiple tables is efficient and ensures data integrity.

The code changes are approved.


91-93: Proper Error Handling

The error handling for the batch execution is correctly implemented.

The code changes are approved.

Comment on lines 98 to 102
tenant := w.database.WritePool.QueryRow(ctx, utils.DeleteTenantTemplate, tenantID)
if err != nil {
return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
}
tenant.Scan(&name, &createdAt)
Copy link

Choose a reason for hiding this comment

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

Handle Potential Errors in QueryRow

Ensure that tenant.Scan(&name, &createdAt) is only called if tenant.QueryRow does not return an error.

Add error handling for tenant.QueryRow:

	tenant := w.database.WritePool.QueryRow(ctx, utils.DeleteTenantTemplate, tenantID)
+	if err = tenant.Scan(&name, &createdAt); err != nil {
+		return nil, utils.HandleError(ctx, span, err, base.ErrorCode_ERROR_CODE_EXECUTION)
+	}

Committable suggestion was skipped due to low confidence.

Copy link

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between eca2763 and 7325a66.

Files selected for processing (1)
  • internal/storage/postgres/tenantWriter.go (2 hunks)
Additional comments not posted (11)
internal/storage/postgres/tenantWriter.go (11)

6-6: LGTM!

The import of the fmt package is appropriate for string formatting.

The code changes are approved.


72-75: LGTM!

Starting a transaction ensures atomicity for the batch deletion process.

The code changes are approved.


76-76: LGTM!

Deferring the rollback ensures that the transaction is rolled back if any error occurs.

The code changes are approved.


78-85: LGTM!

Preparing batch operations for deleting tenant-related records from multiple tables improves efficiency and ensures that all deletions are executed in a single operation.

The code changes are approved.


86-87: LGTM!

Adding the tenant deletion query to the batch ensures that the tenant is deleted after all related records are deleted.

The code changes are approved.


88-90: LGTM!

Executing the batch of delete queries ensures that all deletions are performed in a single operation.

The code changes are approved.


91-106: LGTM!

Iterating through the batch results ensures that any errors are caught and the number of affected rows is counted.

The code changes are approved.


108-111: LGTM!

Retrieving the tenant details after deletion ensures that the tenant's information is returned after the deletion process.

The code changes are approved.


113-119: LGTM!

Handling errors when retrieving tenant details ensures that the system can gracefully manage cases where the tenant does not exist.

The code changes are approved.


121-123: LGTM!

Closing the batch result ensures that resources are properly released.

The code changes are approved.


126-129: LGTM!

Committing the transaction ensures that all deletions are finalized.

The code changes are approved.

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.

3 participants