1 /*-------------------------------------------------------------------------
4 * Declarations for jsonb data type support.
6 * Copyright (c) 1996-2014, PostgreSQL Global Development Group
8 * src/include/utils/jsonb.h
10 *-------------------------------------------------------------------------
15 #include "lib/stringinfo.h"
16 #include "utils/array.h"
17 #include "utils/numeric.h"
19 /* Tokens used when sequentially processing a jsonb value */
32 /* Strategy numbers for GIN index opclasses */
33 #define JsonbContainsStrategyNumber 7
34 #define JsonbExistsStrategyNumber 9
35 #define JsonbExistsAnyStrategyNumber 10
36 #define JsonbExistsAllStrategyNumber 11
39 * In the standard jsonb_ops GIN opclass for jsonb, we choose to index both
40 * keys and values. The storage format is text. The first byte of the text
41 * string distinguishes whether this is a key (always a string), null value,
42 * boolean value, numeric value, or string value. However, array elements
43 * that are strings are marked as though they were keys; this imprecision
44 * supports the definition of the "exists" operator, which treats array
45 * elements like keys. The remainder of the text string is empty for a null
46 * value, "t" or "f" for a boolean value, a normalized print representation of
47 * a numeric value, or the text of a string value. However, if the length of
48 * this text representation would exceed JGIN_MAXLENGTH bytes, we instead hash
49 * the text representation and store an 8-hex-digit representation of the
50 * uint32 hash value, marking the prefix byte with an additional bit to
51 * distinguish that this has happened. Hashing long strings saves space and
52 * ensures that we won't overrun the maximum entry length for a GIN index.
53 * (But JGIN_MAXLENGTH is quite a bit shorter than GIN's limit. It's chosen
54 * to ensure that the on-disk text datum will have a short varlena header.)
55 * Note that when any hashed item appears in a query, we must recheck index
56 * matches against the heap tuple; currently, this costs nothing because we
57 * must always recheck for other reasons.
59 #define JGINFLAG_KEY 0x01 /* key (or string array element) */
60 #define JGINFLAG_NULL 0x02 /* null value */
61 #define JGINFLAG_BOOL 0x03 /* boolean value */
62 #define JGINFLAG_NUM 0x04 /* numeric value */
63 #define JGINFLAG_STR 0x05 /* string value (if not an array element) */
64 #define JGINFLAG_HASHED 0x10 /* OR'd into flag if value was hashed */
65 #define JGIN_MAXLENGTH 125 /* max length of text part before hashing */
67 /* Convenience macros */
68 #define DatumGetJsonb(d) ((Jsonb *) PG_DETOAST_DATUM(d))
69 #define JsonbGetDatum(p) PointerGetDatum(p)
70 #define PG_GETARG_JSONB(x) DatumGetJsonb(PG_GETARG_DATUM(x))
71 #define PG_RETURN_JSONB(x) PG_RETURN_POINTER(x)
73 typedef struct JsonbPair JsonbPair;
74 typedef struct JsonbValue JsonbValue;
77 * Jsonbs are varlena objects, so must meet the varlena convention that the
78 * first int32 of the object contains the total object size in bytes. Be sure
79 * to use VARSIZE() and SET_VARSIZE() to access it, though!
81 * Jsonb is the on-disk representation, in contrast to the in-memory JsonbValue
82 * representation. Often, JsonbValues are just shims through which a Jsonb
83 * buffer is accessed, but they can also be deep copied and passed around.
85 * Jsonb is a tree structure. Each node in the tree consists of a JEntry
86 * header, and a variable-length content. The JEntry header indicates what
87 * kind of a node it is, e.g. a string or an array, and the offset and length
88 * of its variable-length portion within the container.
90 * The JEntry and the content of a node are not stored physically together.
91 * Instead, the container array or object has an array that holds the JEntrys
92 * of all the child nodes, followed by their variable-length portions.
94 * The root node is an exception; it has no parent array or object that could
95 * hold its JEntry. Hence, no JEntry header is stored for the root node. It
96 * is implicitly known that the root node must be an array or an object,
97 * so we can get away without the type indicator as long as we can distinguish
98 * the two. For that purpose, both an array and an object begins with a uint32
99 * header field, which contains an JB_FOBJECT or JB_FARRAY flag. When a naked
100 * scalar value needs to be stored as a Jsonb value, what we actually store is
101 * an array with one element, with the flags in the array's header field set
102 * to JB_FSCALAR | JB_FARRAY.
104 * To encode the length and offset of the variable-length portion of each
105 * node in a compact way, the JEntry stores only the end offset within the
106 * variable-length portion of the container node. For the first JEntry in the
107 * container's JEntry array, that equals to the length of the node data. For
108 * convenience, the JENTRY_ISFIRST flag is set. The begin offset and length
109 * of the rest of the entries can be calculated using the end offset of the
110 * previous JEntry in the array.
112 * Overall, the Jsonb struct requires 4-bytes alignment. Within the struct,
113 * the variable-length portion of some node types is aligned to a 4-byte
114 * boundary, while others are not. When alignment is needed, the padding is
115 * in the beginning of the node that requires it. For example, if a numeric
116 * node is stored after a string node, so that the numeric node begins at
117 * offset 3, the variable-length portion of the numeric node will begin with
124 * The least significant 28 bits store the end offset of the entry (see
125 * JBE_ENDPOS, JBE_OFF, JBE_LEN macros below). The next three bits
126 * are used to store the type of the entry. The most significant bit
127 * is set on the first entry in an array of JEntrys.
129 typedef uint32 JEntry;
131 #define JENTRY_POSMASK 0x0FFFFFFF
132 #define JENTRY_TYPEMASK 0x70000000
134 /* values stored in the type bits */
135 #define JENTRY_ISSTRING 0x00000000
136 #define JENTRY_ISNUMERIC 0x10000000
137 #define JENTRY_ISBOOL_FALSE 0x20000000
138 #define JENTRY_ISBOOL_TRUE 0x30000000
139 #define JENTRY_ISNULL 0x40000000
140 #define JENTRY_ISCONTAINER 0x50000000 /* array or object */
142 /* Note possible multiple evaluations */
143 #define JBE_ISFIRST(je_) (((je_) & JENTRY_ISFIRST) != 0)
144 #define JBE_ISSTRING(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISSTRING)
145 #define JBE_ISNUMERIC(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISNUMERIC)
146 #define JBE_ISCONTAINER(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISCONTAINER)
147 #define JBE_ISNULL(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISNULL)
148 #define JBE_ISBOOL_TRUE(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISBOOL_TRUE)
149 #define JBE_ISBOOL_FALSE(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISBOOL_FALSE)
150 #define JBE_ISBOOL(je_) (JBE_ISBOOL_TRUE(je_) || JBE_ISBOOL_FALSE(je_))
153 * Macros for getting the offset and length of an element. Note multiple
154 * evaluations and access to prior array element.
156 #define JBE_ENDPOS(je_) ((je_) & JENTRY_POSMASK)
157 #define JBE_OFF(ja, i) ((i) == 0 ? 0 : JBE_ENDPOS((ja)[i - 1]))
158 #define JBE_LEN(ja, i) ((i) == 0 ? JBE_ENDPOS((ja)[i]) \
159 : JBE_ENDPOS((ja)[i]) - JBE_ENDPOS((ja)[i - 1]))
162 * A jsonb array or object node, within a Jsonb Datum.
164 * An array has one child for each element. An object has two children for
165 * each key/value pair.
167 typedef struct JsonbContainer
169 uint32 header; /* number of elements or key/value pairs, and
171 JEntry children[1]; /* variable length */
173 /* the data for each child node follows. */
176 /* flags for the header-field in JsonbContainer */
177 #define JB_CMASK 0x0FFFFFFF
178 #define JB_FSCALAR 0x10000000
179 #define JB_FOBJECT 0x20000000
180 #define JB_FARRAY 0x40000000
182 /* The top-level on-disk format for a jsonb datum. */
185 int32 vl_len_; /* varlena header (do not touch directly!) */
189 /* convenience macros for accessing the root container in a Jsonb datum */
190 #define JB_ROOT_COUNT(jbp_) ( *(uint32*) VARDATA(jbp_) & JB_CMASK)
191 #define JB_ROOT_IS_SCALAR(jbp_) ( *(uint32*) VARDATA(jbp_) & JB_FSCALAR)
192 #define JB_ROOT_IS_OBJECT(jbp_) ( *(uint32*) VARDATA(jbp_) & JB_FOBJECT)
193 #define JB_ROOT_IS_ARRAY(jbp_) ( *(uint32*) VARDATA(jbp_) & JB_FARRAY)
197 * JsonbValue: In-memory representation of Jsonb. This is a convenient
198 * deserialized representation, that can easily support using the "val"
199 * union across underlying types during manipulation. The Jsonb on-disk
200 * representation has various alignment considerations.
211 /* Composite types */
214 /* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
216 } type; /* Influences sort order */
225 char *val; /* Not necessarily null-terminated */
226 } string; /* String primitive type */
232 bool rawScalar; /* Top-level "raw scalar" array? */
233 } array; /* Array container type */
237 int nPairs; /* 1 pair, 2 elements */
239 } object; /* Associative container type */
244 JsonbContainer *data;
245 } binary; /* Array or object, in on-disk format */
249 #define IsAJsonbScalar(jsonbval) ((jsonbval)->type >= jbvNull && \
250 (jsonbval)->type <= jbvBool)
253 * Pair within an Object.
255 * Pairs with duplicate keys are de-duplicated. We store the order for the
256 * benefit of doing so in a well-defined way with respect to the original
257 * observed order (which is "last observed wins"). This is only used briefly
258 * when originally constructing a Jsonb.
262 JsonbValue key; /* Must be a jbvString */
263 JsonbValue value; /* May be of any type */
264 uint32 order; /* preserves order of pairs with equal keys */
267 /* Conversion state used when parsing Jsonb from text, or for type coercion */
268 typedef struct JsonbParseState
272 struct JsonbParseState *next;
276 * JsonbIterator holds details of the type for each iteration. It also stores a
277 * Jsonb varlena buffer, which can be directly accessed in some contexts.
288 typedef struct JsonbIterator
290 /* Container being iterated */
291 JsonbContainer *container;
292 uint32 nElems; /* Number of elements in children array (will be
293 * nPairs for objects) */
294 bool isScalar; /* Pseudo-array scalar value? */
297 /* Current item in buffer (up to nElems, but must * 2 for objects) */
301 * Data proper. This points just past end of children array.
302 * We use the JBE_OFF() macro on the Jentrys to find offsets of each
303 * child in this area.
308 JsonbIterState state;
310 struct JsonbIterator *parent;
314 extern Datum jsonb_in(PG_FUNCTION_ARGS);
315 extern Datum jsonb_out(PG_FUNCTION_ARGS);
316 extern Datum jsonb_recv(PG_FUNCTION_ARGS);
317 extern Datum jsonb_send(PG_FUNCTION_ARGS);
318 extern Datum jsonb_typeof(PG_FUNCTION_ARGS);
320 /* Indexing-related ops */
321 extern Datum jsonb_exists(PG_FUNCTION_ARGS);
322 extern Datum jsonb_exists_any(PG_FUNCTION_ARGS);
323 extern Datum jsonb_exists_all(PG_FUNCTION_ARGS);
324 extern Datum jsonb_contains(PG_FUNCTION_ARGS);
325 extern Datum jsonb_contained(PG_FUNCTION_ARGS);
326 extern Datum jsonb_ne(PG_FUNCTION_ARGS);
327 extern Datum jsonb_lt(PG_FUNCTION_ARGS);
328 extern Datum jsonb_gt(PG_FUNCTION_ARGS);
329 extern Datum jsonb_le(PG_FUNCTION_ARGS);
330 extern Datum jsonb_ge(PG_FUNCTION_ARGS);
331 extern Datum jsonb_eq(PG_FUNCTION_ARGS);
332 extern Datum jsonb_cmp(PG_FUNCTION_ARGS);
333 extern Datum jsonb_hash(PG_FUNCTION_ARGS);
335 /* GIN support functions for jsonb_ops */
336 extern Datum gin_compare_jsonb(PG_FUNCTION_ARGS);
337 extern Datum gin_extract_jsonb(PG_FUNCTION_ARGS);
338 extern Datum gin_extract_jsonb_query(PG_FUNCTION_ARGS);
339 extern Datum gin_consistent_jsonb(PG_FUNCTION_ARGS);
340 extern Datum gin_triconsistent_jsonb(PG_FUNCTION_ARGS);
342 /* GIN support functions for jsonb_path_ops */
343 extern Datum gin_extract_jsonb_path(PG_FUNCTION_ARGS);
344 extern Datum gin_extract_jsonb_query_path(PG_FUNCTION_ARGS);
345 extern Datum gin_consistent_jsonb_path(PG_FUNCTION_ARGS);
346 extern Datum gin_triconsistent_jsonb_path(PG_FUNCTION_ARGS);
348 /* Support functions */
349 extern int compareJsonbContainers(JsonbContainer *a, JsonbContainer *b);
350 extern JsonbValue *findJsonbValueFromContainer(JsonbContainer *sheader,
353 extern JsonbValue *getIthJsonbValueFromContainer(JsonbContainer *sheader,
355 extern JsonbValue *pushJsonbValue(JsonbParseState **pstate,
356 JsonbIteratorToken seq, JsonbValue *scalarVal);
357 extern JsonbIterator *JsonbIteratorInit(JsonbContainer *container);
358 extern JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val,
360 extern Jsonb *JsonbValueToJsonb(JsonbValue *val);
361 extern bool JsonbDeepContains(JsonbIterator **val,
362 JsonbIterator **mContained);
363 extern void JsonbHashScalarValue(const JsonbValue *scalarVal, uint32 *hash);
365 /* jsonb.c support function */
366 extern char *JsonbToCString(StringInfo out, JsonbContainer *in,
369 #endif /* __JSONB_H__ */