1 /*-------------------------------------------------------------------------
4 * converting between Jsonb and JsonbValues, and iterating.
6 * Copyright (c) 2014, PostgreSQL Global Development Group
10 * src/backend/utils/adt/jsonb_util.c
12 *-------------------------------------------------------------------------
16 #include "access/hash.h"
17 #include "catalog/pg_collation.h"
18 #include "miscadmin.h"
19 #include "utils/builtins.h"
20 #include "utils/jsonb.h"
21 #include "utils/memutils.h"
24 * Maximum number of elements in an array (or key/value pairs in an object).
25 * This is limited by two things: the size of the JEntry array must fit
26 * in MaxAllocSize, and the number of elements (or pairs) must fit in the bits
27 * reserved for that in the JsonbContainer.header field.
29 * (The total size of an array's or object's elements is also limited by
30 * JENTRY_OFFLENMASK, but we're not concerned about that here.)
32 #define JSONB_MAX_ELEMS (Min(MaxAllocSize / sizeof(JsonbValue), JB_CMASK))
33 #define JSONB_MAX_PAIRS (Min(MaxAllocSize / sizeof(JsonbPair), JB_CMASK))
35 static void fillJsonbValue(JsonbContainer *container, int index,
36 char *base_addr, uint32 offset,
38 static bool equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b);
39 static int compareJsonbScalarValue(JsonbValue *a, JsonbValue *b);
40 static Jsonb *convertToJsonb(JsonbValue *val);
41 static void convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
42 static void convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
43 static void convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
44 static void convertJsonbScalar(StringInfo buffer, JEntry *header, JsonbValue *scalarVal);
46 static int reserveFromBuffer(StringInfo buffer, int len);
47 static void appendToBuffer(StringInfo buffer, const char *data, int len);
48 static void copyToBuffer(StringInfo buffer, int offset, const char *data, int len);
49 static short padBufferToInt(StringInfo buffer);
51 static JsonbIterator *iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent);
52 static JsonbIterator *freeAndGetParent(JsonbIterator *it);
53 static JsonbParseState *pushState(JsonbParseState **pstate);
54 static void appendKey(JsonbParseState *pstate, JsonbValue *scalarVal);
55 static void appendValue(JsonbParseState *pstate, JsonbValue *scalarVal);
56 static void appendElement(JsonbParseState *pstate, JsonbValue *scalarVal);
57 static int lengthCompareJsonbStringValue(const void *a, const void *b);
58 static int lengthCompareJsonbPair(const void *a, const void *b, void *arg);
59 static void uniqueifyJsonbObject(JsonbValue *object);
62 * Turn an in-memory JsonbValue into a Jsonb for on-disk storage.
64 * There isn't a JsonbToJsonbValue(), because generally we find it more
65 * convenient to directly iterate through the Jsonb representation and only
66 * really convert nested scalar values. JsonbIteratorNext() does this, so that
67 * clients of the iteration code don't have to directly deal with the binary
68 * representation (JsonbDeepContains() is a notable exception, although all
69 * exceptions are internal to this module). In general, functions that accept
70 * a JsonbValue argument are concerned with the manipulation of scalar values,
71 * or simple containers of scalar values, where it would be inconvenient to
72 * deal with a great amount of other state.
75 JsonbValueToJsonb(JsonbValue *val)
79 if (IsAJsonbScalar(val))
82 JsonbParseState *pstate = NULL;
84 JsonbValue scalarArray;
86 scalarArray.type = jbvArray;
87 scalarArray.val.array.rawScalar = true;
88 scalarArray.val.array.nElems = 1;
90 pushJsonbValue(&pstate, WJB_BEGIN_ARRAY, &scalarArray);
91 pushJsonbValue(&pstate, WJB_ELEM, val);
92 res = pushJsonbValue(&pstate, WJB_END_ARRAY, NULL);
94 out = convertToJsonb(res);
96 else if (val->type == jbvObject || val->type == jbvArray)
98 out = convertToJsonb(val);
102 Assert(val->type == jbvBinary);
103 out = palloc(VARHDRSZ + val->val.binary.len);
104 SET_VARSIZE(out, VARHDRSZ + val->val.binary.len);
105 memcpy(VARDATA(out), val->val.binary.data, val->val.binary.len);
112 * Get the offset of the variable-length portion of a Jsonb node within
113 * the variable-length-data part of its container. The node is identified
114 * by index within the container's JEntry array.
117 getJsonbOffset(const JsonbContainer *jc, int index)
123 * Start offset of this entry is equal to the end offset of the previous
124 * entry. Walk backwards to the most recent entry stored as an end
125 * offset, returning that offset plus any lengths in between.
127 for (i = index - 1; i >= 0; i--)
129 offset += JBE_OFFLENFLD(jc->children[i]);
130 if (JBE_HAS_OFF(jc->children[i]))
138 * Get the length of the variable-length portion of a Jsonb node.
139 * The node is identified by index within the container's JEntry array.
142 getJsonbLength(const JsonbContainer *jc, int index)
148 * If the length is stored directly in the JEntry, just return it.
149 * Otherwise, get the begin offset of the entry, and subtract that from
150 * the stored end+1 offset.
152 if (JBE_HAS_OFF(jc->children[index]))
154 off = getJsonbOffset(jc, index);
155 len = JBE_OFFLENFLD(jc->children[index]) - off;
158 len = JBE_OFFLENFLD(jc->children[index]);
164 * BT comparator worker function. Returns an integer less than, equal to, or
165 * greater than zero, indicating whether a is less than, equal to, or greater
166 * than b. Consistent with the requirements for a B-Tree operator class
168 * Strings are compared lexically, in contrast with other places where we use a
169 * much simpler comparator logic for searching through Strings. Since this is
170 * called from B-Tree support function 1, we're careful about not leaking
174 compareJsonbContainers(JsonbContainer *a, JsonbContainer *b)
180 ita = JsonbIteratorInit(a);
181 itb = JsonbIteratorInit(b);
190 ra = JsonbIteratorNext(&ita, &va, false);
191 rb = JsonbIteratorNext(&itb, &vb, false);
197 /* Decisively equal */
201 if (ra == WJB_END_ARRAY || ra == WJB_END_OBJECT)
204 * There is no array or object to compare at this stage of
205 * processing. jbvArray/jbvObject values are compared
206 * initially, at the WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT
212 if (va.type == vb.type)
220 res = compareJsonbScalarValue(&va, &vb);
225 * This could be a "raw scalar" pseudo array. That's
226 * a special case here though, since we still want the
227 * general type-based comparisons to apply, and as far
228 * as we're concerned a pseudo array is just a scalar.
230 if (va.val.array.rawScalar != vb.val.array.rawScalar)
231 res = (va.val.array.rawScalar) ? -1 : 1;
232 if (va.val.array.nElems != vb.val.array.nElems)
233 res = (va.val.array.nElems > vb.val.array.nElems) ? 1 : -1;
236 if (va.val.object.nPairs != vb.val.object.nPairs)
237 res = (va.val.object.nPairs > vb.val.object.nPairs) ? 1 : -1;
240 elog(ERROR, "unexpected jbvBinary value");
245 /* Type-defined order */
246 res = (va.type > vb.type) ? 1 : -1;
252 * It's safe to assume that the types differed, and that the va
253 * and vb values passed were set.
255 * If the two values were of the same container type, then there'd
256 * have been a chance to observe the variation in the number of
257 * elements/pairs (when processing WJB_BEGIN_OBJECT, say). They're
258 * either two heterogeneously-typed containers, or a container and
261 * We don't have to consider the WJB_END_ARRAY and WJB_END_OBJECT
262 * cases here, because we would have seen the corresponding
263 * WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT tokens first, and
264 * concluded that they don't match.
266 Assert(ra != WJB_END_ARRAY && ra != WJB_END_OBJECT);
267 Assert(rb != WJB_END_ARRAY && rb != WJB_END_OBJECT);
269 Assert(va.type != vb.type);
270 Assert(va.type != jbvBinary);
271 Assert(vb.type != jbvBinary);
272 /* Type-defined order */
273 res = (va.type > vb.type) ? 1 : -1;
280 JsonbIterator *i = ita->parent;
287 JsonbIterator *i = itb->parent;
297 * Find value in object (i.e. the "value" part of some key/value pair in an
298 * object), or find a matching element if we're looking through an array. Do
299 * so on the basis of equality of the object keys only, or alternatively
300 * element values only, with a caller-supplied value "key". The "flags"
301 * argument allows the caller to specify which container types are of interest.
303 * This exported utility function exists to facilitate various cases concerned
304 * with "containment". If asked to look through an object, the caller had
305 * better pass a Jsonb String, because their keys can only be strings.
306 * Otherwise, for an array, any type of JsonbValue will do.
308 * In order to proceed with the search, it is necessary for callers to have
309 * both specified an interest in exactly one particular container type with an
310 * appropriate flag, as well as having the pointed-to Jsonb container be of
311 * one of those same container types at the top level. (Actually, we just do
312 * whichever makes sense to save callers the trouble of figuring it out - at
313 * most one can make sense, because the container either points to an array
314 * (possibly a "raw scalar" pseudo array) or an object.)
316 * Note that we can return a jbvBinary JsonbValue if this is called on an
317 * object, but we never do so on an array. If the caller asks to look through
318 * a container type that is not of the type pointed to by the container,
319 * immediately fall through and return NULL. If we cannot find the value,
320 * return NULL. Otherwise, return palloc()'d copy of value.
323 findJsonbValueFromContainer(JsonbContainer *container, uint32 flags,
326 JEntry *children = container->children;
327 int count = (container->header & JB_CMASK);
330 Assert((flags & ~(JB_FARRAY | JB_FOBJECT)) == 0);
332 /* Quick out without a palloc cycle if object/array is empty */
336 result = palloc(sizeof(JsonbValue));
338 if (flags & JB_FARRAY & container->header)
340 char *base_addr = (char *) (children + count);
344 for (i = 0; i < count; i++)
346 fillJsonbValue(container, i, base_addr, offset, result);
348 if (key->type == result->type)
350 if (equalsJsonbScalarValue(key, result))
354 JBE_ADVANCE_OFFSET(offset, children[i]);
357 else if (flags & JB_FOBJECT & container->header)
359 /* Since this is an object, account for *Pairs* of Jentrys */
360 char *base_addr = (char *) (children + count * 2);
364 /* Object key passed by caller must be a string */
365 Assert(key->type == jbvString);
367 /* Binary search on object/pair keys *only* */
368 while (stopLow < stopHigh)
372 JsonbValue candidate;
374 stopMiddle = stopLow + (stopHigh - stopLow) / 2;
376 candidate.type = jbvString;
377 candidate.val.string.val =
378 base_addr + getJsonbOffset(container, stopMiddle);
379 candidate.val.string.len = getJsonbLength(container, stopMiddle);
381 difference = lengthCompareJsonbStringValue(&candidate, key);
385 /* Found our key, return corresponding value */
386 int index = stopMiddle + count;
388 fillJsonbValue(container, index, base_addr,
389 getJsonbOffset(container, index),
397 stopLow = stopMiddle + 1;
399 stopHigh = stopMiddle;
410 * Get i-th value of a Jsonb array.
412 * Returns palloc()'d copy of the value, or NULL if it does not exist.
415 getIthJsonbValueFromContainer(JsonbContainer *container, uint32 i)
421 if ((container->header & JB_FARRAY) == 0)
422 elog(ERROR, "not a jsonb array");
424 nelements = container->header & JB_CMASK;
425 base_addr = (char *) &container->children[nelements];
430 result = palloc(sizeof(JsonbValue));
432 fillJsonbValue(container, i, base_addr,
433 getJsonbOffset(container, i),
440 * A helper function to fill in a JsonbValue to represent an element of an
441 * array, or a key or value of an object.
443 * The node's JEntry is at container->children[index], and its variable-length
444 * data is at base_addr + offset. We make the caller determine the offset
445 * since in many cases the caller can amortize that work across multiple
446 * children. When it can't, it can just call getJsonbOffset().
448 * A nested array or object will be returned as jbvBinary, ie. it won't be
452 fillJsonbValue(JsonbContainer *container, int index,
453 char *base_addr, uint32 offset,
456 JEntry entry = container->children[index];
458 if (JBE_ISNULL(entry))
460 result->type = jbvNull;
462 else if (JBE_ISSTRING(entry))
464 result->type = jbvString;
465 result->val.string.val = base_addr + offset;
466 result->val.string.len = getJsonbLength(container, index);
467 Assert(result->val.string.len >= 0);
469 else if (JBE_ISNUMERIC(entry))
471 result->type = jbvNumeric;
472 result->val.numeric = (Numeric) (base_addr + INTALIGN(offset));
474 else if (JBE_ISBOOL_TRUE(entry))
476 result->type = jbvBool;
477 result->val.boolean = true;
479 else if (JBE_ISBOOL_FALSE(entry))
481 result->type = jbvBool;
482 result->val.boolean = false;
486 Assert(JBE_ISCONTAINER(entry));
487 result->type = jbvBinary;
488 /* Remove alignment padding from data pointer and length */
489 result->val.binary.data = (JsonbContainer *) (base_addr + INTALIGN(offset));
490 result->val.binary.len = getJsonbLength(container, index) -
491 (INTALIGN(offset) - offset);
496 * Push JsonbValue into JsonbParseState.
498 * Used when parsing JSON tokens to form Jsonb, or when converting an in-memory
499 * JsonbValue to a Jsonb.
501 * Initial state of *JsonbParseState is NULL, since it'll be allocated here
502 * originally (caller will get JsonbParseState back by reference).
504 * Only sequential tokens pertaining to non-container types should pass a
505 * JsonbValue. There is one exception -- WJB_BEGIN_ARRAY callers may pass a
506 * "raw scalar" pseudo array to append that.
509 pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq,
510 JsonbValue *scalarVal)
512 JsonbValue *result = NULL;
516 case WJB_BEGIN_ARRAY:
517 Assert(!scalarVal || scalarVal->val.array.rawScalar);
518 *pstate = pushState(pstate);
519 result = &(*pstate)->contVal;
520 (*pstate)->contVal.type = jbvArray;
521 (*pstate)->contVal.val.array.nElems = 0;
522 (*pstate)->contVal.val.array.rawScalar = (scalarVal &&
523 scalarVal->val.array.rawScalar);
524 if (scalarVal && scalarVal->val.array.nElems > 0)
526 /* Assume that this array is still really a scalar */
527 Assert(scalarVal->type == jbvArray);
528 (*pstate)->size = scalarVal->val.array.nElems;
534 (*pstate)->contVal.val.array.elems = palloc(sizeof(JsonbValue) *
537 case WJB_BEGIN_OBJECT:
539 *pstate = pushState(pstate);
540 result = &(*pstate)->contVal;
541 (*pstate)->contVal.type = jbvObject;
542 (*pstate)->contVal.val.object.nPairs = 0;
544 (*pstate)->contVal.val.object.pairs = palloc(sizeof(JsonbPair) *
548 Assert(scalarVal->type == jbvString);
549 appendKey(*pstate, scalarVal);
552 Assert(IsAJsonbScalar(scalarVal) ||
553 scalarVal->type == jbvBinary);
554 appendValue(*pstate, scalarVal);
557 Assert(IsAJsonbScalar(scalarVal) ||
558 scalarVal->type == jbvBinary);
559 appendElement(*pstate, scalarVal);
562 uniqueifyJsonbObject(&(*pstate)->contVal);
565 /* Steps here common to WJB_END_OBJECT case */
567 result = &(*pstate)->contVal;
570 * Pop stack and push current array/object as value in parent
573 *pstate = (*pstate)->next;
576 switch ((*pstate)->contVal.type)
579 appendElement(*pstate, result);
582 appendValue(*pstate, result);
585 elog(ERROR, "invalid jsonb container type");
590 elog(ERROR, "unrecognized jsonb sequential processing token");
597 * pushJsonbValue() worker: Iteration-like forming of Jsonb
599 static JsonbParseState *
600 pushState(JsonbParseState **pstate)
602 JsonbParseState *ns = palloc(sizeof(JsonbParseState));
609 * pushJsonbValue() worker: Append a pair key to state when generating a Jsonb
612 appendKey(JsonbParseState *pstate, JsonbValue *string)
614 JsonbValue *object = &pstate->contVal;
616 Assert(object->type == jbvObject);
617 Assert(string->type == jbvString);
619 if (object->val.object.nPairs >= JSONB_MAX_PAIRS)
621 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
622 errmsg("number of jsonb object pairs exceeds the maximum allowed (%zu)",
625 if (object->val.object.nPairs >= pstate->size)
628 object->val.object.pairs = repalloc(object->val.object.pairs,
629 sizeof(JsonbPair) * pstate->size);
632 object->val.object.pairs[object->val.object.nPairs].key = *string;
633 object->val.object.pairs[object->val.object.nPairs].order = object->val.object.nPairs;
637 * pushJsonbValue() worker: Append a pair value to state when generating a
641 appendValue(JsonbParseState *pstate, JsonbValue *scalarVal)
643 JsonbValue *object = &pstate->contVal;
645 Assert(object->type == jbvObject);
647 object->val.object.pairs[object->val.object.nPairs++].value = *scalarVal;
651 * pushJsonbValue() worker: Append an element to state when generating a Jsonb
654 appendElement(JsonbParseState *pstate, JsonbValue *scalarVal)
656 JsonbValue *array = &pstate->contVal;
658 Assert(array->type == jbvArray);
660 if (array->val.array.nElems >= JSONB_MAX_ELEMS)
662 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
663 errmsg("number of jsonb array elements exceeds the maximum allowed (%zu)",
666 if (array->val.array.nElems >= pstate->size)
669 array->val.array.elems = repalloc(array->val.array.elems,
670 sizeof(JsonbValue) * pstate->size);
673 array->val.array.elems[array->val.array.nElems++] = *scalarVal;
677 * Given a JsonbContainer, expand to JsonbIterator to iterate over items
678 * fully expanded to in-memory representation for manipulation.
680 * See JsonbIteratorNext() for notes on memory management.
683 JsonbIteratorInit(JsonbContainer *container)
685 return iteratorFromContainer(container, NULL);
689 * Get next JsonbValue while iterating
691 * Caller should initially pass their own, original iterator. They may get
692 * back a child iterator palloc()'d here instead. The function can be relied
693 * on to free those child iterators, lest the memory allocated for highly
694 * nested objects become unreasonable, but only if callers don't end iteration
695 * early (by breaking upon having found something in a search, for example).
697 * Callers in such a scenario, that are particularly sensitive to leaking
698 * memory in a long-lived context may walk the ancestral tree from the final
699 * iterator we left them with to its oldest ancestor, pfree()ing as they go.
700 * They do not have to free any other memory previously allocated for iterators
701 * but not accessible as direct ancestors of the iterator they're last passed
704 * Returns "Jsonb sequential processing" token value. Iterator "state"
705 * reflects the current stage of the process in a less granular fashion, and is
706 * mostly used here to track things internally with respect to particular
709 * Clients of this function should not have to handle any jbvBinary values
710 * (since recursive calls will deal with this), provided skipNested is false.
711 * It is our job to expand the jbvBinary representation without bothering them
712 * with it. However, clients should not take it upon themselves to touch array
713 * or Object element/pair buffers, since their element/pair pointers are
714 * garbage. Also, *val will not be set when returning WJB_END_ARRAY or
715 * WJB_END_OBJECT, on the assumption that it's only useful to access values
719 JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
725 * When stepping into a nested container, we jump back here to start
726 * processing the child. We will not recurse further in one call, because
727 * processing the child will always begin in JBI_ARRAY_START or
728 * JBI_OBJECT_START state.
731 switch ((*it)->state)
733 case JBI_ARRAY_START:
734 /* Set v to array on first array call */
735 val->type = jbvArray;
736 val->val.array.nElems = (*it)->nElems;
739 * v->val.array.elems is not actually set, because we aren't doing
742 val->val.array.rawScalar = (*it)->isScalar;
744 (*it)->curDataOffset = 0;
745 (*it)->curValueOffset = 0; /* not actually used */
746 /* Set state for next call */
747 (*it)->state = JBI_ARRAY_ELEM;
748 return WJB_BEGIN_ARRAY;
751 if ((*it)->curIndex >= (*it)->nElems)
754 * All elements within array already processed. Report this
755 * to caller, and give it back original parent iterator (which
756 * independently tracks iteration progress at its level of
759 *it = freeAndGetParent(*it);
760 return WJB_END_ARRAY;
763 fillJsonbValue((*it)->container, (*it)->curIndex,
764 (*it)->dataProper, (*it)->curDataOffset,
767 JBE_ADVANCE_OFFSET((*it)->curDataOffset,
768 (*it)->children[(*it)->curIndex]);
771 if (!IsAJsonbScalar(val) && !skipNested)
773 /* Recurse into container. */
774 *it = iteratorFromContainer(val->val.binary.data, *it);
780 * Scalar item in array, or a container and caller didn't want
781 * us to recurse into it.
786 case JBI_OBJECT_START:
787 /* Set v to object on first object call */
788 val->type = jbvObject;
789 val->val.object.nPairs = (*it)->nElems;
792 * v->val.object.pairs is not actually set, because we aren't
793 * doing a full conversion
796 (*it)->curDataOffset = 0;
797 (*it)->curValueOffset = getJsonbOffset((*it)->container,
799 /* Set state for next call */
800 (*it)->state = JBI_OBJECT_KEY;
801 return WJB_BEGIN_OBJECT;
804 if ((*it)->curIndex >= (*it)->nElems)
807 * All pairs within object already processed. Report this to
808 * caller, and give it back original containing iterator
809 * (which independently tracks iteration progress at its level
812 *it = freeAndGetParent(*it);
813 return WJB_END_OBJECT;
817 /* Return key of a key/value pair. */
818 fillJsonbValue((*it)->container, (*it)->curIndex,
819 (*it)->dataProper, (*it)->curDataOffset,
821 if (val->type != jbvString)
822 elog(ERROR, "unexpected jsonb type as object key");
824 /* Set state for next call */
825 (*it)->state = JBI_OBJECT_VALUE;
829 case JBI_OBJECT_VALUE:
830 /* Set state for next call */
831 (*it)->state = JBI_OBJECT_KEY;
833 fillJsonbValue((*it)->container, (*it)->curIndex + (*it)->nElems,
834 (*it)->dataProper, (*it)->curValueOffset,
837 JBE_ADVANCE_OFFSET((*it)->curDataOffset,
838 (*it)->children[(*it)->curIndex]);
839 JBE_ADVANCE_OFFSET((*it)->curValueOffset,
840 (*it)->children[(*it)->curIndex + (*it)->nElems]);
844 * Value may be a container, in which case we recurse with new,
845 * child iterator (unless the caller asked not to, by passing
848 if (!IsAJsonbScalar(val) && !skipNested)
850 *it = iteratorFromContainer(val->val.binary.data, *it);
857 elog(ERROR, "invalid iterator state");
862 * Initialize an iterator for iterating all elements in a container.
864 static JsonbIterator *
865 iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent)
869 it = palloc(sizeof(JsonbIterator));
870 it->container = container;
872 it->nElems = container->header & JB_CMASK;
874 /* Array starts just after header */
875 it->children = container->children;
877 switch (container->header & (JB_FARRAY | JB_FOBJECT))
881 (char *) it->children + it->nElems * sizeof(JEntry);
882 it->isScalar = (container->header & JB_FSCALAR) != 0;
883 /* This is either a "raw scalar", or an array */
884 Assert(!it->isScalar || it->nElems == 1);
886 it->state = JBI_ARRAY_START;
891 (char *) it->children + it->nElems * sizeof(JEntry) * 2;
892 it->state = JBI_OBJECT_START;
896 elog(ERROR, "unknown type of jsonb container");
903 * JsonbIteratorNext() worker: Return parent, while freeing memory for current
906 static JsonbIterator *
907 freeAndGetParent(JsonbIterator *it)
909 JsonbIterator *v = it->parent;
916 * Worker for "contains" operator's function
918 * Formally speaking, containment is top-down, unordered subtree isomorphism.
920 * Takes iterators that belong to some container type. These iterators
921 * "belong" to those values in the sense that they've just been initialized in
922 * respect of them by the caller (perhaps in a nested fashion).
924 * "val" is lhs Jsonb, and mContained is rhs Jsonb when called from top level.
925 * We determine if mContained is contained within val.
928 JsonbDeepContains(JsonbIterator **val, JsonbIterator **mContained)
936 * Guard against stack overflow due to overly complex Jsonb.
938 * Functions called here independently take this precaution, but that
939 * might not be sufficient since this is also a recursive function.
943 rval = JsonbIteratorNext(val, &vval, false);
944 rcont = JsonbIteratorNext(mContained, &vcontained, false);
949 * The differing return values can immediately be taken as indicating
950 * two differing container types at this nesting level, which is
951 * sufficient reason to give up entirely (but it should be the case
952 * that they're both some container type).
954 Assert(rval == WJB_BEGIN_OBJECT || rval == WJB_BEGIN_ARRAY);
955 Assert(rcont == WJB_BEGIN_OBJECT || rcont == WJB_BEGIN_ARRAY);
958 else if (rcont == WJB_BEGIN_OBJECT)
960 Assert(vval.type == jbvObject);
961 Assert(vcontained.type == jbvObject);
964 * If the lhs has fewer pairs than the rhs, it can't possibly contain
965 * the rhs. (This conclusion is safe only because we de-duplicate
966 * keys in all Jsonb objects; thus there can be no corresponding
967 * optimization in the array case.) The case probably won't arise
968 * often, but since it's such a cheap check we may as well make it.
970 if (vval.val.object.nPairs < vcontained.val.object.nPairs)
973 /* Work through rhs "is it contained within?" object */
976 JsonbValue *lhsVal; /* lhsVal is from pair in lhs object */
978 rcont = JsonbIteratorNext(mContained, &vcontained, false);
981 * When we get through caller's rhs "is it contained within?"
982 * object without failing to find one of its values, it's
985 if (rcont == WJB_END_OBJECT)
988 Assert(rcont == WJB_KEY);
990 /* First, find value by key... */
991 lhsVal = findJsonbValueFromContainer((*val)->container,
999 * ...at this stage it is apparent that there is at least a key
1000 * match for this rhs pair.
1002 rcont = JsonbIteratorNext(mContained, &vcontained, true);
1004 Assert(rcont == WJB_VALUE);
1007 * Compare rhs pair's value with lhs pair's value just found using
1010 if (lhsVal->type != vcontained.type)
1014 else if (IsAJsonbScalar(lhsVal))
1016 if (!equalsJsonbScalarValue(lhsVal, &vcontained))
1021 /* Nested container value (object or array) */
1022 JsonbIterator *nestval,
1025 Assert(lhsVal->type == jbvBinary);
1026 Assert(vcontained.type == jbvBinary);
1028 nestval = JsonbIteratorInit(lhsVal->val.binary.data);
1029 nestContained = JsonbIteratorInit(vcontained.val.binary.data);
1032 * Match "value" side of rhs datum object's pair recursively.
1033 * It's a nested structure.
1035 * Note that nesting still has to "match up" at the right
1036 * nesting sub-levels. However, there need only be zero or
1037 * more matching pairs (or elements) at each nesting level
1038 * (provided the *rhs* pairs/elements *all* match on each
1039 * level), which enables searching nested structures for a
1040 * single String or other primitive type sub-datum quite
1041 * effectively (provided the user constructed the rhs nested
1042 * structure such that we "know where to look").
1044 * In other words, the mapping of container nodes in the rhs
1045 * "vcontained" Jsonb to internal nodes on the lhs is
1046 * injective, and parent-child edges on the rhs must be mapped
1047 * to parent-child edges on the lhs to satisfy the condition
1048 * of containment (plus of course the mapped nodes must be
1051 if (!JsonbDeepContains(&nestval, &nestContained))
1056 else if (rcont == WJB_BEGIN_ARRAY)
1058 JsonbValue *lhsConts = NULL;
1059 uint32 nLhsElems = vval.val.array.nElems;
1061 Assert(vval.type == jbvArray);
1062 Assert(vcontained.type == jbvArray);
1065 * Handle distinction between "raw scalar" pseudo arrays, and real
1068 * A raw scalar may contain another raw scalar, and an array may
1069 * contain a raw scalar, but a raw scalar may not contain an array. We
1070 * don't do something like this for the object case, since objects can
1071 * only contain pairs, never raw scalars (a pair is represented by an
1072 * rhs object argument with a single contained pair).
1074 if (vval.val.array.rawScalar && !vcontained.val.array.rawScalar)
1077 /* Work through rhs "is it contained within?" array */
1080 rcont = JsonbIteratorNext(mContained, &vcontained, true);
1083 * When we get through caller's rhs "is it contained within?"
1084 * array without failing to find one of its values, it's
1087 if (rcont == WJB_END_ARRAY)
1090 Assert(rcont == WJB_ELEM);
1092 if (IsAJsonbScalar(&vcontained))
1094 if (!findJsonbValueFromContainer((*val)->container,
1104 * If this is first container found in rhs array (at this
1105 * depth), initialize temp lhs array of containers
1107 if (lhsConts == NULL)
1111 /* Make room for all possible values */
1112 lhsConts = palloc(sizeof(JsonbValue) * nLhsElems);
1114 for (i = 0; i < nLhsElems; i++)
1116 /* Store all lhs elements in temp array */
1117 rcont = JsonbIteratorNext(val, &vval, true);
1118 Assert(rcont == WJB_ELEM);
1120 if (vval.type == jbvBinary)
1121 lhsConts[j++] = vval;
1124 /* No container elements in temp array, so give up now */
1128 /* We may have only partially filled array */
1132 /* XXX: Nested array containment is O(N^2) */
1133 for (i = 0; i < nLhsElems; i++)
1135 /* Nested container value (object or array) */
1136 JsonbIterator *nestval,
1140 nestval = JsonbIteratorInit(lhsConts[i].val.binary.data);
1141 nestContained = JsonbIteratorInit(vcontained.val.binary.data);
1143 contains = JsonbDeepContains(&nestval, &nestContained);
1148 pfree(nestContained);
1154 * Report rhs container value is not contained if couldn't
1155 * match rhs container to *some* lhs cont
1164 elog(ERROR, "invalid jsonb container type");
1167 elog(ERROR, "unexpectedly fell off end of jsonb container");
1172 * Hash a JsonbValue scalar value, mixing the hash value into an existing
1173 * hash provided by the caller.
1175 * Some callers may wish to independently XOR in JB_FOBJECT and JB_FARRAY
1179 JsonbHashScalarValue(const JsonbValue *scalarVal, uint32 *hash)
1183 /* Compute hash value for scalarVal */
1184 switch (scalarVal->type)
1190 tmp = DatumGetUInt32(hash_any((const unsigned char *) scalarVal->val.string.val,
1191 scalarVal->val.string.len));
1194 /* Must hash equal numerics to equal hash codes */
1195 tmp = DatumGetUInt32(DirectFunctionCall1(hash_numeric,
1196 NumericGetDatum(scalarVal->val.numeric)));
1199 tmp = scalarVal->val.boolean ? 0x02 : 0x04;
1202 elog(ERROR, "invalid jsonb scalar type");
1203 tmp = 0; /* keep compiler quiet */
1208 * Combine hash values of successive keys, values and elements by rotating
1209 * the previous value left 1 bit, then XOR'ing in the new
1210 * key/value/element's hash value.
1212 *hash = (*hash << 1) | (*hash >> 31);
1217 * Are two scalar JsonbValues of the same type a and b equal?
1220 equalsJsonbScalarValue(JsonbValue *aScalar, JsonbValue *bScalar)
1222 if (aScalar->type == bScalar->type)
1224 switch (aScalar->type)
1229 return lengthCompareJsonbStringValue(aScalar, bScalar) == 0;
1231 return DatumGetBool(DirectFunctionCall2(numeric_eq,
1232 PointerGetDatum(aScalar->val.numeric),
1233 PointerGetDatum(bScalar->val.numeric)));
1235 return aScalar->val.boolean == bScalar->val.boolean;
1238 elog(ERROR, "invalid jsonb scalar type");
1241 elog(ERROR, "jsonb scalar type mismatch");
1246 * Compare two scalar JsonbValues, returning -1, 0, or 1.
1248 * Strings are compared using the default collation. Used by B-tree
1249 * operators, where a lexical sort order is generally expected.
1252 compareJsonbScalarValue(JsonbValue *aScalar, JsonbValue *bScalar)
1254 if (aScalar->type == bScalar->type)
1256 switch (aScalar->type)
1261 return varstr_cmp(aScalar->val.string.val,
1262 aScalar->val.string.len,
1263 bScalar->val.string.val,
1264 bScalar->val.string.len,
1265 DEFAULT_COLLATION_OID);
1267 return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
1268 PointerGetDatum(aScalar->val.numeric),
1269 PointerGetDatum(bScalar->val.numeric)));
1271 if (aScalar->val.boolean == bScalar->val.boolean)
1273 else if (aScalar->val.boolean > bScalar->val.boolean)
1278 elog(ERROR, "invalid jsonb scalar type");
1281 elog(ERROR, "jsonb scalar type mismatch");
1287 * Functions for manipulating the resizeable buffer used by convertJsonb and
1292 * Reserve 'len' bytes, at the end of the buffer, enlarging it if necessary.
1293 * Returns the offset to the reserved area. The caller is expected to fill
1294 * the reserved area later with copyToBuffer().
1297 reserveFromBuffer(StringInfo buffer, int len)
1301 /* Make more room if needed */
1302 enlargeStringInfo(buffer, len);
1304 /* remember current offset */
1305 offset = buffer->len;
1307 /* reserve the space */
1311 * Keep a trailing null in place, even though it's not useful for us; it
1312 * seems best to preserve the invariants of StringInfos.
1314 buffer->data[buffer->len] = '\0';
1320 * Copy 'len' bytes to a previously reserved area in buffer.
1323 copyToBuffer(StringInfo buffer, int offset, const char *data, int len)
1325 memcpy(buffer->data + offset, data, len);
1329 * A shorthand for reserveFromBuffer + copyToBuffer.
1332 appendToBuffer(StringInfo buffer, const char *data, int len)
1336 offset = reserveFromBuffer(buffer, len);
1337 copyToBuffer(buffer, offset, data, len);
1342 * Append padding, so that the length of the StringInfo is int-aligned.
1343 * Returns the number of padding bytes appended.
1346 padBufferToInt(StringInfo buffer)
1352 padlen = INTALIGN(buffer->len) - buffer->len;
1354 offset = reserveFromBuffer(buffer, padlen);
1356 /* padlen must be small, so this is probably faster than a memset */
1357 for (p = 0; p < padlen; p++)
1358 buffer->data[offset + p] = '\0';
1364 * Given a JsonbValue, convert to Jsonb. The result is palloc'd.
1367 convertToJsonb(JsonbValue *val)
1369 StringInfoData buffer;
1373 /* Should not already have binary representation */
1374 Assert(val->type != jbvBinary);
1376 /* Allocate an output buffer. It will be enlarged as needed */
1377 initStringInfo(&buffer);
1379 /* Make room for the varlena header */
1380 reserveFromBuffer(&buffer, VARHDRSZ);
1382 convertJsonbValue(&buffer, &jentry, val, 0);
1385 * Note: the JEntry of the root is discarded. Therefore the root
1386 * JsonbContainer struct must contain enough information to tell what kind
1390 res = (Jsonb *) buffer.data;
1392 SET_VARSIZE(res, buffer.len);
1398 * Subroutine of convertJsonb: serialize a single JsonbValue into buffer.
1400 * The JEntry header for this node is returned in *header. It is filled in
1401 * with the length of this value and appropriate type bits. If we wish to
1402 * store an end offset rather than a length, it is the caller's responsibility
1403 * to adjust for that.
1405 * If the value is an array or an object, this recurses. 'level' is only used
1406 * for debugging purposes.
1409 convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
1411 check_stack_depth();
1417 * A JsonbValue passed as val should never have a type of jbvBinary, and
1418 * neither should any of its sub-components. Those values will be produced
1419 * by convertJsonbArray and convertJsonbObject, the results of which will
1420 * not be passed back to this function as an argument.
1423 if (IsAJsonbScalar(val))
1424 convertJsonbScalar(buffer, header, val);
1425 else if (val->type == jbvArray)
1426 convertJsonbArray(buffer, header, val, level);
1427 else if (val->type == jbvObject)
1428 convertJsonbObject(buffer, header, val, level);
1430 elog(ERROR, "unknown type of jsonb container to convert");
1434 convertJsonbArray(StringInfo buffer, JEntry *pheader, JsonbValue *val, int level)
1441 int nElems = val->val.array.nElems;
1443 /* Remember where in the buffer this array starts. */
1444 base_offset = buffer->len;
1446 /* Align to 4-byte boundary (any padding counts as part of my data) */
1447 padBufferToInt(buffer);
1450 * Construct the header Jentry and store it in the beginning of the
1451 * variable-length payload.
1453 header = nElems | JB_FARRAY;
1454 if (val->val.array.rawScalar)
1456 Assert(nElems == 1);
1458 header |= JB_FSCALAR;
1461 appendToBuffer(buffer, (char *) &header, sizeof(uint32));
1463 /* Reserve space for the JEntries of the elements. */
1464 jentry_offset = reserveFromBuffer(buffer, sizeof(JEntry) * nElems);
1467 for (i = 0; i < nElems; i++)
1469 JsonbValue *elem = &val->val.array.elems[i];
1474 * Convert element, producing a JEntry and appending its
1475 * variable-length data to buffer
1477 convertJsonbValue(buffer, &meta, elem, level + 1);
1479 len = JBE_OFFLENFLD(meta);
1483 * Bail out if total variable-length data exceeds what will fit in a
1484 * JEntry length field. We check this in each iteration, not just
1485 * once at the end, to forestall possible integer overflow.
1487 if (totallen > JENTRY_OFFLENMASK)
1489 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1490 errmsg("total size of jsonb array elements exceeds the maximum of %u bytes",
1491 JENTRY_OFFLENMASK)));
1494 * Convert each JB_OFFSET_STRIDE'th length to an offset.
1496 if ((i % JB_OFFSET_STRIDE) == 0)
1497 meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF;
1499 copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry));
1500 jentry_offset += sizeof(JEntry);
1503 /* Total data size is everything we've appended to buffer */
1504 totallen = buffer->len - base_offset;
1506 /* Check length again, since we didn't include the metadata above */
1507 if (totallen > JENTRY_OFFLENMASK)
1509 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1510 errmsg("total size of jsonb array elements exceeds the maximum of %u bytes",
1511 JENTRY_OFFLENMASK)));
1513 /* Initialize the header of this node in the container's JEntry array */
1514 *pheader = JENTRY_ISCONTAINER | totallen;
1518 convertJsonbObject(StringInfo buffer, JEntry *pheader, JsonbValue *val, int level)
1525 int nPairs = val->val.object.nPairs;
1527 /* Remember where in the buffer this object starts. */
1528 base_offset = buffer->len;
1530 /* Align to 4-byte boundary (any padding counts as part of my data) */
1531 padBufferToInt(buffer);
1534 * Construct the header Jentry and store it in the beginning of the
1535 * variable-length payload.
1537 header = nPairs | JB_FOBJECT;
1538 appendToBuffer(buffer, (char *) &header, sizeof(uint32));
1540 /* Reserve space for the JEntries of the keys and values. */
1541 jentry_offset = reserveFromBuffer(buffer, sizeof(JEntry) * nPairs * 2);
1544 * Iterate over the keys, then over the values, since that is the ordering
1545 * we want in the on-disk representation.
1548 for (i = 0; i < nPairs; i++)
1550 JsonbPair *pair = &val->val.object.pairs[i];
1555 * Convert key, producing a JEntry and appending its variable-length
1558 convertJsonbScalar(buffer, &meta, &pair->key);
1560 len = JBE_OFFLENFLD(meta);
1564 * Bail out if total variable-length data exceeds what will fit in a
1565 * JEntry length field. We check this in each iteration, not just
1566 * once at the end, to forestall possible integer overflow.
1568 if (totallen > JENTRY_OFFLENMASK)
1570 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1571 errmsg("total size of jsonb object elements exceeds the maximum of %u bytes",
1572 JENTRY_OFFLENMASK)));
1575 * Convert each JB_OFFSET_STRIDE'th length to an offset.
1577 if ((i % JB_OFFSET_STRIDE) == 0)
1578 meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF;
1580 copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry));
1581 jentry_offset += sizeof(JEntry);
1583 for (i = 0; i < nPairs; i++)
1585 JsonbPair *pair = &val->val.object.pairs[i];
1590 * Convert value, producing a JEntry and appending its variable-length
1593 convertJsonbValue(buffer, &meta, &pair->value, level + 1);
1595 len = JBE_OFFLENFLD(meta);
1599 * Bail out if total variable-length data exceeds what will fit in a
1600 * JEntry length field. We check this in each iteration, not just
1601 * once at the end, to forestall possible integer overflow.
1603 if (totallen > JENTRY_OFFLENMASK)
1605 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1606 errmsg("total size of jsonb object elements exceeds the maximum of %u bytes",
1607 JENTRY_OFFLENMASK)));
1610 * Convert each JB_OFFSET_STRIDE'th length to an offset.
1612 if (((i + nPairs) % JB_OFFSET_STRIDE) == 0)
1613 meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF;
1615 copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry));
1616 jentry_offset += sizeof(JEntry);
1619 /* Total data size is everything we've appended to buffer */
1620 totallen = buffer->len - base_offset;
1622 /* Check length again, since we didn't include the metadata above */
1623 if (totallen > JENTRY_OFFLENMASK)
1625 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1626 errmsg("total size of jsonb object elements exceeds the maximum of %u bytes",
1627 JENTRY_OFFLENMASK)));
1629 /* Initialize the header of this node in the container's JEntry array */
1630 *pheader = JENTRY_ISCONTAINER | totallen;
1634 convertJsonbScalar(StringInfo buffer, JEntry *jentry, JsonbValue *scalarVal)
1639 switch (scalarVal->type)
1642 *jentry = JENTRY_ISNULL;
1646 appendToBuffer(buffer, scalarVal->val.string.val, scalarVal->val.string.len);
1648 *jentry = scalarVal->val.string.len;
1652 numlen = VARSIZE_ANY(scalarVal->val.numeric);
1653 padlen = padBufferToInt(buffer);
1655 appendToBuffer(buffer, (char *) scalarVal->val.numeric, numlen);
1657 *jentry = JENTRY_ISNUMERIC | (padlen + numlen);
1661 *jentry = (scalarVal->val.boolean) ?
1662 JENTRY_ISBOOL_TRUE : JENTRY_ISBOOL_FALSE;
1666 elog(ERROR, "invalid jsonb scalar type");
1671 * Compare two jbvString JsonbValue values, a and b.
1673 * This is a special qsort() comparator used to sort strings in certain
1674 * internal contexts where it is sufficient to have a well-defined sort order.
1675 * In particular, object pair keys are sorted according to this criteria to
1676 * facilitate cheap binary searches where we don't care about lexical sort
1679 * a and b are first sorted based on their length. If a tie-breaker is
1680 * required, only then do we consider string binary equality.
1683 lengthCompareJsonbStringValue(const void *a, const void *b)
1685 const JsonbValue *va = (const JsonbValue *) a;
1686 const JsonbValue *vb = (const JsonbValue *) b;
1689 Assert(va->type == jbvString);
1690 Assert(vb->type == jbvString);
1692 if (va->val.string.len == vb->val.string.len)
1694 res = memcmp(va->val.string.val, vb->val.string.val, va->val.string.len);
1698 res = (va->val.string.len > vb->val.string.len) ? 1 : -1;
1705 * qsort_arg() comparator to compare JsonbPair values.
1707 * Third argument 'binequal' may point to a bool. If it's set, *binequal is set
1708 * to true iff a and b have full binary equality, since some callers have an
1709 * interest in whether the two values are equal or merely equivalent.
1711 * N.B: String comparisons here are "length-wise"
1713 * Pairs with equals keys are ordered such that the order field is respected.
1716 lengthCompareJsonbPair(const void *a, const void *b, void *binequal)
1718 const JsonbPair *pa = (const JsonbPair *) a;
1719 const JsonbPair *pb = (const JsonbPair *) b;
1722 res = lengthCompareJsonbStringValue(&pa->key, &pb->key);
1723 if (res == 0 && binequal)
1724 *((bool *) binequal) = true;
1727 * Guarantee keeping order of equal pair. Unique algorithm will prefer
1728 * first element as value.
1731 res = (pa->order > pb->order) ? -1 : 1;
1737 * Sort and unique-ify pairs in JsonbValue object
1740 uniqueifyJsonbObject(JsonbValue *object)
1742 bool hasNonUniq = false;
1744 Assert(object->type == jbvObject);
1746 if (object->val.object.nPairs > 1)
1747 qsort_arg(object->val.object.pairs, object->val.object.nPairs, sizeof(JsonbPair),
1748 lengthCompareJsonbPair, &hasNonUniq);
1752 JsonbPair *ptr = object->val.object.pairs + 1,
1753 *res = object->val.object.pairs;
1755 while (ptr - object->val.object.pairs < object->val.object.nPairs)
1757 /* Avoid copying over duplicate */
1758 if (lengthCompareJsonbStringValue(ptr, res) != 0)
1762 memcpy(res, ptr, sizeof(JsonbPair));
1767 object->val.object.nPairs = res + 1 - object->val.object.pairs;