Re: [PATCH] Fix jsonb comparison for raw scalar pseudo arrays

From: Andrew Dunstan <andrew(at)dunslane(dot)net>
To: Yan Chengpeng <chengpeng_yan(at)outlook(dot)com>, "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: [PATCH] Fix jsonb comparison for raw scalar pseudo arrays
Date: 2024-12-08 14:57:57
Message-ID: d11a4120-13d7-4463-8816-0e2f26d65f88@dunslane.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers


On 2024-12-03 Tu 9:11 AM, Andrew Dunstan wrote:
>
>
> On 2024-11-18 Mo 9:25 AM, Yan Chengpeng wrote:
>>
>> Dear PostgreSQL Hackers,
>>
>> *Problem Description*
>>
>> I encountered an issue with the B-Tree ordering of `jsonb` values.
>> According to the PostgreSQL documentation[1], the ordering should
>> follow this precedence:
>>
>> `Object > Array > Boolean > Number > String > Null`
>>
>> However, empty arrays (`[]`) are currently considered smaller than
>> `null`, which violates the documented rules. This occurs due to
>> improper handling of the `rawScalar` flag when comparing arrays in
>> the `compareJsonbContainers()` function in
>> `src/backend/utils/adt/jsonb_util.c`.
>>
>
> I agree that this is a (10 year old) bug:
>
>
> -                        if (va.val.array.nElems != vb.val.array.nElems)
> +                        else if (va.val.array.nElems !=
> vb.val.array.nElems)
>
>
> But I don't think we can fix it, because there could well be indexes
> that would no longer be valid if we change the sort order. Given that,
> I think the best we can do is adjust the documentation to mention the
> anomaly.
>
> So the actual sort order as implemented is, AIUI,
>
>
> Object > Non-Empty-Array > Boolean > Number > String > Null > Empty-Array
>
>
> which is ugly, but fortunately not many apps rely on jsonb sort order.
>

Nobody else has commented, so I propose to apply this patch documenting
the anomaly.

cheers

andrew

--
Andrew Dunstan
EDB:https://www.enterprisedb.com

Attachment Content-Type Size
jsonb-sort-doc.patch text/x-patch 684 bytes

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Илья Жарков 2024-12-08 15:24:21 Re: Do not scan index in right table if condition for left join evaluates to false using columns in left table
Previous Message vignesh C 2024-12-08 14:27:08 Re: Logical Replication of sequences