Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * jsonb_gin.c
4 : : * GIN support functions for jsonb
5 : : *
6 : : * Copyright (c) 2014-2025, PostgreSQL Global Development Group
7 : : *
8 : : * We provide two opclasses for jsonb indexing: jsonb_ops and jsonb_path_ops.
9 : : * For their description see json.sgml and comments in jsonb.h.
10 : : *
11 : : * The operators support, among the others, "jsonb @? jsonpath" and
12 : : * "jsonb @@ jsonpath". Expressions containing these operators are easily
13 : : * expressed through each other.
14 : : *
15 : : * jb @? 'path' <=> jb @@ 'EXISTS(path)'
16 : : * jb @@ 'expr' <=> jb @? '$ ? (expr)'
17 : : *
18 : : * Thus, we're going to consider only @@ operator, while regarding @? operator
19 : : * the same is true for jb @@ 'EXISTS(path)'.
20 : : *
21 : : * Result of jsonpath query extraction is a tree, which leaf nodes are index
22 : : * entries and non-leaf nodes are AND/OR logical expressions. Basically we
23 : : * extract following statements out of jsonpath:
24 : : *
25 : : * 1) "accessors_chain = const",
26 : : * 2) "EXISTS(accessors_chain)".
27 : : *
28 : : * Accessors chain may consist of .key, [*] and [index] accessors. jsonb_ops
29 : : * additionally supports .* and .**.
30 : : *
31 : : * For now, both jsonb_ops and jsonb_path_ops supports only statements of
32 : : * the 1st find. jsonb_ops might also support statements of the 2nd kind,
33 : : * but given we have no statistics keys extracted from accessors chain
34 : : * are likely non-selective. Therefore, we choose to not confuse optimizer
35 : : * and skip statements of the 2nd kind altogether. In future versions that
36 : : * might be changed.
37 : : *
38 : : * In jsonb_ops statement of the 1st kind is split into expression of AND'ed
39 : : * keys and const. Sometimes const might be interpreted as both value or key
40 : : * in jsonb_ops. Then statement of 1st kind is decomposed into the expression
41 : : * below.
42 : : *
43 : : * key1 AND key2 AND ... AND keyN AND (const_as_value OR const_as_key)
44 : : *
45 : : * jsonb_path_ops transforms each statement of the 1st kind into single hash
46 : : * entry below.
47 : : *
48 : : * HASH(key1, key2, ... , keyN, const)
49 : : *
50 : : * Despite statements of the 2nd kind are not supported by both jsonb_ops and
51 : : * jsonb_path_ops, EXISTS(path) expressions might be still supported,
52 : : * when statements of 1st kind could be extracted out of their filters.
53 : : *
54 : : * IDENTIFICATION
55 : : * src/backend/utils/adt/jsonb_gin.c
56 : : *
57 : : *-------------------------------------------------------------------------
58 : : */
59 : :
60 : : #include "postgres.h"
61 : :
62 : : #include "access/gin.h"
63 : : #include "access/stratnum.h"
64 : : #include "catalog/pg_collation.h"
65 : : #include "catalog/pg_type.h"
66 : : #include "common/hashfn.h"
67 : : #include "miscadmin.h"
68 : : #include "utils/fmgrprotos.h"
69 : : #include "utils/jsonb.h"
70 : : #include "utils/jsonpath.h"
71 : : #include "utils/varlena.h"
72 : :
73 : : typedef struct PathHashStack
74 : : {
75 : : uint32 hash;
76 : : struct PathHashStack *parent;
77 : : } PathHashStack;
78 : :
79 : : /* Buffer for GIN entries */
80 : : typedef struct GinEntries
81 : : {
82 : : Datum *buf;
83 : : int count;
84 : : int allocated;
85 : : } GinEntries;
86 : :
87 : : typedef enum JsonPathGinNodeType
88 : : {
89 : : JSP_GIN_OR,
90 : : JSP_GIN_AND,
91 : : JSP_GIN_ENTRY,
92 : : } JsonPathGinNodeType;
93 : :
94 : : typedef struct JsonPathGinNode JsonPathGinNode;
95 : :
96 : : /* Node in jsonpath expression tree */
97 : : struct JsonPathGinNode
98 : : {
99 : : JsonPathGinNodeType type;
100 : : union
101 : : {
102 : : int nargs; /* valid for OR and AND nodes */
103 : : int entryIndex; /* index in GinEntries array, valid for ENTRY
104 : : * nodes after entries output */
105 : : Datum entryDatum; /* path hash or key name/scalar, valid for
106 : : * ENTRY nodes before entries output */
107 : : } val;
108 : : JsonPathGinNode *args[FLEXIBLE_ARRAY_MEMBER]; /* valid for OR and AND
109 : : * nodes */
110 : : };
111 : :
112 : : /*
113 : : * jsonb_ops entry extracted from jsonpath item. Corresponding path item
114 : : * may be: '.key', '.*', '.**', '[index]' or '[*]'.
115 : : * Entry type is stored in 'type' field.
116 : : */
117 : : typedef struct JsonPathGinPathItem
118 : : {
119 : : struct JsonPathGinPathItem *parent;
120 : : Datum keyName; /* key name (for '.key' path item) or NULL */
121 : : JsonPathItemType type; /* type of jsonpath item */
122 : : } JsonPathGinPathItem;
123 : :
124 : : /* GIN representation of the extracted json path */
125 : : typedef union JsonPathGinPath
126 : : {
127 : : JsonPathGinPathItem *items; /* list of path items (jsonb_ops) */
128 : : uint32 hash; /* hash of the path (jsonb_path_ops) */
129 : : } JsonPathGinPath;
130 : :
131 : : typedef struct JsonPathGinContext JsonPathGinContext;
132 : :
133 : : /* Callback, which stores information about path item into JsonPathGinPath */
134 : : typedef bool (*JsonPathGinAddPathItemFunc) (JsonPathGinPath *path,
135 : : JsonPathItem *jsp);
136 : :
137 : : /*
138 : : * Callback, which extracts set of nodes from statement of 1st kind
139 : : * (scalar != NULL) or statement of 2nd kind (scalar == NULL).
140 : : */
141 : : typedef List *(*JsonPathGinExtractNodesFunc) (JsonPathGinContext *cxt,
142 : : JsonPathGinPath path,
143 : : JsonbValue *scalar,
144 : : List *nodes);
145 : :
146 : : /* Context for jsonpath entries extraction */
147 : : struct JsonPathGinContext
148 : : {
149 : : JsonPathGinAddPathItemFunc add_path_item;
150 : : JsonPathGinExtractNodesFunc extract_nodes;
151 : : bool lax;
152 : : };
153 : :
154 : : static Datum make_text_key(char flag, const char *str, int len);
155 : : static Datum make_scalar_key(const JsonbValue *scalarVal, bool is_key);
156 : :
157 : : static JsonPathGinNode *extract_jsp_bool_expr(JsonPathGinContext *cxt,
158 : : JsonPathGinPath path, JsonPathItem *jsp, bool not);
159 : :
160 : :
161 : : /* Initialize GinEntries struct */
162 : : static void
2452 akorotkov@postgresql 163 :CBC 12672 : init_gin_entries(GinEntries *entries, int preallocated)
164 : : {
165 : 12672 : entries->allocated = preallocated;
7 michael@paquier.xyz 166 [ + - ]:GNC 12672 : entries->buf = preallocated ? palloc_array(Datum, preallocated) : NULL;
2452 akorotkov@postgresql 167 :CBC 12672 : entries->count = 0;
168 : 12672 : }
169 : :
170 : : /* Add new entry to GinEntries */
171 : : static int
172 : 86387 : add_gin_entry(GinEntries *entries, Datum entry)
173 : : {
174 : 86387 : int id = entries->count;
175 : :
176 [ + + ]: 86387 : if (entries->count >= entries->allocated)
177 : : {
178 [ + + ]: 9843 : if (entries->allocated)
179 : : {
180 : 9594 : entries->allocated *= 2;
7 michael@paquier.xyz 181 :GNC 9594 : entries->buf = repalloc_array(entries->buf,
182 : : Datum,
183 : : entries->allocated);
184 : : }
185 : : else
186 : : {
2452 akorotkov@postgresql 187 :CBC 249 : entries->allocated = 8;
7 michael@paquier.xyz 188 :GNC 249 : entries->buf = palloc_array(Datum, entries->allocated);
189 : : }
190 : : }
191 : :
2452 akorotkov@postgresql 192 :CBC 86387 : entries->buf[entries->count++] = entry;
193 : :
194 : 86387 : return id;
195 : : }
196 : :
197 : : /*
198 : : *
199 : : * jsonb_ops GIN opclass support functions
200 : : *
201 : : */
202 : :
203 : : Datum
4287 andrew@dunslane.net 204 : 572854 : gin_compare_jsonb(PG_FUNCTION_ARGS)
205 : : {
206 : 572854 : text *arg1 = PG_GETARG_TEXT_PP(0);
207 : 572854 : text *arg2 = PG_GETARG_TEXT_PP(1);
208 : : int32 result;
209 : : char *a1p,
210 : : *a2p;
211 : : int len1,
212 : : len2;
213 : :
214 [ + + ]: 572854 : a1p = VARDATA_ANY(arg1);
215 [ + + ]: 572854 : a2p = VARDATA_ANY(arg2);
216 : :
217 [ - + - - : 572854 : len1 = VARSIZE_ANY_EXHDR(arg1);
- - - - +
+ ]
218 [ - + - - : 572854 : len2 = VARSIZE_ANY_EXHDR(arg2);
- - - - +
+ ]
219 : :
220 : : /* Compare text as bttextcmp does, but always using C collation */
221 : 572854 : result = varstr_cmp(a1p, len1, a2p, len2, C_COLLATION_OID);
222 : :
223 [ - + ]: 572854 : PG_FREE_IF_COPY(arg1, 0);
224 [ - + ]: 572854 : PG_FREE_IF_COPY(arg2, 1);
225 : :
226 : 572854 : PG_RETURN_INT32(result);
227 : : }
228 : :
229 : : Datum
230 : 10281 : gin_extract_jsonb(PG_FUNCTION_ARGS)
231 : : {
3012 tgl@sss.pgh.pa.us 232 : 10281 : Jsonb *jb = (Jsonb *) PG_GETARG_JSONB_P(0);
4287 andrew@dunslane.net 233 : 10281 : int32 *nentries = (int32 *) PG_GETARG_POINTER(1);
2452 akorotkov@postgresql 234 : 10281 : int total = JB_ROOT_COUNT(jb);
235 : : JsonbIterator *it;
236 : : JsonbValue v;
237 : : JsonbIteratorToken r;
238 : : GinEntries entries;
239 : :
240 : : /* If the root level is empty, we certainly have no keys */
4287 andrew@dunslane.net 241 [ + + ]: 10281 : if (total == 0)
242 : : {
243 : 360 : *nentries = 0;
244 : 360 : PG_RETURN_POINTER(NULL);
245 : : }
246 : :
247 : : /* Otherwise, use 2 * root count as initial estimate of result size */
2452 akorotkov@postgresql 248 : 9921 : init_gin_entries(&entries, 2 * total);
249 : :
4242 heikki.linnakangas@i 250 : 9921 : it = JsonbIteratorInit(&jb->root);
251 : :
4287 andrew@dunslane.net 252 [ + + ]: 140165 : while ((r = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
253 : : {
254 [ + + + + ]: 130244 : switch (r)
255 : : {
256 : 28890 : case WJB_KEY:
2452 akorotkov@postgresql 257 : 28890 : add_gin_entry(&entries, make_scalar_key(&v, true));
4287 andrew@dunslane.net 258 : 28890 : break;
259 : 17009 : case WJB_ELEM:
260 : : /* Pretend string array elements are keys, see jsonb.h */
2452 akorotkov@postgresql 261 : 17009 : add_gin_entry(&entries, make_scalar_key(&v, v.type == jbvString));
4287 andrew@dunslane.net 262 : 17009 : break;
263 : 25503 : case WJB_VALUE:
2452 akorotkov@postgresql 264 : 25503 : add_gin_entry(&entries, make_scalar_key(&v, false));
4287 andrew@dunslane.net 265 : 25503 : break;
266 : 58842 : default:
267 : : /* we can ignore structural items */
4240 tgl@sss.pgh.pa.us 268 : 58842 : break;
269 : : }
270 : : }
271 : :
2452 akorotkov@postgresql 272 : 9921 : *nentries = entries.count;
273 : :
274 : 9921 : PG_RETURN_POINTER(entries.buf);
275 : : }
276 : :
277 : : /* Append JsonPathGinPathItem to JsonPathGinPath (jsonb_ops) */
278 : : static bool
279 : 426 : jsonb_ops__add_path_item(JsonPathGinPath *path, JsonPathItem *jsp)
280 : : {
281 : : JsonPathGinPathItem *pentry;
282 : : Datum keyName;
283 : :
284 [ + + + - ]: 426 : switch (jsp->type)
285 : : {
286 : 192 : case jpiRoot:
287 : 192 : path->items = NULL; /* reset path */
288 : 192 : return true;
289 : :
290 : 186 : case jpiKey:
291 : : {
292 : : int len;
293 : 186 : char *key = jspGetString(jsp, &len);
294 : :
295 : 186 : keyName = make_text_key(JGINFLAG_KEY, key, len);
296 : 186 : break;
297 : : }
298 : :
299 : 48 : case jpiAny:
300 : : case jpiAnyKey:
301 : : case jpiAnyArray:
302 : : case jpiIndexArray:
303 : 48 : keyName = PointerGetDatum(NULL);
304 : 48 : break;
305 : :
2452 akorotkov@postgresql 306 :UBC 0 : default:
307 : : /* other path items like item methods are not supported */
308 : 0 : return false;
309 : : }
310 : :
7 michael@paquier.xyz 311 :GNC 234 : pentry = palloc_object(JsonPathGinPathItem);
312 : :
2452 akorotkov@postgresql 313 :CBC 234 : pentry->type = jsp->type;
314 : 234 : pentry->keyName = keyName;
315 : 234 : pentry->parent = path->items;
316 : :
317 : 234 : path->items = pentry;
318 : :
319 : 234 : return true;
320 : : }
321 : :
322 : : /* Combine existing path hash with next key hash (jsonb_path_ops) */
323 : : static bool
324 : 348 : jsonb_path_ops__add_path_item(JsonPathGinPath *path, JsonPathItem *jsp)
325 : : {
326 [ + + + - ]: 348 : switch (jsp->type)
327 : : {
328 : 153 : case jpiRoot:
329 : 153 : path->hash = 0; /* reset path hash */
330 : 153 : return true;
331 : :
332 : 147 : case jpiKey:
333 : : {
334 : : JsonbValue jbv;
335 : :
336 : 147 : jbv.type = jbvString;
337 : 147 : jbv.val.string.val = jspGetString(jsp, &jbv.val.string.len);
338 : :
339 : 147 : JsonbHashScalarValue(&jbv, &path->hash);
340 : 147 : return true;
341 : : }
342 : :
343 : 48 : case jpiIndexArray:
344 : : case jpiAnyArray:
345 : 48 : return true; /* path hash is unchanged */
346 : :
2452 akorotkov@postgresql 347 :UBC 0 : default:
348 : : /* other items (wildcard paths, item methods) are not supported */
349 : 0 : return false;
350 : : }
351 : : }
352 : :
353 : : static JsonPathGinNode *
2452 akorotkov@postgresql 354 :CBC 483 : make_jsp_entry_node(Datum entry)
355 : : {
356 : 483 : JsonPathGinNode *node = palloc(offsetof(JsonPathGinNode, args));
357 : :
358 : 483 : node->type = JSP_GIN_ENTRY;
359 : 483 : node->val.entryDatum = entry;
360 : :
361 : 483 : return node;
362 : : }
363 : :
364 : : static JsonPathGinNode *
365 : 210 : make_jsp_entry_node_scalar(JsonbValue *scalar, bool iskey)
366 : : {
367 : 210 : return make_jsp_entry_node(make_scalar_key(scalar, iskey));
368 : : }
369 : :
370 : : static JsonPathGinNode *
371 : 234 : make_jsp_expr_node(JsonPathGinNodeType type, int nargs)
372 : : {
373 : 234 : JsonPathGinNode *node = palloc(offsetof(JsonPathGinNode, args) +
374 : : sizeof(node->args[0]) * nargs);
375 : :
376 : 234 : node->type = type;
377 : 234 : node->val.nargs = nargs;
378 : :
379 : 234 : return node;
380 : : }
381 : :
382 : : static JsonPathGinNode *
383 : 138 : make_jsp_expr_node_args(JsonPathGinNodeType type, List *args)
384 : : {
385 : 138 : JsonPathGinNode *node = make_jsp_expr_node(type, list_length(args));
386 : : ListCell *lc;
387 : 138 : int i = 0;
388 : :
389 [ + - + + : 414 : foreach(lc, args)
+ + ]
390 : 276 : node->args[i++] = lfirst(lc);
391 : :
392 : 138 : return node;
393 : : }
394 : :
395 : : static JsonPathGinNode *
396 : 96 : make_jsp_expr_node_binary(JsonPathGinNodeType type,
397 : : JsonPathGinNode *arg1, JsonPathGinNode *arg2)
398 : : {
399 : 96 : JsonPathGinNode *node = make_jsp_expr_node(type, 2);
400 : :
401 : 96 : node->args[0] = arg1;
402 : 96 : node->args[1] = arg2;
403 : :
404 : 96 : return node;
405 : : }
406 : :
407 : : /* Append a list of nodes from the jsonpath (jsonb_ops). */
408 : : static List *
409 : 279 : jsonb_ops__extract_nodes(JsonPathGinContext *cxt, JsonPathGinPath path,
410 : : JsonbValue *scalar, List *nodes)
411 : : {
412 : : JsonPathGinPathItem *pentry;
413 : :
414 [ + + ]: 279 : if (scalar)
415 : : {
416 : : JsonPathGinNode *node;
417 : :
418 : : /*
419 : : * Append path entry nodes only if scalar is provided. See header
420 : : * comment for details.
421 : : */
422 [ + + ]: 324 : for (pentry = path.items; pentry; pentry = pentry->parent)
423 : : {
424 [ + + ]: 186 : if (pentry->type == jpiKey) /* only keys are indexed */
425 : 138 : nodes = lappend(nodes, make_jsp_entry_node(pentry->keyName));
426 : : }
427 : :
428 : : /* Append scalar node for equality queries. */
429 [ + + ]: 138 : if (scalar->type == jbvString)
430 : : {
431 : 72 : JsonPathGinPathItem *last = path.items;
432 : : GinTernaryValue key_entry;
433 : :
434 : : /*
435 : : * Assuming that jsonb_ops interprets string array elements as
436 : : * keys, we may extract key or non-key entry or even both. In the
437 : : * latter case we create OR-node. It is possible in lax mode
438 : : * where arrays are automatically unwrapped, or in strict mode for
439 : : * jpiAny items.
440 : : */
441 : :
442 [ + - ]: 72 : if (cxt->lax)
443 : 72 : key_entry = GIN_MAYBE;
2452 akorotkov@postgresql 444 [ # # ]:UBC 0 : else if (!last) /* root ($) */
445 : 0 : key_entry = GIN_FALSE;
446 [ # # # # ]: 0 : else if (last->type == jpiAnyArray || last->type == jpiIndexArray)
447 : 0 : key_entry = GIN_TRUE;
448 [ # # ]: 0 : else if (last->type == jpiAny)
449 : 0 : key_entry = GIN_MAYBE;
450 : : else
451 : 0 : key_entry = GIN_FALSE;
452 : :
2452 akorotkov@postgresql 453 [ + - ]:CBC 72 : if (key_entry == GIN_MAYBE)
454 : : {
455 : 72 : JsonPathGinNode *n1 = make_jsp_entry_node_scalar(scalar, true);
456 : 72 : JsonPathGinNode *n2 = make_jsp_entry_node_scalar(scalar, false);
457 : :
458 : 72 : node = make_jsp_expr_node_binary(JSP_GIN_OR, n1, n2);
459 : : }
460 : : else
461 : : {
2452 akorotkov@postgresql 462 :UBC 0 : node = make_jsp_entry_node_scalar(scalar,
463 : : key_entry == GIN_TRUE);
464 : : }
465 : : }
466 : : else
467 : : {
2452 akorotkov@postgresql 468 :CBC 66 : node = make_jsp_entry_node_scalar(scalar, false);
469 : : }
470 : :
471 : 138 : nodes = lappend(nodes, node);
472 : : }
473 : :
474 : 279 : return nodes;
475 : : }
476 : :
477 : : /* Append a list of nodes from the jsonpath (jsonb_path_ops). */
478 : : static List *
479 : 240 : jsonb_path_ops__extract_nodes(JsonPathGinContext *cxt, JsonPathGinPath path,
480 : : JsonbValue *scalar, List *nodes)
481 : : {
482 [ + + ]: 240 : if (scalar)
483 : : {
484 : : /* append path hash node for equality queries */
485 : 135 : uint32 hash = path.hash;
486 : :
487 : 135 : JsonbHashScalarValue(scalar, &hash);
488 : :
489 : 135 : return lappend(nodes,
490 : 135 : make_jsp_entry_node(UInt32GetDatum(hash)));
491 : : }
492 : : else
493 : : {
494 : : /* jsonb_path_ops doesn't support EXISTS queries => nothing to append */
495 : 105 : return nodes;
496 : : }
497 : : }
498 : :
499 : : /*
500 : : * Extract a list of expression nodes that need to be AND-ed by the caller.
501 : : * Extracted expression is 'path == scalar' if 'scalar' is non-NULL, and
502 : : * 'EXISTS(path)' otherwise.
503 : : */
504 : : static List *
505 : 519 : extract_jsp_path_expr_nodes(JsonPathGinContext *cxt, JsonPathGinPath path,
506 : : JsonPathItem *jsp, JsonbValue *scalar)
507 : : {
508 : : JsonPathItem next;
509 : 519 : List *nodes = NIL;
510 : :
511 : : for (;;)
512 : : {
513 [ + + + ]: 1110 : switch (jsp->type)
514 : : {
515 : 174 : case jpiCurrent:
516 : 174 : break;
517 : :
518 : 162 : case jpiFilter:
519 : : {
520 : : JsonPathItem arg;
521 : : JsonPathGinNode *filter;
522 : :
523 : 162 : jspGetArg(jsp, &arg);
524 : :
525 : 162 : filter = extract_jsp_bool_expr(cxt, path, &arg, false);
526 : :
527 [ + - ]: 162 : if (filter)
528 : 162 : nodes = lappend(nodes, filter);
529 : :
530 : 162 : break;
531 : : }
532 : :
533 : 774 : default:
534 [ - + ]: 774 : if (!cxt->add_path_item(&path, jsp))
535 : :
536 : : /*
537 : : * Path is not supported by the index opclass, return only
538 : : * the extracted filter nodes.
539 : : */
2452 akorotkov@postgresql 540 :UBC 0 : return nodes;
2452 akorotkov@postgresql 541 :CBC 774 : break;
542 : : }
543 : :
544 [ + + ]: 1110 : if (!jspGetNext(jsp, &next))
545 : 519 : break;
546 : :
547 : 591 : jsp = &next;
548 : : }
549 : :
550 : : /*
551 : : * Append nodes from the path expression itself to the already extracted
552 : : * list of filter nodes.
553 : : */
554 : 519 : return cxt->extract_nodes(cxt, path, scalar, nodes);
555 : : }
556 : :
557 : : /*
558 : : * Extract an expression node from one of following jsonpath path expressions:
559 : : * EXISTS(jsp) (when 'scalar' is NULL)
560 : : * jsp == scalar (when 'scalar' is not NULL).
561 : : *
562 : : * The current path (@) is passed in 'path'.
563 : : */
564 : : static JsonPathGinNode *
565 : 519 : extract_jsp_path_expr(JsonPathGinContext *cxt, JsonPathGinPath path,
566 : : JsonPathItem *jsp, JsonbValue *scalar)
567 : : {
568 : : /* extract a list of nodes to be AND-ed */
569 : 519 : List *nodes = extract_jsp_path_expr_nodes(cxt, path, jsp, scalar);
570 : :
1218 tgl@sss.pgh.pa.us 571 [ + + ]: 519 : if (nodes == NIL)
572 : : /* no nodes were extracted => full scan is needed for this path */
2452 akorotkov@postgresql 573 : 84 : return NULL;
574 : :
575 [ + + ]: 435 : if (list_length(nodes) == 1)
576 : 297 : return linitial(nodes); /* avoid extra AND-node */
577 : :
578 : : /* construct AND-node for path with filters */
579 : 138 : return make_jsp_expr_node_args(JSP_GIN_AND, nodes);
580 : : }
581 : :
582 : : /* Recursively extract nodes from the boolean jsonpath expression. */
583 : : static JsonPathGinNode *
584 : 417 : extract_jsp_bool_expr(JsonPathGinContext *cxt, JsonPathGinPath path,
585 : : JsonPathItem *jsp, bool not)
586 : : {
587 : 417 : check_stack_depth();
588 : :
589 [ + - + - : 417 : switch (jsp->type)
+ - ]
590 : : {
591 : 36 : case jpiAnd: /* expr && expr */
592 : : case jpiOr: /* expr || expr */
593 : : {
594 : : JsonPathItem arg;
595 : : JsonPathGinNode *larg;
596 : : JsonPathGinNode *rarg;
597 : : JsonPathGinNodeType type;
598 : :
599 : 36 : jspGetLeftArg(jsp, &arg);
600 : 36 : larg = extract_jsp_bool_expr(cxt, path, &arg, not);
601 : :
602 : 36 : jspGetRightArg(jsp, &arg);
603 : 36 : rarg = extract_jsp_bool_expr(cxt, path, &arg, not);
604 : :
605 [ + + - + ]: 36 : if (!larg || !rarg)
606 : : {
607 [ + + ]: 12 : if (jsp->type == jpiOr)
608 : 6 : return NULL;
609 : :
610 [ - + ]: 6 : return larg ? larg : rarg;
611 : : }
612 : :
613 : 24 : type = not ^ (jsp->type == jpiAnd) ? JSP_GIN_AND : JSP_GIN_OR;
614 : :
615 : 24 : return make_jsp_expr_node_binary(type, larg, rarg);
616 : : }
617 : :
2452 akorotkov@postgresql 618 :UBC 0 : case jpiNot: /* !expr */
619 : : {
620 : : JsonPathItem arg;
621 : :
622 : 0 : jspGetArg(jsp, &arg);
623 : :
624 : : /* extract child expression inverting 'not' flag */
625 : 0 : return extract_jsp_bool_expr(cxt, path, &arg, !not);
626 : : }
627 : :
2452 akorotkov@postgresql 628 :CBC 108 : case jpiExists: /* EXISTS(path) */
629 : : {
630 : : JsonPathItem arg;
631 : :
632 [ - + ]: 108 : if (not)
2452 akorotkov@postgresql 633 :UBC 0 : return NULL; /* NOT EXISTS is not supported */
634 : :
2452 akorotkov@postgresql 635 :CBC 108 : jspGetArg(jsp, &arg);
636 : :
637 : 108 : return extract_jsp_path_expr(cxt, path, &arg, NULL);
638 : : }
639 : :
2452 akorotkov@postgresql 640 :UBC 0 : case jpiNotEqual:
641 : :
642 : : /*
643 : : * 'not' == true case is not supported here because '!(path !=
644 : : * scalar)' is not equivalent to 'path == scalar' in the general
645 : : * case because of sequence comparison semantics: 'path == scalar'
646 : : * === 'EXISTS (path, @ == scalar)', '!(path != scalar)' ===
647 : : * 'FOR_ALL(path, @ == scalar)'. So, we should translate '!(path
648 : : * != scalar)' into GIN query 'path == scalar || EMPTY(path)', but
649 : : * 'EMPTY(path)' queries are not supported by the both jsonb
650 : : * opclasses. However in strict mode we could omit 'EMPTY(path)'
651 : : * part if the path can return exactly one item (it does not
652 : : * contain wildcard accessors or item methods like .keyvalue()
653 : : * etc.).
654 : : */
655 : 0 : return NULL;
656 : :
2452 akorotkov@postgresql 657 :CBC 273 : case jpiEqual: /* path == scalar */
658 : : {
659 : : JsonPathItem left_item;
660 : : JsonPathItem right_item;
661 : : JsonPathItem *path_item;
662 : : JsonPathItem *scalar_item;
663 : : JsonbValue scalar;
664 : :
665 [ - + ]: 273 : if (not)
2452 akorotkov@postgresql 666 :UBC 0 : return NULL;
667 : :
2452 akorotkov@postgresql 668 :CBC 273 : jspGetLeftArg(jsp, &left_item);
669 : 273 : jspGetRightArg(jsp, &right_item);
670 : :
671 [ + + ]: 273 : if (jspIsScalar(left_item.type))
672 : : {
673 : 48 : scalar_item = &left_item;
674 : 48 : path_item = &right_item;
675 : : }
676 [ + - ]: 225 : else if (jspIsScalar(right_item.type))
677 : : {
678 : 225 : scalar_item = &right_item;
679 : 225 : path_item = &left_item;
680 : : }
681 : : else
2452 akorotkov@postgresql 682 :UBC 0 : return NULL; /* at least one operand should be a scalar */
683 : :
2452 akorotkov@postgresql 684 [ + + + + :CBC 273 : switch (scalar_item->type)
- ]
685 : : {
686 : 57 : case jpiNull:
687 : 57 : scalar.type = jbvNull;
688 : 57 : break;
689 : 24 : case jpiBool:
690 : 24 : scalar.type = jbvBool;
691 : 24 : scalar.val.boolean = !!*scalar_item->content.value.data;
692 : 24 : break;
693 : 48 : case jpiNumeric:
694 : 48 : scalar.type = jbvNumeric;
695 : 48 : scalar.val.numeric =
696 : 48 : (Numeric) scalar_item->content.value.data;
697 : 48 : break;
698 : 144 : case jpiString:
699 : 144 : scalar.type = jbvString;
700 : 144 : scalar.val.string.val = scalar_item->content.value.data;
701 : 144 : scalar.val.string.len =
702 : 144 : scalar_item->content.value.datalen;
703 : 144 : break;
2452 akorotkov@postgresql 704 :UBC 0 : default:
705 [ # # ]: 0 : elog(ERROR, "invalid scalar jsonpath item type: %d",
706 : : scalar_item->type);
707 : : return NULL;
708 : : }
709 : :
2452 akorotkov@postgresql 710 :CBC 273 : return extract_jsp_path_expr(cxt, path, path_item, &scalar);
711 : : }
712 : :
2452 akorotkov@postgresql 713 :UBC 0 : default:
714 : 0 : return NULL; /* not a boolean expression */
715 : : }
716 : : }
717 : :
718 : : /* Recursively emit all GIN entries found in the node tree */
719 : : static void
2452 akorotkov@postgresql 720 :CBC 717 : emit_jsp_gin_entries(JsonPathGinNode *node, GinEntries *entries)
721 : : {
722 : 717 : check_stack_depth();
723 : :
724 [ + + - ]: 717 : switch (node->type)
725 : : {
726 : 483 : case JSP_GIN_ENTRY:
727 : : /* replace datum with its index in the array */
728 : 483 : node->val.entryIndex = add_gin_entry(entries, node->val.entryDatum);
729 : 483 : break;
730 : :
731 : 234 : case JSP_GIN_OR:
732 : : case JSP_GIN_AND:
733 : : {
734 : : int i;
735 : :
736 [ + + ]: 702 : for (i = 0; i < node->val.nargs; i++)
737 : 468 : emit_jsp_gin_entries(node->args[i], entries);
738 : :
739 : 234 : break;
740 : : }
741 : : }
742 : 717 : }
743 : :
744 : : /*
745 : : * Recursively extract GIN entries from jsonpath query.
746 : : * Root expression node is put into (*extra_data)[0].
747 : : */
748 : : static Datum *
749 : 321 : extract_jsp_query(JsonPath *jp, StrategyNumber strat, bool pathOps,
750 : : int32 *nentries, Pointer **extra_data)
751 : : {
752 : : JsonPathGinContext cxt;
753 : : JsonPathItem root;
754 : : JsonPathGinNode *node;
755 : 321 : JsonPathGinPath path = {0};
756 : 321 : GinEntries entries = {0};
757 : :
758 : 321 : cxt.lax = (jp->header & JSONPATH_LAX) != 0;
759 : :
760 [ + + ]: 321 : if (pathOps)
761 : : {
762 : 147 : cxt.add_path_item = jsonb_path_ops__add_path_item;
763 : 147 : cxt.extract_nodes = jsonb_path_ops__extract_nodes;
764 : : }
765 : : else
766 : : {
767 : 174 : cxt.add_path_item = jsonb_ops__add_path_item;
768 : 174 : cxt.extract_nodes = jsonb_ops__extract_nodes;
769 : : }
770 : :
771 : 321 : jspInit(&root, jp);
772 : :
773 : 321 : node = strat == JsonbJsonpathExistsStrategyNumber
774 : 138 : ? extract_jsp_path_expr(&cxt, path, &root, NULL)
775 [ + + ]: 321 : : extract_jsp_bool_expr(&cxt, path, &root, false);
776 : :
777 [ + + ]: 321 : if (!node)
778 : : {
779 : 72 : *nentries = 0;
780 : 72 : return NULL;
781 : : }
782 : :
783 : 249 : emit_jsp_gin_entries(node, &entries);
784 : :
785 : 249 : *nentries = entries.count;
786 [ - + ]: 249 : if (!*nentries)
2452 akorotkov@postgresql 787 :UBC 0 : return NULL;
788 : :
7 michael@paquier.xyz 789 :GNC 249 : *extra_data = palloc0_array(Pointer, entries.count);
2452 akorotkov@postgresql 790 :CBC 249 : **extra_data = (Pointer) node;
791 : :
792 : 249 : return entries.buf;
793 : : }
794 : :
795 : : /*
796 : : * Recursively execute jsonpath expression.
797 : : * 'check' is a bool[] or a GinTernaryValue[] depending on 'ternary' flag.
798 : : */
799 : : static GinTernaryValue
800 : 6306 : execute_jsp_gin_node(JsonPathGinNode *node, void *check, bool ternary)
801 : : {
802 : : GinTernaryValue res;
803 : : GinTernaryValue v;
804 : : int i;
805 : :
806 [ + + + - ]: 6306 : switch (node->type)
807 : : {
808 : 2544 : case JSP_GIN_AND:
809 : 2544 : res = GIN_TRUE;
810 [ + + ]: 4032 : for (i = 0; i < node->val.nargs; i++)
811 : : {
812 : 3444 : v = execute_jsp_gin_node(node->args[i], check, ternary);
813 [ + + ]: 3444 : if (v == GIN_FALSE)
814 : 1956 : return GIN_FALSE;
815 [ + + ]: 1488 : else if (v == GIN_MAYBE)
816 : 120 : res = GIN_MAYBE;
817 : : }
818 : 588 : return res;
819 : :
820 : 528 : case JSP_GIN_OR:
821 : 528 : res = GIN_FALSE;
822 [ + + ]: 1080 : for (i = 0; i < node->val.nargs; i++)
823 : : {
824 : 984 : v = execute_jsp_gin_node(node->args[i], check, ternary);
825 [ + + ]: 984 : if (v == GIN_TRUE)
826 : 432 : return GIN_TRUE;
827 [ + + ]: 552 : else if (v == GIN_MAYBE)
828 : 36 : res = GIN_MAYBE;
829 : : }
830 : 96 : return res;
831 : :
832 : 3234 : case JSP_GIN_ENTRY:
833 : : {
834 : 3234 : int index = node->val.entryIndex;
835 : :
836 [ + - ]: 3234 : if (ternary)
837 : 3234 : return ((GinTernaryValue *) check)[index];
838 : : else
2452 akorotkov@postgresql 839 :UBC 0 : return ((bool *) check)[index] ? GIN_TRUE : GIN_FALSE;
840 : : }
841 : :
842 : 0 : default:
843 [ # # ]: 0 : elog(ERROR, "invalid jsonpath gin node type: %d", node->type);
844 : : return GIN_FALSE; /* keep compiler quiet */
845 : : }
846 : : }
847 : :
848 : : Datum
4287 andrew@dunslane.net 849 :CBC 264 : gin_extract_jsonb_query(PG_FUNCTION_ARGS)
850 : : {
851 : 264 : int32 *nentries = (int32 *) PG_GETARG_POINTER(1);
852 : 264 : StrategyNumber strategy = PG_GETARG_UINT16(2);
853 : 264 : int32 *searchMode = (int32 *) PG_GETARG_POINTER(6);
854 : : Datum *entries;
855 : :
856 [ + + ]: 264 : if (strategy == JsonbContainsStrategyNumber)
857 : : {
858 : : /* Query is a jsonb, so just apply gin_extract_jsonb... */
859 : : entries = (Datum *)
860 : 54 : DatumGetPointer(DirectFunctionCall2(gin_extract_jsonb,
861 : : PG_GETARG_DATUM(0),
862 : : PointerGetDatum(nentries)));
863 : : /* ...although "contains {}" requires a full index scan */
4240 tgl@sss.pgh.pa.us 864 [ + + ]: 54 : if (*nentries == 0)
4287 andrew@dunslane.net 865 : 6 : *searchMode = GIN_SEARCH_MODE_ALL;
866 : : }
867 [ + + ]: 210 : else if (strategy == JsonbExistsStrategyNumber)
868 : : {
869 : : /* Query is a text string, which we treat as a key */
870 : 24 : text *query = PG_GETARG_TEXT_PP(0);
871 : :
872 : 24 : *nentries = 1;
7 michael@paquier.xyz 873 :GNC 24 : entries = palloc_object(Datum);
4240 tgl@sss.pgh.pa.us 874 :CBC 24 : entries[0] = make_text_key(JGINFLAG_KEY,
875 [ - + ]: 24 : VARDATA_ANY(query),
876 [ - + - - : 24 : VARSIZE_ANY_EXHDR(query));
- - - - -
+ ]
877 : : }
4287 andrew@dunslane.net 878 [ + + + + ]: 186 : else if (strategy == JsonbExistsAnyStrategyNumber ||
879 : : strategy == JsonbExistsAllStrategyNumber)
880 : 12 : {
881 : : /* Query is a text array; each element is treated as a key */
882 : 12 : ArrayType *query = PG_GETARG_ARRAYTYPE_P(0);
883 : : Datum *key_datums;
884 : : bool *key_nulls;
885 : : int key_count;
886 : : int i,
887 : : j;
888 : :
1265 peter@eisentraut.org 889 : 12 : deconstruct_array_builtin(query, TEXTOID, &key_datums, &key_nulls, &key_count);
890 : :
7 michael@paquier.xyz 891 :GNC 12 : entries = palloc_array(Datum, key_count);
892 : :
4240 tgl@sss.pgh.pa.us 893 [ + + ]:CBC 36 : for (i = 0, j = 0; i < key_count; i++)
894 : : {
895 : : /* Nulls in the array are ignored */
4287 andrew@dunslane.net 896 [ - + ]: 24 : if (key_nulls[i])
4287 andrew@dunslane.net 897 :UBC 0 : continue;
898 : : /* We rely on the array elements not being toasted */
4240 tgl@sss.pgh.pa.us 899 :CBC 24 : entries[j++] = make_text_key(JGINFLAG_KEY,
134 peter@eisentraut.org 900 :GNC 24 : VARDATA_ANY(DatumGetPointer(key_datums[i])),
901 : 24 : VARSIZE_ANY_EXHDR(DatumGetPointer(key_datums[i])));
902 : : }
903 : :
4287 andrew@dunslane.net 904 :CBC 12 : *nentries = j;
905 : : /* ExistsAll with no keys should match everything */
906 [ - + - - ]: 12 : if (j == 0 && strategy == JsonbExistsAllStrategyNumber)
4287 andrew@dunslane.net 907 :UBC 0 : *searchMode = GIN_SEARCH_MODE_ALL;
908 : : }
2452 akorotkov@postgresql 909 [ + + + - ]:CBC 174 : else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
910 : : strategy == JsonbJsonpathExistsStrategyNumber)
911 : 174 : {
912 : 174 : JsonPath *jp = PG_GETARG_JSONPATH_P(0);
913 : 174 : Pointer **extra_data = (Pointer **) PG_GETARG_POINTER(4);
914 : :
915 : 174 : entries = extract_jsp_query(jp, strategy, false, nentries, extra_data);
916 : :
917 [ + + ]: 174 : if (!entries)
918 : 48 : *searchMode = GIN_SEARCH_MODE_ALL;
919 : : }
920 : : else
921 : : {
4287 andrew@dunslane.net 922 [ # # ]:UBC 0 : elog(ERROR, "unrecognized strategy number: %d", strategy);
923 : : entries = NULL; /* keep compiler quiet */
924 : : }
925 : :
4287 andrew@dunslane.net 926 :CBC 264 : PG_RETURN_POINTER(entries);
927 : : }
928 : :
929 : : Datum
4287 andrew@dunslane.net 930 :UBC 0 : gin_consistent_jsonb(PG_FUNCTION_ARGS)
931 : : {
932 : 0 : bool *check = (bool *) PG_GETARG_POINTER(0);
933 : 0 : StrategyNumber strategy = PG_GETARG_UINT16(1);
934 : :
935 : : /* Jsonb *query = PG_GETARG_JSONB_P(2); */
936 : 0 : int32 nkeys = PG_GETARG_INT32(3);
937 : :
2452 akorotkov@postgresql 938 : 0 : Pointer *extra_data = (Pointer *) PG_GETARG_POINTER(4);
4287 andrew@dunslane.net 939 : 0 : bool *recheck = (bool *) PG_GETARG_POINTER(5);
940 : 0 : bool res = true;
941 : : int32 i;
942 : :
943 [ # # ]: 0 : if (strategy == JsonbContainsStrategyNumber)
944 : : {
945 : : /*
946 : : * We must always recheck, since we can't tell from the index whether
947 : : * the positions of the matched items match the structure of the query
948 : : * object. (Even if we could, we'd also have to worry about hashed
949 : : * keys and the index's failure to distinguish keys from string array
950 : : * elements.) However, the tuple certainly doesn't match unless it
951 : : * contains all the query keys.
952 : : */
953 : 0 : *recheck = true;
954 [ # # ]: 0 : for (i = 0; i < nkeys; i++)
955 : : {
956 [ # # ]: 0 : if (!check[i])
957 : : {
958 : 0 : res = false;
959 : 0 : break;
960 : : }
961 : : }
962 : : }
963 [ # # ]: 0 : else if (strategy == JsonbExistsStrategyNumber)
964 : : {
965 : : /*
966 : : * Although the key is certainly present in the index, we must recheck
967 : : * because (1) the key might be hashed, and (2) the index match might
968 : : * be for a key that's not at top level of the JSON object. For (1),
969 : : * we could look at the query key to see if it's hashed and not
970 : : * recheck if not, but the index lacks enough info to tell about (2).
971 : : */
4240 tgl@sss.pgh.pa.us 972 : 0 : *recheck = true;
4287 andrew@dunslane.net 973 : 0 : res = true;
974 : : }
975 [ # # ]: 0 : else if (strategy == JsonbExistsAnyStrategyNumber)
976 : : {
977 : : /* As for plain exists, we must recheck */
4240 tgl@sss.pgh.pa.us 978 : 0 : *recheck = true;
4287 andrew@dunslane.net 979 : 0 : res = true;
980 : : }
981 [ # # ]: 0 : else if (strategy == JsonbExistsAllStrategyNumber)
982 : : {
983 : : /* As for plain exists, we must recheck */
4240 tgl@sss.pgh.pa.us 984 : 0 : *recheck = true;
985 : : /* ... but unless all the keys are present, we can say "false" */
4287 andrew@dunslane.net 986 [ # # ]: 0 : for (i = 0; i < nkeys; i++)
987 : : {
988 [ # # ]: 0 : if (!check[i])
989 : : {
990 : 0 : res = false;
991 : 0 : break;
992 : : }
993 : : }
994 : : }
2452 akorotkov@postgresql 995 [ # # # # ]: 0 : else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
996 : : strategy == JsonbJsonpathExistsStrategyNumber)
997 : : {
998 : 0 : *recheck = true;
999 : :
1000 [ # # ]: 0 : if (nkeys > 0)
1001 : : {
1002 [ # # # # ]: 0 : Assert(extra_data && extra_data[0]);
13 peter@eisentraut.org 1003 :UNC 0 : res = execute_jsp_gin_node(extra_data[0], check, false) != GIN_FALSE;
1004 : : }
1005 : : }
1006 : : else
4287 andrew@dunslane.net 1007 [ # # ]:UBC 0 : elog(ERROR, "unrecognized strategy number: %d", strategy);
1008 : :
1009 : 0 : PG_RETURN_BOOL(res);
1010 : : }
1011 : :
1012 : : Datum
4287 andrew@dunslane.net 1013 :CBC 31821 : gin_triconsistent_jsonb(PG_FUNCTION_ARGS)
1014 : : {
4279 heikki.linnakangas@i 1015 : 31821 : GinTernaryValue *check = (GinTernaryValue *) PG_GETARG_POINTER(0);
4287 andrew@dunslane.net 1016 : 31821 : StrategyNumber strategy = PG_GETARG_UINT16(1);
1017 : :
1018 : : /* Jsonb *query = PG_GETARG_JSONB_P(2); */
1019 : 31821 : int32 nkeys = PG_GETARG_INT32(3);
2452 akorotkov@postgresql 1020 : 31821 : Pointer *extra_data = (Pointer *) PG_GETARG_POINTER(4);
4240 tgl@sss.pgh.pa.us 1021 : 31821 : GinTernaryValue res = GIN_MAYBE;
1022 : : int32 i;
1023 : :
1024 : : /*
1025 : : * Note that we never return GIN_TRUE, only GIN_MAYBE or GIN_FALSE; this
1026 : : * corresponds to always forcing recheck in the regular consistent
1027 : : * function, for the reasons listed there.
1028 : : */
1029 [ + + + + ]: 31821 : if (strategy == JsonbContainsStrategyNumber ||
1030 : : strategy == JsonbExistsAllStrategyNumber)
1031 : : {
1032 : : /* All extracted keys must be present */
4287 andrew@dunslane.net 1033 [ + + ]: 5070 : for (i = 0; i < nkeys; i++)
1034 : : {
1035 [ + + ]: 1767 : if (check[i] == GIN_FALSE)
1036 : : {
1037 : 1026 : res = GIN_FALSE;
1038 : 1026 : break;
1039 : : }
1040 : : }
1041 : : }
1042 [ + + + + ]: 27492 : else if (strategy == JsonbExistsStrategyNumber ||
1043 : : strategy == JsonbExistsAnyStrategyNumber)
1044 : : {
1045 : : /* At least one extracted key must be present */
1046 : 1620 : res = GIN_FALSE;
1047 [ + - ]: 2049 : for (i = 0; i < nkeys; i++)
1048 : : {
4240 tgl@sss.pgh.pa.us 1049 [ + + ]: 2049 : if (check[i] == GIN_TRUE ||
1050 [ + + ]: 432 : check[i] == GIN_MAYBE)
1051 : : {
4287 andrew@dunslane.net 1052 : 1620 : res = GIN_MAYBE;
1053 : 1620 : break;
1054 : : }
1055 : : }
1056 : : }
2452 akorotkov@postgresql 1057 [ + + + - ]: 25872 : else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
1058 : : strategy == JsonbJsonpathExistsStrategyNumber)
1059 : : {
1060 [ + + ]: 25872 : if (nkeys > 0)
1061 : : {
1062 [ + - - + ]: 1584 : Assert(extra_data && extra_data[0]);
13 peter@eisentraut.org 1063 :GNC 1584 : res = execute_jsp_gin_node(extra_data[0], check, true);
1064 : :
1065 : : /* Should always recheck the result */
2452 akorotkov@postgresql 1066 [ + + ]:CBC 1584 : if (res == GIN_TRUE)
1067 : 318 : res = GIN_MAYBE;
1068 : : }
1069 : : }
1070 : : else
4287 andrew@dunslane.net 1071 [ # # ]:UBC 0 : elog(ERROR, "unrecognized strategy number: %d", strategy);
1072 : :
4279 heikki.linnakangas@i 1073 :CBC 31821 : PG_RETURN_GIN_TERNARY_VALUE(res);
1074 : : }
1075 : :
1076 : : /*
1077 : : *
1078 : : * jsonb_path_ops GIN opclass support functions
1079 : : *
1080 : : * In a jsonb_path_ops index, the GIN keys are uint32 hashes, one per JSON
1081 : : * value; but the JSON key(s) leading to each value are also included in its
1082 : : * hash computation. This means we can only support containment queries,
1083 : : * but the index can distinguish, for example, {"foo": 42} from {"bar": 42}
1084 : : * since different hashes will be generated.
1085 : : *
1086 : : */
1087 : :
1088 : : Datum
4238 tgl@sss.pgh.pa.us 1089 : 3111 : gin_extract_jsonb_path(PG_FUNCTION_ARGS)
1090 : : {
3012 1091 : 3111 : Jsonb *jb = PG_GETARG_JSONB_P(0);
4287 andrew@dunslane.net 1092 : 3111 : int32 *nentries = (int32 *) PG_GETARG_POINTER(1);
2452 akorotkov@postgresql 1093 : 3111 : int total = JB_ROOT_COUNT(jb);
1094 : : JsonbIterator *it;
1095 : : JsonbValue v;
1096 : : JsonbIteratorToken r;
1097 : : PathHashStack tail;
1098 : : PathHashStack *stack;
1099 : : GinEntries entries;
1100 : :
1101 : : /* If the root level is empty, we certainly have no keys */
4287 andrew@dunslane.net 1102 [ + + ]: 3111 : if (total == 0)
1103 : : {
1104 : 360 : *nentries = 0;
1105 : 360 : PG_RETURN_POINTER(NULL);
1106 : : }
1107 : :
1108 : : /* Otherwise, use 2 * root count as initial estimate of result size */
2452 akorotkov@postgresql 1109 : 2751 : init_gin_entries(&entries, 2 * total);
1110 : :
1111 : : /* We keep a stack of partial hashes corresponding to parent key levels */
4287 andrew@dunslane.net 1112 : 2751 : tail.parent = NULL;
1113 : 2751 : tail.hash = 0;
1114 : 2751 : stack = &tail;
1115 : :
4240 tgl@sss.pgh.pa.us 1116 : 2751 : it = JsonbIteratorInit(&jb->root);
1117 : :
4287 andrew@dunslane.net 1118 [ + + ]: 37392 : while ((r = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
1119 : : {
1120 : : PathHashStack *parent;
1121 : :
1122 [ + + + + : 34641 : switch (r)
- ]
1123 : : {
1124 : 2839 : case WJB_BEGIN_ARRAY:
1125 : : case WJB_BEGIN_OBJECT:
1126 : : /* Push a stack level for this object */
4240 tgl@sss.pgh.pa.us 1127 : 2839 : parent = stack;
7 michael@paquier.xyz 1128 :GNC 2839 : stack = palloc_object(PathHashStack);
1129 : :
1130 : : /*
1131 : : * We pass forward hashes from outer nesting levels so that
1132 : : * the hashes for nested values will include outer keys as
1133 : : * well as their own keys.
1134 : : *
1135 : : * Nesting an array within another array will not alter
1136 : : * innermost scalar element hash values, but that seems
1137 : : * inconsequential.
1138 : : */
3695 tgl@sss.pgh.pa.us 1139 :CBC 2839 : stack->hash = parent->hash;
4240 1140 : 2839 : stack->parent = parent;
4287 andrew@dunslane.net 1141 : 2839 : break;
1142 : 14461 : case WJB_KEY:
1143 : : /* mix this key into the current outer hash */
1144 : 14461 : JsonbHashScalarValue(&v, &stack->hash);
1145 : : /* hash is now ready to incorporate the value */
1146 : 14461 : break;
1147 : 14502 : case WJB_ELEM:
1148 : : case WJB_VALUE:
1149 : : /* mix the element or value's hash into the prepared hash */
1150 : 14502 : JsonbHashScalarValue(&v, &stack->hash);
1151 : : /* and emit an index entry */
2452 akorotkov@postgresql 1152 : 14502 : add_gin_entry(&entries, UInt32GetDatum(stack->hash));
1153 : : /* reset hash for next key, value, or sub-object */
3695 tgl@sss.pgh.pa.us 1154 : 14502 : stack->hash = stack->parent->hash;
4287 andrew@dunslane.net 1155 : 14502 : break;
1156 : 2839 : case WJB_END_ARRAY:
1157 : : case WJB_END_OBJECT:
1158 : : /* Pop the stack */
4240 tgl@sss.pgh.pa.us 1159 : 2839 : parent = stack->parent;
4287 andrew@dunslane.net 1160 : 2839 : pfree(stack);
4240 tgl@sss.pgh.pa.us 1161 : 2839 : stack = parent;
1162 : : /* reset hash for next key, value, or sub-object */
3695 1163 [ + + ]: 2839 : if (stack->parent)
1164 : 88 : stack->hash = stack->parent->hash;
1165 : : else
1166 : 2751 : stack->hash = 0;
4287 andrew@dunslane.net 1167 : 2839 : break;
4287 andrew@dunslane.net 1168 :UBC 0 : default:
3720 noah@leadboat.com 1169 [ # # ]: 0 : elog(ERROR, "invalid JsonbIteratorNext rc: %d", (int) r);
1170 : : }
1171 : : }
1172 : :
2452 akorotkov@postgresql 1173 :CBC 2751 : *nentries = entries.count;
1174 : :
1175 : 2751 : PG_RETURN_POINTER(entries.buf);
1176 : : }
1177 : :
1178 : : Datum
4238 tgl@sss.pgh.pa.us 1179 : 210 : gin_extract_jsonb_query_path(PG_FUNCTION_ARGS)
1180 : : {
4287 andrew@dunslane.net 1181 : 210 : int32 *nentries = (int32 *) PG_GETARG_POINTER(1);
1182 : 210 : StrategyNumber strategy = PG_GETARG_UINT16(2);
1183 : 210 : int32 *searchMode = (int32 *) PG_GETARG_POINTER(6);
1184 : : Datum *entries;
1185 : :
2452 akorotkov@postgresql 1186 [ + + ]: 210 : if (strategy == JsonbContainsStrategyNumber)
1187 : : {
1188 : : /* Query is a jsonb, so just apply gin_extract_jsonb_path ... */
1189 : : entries = (Datum *)
1190 : 63 : DatumGetPointer(DirectFunctionCall2(gin_extract_jsonb_path,
1191 : : PG_GETARG_DATUM(0),
1192 : : PointerGetDatum(nentries)));
1193 : :
1194 : : /* ... although "contains {}" requires a full index scan */
1195 [ + + ]: 63 : if (*nentries == 0)
1196 : 6 : *searchMode = GIN_SEARCH_MODE_ALL;
1197 : : }
1198 [ + + + - ]: 147 : else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
1199 : : strategy == JsonbJsonpathExistsStrategyNumber)
1200 : 147 : {
1201 : 147 : JsonPath *jp = PG_GETARG_JSONPATH_P(0);
1202 : 147 : Pointer **extra_data = (Pointer **) PG_GETARG_POINTER(4);
1203 : :
1204 : 147 : entries = extract_jsp_query(jp, strategy, true, nentries, extra_data);
1205 : :
1206 [ + + ]: 147 : if (!entries)
1207 : 24 : *searchMode = GIN_SEARCH_MODE_ALL;
1208 : : }
1209 : : else
1210 : : {
2452 akorotkov@postgresql 1211 [ # # ]:UBC 0 : elog(ERROR, "unrecognized strategy number: %d", strategy);
1212 : : entries = NULL;
1213 : : }
1214 : :
4287 andrew@dunslane.net 1215 :CBC 210 : PG_RETURN_POINTER(entries);
1216 : : }
1217 : :
1218 : : Datum
4238 tgl@sss.pgh.pa.us 1219 :UBC 0 : gin_consistent_jsonb_path(PG_FUNCTION_ARGS)
1220 : : {
4240 1221 : 0 : bool *check = (bool *) PG_GETARG_POINTER(0);
1222 : 0 : StrategyNumber strategy = PG_GETARG_UINT16(1);
1223 : :
1224 : : /* Jsonb *query = PG_GETARG_JSONB_P(2); */
1225 : 0 : int32 nkeys = PG_GETARG_INT32(3);
2452 akorotkov@postgresql 1226 : 0 : Pointer *extra_data = (Pointer *) PG_GETARG_POINTER(4);
4240 tgl@sss.pgh.pa.us 1227 : 0 : bool *recheck = (bool *) PG_GETARG_POINTER(5);
1228 : 0 : bool res = true;
1229 : : int32 i;
1230 : :
2452 akorotkov@postgresql 1231 [ # # ]: 0 : if (strategy == JsonbContainsStrategyNumber)
1232 : : {
1233 : : /*
1234 : : * jsonb_path_ops is necessarily lossy, not only because of hash
1235 : : * collisions but also because it doesn't preserve complete
1236 : : * information about the structure of the JSON object. Besides, there
1237 : : * are some special rules around the containment of raw scalars in
1238 : : * arrays that are not handled here. So we must always recheck a
1239 : : * match. However, if not all of the keys are present, the tuple
1240 : : * certainly doesn't match.
1241 : : */
1242 : 0 : *recheck = true;
1243 [ # # ]: 0 : for (i = 0; i < nkeys; i++)
1244 : : {
1245 [ # # ]: 0 : if (!check[i])
1246 : : {
1247 : 0 : res = false;
1248 : 0 : break;
1249 : : }
1250 : : }
1251 : : }
1252 [ # # # # ]: 0 : else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
1253 : : strategy == JsonbJsonpathExistsStrategyNumber)
1254 : : {
1255 : 0 : *recheck = true;
1256 : :
1257 [ # # ]: 0 : if (nkeys > 0)
1258 : : {
1259 [ # # # # ]: 0 : Assert(extra_data && extra_data[0]);
13 peter@eisentraut.org 1260 :UNC 0 : res = execute_jsp_gin_node(extra_data[0], check, false) != GIN_FALSE;
1261 : : }
1262 : : }
1263 : : else
2452 akorotkov@postgresql 1264 [ # # ]:UBC 0 : elog(ERROR, "unrecognized strategy number: %d", strategy);
1265 : :
4240 tgl@sss.pgh.pa.us 1266 : 0 : PG_RETURN_BOOL(res);
1267 : : }
1268 : :
1269 : : Datum
4238 tgl@sss.pgh.pa.us 1270 :CBC 15594 : gin_triconsistent_jsonb_path(PG_FUNCTION_ARGS)
1271 : : {
4240 1272 : 15594 : GinTernaryValue *check = (GinTernaryValue *) PG_GETARG_POINTER(0);
1273 : 15594 : StrategyNumber strategy = PG_GETARG_UINT16(1);
1274 : :
1275 : : /* Jsonb *query = PG_GETARG_JSONB_P(2); */
1276 : 15594 : int32 nkeys = PG_GETARG_INT32(3);
2452 akorotkov@postgresql 1277 : 15594 : Pointer *extra_data = (Pointer *) PG_GETARG_POINTER(4);
4240 tgl@sss.pgh.pa.us 1278 : 15594 : GinTernaryValue res = GIN_MAYBE;
1279 : : int32 i;
1280 : :
2452 akorotkov@postgresql 1281 [ + + ]: 15594 : if (strategy == JsonbContainsStrategyNumber)
1282 : : {
1283 : : /*
1284 : : * Note that we never return GIN_TRUE, only GIN_MAYBE or GIN_FALSE;
1285 : : * this corresponds to always forcing recheck in the regular
1286 : : * consistent function, for the reasons listed there.
1287 : : */
1288 [ + + ]: 3279 : for (i = 0; i < nkeys; i++)
1289 : : {
1290 [ + + ]: 165 : if (check[i] == GIN_FALSE)
1291 : : {
1292 : 42 : res = GIN_FALSE;
1293 : 42 : break;
1294 : : }
1295 : : }
1296 : : }
1297 [ + + + - ]: 12438 : else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
1298 : : strategy == JsonbJsonpathExistsStrategyNumber)
1299 : : {
1300 [ + + ]: 12438 : if (nkeys > 0)
1301 : : {
1302 [ + - - + ]: 294 : Assert(extra_data && extra_data[0]);
13 peter@eisentraut.org 1303 :GNC 294 : res = execute_jsp_gin_node(extra_data[0], check, true);
1304 : :
1305 : : /* Should always recheck the result */
2452 akorotkov@postgresql 1306 [ + + ]:CBC 294 : if (res == GIN_TRUE)
1307 : 210 : res = GIN_MAYBE;
1308 : : }
1309 : : }
1310 : : else
2452 akorotkov@postgresql 1311 [ # # ]:UBC 0 : elog(ERROR, "unrecognized strategy number: %d", strategy);
1312 : :
4240 tgl@sss.pgh.pa.us 1313 :CBC 15594 : PG_RETURN_GIN_TERNARY_VALUE(res);
1314 : : }
1315 : :
1316 : : /*
1317 : : * Construct a jsonb_ops GIN key from a flag byte and a textual representation
1318 : : * (which need not be null-terminated). This function is responsible
1319 : : * for hashing overlength text representations; it will add the
1320 : : * JGINFLAG_HASHED bit to the flag value if it does that.
1321 : : */
1322 : : static Datum
1323 : 71846 : make_text_key(char flag, const char *str, int len)
1324 : : {
1325 : : text *item;
1326 : : char hashbuf[10];
1327 : :
1328 [ - + ]: 71846 : if (len > JGIN_MAXLENGTH)
1329 : : {
1330 : : uint32 hashval;
1331 : :
4240 tgl@sss.pgh.pa.us 1332 :UBC 0 : hashval = DatumGetUInt32(hash_any((const unsigned char *) str, len));
1333 : 0 : snprintf(hashbuf, sizeof(hashbuf), "%08x", hashval);
1334 : 0 : str = hashbuf;
1335 : 0 : len = 8;
1336 : 0 : flag |= JGINFLAG_HASHED;
1337 : : }
1338 : :
1339 : : /*
1340 : : * Now build the text Datum. For simplicity we build a 4-byte-header
1341 : : * varlena text Datum here, but we expect it will get converted to short
1342 : : * header format when stored in the index.
1343 : : */
4287 andrew@dunslane.net 1344 :CBC 71846 : item = (text *) palloc(VARHDRSZ + len + 1);
1345 : 71846 : SET_VARSIZE(item, VARHDRSZ + len + 1);
1346 : :
1347 : 71846 : *VARDATA(item) = flag;
1348 : :
1349 : 71846 : memcpy(VARDATA(item) + 1, str, len);
1350 : :
4240 tgl@sss.pgh.pa.us 1351 : 71846 : return PointerGetDatum(item);
1352 : : }
1353 : :
1354 : : /*
1355 : : * Create a textual representation of a JsonbValue that will serve as a GIN
1356 : : * key in a jsonb_ops index. is_key is true if the JsonbValue is a key,
1357 : : * or if it is a string array element (since we pretend those are keys,
1358 : : * see jsonb.h).
1359 : : */
1360 : : static Datum
1361 : 71612 : make_scalar_key(const JsonbValue *scalarVal, bool is_key)
1362 : : {
1363 : : Datum item;
1364 : : char *cstr;
1365 : :
4287 andrew@dunslane.net 1366 [ + + + + : 71612 : switch (scalarVal->type)
- ]
1367 : : {
1368 : 206 : case jbvNull:
4240 tgl@sss.pgh.pa.us 1369 [ - + ]: 206 : Assert(!is_key);
1370 : 206 : item = make_text_key(JGINFLAG_NULL, "", 0);
4287 andrew@dunslane.net 1371 : 206 : break;
1372 : 2932 : case jbvBool:
4240 tgl@sss.pgh.pa.us 1373 [ - + ]: 2932 : Assert(!is_key);
1374 : 2932 : item = make_text_key(JGINFLAG_BOOL,
1375 [ + + ]: 2932 : scalarVal->val.boolean ? "t" : "f", 1);
4287 andrew@dunslane.net 1376 : 2932 : break;
1377 : 26143 : case jbvNumeric:
4240 tgl@sss.pgh.pa.us 1378 [ - + ]: 26143 : Assert(!is_key);
1379 : :
1380 : : /*
1381 : : * A normalized textual representation, free of trailing zeroes,
1382 : : * is required so that numerically equal values will produce equal
1383 : : * strings.
1384 : : *
1385 : : * It isn't ideal that numerics are stored in a relatively bulky
1386 : : * textual format. However, it's a notationally convenient way of
1387 : : * storing a "union" type in the GIN B-Tree, and indexing Jsonb
1388 : : * strings takes precedence.
1389 : : */
4277 1390 : 26143 : cstr = numeric_normalize(scalarVal->val.numeric);
4240 1391 : 26143 : item = make_text_key(JGINFLAG_NUM, cstr, strlen(cstr));
4287 andrew@dunslane.net 1392 : 26143 : pfree(cstr);
1393 : 26143 : break;
1394 : 42331 : case jbvString:
4240 tgl@sss.pgh.pa.us 1395 : 42331 : item = make_text_key(is_key ? JGINFLAG_KEY : JGINFLAG_STR,
1396 : 42331 : scalarVal->val.string.val,
1397 [ + + ]: 42331 : scalarVal->val.string.len);
4287 andrew@dunslane.net 1398 : 42331 : break;
4287 andrew@dunslane.net 1399 :UBC 0 : default:
4240 tgl@sss.pgh.pa.us 1400 [ # # ]: 0 : elog(ERROR, "unrecognized jsonb scalar type: %d", scalarVal->type);
1401 : : item = 0; /* keep compiler quiet */
1402 : : break;
1403 : : }
1404 : :
4287 andrew@dunslane.net 1405 :CBC 71612 : return item;
1406 : : }
|