Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Generated by Django 5.2.7 on 2025-10-16 03:21

from django.db import migrations
from django.db.models.functions import RowNumber


def remove_duplicates(apps, schema_editor):
from django.db.models import Window, F
workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')

duplicates = workspace_user_resource_permission_model.objects.annotate(
row_num=Window(
expression=RowNumber(),
partition_by=[F('workspace_id'), F('user'), F('auth_target_type'), F('target')],
order_by=[F('create_time').desc()],
)
).filter(row_num__gt=1)

ids_to_delete = list(duplicates.values_list('id', flat=True))
if ids_to_delete:
workspace_user_resource_permission_model.objects.filter(id__in=ids_to_delete).delete()

class Migration(migrations.Migration):

dependencies = [
('system_manage', '0003_alter_workspaceuserresourcepermission_target'),
('users', '0001_initial'),
]

operations = [
migrations.RunPython(remove_duplicates,
),
migrations.AlterUniqueTogether(
name='workspaceuserresourcepermission',
unique_together={('workspace_id', 'user', 'auth_target_type', 'target')},
),
]
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code checks for duplicate entries in the WorkspaceUserResourcePermission model based on specific fields: workspace_id, user, auth_target_type, and target. Then deletes all but one occurrence of each duplicate. Here are some points to consider:

  1. Duplicate Check: The query uses the RowNumber() function from django.db.models.functions.RowNumber(). This is correct for filtering out duplicates.

  2. Field Partitioning: The partitioning criteria are set by F('workspace_id'), F('user'), F('auth_target_type'), and F('target'), which ensures that duplicates within these groups are identified.

  3. Order By and Filter: The ordering is done by _time.desc() to ensure the latest entry remains, while duplicates with earlier creation times are filtered out.

  4. Run Python Operation: The migrations.RunPython operation correctly calls the remove_duplicates function during migration.

  5. Alter Unique Together Constraint: After removing duplicates, the unique-together constraint is added back with the same fields.

  6. No Optimization Suggestions: Based on the current implementation, there aren't many areas where optimization can be applied directly. However, consider creating an index on the combination of workspace_user_resource_permission_model._meta.fields to improve performance if the table grows significantly.

Overall, the code appears well-structured and should work as intended for deduplicating entries according to specified rules.

1 change: 1 addition & 0 deletions apps/system_manage/models/workspace_user_permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ class WorkspaceUserResourcePermission(models.Model):

class Meta:
db_table = "workspace_user_resource_permission"
unique_together = ('workspace_id', 'user', 'auth_target_type', 'target')
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code snippet is mostly correct for a Django model to manage permissions related to workspace user resources. However, there are a few suggestions for improvement:

  1. Docstring: It's a good practice to add a docstring explaining the purpose of each attribute.

  2. Meta.ordering (Optional): If you want certain orderings, you can specify them here without needing a separate order_by queryset method in views or elsewhere.

Here's improved version with the suggested changes:

from django.db import models

class WorkspaceUserResourcePermission(models.Model):
    # Attributes
    workspace = models.ForeignKey('Workspaces', on_delete=models.CASCADE)
    user = models.ForeignKey('WorkspaceUsers', on_delete=models.CASCADE)
    auth_target_type = models.CharField(max_length=100)  # Assuming this should be specific like 'permission_group'
    target = models.CharField(max_length=255)

    # Metadata
    class Meta:
        db_table = "workspace_user_resource_permission"
        unique_together = ('workspace_id', 'user', 'auth_target_type', 'target')
        
        # Optional ordering
        # ordering = ['-created_at']  # For example, sort by creation time
        
    def __str__(self):
        return f"{self.user} {self.auth_target_type}.{self.target}"

Explanation:

  1. Unique Togetherness: Ensures that no two records in the database have the same combination of workspace_id, user, auth_target_type, and target.

  2. Ordering (Optional): Uncommenting ordering = ['-created_at'] adds an optional option to display these entries in descending order based on their creation date (created_at). This is useful for listing recent permissions or other chronological data.

  3. Str Representation: The __str__() method provides a readable string representation of the object, which can improve debugability.

If you plan to include additional fields or methods in your WorkspaceUserResourcePermission model, make sure they align with the intended use case and adhere to best practices from Django's ORM design principles.

Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ FROM (
user_id,
workspace_id,
icon,
folder_id
folder_id,
create_time
FROM application
${query_set}
UNION
Expand All @@ -22,7 +23,8 @@ FROM (
application_folder."user_id",
application_folder."workspace_id",
NULL AS "icon",
application_folder."parent_id" AS "folder_id"
application_folder."parent_id" AS "folder_id",
application_folder."create_time"
FROM application_folder
${folder_query_set}
) resource_or_folder
Expand All @@ -42,3 +44,4 @@ LEFT JOIN (
) wurp
ON wurp.target::text = resource_or_folder.id
${resource_query_set}
ORDER BY resource_or_folder.create_time DESC
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ FROM (
user_id,
workspace_id,
"type"::varchar AS "icon",
folder_id
folder_id,
create_time
FROM knowledge
${query_set}
UNION
Expand All @@ -23,7 +24,8 @@ FROM (
knowledge_folder."user_id",
knowledge_folder."workspace_id",
NULL AS "icon",
knowledge_folder."parent_id" AS "folder_id"
knowledge_folder."parent_id" AS "folder_id",
knowledge_folder."create_time"
FROM knowledge_folder
${folder_query_set}
) resource_or_folder
Expand All @@ -44,4 +46,5 @@ LEFT JOIN (
${workspace_user_resource_permission_query_set}
) wurp
ON wurp.target::text = resource_or_folder.id
${resource_query_set}
${resource_query_set}
ORDER BY resource_or_folder.create_time DESC
9 changes: 6 additions & 3 deletions apps/system_manage/sql/get_model_user_resource_permission.sql
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ FROM (
user_id,
workspace_id,
provider as icon,
'default' as folder_id
'default' as folder_id,
create_time
FROM
model
${query_set}
Expand All @@ -27,7 +28,8 @@ FROM (
user_id,
workspace_id,
provider as icon,
'default' as folder_id
'default' as folder_id,
create_time
FROM model
${folder_query_set}
AND 1=0
Expand All @@ -49,4 +51,5 @@ LEFT JOIN (
${workspace_user_resource_permission_query_set}
) wurp
ON wurp.target = resource_or_folder."id"
${resource_query_set}
${resource_query_set}
ORDER BY resource_or_folder.create_time DESC
7 changes: 5 additions & 2 deletions apps/system_manage/sql/get_tool_user_resource_permission.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ FROM (
workspace_id,
icon,
folder_id,
tool_type
tool_type,
create_time
FROM tool
${query_set}
UNION
Expand All @@ -24,7 +25,8 @@ FROM (
tool_folder."workspace_id",
NULL AS "icon",
tool_folder."parent_id" AS "folder_id",
NULL AS "tool_type"
NULL AS "tool_type",
tool_folder."create_time"
FROM tool_folder
${folder_query_set}
) resource_or_folder
Expand All @@ -45,4 +47,5 @@ LEFT JOIN (
) wurp
ON wurp.target::text = resource_or_folder."id"
${resource_query_set}
ORDER BY resource_or_folder.create_time DESC

Loading