#37558 new Uncategorized

Annotation yielding sets are not filterable on PostgreSQL

Reported by: David Owned by:
Component: Database layer (models, ORM) Version: 6.1
Severity: Normal Keywords: postgres, set_returning
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Annotating a queryset with an expression marked as ​`set_returning = True` and then using the annotation in a .filter causes the compiler to build an invalid query on PostgreSQL because the expression is put in the WHERE clause instead of building a subquery.

Here is a sample code to reproduce the issue:

# models.py
from django.db import models


class JsonModel(models.Model):
    data = models.JSONField(null=True)


# tests.py
from django.db import models
from django.test import TestCase

from .models import JsonModel


class JSONBPathQuery(models.Func):
    function = "jsonb_path_query"
    arity = 1
    output_field = models.JSONField()
    set_returning = True


class SetReturningFilterTests(TestCase):

    def test_filter_on_set_returning_annotation(self):

        test_model = JsonModel.objects.create(
            data={"key": [{"id": 1, "name": "test1"}, {"id": 2, "name": "test2"}]}, id=1
        )
        qs = JsonModel.objects.annotate(
            table_element=JSONBPathQuery("data", Value("$.key[*]"))
        ).filter(table_element={"id": 1, "name": "test1"})

        # django.db.utils.NotSupportedError: set-returning functions are not allowed in WHERE
        self.assertSequenceEqual(
            qs.values_list("table_element", flat=True),
            [{"id": 1, "name": "test1"}],
        )

Currently annotating an expression with set_returning = True and then using it in a filter generates the following SQL:

SELECT jsonb_path_query("annotations_jsonmodel"."data", %s) AS "table_element"
FROM "annotations_jsonmodel"
WHERE jsonb_path_query("annotations_jsonmodel"."data", %s) = %s

While the expected SQL is:

SELECT "qualify"."table_element" FROM (
  SELECT jsonb_path_query("annotations_jsonmodel"."data", %s) AS "table_element"
  FROM "annotations_jsonmodel"
) "qualify" WHERE "table_element" = %s

NOTE: this behaviour can be achieved by using contains_over_clause = True, this feels strange to me: because it has a different semanthic meaning and I did not expect it to work like this since it should work with Window.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top