Skip to content

Commit 30f0176

Browse files
committed
Document strange jsonb sort order for empty top level arrays
Slightly faulty logic in the original jsonb code (commit d9134d0) results in an empty top level array sorting less than a json null. We can't change the sort order now since it would affect btree indexes over jsonb, so document the anomaly. Backpatch to all live branches (13 .. 17) In master, also add a code comment noting the anomaly. Reported-by: Yan Chengpen Reviewed-by: Jian He Discussion: https://postgr.es/m/OSBPR01MB45199DD8DA2D1CECD50518188E272@OSBPR01MB4519.jpnprd01.prod.outlook.com
1 parent e28033f commit 30f0176

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

doc/src/sgml/json.sgml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,12 +584,13 @@ SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @@ '$.tags[*] == "qui"';
584584
The <literal>btree</literal> ordering for <type>jsonb</type> datums is seldom
585585
of great interest, but for completeness it is:
586586
<synopsis>
587-
<replaceable>Object</replaceable> > <replaceable>Array</replaceable> > <replaceable>Boolean</replaceable> > <replaceable>Number</replaceable> > <replaceable>String</replaceable> > <replaceable>Null</replaceable>
587+
<replaceable>Object</replaceable> > <replaceable>Array</replaceable> > <replaceable>Boolean</replaceable> > <replaceable>Number</replaceable> > <replaceable>String</replaceable> > <replaceable>null</replaceable>
588588

589589
<replaceable>Object with n pairs</replaceable> > <replaceable>object with n - 1 pairs</replaceable>
590590

591591
<replaceable>Array with n elements</replaceable> > <replaceable>array with n - 1 elements</replaceable>
592592
</synopsis>
593+
with the exception that (for historical reasons) an empty top level array sorts less than <replaceable>null</replaceable>.
593594
Objects with equal numbers of pairs are compared in the order:
594595
<synopsis>
595596
<replaceable>key-1</replaceable>, <replaceable>value-1</replaceable>, <replaceable>key-2</replaceable> ...

src/backend/utils/adt/jsonb_util.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,13 @@ compareJsonbContainers(JsonbContainer *a, JsonbContainer *b)
246246
*/
247247
if (va.val.array.rawScalar != vb.val.array.rawScalar)
248248
res = (va.val.array.rawScalar) ? -1 : 1;
249+
250+
/*
251+
* There should be an "else" here, to prevent us from
252+
* overriding the above, but we can't change the sort
253+
* order now, so there is a mild anomaly that an empty
254+
* top level array sorts less than null.
255+
*/
249256
if (va.val.array.nElems != vb.val.array.nElems)
250257
res = (va.val.array.nElems > vb.val.array.nElems) ? 1 : -1;
251258
break;

0 commit comments

Comments
 (0)