#25772 closed Bug (fixed)
ArrayField: incorrent len lookup on empty arrays
Reported by: | mrAdm | Owned by: | |
---|---|---|---|
Component: | contrib.postgres | Version: | 1.8 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
Models:
NullableIntegerArrayModel.objects.create(field=[]) NullableIntegerArrayModel.objects.create(field=[1]) NullableIntegerArrayModel.objects.create(field=[2, 3]) NullableIntegerArrayModel.objects.create(field=[20, 30, 40])
Queries:
NullableIntegerArrayModel.objects.filter(field__len=0) # return: empty queryset NullableIntegerArrayModel.objects.filter(field__len__lt=2) # return only one model (field=[1])
Reason:
PostgreSQL function array_length(ARRAY[]::int4[], 1) return null if array empty.
The solution is to use a function PostgreSQL: COALESCE ().
SELECT * FROM ... WHERE COALESCE(array_length("field", 1), 0)=0
Attachments (1)
Change History (7)
comment:1 by , 9 years ago
Description: | modified (diff) |
---|
comment:2 by , 9 years ago
Summary: | ArrayField: incorrent len lookup → ArrayField: incorrent len lookup on empty arrays |
---|---|
Triage Stage: | Unreviewed → Accepted |
by , 9 years ago
Attachment: | 25772-test.diff added |
---|
comment:3 by , 9 years ago
Has patch: | set |
---|
In case field is None coalesce will return 0. So,
SELECT * FROM ... WHERE COALESCE(array_length("field", 1), 0)=0
will also return entries with field==None.
The solution is probably to change line in https://github.com/django/django/blob/master/django/contrib/postgres/fields/array.py#L205 to
return '%s IS NOT NULL AND \ coalesce(array_length(%s, 1), 0)' % (lhs, lhs), params
or
return 'CASE WHEN %s IS NULL THEN NULL \ ELSE coalesce(array_length(%s, 1), 0) \ END' % (lhs, lhs), params
Note:
See TracTickets
for help on using tickets.
Regression test attached.