prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Saving existing explorations is broken: UIQuery names need to be unique
  ## Description
  https://github.com/centerofci/mathesar/pull/2315 modified query names to be unique per schema.
  It does not ignore the current name of the query while checking the condition.
  
  To reproduce: Try saving an existing query after making changes.
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `mathesar/api/serializers/queries.py`
  Content:
  ```
  1 from django.core.exceptions import ValidationError
  2 from django.urls import reverse
  3 from rest_access_policy import PermittedPkRelatedField
  4 from rest_framework import serializers
  5 
  6 from mathesar.api.db.permissions.query_table import QueryTableAccessPolicy
  7 from mathesar.api.exceptions.mixins import MathesarErrorMessageMixin
  8 from mathesar.api.exceptions.validation_exceptions.exceptions import DuplicateUIQueryInSchemaAPIException
  9 from mathesar.models.base import Table
  10 from mathesar.models.query import UIQuery
  11 
  12 
  13 class BaseQuerySerializer(MathesarErrorMessageMixin, serializers.ModelSerializer):
  14     schema = serializers.SerializerMethodField('get_schema')
  15     base_table = PermittedPkRelatedField(
  16         access_policy=QueryTableAccessPolicy,
  17         queryset=Table.current_objects.all()
  18     )
  19 
  20     class Meta:
  21         model = UIQuery
  22         fields = ['schema', 'initial_columns', 'transformations', 'base_table', 'display_names']
  23 
  24     def get_schema(self, uiquery):
  25         base_table = uiquery.base_table
  26         if base_table:
  27             return base_table.schema.id
  28 
  29     def validate(self, attrs):
  30         unexpected_fields = set(self.initial_data) - set(self.fields)
  31         if unexpected_fields:
  32             raise ValidationError(f"Unexpected field(s): {unexpected_fields}")
  33         self._validate_uniqueness(attrs)
  34         return attrs
  35 
  36     def _validate_uniqueness(self, attrs):
  37         """
  38         Uniqueness is only defined when both name and base_table are defined.
  39 
  40         Would be nice to define this in terms of Django's UniqueConstraint, but that doesn't seem
  41         possible, due to schema being a child property of base_table.
  42         """
  43         name = attrs.get('name')
  44         if name:
  45             base_table = attrs.get('base_table')
  46             if base_table:
  47                 schema = base_table.schema
  48                 queries_with_same_name = UIQuery.objects.filter(name=name)
  49                 duplicate_in_schema_exists = \
  50                     queries_with_same_name\
  51                     .filter(base_table__schema=schema)\
  52                     .exists()
  53                 if duplicate_in_schema_exists:
  54                     raise DuplicateUIQueryInSchemaAPIException(field='name')
  55 
  56 
  57 class QuerySerializer(BaseQuerySerializer):
  58     results_url = serializers.SerializerMethodField('get_results_url')
  59     records_url = serializers.SerializerMethodField('get_records_url')
  60     columns_url = serializers.SerializerMethodField('get_columns_url')
  61 
  62     class Meta:
  63         model = UIQuery
  64         fields = '__all__'
  65 
  66     def get_records_url(self, obj):
  67         if isinstance(obj, UIQuery) and obj.pk is not None:
  68             # Only get records_url if we are serializing an existing persisted UIQuery
  69             request = self.context['request']
  70             return request.build_absolute_uri(reverse('query-records', kwargs={'pk': obj.pk}))
  71         else:
  72             return None
  73 
  74     def get_columns_url(self, obj):
  75         if isinstance(obj, UIQuery) and obj.pk is not None:
  76             # Only get columns_url if we are serializing an existing persisted UIQuery
  77             request = self.context['request']
  78             return request.build_absolute_uri(reverse('query-columns', kwargs={'pk': obj.pk}))
  79         else:
  80             return None
  81 
  82     def get_results_url(self, obj):
  83         if isinstance(obj, UIQuery) and obj.pk is not None:
  84             # Only get records_url if we are serializing an existing persisted UIQuery
  85             request = self.context['request']
  86             return request.build_absolute_uri(reverse('query-results', kwargs={'pk': obj.pk}))
  87         else:
  88             return None
  89
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/mathesar/api/serializers/queries.py b/mathesar/api/serializers/queries.py
  --- a/mathesar/api/serializers/queries.py
  +++ b/mathesar/api/serializers/queries.py
  @@ -1,5 +1,7 @@
   from django.core.exceptions import ValidationError
   from django.urls import reverse
  +from django.db.models import Q
  +
   from rest_access_policy import PermittedPkRelatedField
   from rest_framework import serializers
   
  @@ -45,14 +47,23 @@
               base_table = attrs.get('base_table')
               if base_table:
                   schema = base_table.schema
  -                queries_with_same_name = UIQuery.objects.filter(name=name)
  -                duplicate_in_schema_exists = \
  -                    queries_with_same_name\
  -                    .filter(base_table__schema=schema)\
  -                    .exists()
  -                if duplicate_in_schema_exists:
  +                is_duplicate_q = self._get_is_duplicate_q(name, schema)
  +                duplicates = UIQuery.objects.filter(is_duplicate_q)
  +                if duplicates.exists():
                       raise DuplicateUIQueryInSchemaAPIException(field='name')
   
  +    def _get_is_duplicate_q(self, name, schema):
  +        has_same_name_q = Q(name=name)
  +        has_same_schema_q = Q(base_table__schema=schema)
  +        is_duplicate_q = has_same_name_q & has_same_schema_q
  +        is_update = self.instance is not None
  +        if is_update:
  +            # If this is an update, filter self out of found duplicates
  +            id = self.instance.id
  +            is_not_this_instance_q = ~Q(id=id)
  +            is_duplicate_q = is_duplicate_q & is_not_this_instance_q
  +        return is_duplicate_q
  +
   
   class QuerySerializer(BaseQuerySerializer):
       results_url = serializers.SerializerMethodField('get_results_url')
  
verification_info: {"golden_diff": "diff --git a/mathesar/api/serializers/queries.py b/mathesar/api/serializers/queries.py\n--- a/mathesar/api/serializers/queries.py\n+++ b/mathesar/api/serializers/queries.py\n@@ -1,5 +1,7 @@\n from django.core.exceptions import ValidationError\n from django.urls import reverse\n+from django.db.models import Q\n+\n from rest_access_policy import PermittedPkRelatedField\n from rest_framework import serializers\n \n@@ -45,14 +47,23 @@\n             base_table = attrs.get('base_table')\n             if base_table:\n                 schema = base_table.schema\n-                queries_with_same_name = UIQuery.objects.filter(name=name)\n-                duplicate_in_schema_exists = \\\n-                    queries_with_same_name\\\n-                    .filter(base_table__schema=schema)\\\n-                    .exists()\n-                if duplicate_in_schema_exists:\n+                is_duplicate_q = self._get_is_duplicate_q(name, schema)\n+                duplicates = UIQuery.objects.filter(is_duplicate_q)\n+                if duplicates.exists():\n                     raise DuplicateUIQueryInSchemaAPIException(field='name')\n \n+    def _get_is_duplicate_q(self, name, schema):\n+        has_same_name_q = Q(name=name)\n+        has_same_schema_q = Q(base_table__schema=schema)\n+        is_duplicate_q = has_same_name_q & has_same_schema_q\n+        is_update = self.instance is not None\n+        if is_update:\n+            # If this is an update, filter self out of found duplicates\n+            id = self.instance.id\n+            is_not_this_instance_q = ~Q(id=id)\n+            is_duplicate_q = is_duplicate_q & is_not_this_instance_q\n+        return is_duplicate_q\n+\n \n class QuerySerializer(BaseQuerySerializer):\n     results_url = serializers.SerializerMethodField('get_results_url')\n", "issue": "Saving existing explorations is broken: UIQuery names need to be unique\n## Description\r\nhttps://github.com/centerofci/mathesar/pull/2315 modified query names to be unique per schema.\r\nIt does not ignore the current name of the query while checking the condition.\r\n\r\nTo reproduce: Try saving an existing query after making changes.\r\n\n", "before_files": [{"content": "from django.core.exceptions import ValidationError\nfrom django.urls import reverse\nfrom rest_access_policy import PermittedPkRelatedField\nfrom rest_framework import serializers\n\nfrom mathesar.api.db.permissions.query_table import QueryTableAccessPolicy\nfrom mathesar.api.exceptions.mixins import MathesarErrorMessageMixin\nfrom mathesar.api.exceptions.validation_exceptions.exceptions import DuplicateUIQueryInSchemaAPIException\nfrom mathesar.models.base import Table\nfrom mathesar.models.query import UIQuery\n\n\nclass BaseQuerySerializer(MathesarErrorMessageMixin, serializers.ModelSerializer):\n    schema = serializers.SerializerMethodField('get_schema')\n    base_table = PermittedPkRelatedField(\n        access_policy=QueryTableAccessPolicy,\n        queryset=Table.current_objects.all()\n    )\n\n    class Meta:\n        model = UIQuery\n        fields = ['schema', 'initial_columns', 'transformations', 'base_table', 'display_names']\n\n    def get_schema(self, uiquery):\n        base_table = uiquery.base_table\n        if base_table:\n            return base_table.schema.id\n\n    def validate(self, attrs):\n        unexpected_fields = set(self.initial_data) - set(self.fields)\n        if unexpected_fields:\n            raise ValidationError(f\"Unexpected field(s): {unexpected_fields}\")\n        self._validate_uniqueness(attrs)\n        return attrs\n\n    def _validate_uniqueness(self, attrs):\n        \"\"\"\n        Uniqueness is only defined when both name and base_table are defined.\n\n        Would be nice to define this in terms of Django's UniqueConstraint, but that doesn't seem\n        possible, due to schema being a child property of base_table.\n        \"\"\"\n        name = attrs.get('name')\n        if name:\n            base_table = attrs.get('base_table')\n            if base_table:\n                schema = base_table.schema\n                queries_with_same_name = UIQuery.objects.filter(name=name)\n                duplicate_in_schema_exists = \\\n                    queries_with_same_name\\\n                    .filter(base_table__schema=schema)\\\n                    .exists()\n                if duplicate_in_schema_exists:\n                    raise DuplicateUIQueryInSchemaAPIException(field='name')\n\n\nclass QuerySerializer(BaseQuerySerializer):\n    results_url = serializers.SerializerMethodField('get_results_url')\n    records_url = serializers.SerializerMethodField('get_records_url')\n    columns_url = serializers.SerializerMethodField('get_columns_url')\n\n    class Meta:\n        model = UIQuery\n        fields = '__all__'\n\n    def get_records_url(self, obj):\n        if isinstance(obj, UIQuery) and obj.pk is not None:\n            # Only get records_url if we are serializing an existing persisted UIQuery\n            request = self.context['request']\n            return request.build_absolute_uri(reverse('query-records', kwargs={'pk': obj.pk}))\n        else:\n            return None\n\n    def get_columns_url(self, obj):\n        if isinstance(obj, UIQuery) and obj.pk is not None:\n            # Only get columns_url if we are serializing an existing persisted UIQuery\n            request = self.context['request']\n            return request.build_absolute_uri(reverse('query-columns', kwargs={'pk': obj.pk}))\n        else:\n            return None\n\n    def get_results_url(self, obj):\n        if isinstance(obj, UIQuery) and obj.pk is not None:\n            # Only get records_url if we are serializing an existing persisted UIQuery\n            request = self.context['request']\n            return request.build_absolute_uri(reverse('query-results', kwargs={'pk': obj.pk}))\n        else:\n            return None\n", "path": "mathesar/api/serializers/queries.py"}], "after_files": [{"content": "from django.core.exceptions import ValidationError\nfrom django.urls import reverse\nfrom django.db.models import Q\n\nfrom rest_access_policy import PermittedPkRelatedField\nfrom rest_framework import serializers\n\nfrom mathesar.api.db.permissions.query_table import QueryTableAccessPolicy\nfrom mathesar.api.exceptions.mixins import MathesarErrorMessageMixin\nfrom mathesar.api.exceptions.validation_exceptions.exceptions import DuplicateUIQueryInSchemaAPIException\nfrom mathesar.models.base import Table\nfrom mathesar.models.query import UIQuery\n\n\nclass BaseQuerySerializer(MathesarErrorMessageMixin, serializers.ModelSerializer):\n    schema = serializers.SerializerMethodField('get_schema')\n    base_table = PermittedPkRelatedField(\n        access_policy=QueryTableAccessPolicy,\n        queryset=Table.current_objects.all()\n    )\n\n    class Meta:\n        model = UIQuery\n        fields = ['schema', 'initial_columns', 'transformations', 'base_table', 'display_names']\n\n    def get_schema(self, uiquery):\n        base_table = uiquery.base_table\n        if base_table:\n            return base_table.schema.id\n\n    def validate(self, attrs):\n        unexpected_fields = set(self.initial_data) - set(self.fields)\n        if unexpected_fields:\n            raise ValidationError(f\"Unexpected field(s): {unexpected_fields}\")\n        self._validate_uniqueness(attrs)\n        return attrs\n\n    def _validate_uniqueness(self, attrs):\n        \"\"\"\n        Uniqueness is only defined when both name and base_table are defined.\n\n        Would be nice to define this in terms of Django's UniqueConstraint, but that doesn't seem\n        possible, due to schema being a child property of base_table.\n        \"\"\"\n        name = attrs.get('name')\n        if name:\n            base_table = attrs.get('base_table')\n            if base_table:\n                schema = base_table.schema\n                is_duplicate_q = self._get_is_duplicate_q(name, schema)\n                duplicates = UIQuery.objects.filter(is_duplicate_q)\n                if duplicates.exists():\n                    raise DuplicateUIQueryInSchemaAPIException(field='name')\n\n    def _get_is_duplicate_q(self, name, schema):\n        has_same_name_q = Q(name=name)\n        has_same_schema_q = Q(base_table__schema=schema)\n        is_duplicate_q = has_same_name_q & has_same_schema_q\n        is_update = self.instance is not None\n        if is_update:\n            # If this is an update, filter self out of found duplicates\n            id = self.instance.id\n            is_not_this_instance_q = ~Q(id=id)\n            is_duplicate_q = is_duplicate_q & is_not_this_instance_q\n        return is_duplicate_q\n\n\nclass QuerySerializer(BaseQuerySerializer):\n    results_url = serializers.SerializerMethodField('get_results_url')\n    records_url = serializers.SerializerMethodField('get_records_url')\n    columns_url = serializers.SerializerMethodField('get_columns_url')\n\n    class Meta:\n        model = UIQuery\n        fields = '__all__'\n\n    def get_records_url(self, obj):\n        if isinstance(obj, UIQuery) and obj.pk is not None:\n            # Only get records_url if we are serializing an existing persisted UIQuery\n            request = self.context['request']\n            return request.build_absolute_uri(reverse('query-records', kwargs={'pk': obj.pk}))\n        else:\n            return None\n\n    def get_columns_url(self, obj):\n        if isinstance(obj, UIQuery) and obj.pk is not None:\n            # Only get columns_url if we are serializing an existing persisted UIQuery\n            request = self.context['request']\n            return request.build_absolute_uri(reverse('query-columns', kwargs={'pk': obj.pk}))\n        else:\n            return None\n\n    def get_results_url(self, obj):\n        if isinstance(obj, UIQuery) and obj.pk is not None:\n            # Only get records_url if we are serializing an existing persisted UIQuery\n            request = self.context['request']\n            return request.build_absolute_uri(reverse('query-results', kwargs={'pk': obj.pk}))\n        else:\n            return None\n", "path": "mathesar/api/serializers/queries.py"}]}