PostgreSQL Source Code git master
execExprInterp.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * execExprInterp.c
4 * Interpreted evaluation of an expression step list.
5 *
6 * This file provides either a "direct threaded" (for gcc, clang and
7 * compatible) or a "switch threaded" (for all compilers) implementation of
8 * expression evaluation. The former is amongst the fastest known methods
9 * of interpreting programs without resorting to assembly level work, or
10 * just-in-time compilation, but it requires support for computed gotos.
11 * The latter is amongst the fastest approaches doable in standard C.
12 *
13 * In either case we use ExprEvalStep->opcode to dispatch to the code block
14 * within ExecInterpExpr() that implements the specific opcode type.
15 *
16 * Switch-threading uses a plain switch() statement to perform the
17 * dispatch. This has the advantages of being plain C and allowing the
18 * compiler to warn if implementation of a specific opcode has been forgotten.
19 * The disadvantage is that dispatches will, as commonly implemented by
20 * compilers, happen from a single location, requiring more jumps and causing
21 * bad branch prediction.
22 *
23 * In direct threading, we use gcc's label-as-values extension - also adopted
24 * by some other compilers - to replace ExprEvalStep->opcode with the address
25 * of the block implementing the instruction. Dispatch to the next instruction
26 * is done by a "computed goto". This allows for better branch prediction
27 * (as the jumps are happening from different locations) and fewer jumps
28 * (as no preparatory jump to a common dispatch location is needed).
29 *
30 * When using direct threading, ExecReadyInterpretedExpr will replace
31 * each step's opcode field with the address of the relevant code block and
32 * ExprState->flags will contain EEO_FLAG_DIRECT_THREADED to remember that
33 * that's been done.
34 *
35 * For very simple instructions the overhead of the full interpreter
36 * "startup", as minimal as it is, is noticeable. Therefore
37 * ExecReadyInterpretedExpr will choose to implement certain simple
38 * opcode patterns using special fast-path routines (ExecJust*).
39 *
40 * Complex or uncommon instructions are not implemented in-line in
41 * ExecInterpExpr(), rather we call out to a helper function appearing later
42 * in this file. For one reason, there'd not be a noticeable performance
43 * benefit, but more importantly those complex routines are intended to be
44 * shared between different expression evaluation approaches. For instance
45 * a JIT compiler would generate calls to them. (This is why they are
46 * exported rather than being "static" in this file.)
47 *
48 *
49 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
50 * Portions Copyright (c) 1994, Regents of the University of California
51 *
52 * IDENTIFICATION
53 * src/backend/executor/execExprInterp.c
54 *
55 *-------------------------------------------------------------------------
56 */
57#include "postgres.h"
58
59#include "access/heaptoast.h"
60#include "catalog/pg_type.h"
61#include "commands/sequence.h"
62#include "executor/execExpr.h"
64#include "funcapi.h"
65#include "miscadmin.h"
66#include "nodes/miscnodes.h"
67#include "nodes/nodeFuncs.h"
68#include "pgstat.h"
69#include "utils/array.h"
70#include "utils/builtins.h"
71#include "utils/date.h"
72#include "utils/datum.h"
74#include "utils/json.h"
75#include "utils/jsonfuncs.h"
76#include "utils/jsonpath.h"
77#include "utils/lsyscache.h"
78#include "utils/memutils.h"
79#include "utils/timestamp.h"
80#include "utils/typcache.h"
81#include "utils/xml.h"
82
83/*
84 * Use computed-goto-based opcode dispatch when computed gotos are available.
85 * But use a separate symbol so that it's easy to adjust locally in this file
86 * for development and testing.
87 */
88#ifdef HAVE_COMPUTED_GOTO
89#define EEO_USE_COMPUTED_GOTO
90#endif /* HAVE_COMPUTED_GOTO */
91
92/*
93 * Macros for opcode dispatch.
94 *
95 * EEO_SWITCH - just hides the switch if not in use.
96 * EEO_CASE - labels the implementation of named expression step type.
97 * EEO_DISPATCH - jump to the implementation of the step type for 'op'.
98 * EEO_OPCODE - compute opcode required by used expression evaluation method.
99 * EEO_NEXT - increment 'op' and jump to correct next step type.
100 * EEO_JUMP - jump to the specified step number within the current expression.
101 */
102#if defined(EEO_USE_COMPUTED_GOTO)
103
104/* struct for jump target -> opcode lookup table */
105typedef struct ExprEvalOpLookup
106{
107 const void *opcode;
108 ExprEvalOp op;
109} ExprEvalOpLookup;
110
111/* to make dispatch_table accessible outside ExecInterpExpr() */
112static const void **dispatch_table = NULL;
113
114/* jump target -> opcode lookup table */
115static ExprEvalOpLookup reverse_dispatch_table[EEOP_LAST];
116
117#define EEO_SWITCH()
118#define EEO_CASE(name) CASE_##name:
119#define EEO_DISPATCH() goto *((void *) op->opcode)
120#define EEO_OPCODE(opcode) ((intptr_t) dispatch_table[opcode])
121
122#else /* !EEO_USE_COMPUTED_GOTO */
123
124#define EEO_SWITCH() starteval: switch ((ExprEvalOp) op->opcode)
125#define EEO_CASE(name) case name:
126#define EEO_DISPATCH() goto starteval
127#define EEO_OPCODE(opcode) (opcode)
128
129#endif /* EEO_USE_COMPUTED_GOTO */
130
131#define EEO_NEXT() \
132 do { \
133 op++; \
134 EEO_DISPATCH(); \
135 } while (0)
136
137#define EEO_JUMP(stepno) \
138 do { \
139 op = &state->steps[stepno]; \
140 EEO_DISPATCH(); \
141 } while (0)
142
143
144static Datum ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull);
145static void ExecInitInterpreter(void);
146
147/* support functions */
148static void CheckVarSlotCompatibility(TupleTableSlot *slot, int attnum, Oid vartype);
150static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
151 ExprEvalRowtypeCache *rowcache,
152 bool *changed);
154 ExprContext *econtext, bool checkisnull);
155
156/* fast-path evaluation functions */
157static Datum ExecJustInnerVar(ExprState *state, ExprContext *econtext, bool *isnull);
158static Datum ExecJustOuterVar(ExprState *state, ExprContext *econtext, bool *isnull);
159static Datum ExecJustScanVar(ExprState *state, ExprContext *econtext, bool *isnull);
160static Datum ExecJustAssignInnerVar(ExprState *state, ExprContext *econtext, bool *isnull);
161static Datum ExecJustAssignOuterVar(ExprState *state, ExprContext *econtext, bool *isnull);
162static Datum ExecJustAssignScanVar(ExprState *state, ExprContext *econtext, bool *isnull);
163static Datum ExecJustApplyFuncToCase(ExprState *state, ExprContext *econtext, bool *isnull);
164static Datum ExecJustConst(ExprState *state, ExprContext *econtext, bool *isnull);
165static Datum ExecJustInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
166static Datum ExecJustOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
167static Datum ExecJustScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
168static Datum ExecJustAssignInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
169static Datum ExecJustAssignOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
170static Datum ExecJustAssignScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
171static Datum ExecJustHashInnerVarWithIV(ExprState *state, ExprContext *econtext, bool *isnull);
172static Datum ExecJustHashOuterVar(ExprState *state, ExprContext *econtext, bool *isnull);
173static Datum ExecJustHashInnerVar(ExprState *state, ExprContext *econtext, bool *isnull);
174static Datum ExecJustHashOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
175static Datum ExecJustHashInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
176static Datum ExecJustHashOuterVarStrict(ExprState *state, ExprContext *econtext, bool *isnull);
177
178/* execution helper functions */
180 AggStatePerTrans pertrans,
181 AggStatePerGroup pergroup,
182 ExprContext *aggcontext,
183 int setno);
185 AggStatePerTrans pertrans,
186 AggStatePerGroup pergroup,
187 ExprContext *aggcontext,
188 int setno);
189static char *ExecGetJsonValueItemString(JsonbValue *item, bool *resnull);
190
191/*
192 * ScalarArrayOpExprHashEntry
193 * Hash table entry type used during EEOP_HASHED_SCALARARRAYOP
194 */
196{
198 uint32 status; /* hash status */
199 uint32 hash; /* hash value (cached) */
201
202#define SH_PREFIX saophash
203#define SH_ELEMENT_TYPE ScalarArrayOpExprHashEntry
204#define SH_KEY_TYPE Datum
205#define SH_SCOPE static inline
206#define SH_DECLARE
207#include "lib/simplehash.h"
208
209static bool saop_hash_element_match(struct saophash_hash *tb, Datum key1,
210 Datum key2);
211static uint32 saop_element_hash(struct saophash_hash *tb, Datum key);
212
213/*
214 * ScalarArrayOpExprHashTable
215 * Hash table for EEOP_HASHED_SCALARARRAYOP
216 */
218{
219 saophash_hash *hashtab; /* underlying hash table */
221 FmgrInfo hash_finfo; /* function's lookup data */
224
225/* Define parameters for ScalarArrayOpExpr hash table code generation. */
226#define SH_PREFIX saophash
227#define SH_ELEMENT_TYPE ScalarArrayOpExprHashEntry
228#define SH_KEY_TYPE Datum
229#define SH_KEY key
230#define SH_HASH_KEY(tb, key) saop_element_hash(tb, key)
231#define SH_EQUAL(tb, a, b) saop_hash_element_match(tb, a, b)
232#define SH_SCOPE static inline
233#define SH_STORE_HASH
234#define SH_GET_HASH(tb, a) a->hash
235#define SH_DEFINE
236#include "lib/simplehash.h"
237
238/*
239 * Prepare ExprState for interpreted execution.
240 */
241void
243{
244 /* Ensure one-time interpreter setup has been done */
246
247 /* Simple validity checks on expression */
248 Assert(state->steps_len >= 1);
249 Assert(state->steps[state->steps_len - 1].opcode == EEOP_DONE);
250
251 /*
252 * Don't perform redundant initialization. This is unreachable in current
253 * cases, but might be hit if there's additional expression evaluation
254 * methods that rely on interpreted execution to work.
255 */
257 return;
258
259 /*
260 * First time through, check whether attribute matches Var. Might not be
261 * ok anymore, due to schema changes. We do that by setting up a callback
262 * that does checking on the first call, which then sets the evalfunc
263 * callback to the actual method of execution.
264 */
266
267 /* DIRECT_THREADED should not already be set */
268 Assert((state->flags & EEO_FLAG_DIRECT_THREADED) == 0);
269
270 /*
271 * There shouldn't be any errors before the expression is fully
272 * initialized, and even if so, it'd lead to the expression being
273 * abandoned. So we can set the flag now and save some code.
274 */
276
277 /*
278 * Select fast-path evalfuncs for very simple expressions. "Starting up"
279 * the full interpreter is a measurable overhead for these, and these
280 * patterns occur often enough to be worth optimizing.
281 */
282 if (state->steps_len == 5)
283 {
284 ExprEvalOp step0 = state->steps[0].opcode;
285 ExprEvalOp step1 = state->steps[1].opcode;
286 ExprEvalOp step2 = state->steps[2].opcode;
287 ExprEvalOp step3 = state->steps[3].opcode;
288
289 if (step0 == EEOP_INNER_FETCHSOME &&
291 step2 == EEOP_INNER_VAR &&
292 step3 == EEOP_HASHDATUM_NEXT32)
293 {
294 state->evalfunc_private = (void *) ExecJustHashInnerVarWithIV;
295 return;
296 }
297 }
298 else if (state->steps_len == 4)
299 {
300 ExprEvalOp step0 = state->steps[0].opcode;
301 ExprEvalOp step1 = state->steps[1].opcode;
302 ExprEvalOp step2 = state->steps[2].opcode;
303
304 if (step0 == EEOP_OUTER_FETCHSOME &&
305 step1 == EEOP_OUTER_VAR &&
306 step2 == EEOP_HASHDATUM_FIRST)
307 {
308 state->evalfunc_private = (void *) ExecJustHashOuterVar;
309 return;
310 }
311 else if (step0 == EEOP_INNER_FETCHSOME &&
312 step1 == EEOP_INNER_VAR &&
313 step2 == EEOP_HASHDATUM_FIRST)
314 {
315 state->evalfunc_private = (void *) ExecJustHashInnerVar;
316 return;
317 }
318 else if (step0 == EEOP_OUTER_FETCHSOME &&
319 step1 == EEOP_OUTER_VAR &&
321 {
322 state->evalfunc_private = (void *) ExecJustHashOuterVarStrict;
323 return;
324 }
325 }
326 else if (state->steps_len == 3)
327 {
328 ExprEvalOp step0 = state->steps[0].opcode;
329 ExprEvalOp step1 = state->steps[1].opcode;
330
331 if (step0 == EEOP_INNER_FETCHSOME &&
332 step1 == EEOP_INNER_VAR)
333 {
334 state->evalfunc_private = ExecJustInnerVar;
335 return;
336 }
337 else if (step0 == EEOP_OUTER_FETCHSOME &&
338 step1 == EEOP_OUTER_VAR)
339 {
340 state->evalfunc_private = ExecJustOuterVar;
341 return;
342 }
343 else if (step0 == EEOP_SCAN_FETCHSOME &&
344 step1 == EEOP_SCAN_VAR)
345 {
346 state->evalfunc_private = ExecJustScanVar;
347 return;
348 }
349 else if (step0 == EEOP_INNER_FETCHSOME &&
350 step1 == EEOP_ASSIGN_INNER_VAR)
351 {
352 state->evalfunc_private = ExecJustAssignInnerVar;
353 return;
354 }
355 else if (step0 == EEOP_OUTER_FETCHSOME &&
356 step1 == EEOP_ASSIGN_OUTER_VAR)
357 {
358 state->evalfunc_private = ExecJustAssignOuterVar;
359 return;
360 }
361 else if (step0 == EEOP_SCAN_FETCHSOME &&
362 step1 == EEOP_ASSIGN_SCAN_VAR)
363 {
364 state->evalfunc_private = ExecJustAssignScanVar;
365 return;
366 }
367 else if (step0 == EEOP_CASE_TESTVAL &&
368 step1 == EEOP_FUNCEXPR_STRICT &&
369 state->steps[0].d.casetest.value)
370 {
371 state->evalfunc_private = ExecJustApplyFuncToCase;
372 return;
373 }
374 else if (step0 == EEOP_INNER_VAR &&
375 step1 == EEOP_HASHDATUM_FIRST)
376 {
377 state->evalfunc_private = (void *) ExecJustHashInnerVarVirt;
378 return;
379 }
380 else if (step0 == EEOP_OUTER_VAR &&
381 step1 == EEOP_HASHDATUM_FIRST)
382 {
383 state->evalfunc_private = (void *) ExecJustHashOuterVarVirt;
384 return;
385 }
386 }
387 else if (state->steps_len == 2)
388 {
389 ExprEvalOp step0 = state->steps[0].opcode;
390
391 if (step0 == EEOP_CONST)
392 {
393 state->evalfunc_private = ExecJustConst;
394 return;
395 }
396 else if (step0 == EEOP_INNER_VAR)
397 {
398 state->evalfunc_private = ExecJustInnerVarVirt;
399 return;
400 }
401 else if (step0 == EEOP_OUTER_VAR)
402 {
403 state->evalfunc_private = ExecJustOuterVarVirt;
404 return;
405 }
406 else if (step0 == EEOP_SCAN_VAR)
407 {
408 state->evalfunc_private = ExecJustScanVarVirt;
409 return;
410 }
411 else if (step0 == EEOP_ASSIGN_INNER_VAR)
412 {
413 state->evalfunc_private = ExecJustAssignInnerVarVirt;
414 return;
415 }
416 else if (step0 == EEOP_ASSIGN_OUTER_VAR)
417 {
418 state->evalfunc_private = ExecJustAssignOuterVarVirt;
419 return;
420 }
421 else if (step0 == EEOP_ASSIGN_SCAN_VAR)
422 {
423 state->evalfunc_private = ExecJustAssignScanVarVirt;
424 return;
425 }
426 }
427
428#if defined(EEO_USE_COMPUTED_GOTO)
429
430 /*
431 * In the direct-threaded implementation, replace each opcode with the
432 * address to jump to. (Use ExecEvalStepOp() to get back the opcode.)
433 */
434 for (int off = 0; off < state->steps_len; off++)
435 {
436 ExprEvalStep *op = &state->steps[off];
437
438 op->opcode = EEO_OPCODE(op->opcode);
439 }
440
442#endif /* EEO_USE_COMPUTED_GOTO */
443
444 state->evalfunc_private = ExecInterpExpr;
445}
446
447
448/*
449 * Evaluate expression identified by "state" in the execution context
450 * given by "econtext". *isnull is set to the is-null flag for the result,
451 * and the Datum value is the function result.
452 *
453 * As a special case, return the dispatch table's address if state is NULL.
454 * This is used by ExecInitInterpreter to set up the dispatch_table global.
455 * (Only applies when EEO_USE_COMPUTED_GOTO is defined.)
456 */
457static Datum
459{
461 TupleTableSlot *resultslot;
462 TupleTableSlot *innerslot;
463 TupleTableSlot *outerslot;
464 TupleTableSlot *scanslot;
465 TupleTableSlot *oldslot;
466 TupleTableSlot *newslot;
467
468 /*
469 * This array has to be in the same order as enum ExprEvalOp.
470 */
471#if defined(EEO_USE_COMPUTED_GOTO)
472 static const void *const dispatch_table[] = {
473 &&CASE_EEOP_DONE,
474 &&CASE_EEOP_INNER_FETCHSOME,
475 &&CASE_EEOP_OUTER_FETCHSOME,
476 &&CASE_EEOP_SCAN_FETCHSOME,
477 &&CASE_EEOP_OLD_FETCHSOME,
478 &&CASE_EEOP_NEW_FETCHSOME,
479 &&CASE_EEOP_INNER_VAR,
480 &&CASE_EEOP_OUTER_VAR,
481 &&CASE_EEOP_SCAN_VAR,
482 &&CASE_EEOP_OLD_VAR,
483 &&CASE_EEOP_NEW_VAR,
484 &&CASE_EEOP_INNER_SYSVAR,
485 &&CASE_EEOP_OUTER_SYSVAR,
486 &&CASE_EEOP_SCAN_SYSVAR,
487 &&CASE_EEOP_OLD_SYSVAR,
488 &&CASE_EEOP_NEW_SYSVAR,
489 &&CASE_EEOP_WHOLEROW,
490 &&CASE_EEOP_ASSIGN_INNER_VAR,
491 &&CASE_EEOP_ASSIGN_OUTER_VAR,
492 &&CASE_EEOP_ASSIGN_SCAN_VAR,
493 &&CASE_EEOP_ASSIGN_OLD_VAR,
494 &&CASE_EEOP_ASSIGN_NEW_VAR,
495 &&CASE_EEOP_ASSIGN_TMP,
496 &&CASE_EEOP_ASSIGN_TMP_MAKE_RO,
497 &&CASE_EEOP_CONST,
498 &&CASE_EEOP_FUNCEXPR,
499 &&CASE_EEOP_FUNCEXPR_STRICT,
500 &&CASE_EEOP_FUNCEXPR_FUSAGE,
501 &&CASE_EEOP_FUNCEXPR_STRICT_FUSAGE,
502 &&CASE_EEOP_BOOL_AND_STEP_FIRST,
503 &&CASE_EEOP_BOOL_AND_STEP,
504 &&CASE_EEOP_BOOL_AND_STEP_LAST,
505 &&CASE_EEOP_BOOL_OR_STEP_FIRST,
506 &&CASE_EEOP_BOOL_OR_STEP,
507 &&CASE_EEOP_BOOL_OR_STEP_LAST,
508 &&CASE_EEOP_BOOL_NOT_STEP,
509 &&CASE_EEOP_QUAL,
510 &&CASE_EEOP_JUMP,
511 &&CASE_EEOP_JUMP_IF_NULL,
512 &&CASE_EEOP_JUMP_IF_NOT_NULL,
513 &&CASE_EEOP_JUMP_IF_NOT_TRUE,
514 &&CASE_EEOP_NULLTEST_ISNULL,
515 &&CASE_EEOP_NULLTEST_ISNOTNULL,
516 &&CASE_EEOP_NULLTEST_ROWISNULL,
517 &&CASE_EEOP_NULLTEST_ROWISNOTNULL,
518 &&CASE_EEOP_BOOLTEST_IS_TRUE,
519 &&CASE_EEOP_BOOLTEST_IS_NOT_TRUE,
520 &&CASE_EEOP_BOOLTEST_IS_FALSE,
521 &&CASE_EEOP_BOOLTEST_IS_NOT_FALSE,
522 &&CASE_EEOP_PARAM_EXEC,
523 &&CASE_EEOP_PARAM_EXTERN,
524 &&CASE_EEOP_PARAM_CALLBACK,
525 &&CASE_EEOP_PARAM_SET,
526 &&CASE_EEOP_CASE_TESTVAL,
527 &&CASE_EEOP_MAKE_READONLY,
528 &&CASE_EEOP_IOCOERCE,
529 &&CASE_EEOP_IOCOERCE_SAFE,
530 &&CASE_EEOP_DISTINCT,
531 &&CASE_EEOP_NOT_DISTINCT,
532 &&CASE_EEOP_NULLIF,
533 &&CASE_EEOP_SQLVALUEFUNCTION,
534 &&CASE_EEOP_CURRENTOFEXPR,
535 &&CASE_EEOP_NEXTVALUEEXPR,
536 &&CASE_EEOP_RETURNINGEXPR,
537 &&CASE_EEOP_ARRAYEXPR,
538 &&CASE_EEOP_ARRAYCOERCE,
539 &&CASE_EEOP_ROW,
540 &&CASE_EEOP_ROWCOMPARE_STEP,
541 &&CASE_EEOP_ROWCOMPARE_FINAL,
542 &&CASE_EEOP_MINMAX,
543 &&CASE_EEOP_FIELDSELECT,
544 &&CASE_EEOP_FIELDSTORE_DEFORM,
545 &&CASE_EEOP_FIELDSTORE_FORM,
546 &&CASE_EEOP_SBSREF_SUBSCRIPTS,
547 &&CASE_EEOP_SBSREF_OLD,
548 &&CASE_EEOP_SBSREF_ASSIGN,
549 &&CASE_EEOP_SBSREF_FETCH,
550 &&CASE_EEOP_DOMAIN_TESTVAL,
551 &&CASE_EEOP_DOMAIN_NOTNULL,
552 &&CASE_EEOP_DOMAIN_CHECK,
553 &&CASE_EEOP_HASHDATUM_SET_INITVAL,
554 &&CASE_EEOP_HASHDATUM_FIRST,
555 &&CASE_EEOP_HASHDATUM_FIRST_STRICT,
556 &&CASE_EEOP_HASHDATUM_NEXT32,
557 &&CASE_EEOP_HASHDATUM_NEXT32_STRICT,
558 &&CASE_EEOP_CONVERT_ROWTYPE,
559 &&CASE_EEOP_SCALARARRAYOP,
560 &&CASE_EEOP_HASHED_SCALARARRAYOP,
561 &&CASE_EEOP_XMLEXPR,
562 &&CASE_EEOP_JSON_CONSTRUCTOR,
563 &&CASE_EEOP_IS_JSON,
564 &&CASE_EEOP_JSONEXPR_PATH,
565 &&CASE_EEOP_JSONEXPR_COERCION,
566 &&CASE_EEOP_JSONEXPR_COERCION_FINISH,
567 &&CASE_EEOP_AGGREF,
568 &&CASE_EEOP_GROUPING_FUNC,
569 &&CASE_EEOP_WINDOW_FUNC,
570 &&CASE_EEOP_MERGE_SUPPORT_FUNC,
571 &&CASE_EEOP_SUBPLAN,
572 &&CASE_EEOP_AGG_STRICT_DESERIALIZE,
573 &&CASE_EEOP_AGG_DESERIALIZE,
574 &&CASE_EEOP_AGG_STRICT_INPUT_CHECK_ARGS,
575 &&CASE_EEOP_AGG_STRICT_INPUT_CHECK_NULLS,
576 &&CASE_EEOP_AGG_PLAIN_PERGROUP_NULLCHECK,
577 &&CASE_EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL,
578 &&CASE_EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL,
579 &&CASE_EEOP_AGG_PLAIN_TRANS_BYVAL,
580 &&CASE_EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYREF,
581 &&CASE_EEOP_AGG_PLAIN_TRANS_STRICT_BYREF,
582 &&CASE_EEOP_AGG_PLAIN_TRANS_BYREF,
583 &&CASE_EEOP_AGG_PRESORTED_DISTINCT_SINGLE,
584 &&CASE_EEOP_AGG_PRESORTED_DISTINCT_MULTI,
585 &&CASE_EEOP_AGG_ORDERED_TRANS_DATUM,
586 &&CASE_EEOP_AGG_ORDERED_TRANS_TUPLE,
587 &&CASE_EEOP_LAST
588 };
589
590 StaticAssertDecl(lengthof(dispatch_table) == EEOP_LAST + 1,
591 "dispatch_table out of whack with ExprEvalOp");
592
593 if (unlikely(state == NULL))
594 return PointerGetDatum(dispatch_table);
595#else
596 Assert(state != NULL);
597#endif /* EEO_USE_COMPUTED_GOTO */
598
599 /* setup state */
600 op = state->steps;
601 resultslot = state->resultslot;
602 innerslot = econtext->ecxt_innertuple;
603 outerslot = econtext->ecxt_outertuple;
604 scanslot = econtext->ecxt_scantuple;
605 oldslot = econtext->ecxt_oldtuple;
606 newslot = econtext->ecxt_newtuple;
607
608#if defined(EEO_USE_COMPUTED_GOTO)
609 EEO_DISPATCH();
610#endif
611
612 EEO_SWITCH()
613 {
615 {
616 goto out;
617 }
618
620 {
621 CheckOpSlotCompatibility(op, innerslot);
622
623 slot_getsomeattrs(innerslot, op->d.fetch.last_var);
624
625 EEO_NEXT();
626 }
627
629 {
630 CheckOpSlotCompatibility(op, outerslot);
631
632 slot_getsomeattrs(outerslot, op->d.fetch.last_var);
633
634 EEO_NEXT();
635 }
636
638 {
639 CheckOpSlotCompatibility(op, scanslot);
640
641 slot_getsomeattrs(scanslot, op->d.fetch.last_var);
642
643 EEO_NEXT();
644 }
645
647 {
649
650 slot_getsomeattrs(oldslot, op->d.fetch.last_var);
651
652 EEO_NEXT();
653 }
654
656 {
658
659 slot_getsomeattrs(newslot, op->d.fetch.last_var);
660
661 EEO_NEXT();
662 }
663
665 {
666 int attnum = op->d.var.attnum;
667
668 /*
669 * Since we already extracted all referenced columns from the
670 * tuple with a FETCHSOME step, we can just grab the value
671 * directly out of the slot's decomposed-data arrays. But let's
672 * have an Assert to check that that did happen.
673 */
674 Assert(attnum >= 0 && attnum < innerslot->tts_nvalid);
675 *op->resvalue = innerslot->tts_values[attnum];
676 *op->resnull = innerslot->tts_isnull[attnum];
677
678 EEO_NEXT();
679 }
680
682 {
683 int attnum = op->d.var.attnum;
684
685 /* See EEOP_INNER_VAR comments */
686
687 Assert(attnum >= 0 && attnum < outerslot->tts_nvalid);
688 *op->resvalue = outerslot->tts_values[attnum];
689 *op->resnull = outerslot->tts_isnull[attnum];
690
691 EEO_NEXT();
692 }
693
695 {
696 int attnum = op->d.var.attnum;
697
698 /* See EEOP_INNER_VAR comments */
699
700 Assert(attnum >= 0 && attnum < scanslot->tts_nvalid);
701 *op->resvalue = scanslot->tts_values[attnum];
702 *op->resnull = scanslot->tts_isnull[attnum];
703
704 EEO_NEXT();
705 }
706
708 {
709 int attnum = op->d.var.attnum;
710
711 /* See EEOP_INNER_VAR comments */
712
713 Assert(attnum >= 0 && attnum < oldslot->tts_nvalid);
714 *op->resvalue = oldslot->tts_values[attnum];
715 *op->resnull = oldslot->tts_isnull[attnum];
716
717 EEO_NEXT();
718 }
719
721 {
722 int attnum = op->d.var.attnum;
723
724 /* See EEOP_INNER_VAR comments */
725
726 Assert(attnum >= 0 && attnum < newslot->tts_nvalid);
727 *op->resvalue = newslot->tts_values[attnum];
728 *op->resnull = newslot->tts_isnull[attnum];
729
730 EEO_NEXT();
731 }
732
734 {
735 ExecEvalSysVar(state, op, econtext, innerslot);
736 EEO_NEXT();
737 }
738
740 {
741 ExecEvalSysVar(state, op, econtext, outerslot);
742 EEO_NEXT();
743 }
744
746 {
747 ExecEvalSysVar(state, op, econtext, scanslot);
748 EEO_NEXT();
749 }
750
752 {
753 ExecEvalSysVar(state, op, econtext, oldslot);
754 EEO_NEXT();
755 }
756
758 {
759 ExecEvalSysVar(state, op, econtext, newslot);
760 EEO_NEXT();
761 }
762
764 {
765 /* too complex for an inline implementation */
766 ExecEvalWholeRowVar(state, op, econtext);
767
768 EEO_NEXT();
769 }
770
772 {
773 int resultnum = op->d.assign_var.resultnum;
774 int attnum = op->d.assign_var.attnum;
775
776 /*
777 * We do not need CheckVarSlotCompatibility here; that was taken
778 * care of at compilation time. But see EEOP_INNER_VAR comments.
779 */
780 Assert(attnum >= 0 && attnum < innerslot->tts_nvalid);
781 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
782 resultslot->tts_values[resultnum] = innerslot->tts_values[attnum];
783 resultslot->tts_isnull[resultnum] = innerslot->tts_isnull[attnum];
784
785 EEO_NEXT();
786 }
787
789 {
790 int resultnum = op->d.assign_var.resultnum;
791 int attnum = op->d.assign_var.attnum;
792
793 /*
794 * We do not need CheckVarSlotCompatibility here; that was taken
795 * care of at compilation time. But see EEOP_INNER_VAR comments.
796 */
797 Assert(attnum >= 0 && attnum < outerslot->tts_nvalid);
798 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
799 resultslot->tts_values[resultnum] = outerslot->tts_values[attnum];
800 resultslot->tts_isnull[resultnum] = outerslot->tts_isnull[attnum];
801
802 EEO_NEXT();
803 }
804
806 {
807 int resultnum = op->d.assign_var.resultnum;
808 int attnum = op->d.assign_var.attnum;
809
810 /*
811 * We do not need CheckVarSlotCompatibility here; that was taken
812 * care of at compilation time. But see EEOP_INNER_VAR comments.
813 */
814 Assert(attnum >= 0 && attnum < scanslot->tts_nvalid);
815 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
816 resultslot->tts_values[resultnum] = scanslot->tts_values[attnum];
817 resultslot->tts_isnull[resultnum] = scanslot->tts_isnull[attnum];
818
819 EEO_NEXT();
820 }
821
823 {
824 int resultnum = op->d.assign_var.resultnum;
825 int attnum = op->d.assign_var.attnum;
826
827 /*
828 * We do not need CheckVarSlotCompatibility here; that was taken
829 * care of at compilation time. But see EEOP_INNER_VAR comments.
830 */
831 Assert(attnum >= 0 && attnum < oldslot->tts_nvalid);
832 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
833 resultslot->tts_values[resultnum] = oldslot->tts_values[attnum];
834 resultslot->tts_isnull[resultnum] = oldslot->tts_isnull[attnum];
835
836 EEO_NEXT();
837 }
838
840 {
841 int resultnum = op->d.assign_var.resultnum;
842 int attnum = op->d.assign_var.attnum;
843
844 /*
845 * We do not need CheckVarSlotCompatibility here; that was taken
846 * care of at compilation time. But see EEOP_INNER_VAR comments.
847 */
848 Assert(attnum >= 0 && attnum < newslot->tts_nvalid);
849 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
850 resultslot->tts_values[resultnum] = newslot->tts_values[attnum];
851 resultslot->tts_isnull[resultnum] = newslot->tts_isnull[attnum];
852
853 EEO_NEXT();
854 }
855
857 {
858 int resultnum = op->d.assign_tmp.resultnum;
859
860 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
861 resultslot->tts_values[resultnum] = state->resvalue;
862 resultslot->tts_isnull[resultnum] = state->resnull;
863
864 EEO_NEXT();
865 }
866
868 {
869 int resultnum = op->d.assign_tmp.resultnum;
870
871 Assert(resultnum >= 0 && resultnum < resultslot->tts_tupleDescriptor->natts);
872 resultslot->tts_isnull[resultnum] = state->resnull;
873 if (!resultslot->tts_isnull[resultnum])
874 resultslot->tts_values[resultnum] =
876 else
877 resultslot->tts_values[resultnum] = state->resvalue;
878
879 EEO_NEXT();
880 }
881
883 {
884 *op->resnull = op->d.constval.isnull;
885 *op->resvalue = op->d.constval.value;
886
887 EEO_NEXT();
888 }
889
890 /*
891 * Function-call implementations. Arguments have previously been
892 * evaluated directly into fcinfo->args.
893 *
894 * As both STRICT checks and function-usage are noticeable performance
895 * wise, and function calls are a very hot-path (they also back
896 * operators!), it's worth having so many separate opcodes.
897 *
898 * Note: the reason for using a temporary variable "d", here and in
899 * other places, is that some compilers think "*op->resvalue = f();"
900 * requires them to evaluate op->resvalue into a register before
901 * calling f(), just in case f() is able to modify op->resvalue
902 * somehow. The extra line of code can save a useless register spill
903 * and reload across the function call.
904 */
906 {
907 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
908 Datum d;
909
910 fcinfo->isnull = false;
911 d = op->d.func.fn_addr(fcinfo);
912 *op->resvalue = d;
913 *op->resnull = fcinfo->isnull;
914
915 EEO_NEXT();
916 }
917
919 {
920 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
921 NullableDatum *args = fcinfo->args;
922 int nargs = op->d.func.nargs;
923 Datum d;
924
925 /* strict function, so check for NULL args */
926 for (int argno = 0; argno < nargs; argno++)
927 {
928 if (args[argno].isnull)
929 {
930 *op->resnull = true;
931 goto strictfail;
932 }
933 }
934 fcinfo->isnull = false;
935 d = op->d.func.fn_addr(fcinfo);
936 *op->resvalue = d;
937 *op->resnull = fcinfo->isnull;
938
939 strictfail:
940 EEO_NEXT();
941 }
942
944 {
945 /* not common enough to inline */
946 ExecEvalFuncExprFusage(state, op, econtext);
947
948 EEO_NEXT();
949 }
950
952 {
953 /* not common enough to inline */
955
956 EEO_NEXT();
957 }
958
959 /*
960 * If any of its clauses is FALSE, an AND's result is FALSE regardless
961 * of the states of the rest of the clauses, so we can stop evaluating
962 * and return FALSE immediately. If none are FALSE and one or more is
963 * NULL, we return NULL; otherwise we return TRUE. This makes sense
964 * when you interpret NULL as "don't know": perhaps one of the "don't
965 * knows" would have been FALSE if we'd known its value. Only when
966 * all the inputs are known to be TRUE can we state confidently that
967 * the AND's result is TRUE.
968 */
970 {
971 *op->d.boolexpr.anynull = false;
972
973 /*
974 * EEOP_BOOL_AND_STEP_FIRST resets anynull, otherwise it's the
975 * same as EEOP_BOOL_AND_STEP - so fall through to that.
976 */
977
978 /* FALL THROUGH */
979 }
980
982 {
983 if (*op->resnull)
984 {
985 *op->d.boolexpr.anynull = true;
986 }
987 else if (!DatumGetBool(*op->resvalue))
988 {
989 /* result is already set to FALSE, need not change it */
990 /* bail out early */
991 EEO_JUMP(op->d.boolexpr.jumpdone);
992 }
993
994 EEO_NEXT();
995 }
996
998 {
999 if (*op->resnull)
1000 {
1001 /* result is already set to NULL, need not change it */
1002 }
1003 else if (!DatumGetBool(*op->resvalue))
1004 {
1005 /* result is already set to FALSE, need not change it */
1006
1007 /*
1008 * No point jumping early to jumpdone - would be same target
1009 * (as this is the last argument to the AND expression),
1010 * except more expensive.
1011 */
1012 }
1013 else if (*op->d.boolexpr.anynull)
1014 {
1015 *op->resvalue = (Datum) 0;
1016 *op->resnull = true;
1017 }
1018 else
1019 {
1020 /* result is already set to TRUE, need not change it */
1021 }
1022
1023 EEO_NEXT();
1024 }
1025
1026 /*
1027 * If any of its clauses is TRUE, an OR's result is TRUE regardless of
1028 * the states of the rest of the clauses, so we can stop evaluating
1029 * and return TRUE immediately. If none are TRUE and one or more is
1030 * NULL, we return NULL; otherwise we return FALSE. This makes sense
1031 * when you interpret NULL as "don't know": perhaps one of the "don't
1032 * knows" would have been TRUE if we'd known its value. Only when all
1033 * the inputs are known to be FALSE can we state confidently that the
1034 * OR's result is FALSE.
1035 */
1037 {
1038 *op->d.boolexpr.anynull = false;
1039
1040 /*
1041 * EEOP_BOOL_OR_STEP_FIRST resets anynull, otherwise it's the same
1042 * as EEOP_BOOL_OR_STEP - so fall through to that.
1043 */
1044
1045 /* FALL THROUGH */
1046 }
1047
1049 {
1050 if (*op->resnull)
1051 {
1052 *op->d.boolexpr.anynull = true;
1053 }
1054 else if (DatumGetBool(*op->resvalue))
1055 {
1056 /* result is already set to TRUE, need not change it */
1057 /* bail out early */
1058 EEO_JUMP(op->d.boolexpr.jumpdone);
1059 }
1060
1061 EEO_NEXT();
1062 }
1063
1065 {
1066 if (*op->resnull)
1067 {
1068 /* result is already set to NULL, need not change it */
1069 }
1070 else if (DatumGetBool(*op->resvalue))
1071 {
1072 /* result is already set to TRUE, need not change it */
1073
1074 /*
1075 * No point jumping to jumpdone - would be same target (as
1076 * this is the last argument to the AND expression), except
1077 * more expensive.
1078 */
1079 }
1080 else if (*op->d.boolexpr.anynull)
1081 {
1082 *op->resvalue = (Datum) 0;
1083 *op->resnull = true;
1084 }
1085 else
1086 {
1087 /* result is already set to FALSE, need not change it */
1088 }
1089
1090 EEO_NEXT();
1091 }
1092
1094 {
1095 /*
1096 * Evaluation of 'not' is simple... if expr is false, then return
1097 * 'true' and vice versa. It's safe to do this even on a
1098 * nominally null value, so we ignore resnull; that means that
1099 * NULL in produces NULL out, which is what we want.
1100 */
1101 *op->resvalue = BoolGetDatum(!DatumGetBool(*op->resvalue));
1102
1103 EEO_NEXT();
1104 }
1105
1107 {
1108 /* simplified version of BOOL_AND_STEP for use by ExecQual() */
1109
1110 /* If argument (also result) is false or null ... */
1111 if (*op->resnull ||
1112 !DatumGetBool(*op->resvalue))
1113 {
1114 /* ... bail out early, returning FALSE */
1115 *op->resnull = false;
1116 *op->resvalue = BoolGetDatum(false);
1117 EEO_JUMP(op->d.qualexpr.jumpdone);
1118 }
1119
1120 /*
1121 * Otherwise, leave the TRUE value in place, in case this is the
1122 * last qual. Then, TRUE is the correct answer.
1123 */
1124
1125 EEO_NEXT();
1126 }
1127
1129 {
1130 /* Unconditionally jump to target step */
1131 EEO_JUMP(op->d.jump.jumpdone);
1132 }
1133
1135 {
1136 /* Transfer control if current result is null */
1137 if (*op->resnull)
1138 EEO_JUMP(op->d.jump.jumpdone);
1139
1140 EEO_NEXT();
1141 }
1142
1144 {
1145 /* Transfer control if current result is non-null */
1146 if (!*op->resnull)
1147 EEO_JUMP(op->d.jump.jumpdone);
1148
1149 EEO_NEXT();
1150 }
1151
1153 {
1154 /* Transfer control if current result is null or false */
1155 if (*op->resnull || !DatumGetBool(*op->resvalue))
1156 EEO_JUMP(op->d.jump.jumpdone);
1157
1158 EEO_NEXT();
1159 }
1160
1162 {
1163 *op->resvalue = BoolGetDatum(*op->resnull);
1164 *op->resnull = false;
1165
1166 EEO_NEXT();
1167 }
1168
1170 {
1171 *op->resvalue = BoolGetDatum(!*op->resnull);
1172 *op->resnull = false;
1173
1174 EEO_NEXT();
1175 }
1176
1178 {
1179 /* out of line implementation: too large */
1180 ExecEvalRowNull(state, op, econtext);
1181
1182 EEO_NEXT();
1183 }
1184
1186 {
1187 /* out of line implementation: too large */
1188 ExecEvalRowNotNull(state, op, econtext);
1189
1190 EEO_NEXT();
1191 }
1192
1193 /* BooleanTest implementations for all booltesttypes */
1194
1196 {
1197 if (*op->resnull)
1198 {
1199 *op->resvalue = BoolGetDatum(false);
1200 *op->resnull = false;
1201 }
1202 /* else, input value is the correct output as well */
1203
1204 EEO_NEXT();
1205 }
1206
1208 {
1209 if (*op->resnull)
1210 {
1211 *op->resvalue = BoolGetDatum(true);
1212 *op->resnull = false;
1213 }
1214 else
1215 *op->resvalue = BoolGetDatum(!DatumGetBool(*op->resvalue));
1216
1217 EEO_NEXT();
1218 }
1219
1221 {
1222 if (*op->resnull)
1223 {
1224 *op->resvalue = BoolGetDatum(false);
1225 *op->resnull = false;
1226 }
1227 else
1228 *op->resvalue = BoolGetDatum(!DatumGetBool(*op->resvalue));
1229
1230 EEO_NEXT();
1231 }
1232
1234 {
1235 if (*op->resnull)
1236 {
1237 *op->resvalue = BoolGetDatum(true);
1238 *op->resnull = false;
1239 }
1240 /* else, input value is the correct output as well */
1241
1242 EEO_NEXT();
1243 }
1244
1246 {
1247 /* out of line implementation: too large */
1248 ExecEvalParamExec(state, op, econtext);
1249
1250 EEO_NEXT();
1251 }
1252
1254 {
1255 /* out of line implementation: too large */
1256 ExecEvalParamExtern(state, op, econtext);
1257 EEO_NEXT();
1258 }
1259
1261 {
1262 /* allow an extension module to supply a PARAM_EXTERN value */
1263 op->d.cparam.paramfunc(state, op, econtext);
1264 EEO_NEXT();
1265 }
1266
1268 {
1269 /* out of line, unlikely to matter performance-wise */
1270 ExecEvalParamSet(state, op, econtext);
1271 EEO_NEXT();
1272 }
1273
1275 {
1276 /*
1277 * Normally upper parts of the expression tree have setup the
1278 * values to be returned here, but some parts of the system
1279 * currently misuse {caseValue,domainValue}_{datum,isNull} to set
1280 * run-time data. So if no values have been set-up, use
1281 * ExprContext's. This isn't pretty, but also not *that* ugly,
1282 * and this is unlikely to be performance sensitive enough to
1283 * worry about an extra branch.
1284 */
1285 if (op->d.casetest.value)
1286 {
1287 *op->resvalue = *op->d.casetest.value;
1288 *op->resnull = *op->d.casetest.isnull;
1289 }
1290 else
1291 {
1292 *op->resvalue = econtext->caseValue_datum;
1293 *op->resnull = econtext->caseValue_isNull;
1294 }
1295
1296 EEO_NEXT();
1297 }
1298
1300 {
1301 /*
1302 * See EEOP_CASE_TESTVAL comment.
1303 */
1304 if (op->d.casetest.value)
1305 {
1306 *op->resvalue = *op->d.casetest.value;
1307 *op->resnull = *op->d.casetest.isnull;
1308 }
1309 else
1310 {
1311 *op->resvalue = econtext->domainValue_datum;
1312 *op->resnull = econtext->domainValue_isNull;
1313 }
1314
1315 EEO_NEXT();
1316 }
1317
1319 {
1320 /*
1321 * Force a varlena value that might be read multiple times to R/O
1322 */
1323 if (!*op->d.make_readonly.isnull)
1324 *op->resvalue =
1325 MakeExpandedObjectReadOnlyInternal(*op->d.make_readonly.value);
1326 *op->resnull = *op->d.make_readonly.isnull;
1327
1328 EEO_NEXT();
1329 }
1330
1332 {
1333 /*
1334 * Evaluate a CoerceViaIO node. This can be quite a hot path, so
1335 * inline as much work as possible. The source value is in our
1336 * result variable.
1337 *
1338 * Also look at ExecEvalCoerceViaIOSafe() if you change anything
1339 * here.
1340 */
1341 char *str;
1342
1343 /* call output function (similar to OutputFunctionCall) */
1344 if (*op->resnull)
1345 {
1346 /* output functions are not called on nulls */
1347 str = NULL;
1348 }
1349 else
1350 {
1351 FunctionCallInfo fcinfo_out;
1352
1353 fcinfo_out = op->d.iocoerce.fcinfo_data_out;
1354 fcinfo_out->args[0].value = *op->resvalue;
1355 fcinfo_out->args[0].isnull = false;
1356
1357 fcinfo_out->isnull = false;
1358 str = DatumGetCString(FunctionCallInvoke(fcinfo_out));
1359
1360 /* OutputFunctionCall assumes result isn't null */
1361 Assert(!fcinfo_out->isnull);
1362 }
1363
1364 /* call input function (similar to InputFunctionCall) */
1365 if (!op->d.iocoerce.finfo_in->fn_strict || str != NULL)
1366 {
1367 FunctionCallInfo fcinfo_in;
1368 Datum d;
1369
1370 fcinfo_in = op->d.iocoerce.fcinfo_data_in;
1371 fcinfo_in->args[0].value = PointerGetDatum(str);
1372 fcinfo_in->args[0].isnull = *op->resnull;
1373 /* second and third arguments are already set up */
1374
1375 fcinfo_in->isnull = false;
1376 d = FunctionCallInvoke(fcinfo_in);
1377 *op->resvalue = d;
1378
1379 /* Should get null result if and only if str is NULL */
1380 if (str == NULL)
1381 {
1382 Assert(*op->resnull);
1383 Assert(fcinfo_in->isnull);
1384 }
1385 else
1386 {
1387 Assert(!*op->resnull);
1388 Assert(!fcinfo_in->isnull);
1389 }
1390 }
1391
1392 EEO_NEXT();
1393 }
1394
1396 {
1398 EEO_NEXT();
1399 }
1400
1402 {
1403 /*
1404 * IS DISTINCT FROM must evaluate arguments (already done into
1405 * fcinfo->args) to determine whether they are NULL; if either is
1406 * NULL then the result is determined. If neither is NULL, then
1407 * proceed to evaluate the comparison function, which is just the
1408 * type's standard equality operator. We need not care whether
1409 * that function is strict. Because the handling of nulls is
1410 * different, we can't just reuse EEOP_FUNCEXPR.
1411 */
1412 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
1413
1414 /* check function arguments for NULLness */
1415 if (fcinfo->args[0].isnull && fcinfo->args[1].isnull)
1416 {
1417 /* Both NULL? Then is not distinct... */
1418 *op->resvalue = BoolGetDatum(false);
1419 *op->resnull = false;
1420 }
1421 else if (fcinfo->args[0].isnull || fcinfo->args[1].isnull)
1422 {
1423 /* Only one is NULL? Then is distinct... */
1424 *op->resvalue = BoolGetDatum(true);
1425 *op->resnull = false;
1426 }
1427 else
1428 {
1429 /* Neither null, so apply the equality function */
1430 Datum eqresult;
1431
1432 fcinfo->isnull = false;
1433 eqresult = op->d.func.fn_addr(fcinfo);
1434 /* Must invert result of "="; safe to do even if null */
1435 *op->resvalue = BoolGetDatum(!DatumGetBool(eqresult));
1436 *op->resnull = fcinfo->isnull;
1437 }
1438
1439 EEO_NEXT();
1440 }
1441
1442 /* see EEOP_DISTINCT for comments, this is just inverted */
1444 {
1445 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
1446
1447 if (fcinfo->args[0].isnull && fcinfo->args[1].isnull)
1448 {
1449 *op->resvalue = BoolGetDatum(true);
1450 *op->resnull = false;
1451 }
1452 else if (fcinfo->args[0].isnull || fcinfo->args[1].isnull)
1453 {
1454 *op->resvalue = BoolGetDatum(false);
1455 *op->resnull = false;
1456 }
1457 else
1458 {
1459 Datum eqresult;
1460
1461 fcinfo->isnull = false;
1462 eqresult = op->d.func.fn_addr(fcinfo);
1463 *op->resvalue = eqresult;
1464 *op->resnull = fcinfo->isnull;
1465 }
1466
1467 EEO_NEXT();
1468 }
1469
1471 {
1472 /*
1473 * The arguments are already evaluated into fcinfo->args.
1474 */
1475 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
1476 Datum save_arg0 = fcinfo->args[0].value;
1477
1478 /* if either argument is NULL they can't be equal */
1479 if (!fcinfo->args[0].isnull && !fcinfo->args[1].isnull)
1480 {
1481 Datum result;
1482
1483 /*
1484 * If first argument is of varlena type, it might be an
1485 * expanded datum. We need to ensure that the value passed to
1486 * the comparison function is a read-only pointer. However,
1487 * if we end by returning the first argument, that will be the
1488 * original read-write pointer if it was read-write.
1489 */
1490 if (op->d.func.make_ro)
1491 fcinfo->args[0].value =
1493
1494 fcinfo->isnull = false;
1495 result = op->d.func.fn_addr(fcinfo);
1496
1497 /* if the arguments are equal return null */
1498 if (!fcinfo->isnull && DatumGetBool(result))
1499 {
1500 *op->resvalue = (Datum) 0;
1501 *op->resnull = true;
1502
1503 EEO_NEXT();
1504 }
1505 }
1506
1507 /* Arguments aren't equal, so return the first one */
1508 *op->resvalue = save_arg0;
1509 *op->resnull = fcinfo->args[0].isnull;
1510
1511 EEO_NEXT();
1512 }
1513
1515 {
1516 /*
1517 * Doesn't seem worthwhile to have an inline implementation
1518 * efficiency-wise.
1519 */
1521
1522 EEO_NEXT();
1523 }
1524
1526 {
1527 /* error invocation uses space, and shouldn't ever occur */
1529
1530 EEO_NEXT();
1531 }
1532
1534 {
1535 /*
1536 * Doesn't seem worthwhile to have an inline implementation
1537 * efficiency-wise.
1538 */
1540
1541 EEO_NEXT();
1542 }
1543
1545 {
1546 /*
1547 * The next op actually evaluates the expression. If the OLD/NEW
1548 * row doesn't exist, skip that and return NULL.
1549 */
1550 if (state->flags & op->d.returningexpr.nullflag)
1551 {
1552 *op->resvalue = (Datum) 0;
1553 *op->resnull = true;
1554
1555 EEO_JUMP(op->d.returningexpr.jumpdone);
1556 }
1557
1558 EEO_NEXT();
1559 }
1560
1562 {
1563 /* too complex for an inline implementation */
1565
1566 EEO_NEXT();
1567 }
1568
1570 {
1571 /* too complex for an inline implementation */
1572 ExecEvalArrayCoerce(state, op, econtext);
1573
1574 EEO_NEXT();
1575 }
1576
1578 {
1579 /* too complex for an inline implementation */
1581
1582 EEO_NEXT();
1583 }
1584
1586 {
1587 FunctionCallInfo fcinfo = op->d.rowcompare_step.fcinfo_data;
1588 Datum d;
1589
1590 /* force NULL result if strict fn and NULL input */
1591 if (op->d.rowcompare_step.finfo->fn_strict &&
1592 (fcinfo->args[0].isnull || fcinfo->args[1].isnull))
1593 {
1594 *op->resnull = true;
1595 EEO_JUMP(op->d.rowcompare_step.jumpnull);
1596 }
1597
1598 /* Apply comparison function */
1599 fcinfo->isnull = false;
1600 d = op->d.rowcompare_step.fn_addr(fcinfo);
1601 *op->resvalue = d;
1602
1603 /* force NULL result if NULL function result */
1604 if (fcinfo->isnull)
1605 {
1606 *op->resnull = true;
1607 EEO_JUMP(op->d.rowcompare_step.jumpnull);
1608 }
1609 *op->resnull = false;
1610
1611 /* If unequal, no need to compare remaining columns */
1612 if (DatumGetInt32(*op->resvalue) != 0)
1613 {
1614 EEO_JUMP(op->d.rowcompare_step.jumpdone);
1615 }
1616
1617 EEO_NEXT();
1618 }
1619
1621 {
1622 int32 cmpresult = DatumGetInt32(*op->resvalue);
1623 CompareType cmptype = op->d.rowcompare_final.cmptype;
1624
1625 *op->resnull = false;
1626 switch (cmptype)
1627 {
1628 /* EQ and NE cases aren't allowed here */
1629 case COMPARE_LT:
1630 *op->resvalue = BoolGetDatum(cmpresult < 0);
1631 break;
1632 case COMPARE_LE:
1633 *op->resvalue = BoolGetDatum(cmpresult <= 0);
1634 break;
1635 case COMPARE_GE:
1636 *op->resvalue = BoolGetDatum(cmpresult >= 0);
1637 break;
1638 case COMPARE_GT:
1639 *op->resvalue = BoolGetDatum(cmpresult > 0);
1640 break;
1641 default:
1642 Assert(false);
1643 break;
1644 }
1645
1646 EEO_NEXT();
1647 }
1648
1650 {
1651 /* too complex for an inline implementation */
1653
1654 EEO_NEXT();
1655 }
1656
1658 {
1659 /* too complex for an inline implementation */
1660 ExecEvalFieldSelect(state, op, econtext);
1661
1662 EEO_NEXT();
1663 }
1664
1666 {
1667 /* too complex for an inline implementation */
1668 ExecEvalFieldStoreDeForm(state, op, econtext);
1669
1670 EEO_NEXT();
1671 }
1672
1674 {
1675 /* too complex for an inline implementation */
1676 ExecEvalFieldStoreForm(state, op, econtext);
1677
1678 EEO_NEXT();
1679 }
1680
1682 {
1683 /* Precheck SubscriptingRef subscript(s) */
1684 if (op->d.sbsref_subscript.subscriptfunc(state, op, econtext))
1685 {
1686 EEO_NEXT();
1687 }
1688 else
1689 {
1690 /* Subscript is null, short-circuit SubscriptingRef to NULL */
1691 EEO_JUMP(op->d.sbsref_subscript.jumpdone);
1692 }
1693 }
1694
1698 {
1699 /* Perform a SubscriptingRef fetch or assignment */
1700 op->d.sbsref.subscriptfunc(state, op, econtext);
1701
1702 EEO_NEXT();
1703 }
1704
1706 {
1707 /* too complex for an inline implementation */
1708 ExecEvalConvertRowtype(state, op, econtext);
1709
1710 EEO_NEXT();
1711 }
1712
1714 {
1715 /* too complex for an inline implementation */
1717
1718 EEO_NEXT();
1719 }
1720
1722 {
1723 /* too complex for an inline implementation */
1725
1726 EEO_NEXT();
1727 }
1728
1730 {
1731 /* too complex for an inline implementation */
1733
1734 EEO_NEXT();
1735 }
1736
1738 {
1739 /* too complex for an inline implementation */
1741
1742 EEO_NEXT();
1743 }
1744
1746 {
1747 *op->resvalue = op->d.hashdatum_initvalue.init_value;
1748 *op->resnull = false;
1749
1750 EEO_NEXT();
1751 }
1752
1754 {
1755 FunctionCallInfo fcinfo = op->d.hashdatum.fcinfo_data;
1756
1757 /*
1758 * Save the Datum on non-null inputs, otherwise store 0 so that
1759 * subsequent NEXT32 operations combine with an initialized value.
1760 */
1761 if (!fcinfo->args[0].isnull)
1762 *op->resvalue = op->d.hashdatum.fn_addr(fcinfo);
1763 else
1764 *op->resvalue = (Datum) 0;
1765
1766 *op->resnull = false;
1767
1768 EEO_NEXT();
1769 }
1770
1772 {
1773 FunctionCallInfo fcinfo = op->d.hashdatum.fcinfo_data;
1774
1775 if (fcinfo->args[0].isnull)
1776 {
1777 /*
1778 * With strict we have the expression return NULL instead of
1779 * ignoring NULL input values. We've nothing more to do after
1780 * finding a NULL.
1781 */
1782 *op->resnull = true;
1783 *op->resvalue = (Datum) 0;
1784 EEO_JUMP(op->d.hashdatum.jumpdone);
1785 }
1786
1787 /* execute the hash function and save the resulting value */
1788 *op->resvalue = op->d.hashdatum.fn_addr(fcinfo);
1789 *op->resnull = false;
1790
1791 EEO_NEXT();
1792 }
1793
1795 {
1796 FunctionCallInfo fcinfo = op->d.hashdatum.fcinfo_data;
1797 uint32 existinghash;
1798
1799 existinghash = DatumGetUInt32(op->d.hashdatum.iresult->value);
1800 /* combine successive hash values by rotating */
1801 existinghash = pg_rotate_left32(existinghash, 1);
1802
1803 /* leave the hash value alone on NULL inputs */
1804 if (!fcinfo->args[0].isnull)
1805 {
1806 uint32 hashvalue;
1807
1808 /* execute hash func and combine with previous hash value */
1809 hashvalue = DatumGetUInt32(op->d.hashdatum.fn_addr(fcinfo));
1810 existinghash = existinghash ^ hashvalue;
1811 }
1812
1813 *op->resvalue = UInt32GetDatum(existinghash);
1814 *op->resnull = false;
1815
1816 EEO_NEXT();
1817 }
1818
1820 {
1821 FunctionCallInfo fcinfo = op->d.hashdatum.fcinfo_data;
1822
1823 if (fcinfo->args[0].isnull)
1824 {
1825 /*
1826 * With strict we have the expression return NULL instead of
1827 * ignoring NULL input values. We've nothing more to do after
1828 * finding a NULL.
1829 */
1830 *op->resnull = true;
1831 *op->resvalue = (Datum) 0;
1832 EEO_JUMP(op->d.hashdatum.jumpdone);
1833 }
1834 else
1835 {
1836 uint32 existinghash;
1837 uint32 hashvalue;
1838
1839 existinghash = DatumGetUInt32(op->d.hashdatum.iresult->value);
1840 /* combine successive hash values by rotating */
1841 existinghash = pg_rotate_left32(existinghash, 1);
1842
1843 /* execute hash func and combine with previous hash value */
1844 hashvalue = DatumGetUInt32(op->d.hashdatum.fn_addr(fcinfo));
1845 *op->resvalue = UInt32GetDatum(existinghash ^ hashvalue);
1846 *op->resnull = false;
1847 }
1848
1849 EEO_NEXT();
1850 }
1851
1853 {
1854 /* too complex for an inline implementation */
1856
1857 EEO_NEXT();
1858 }
1859
1861 {
1862 /* too complex for an inline implementation */
1863 ExecEvalJsonConstructor(state, op, econtext);
1864 EEO_NEXT();
1865 }
1866
1868 {
1869 /* too complex for an inline implementation */
1871
1872 EEO_NEXT();
1873 }
1874
1876 {
1877 /* too complex for an inline implementation */
1879 }
1880
1882 {
1883 /* too complex for an inline implementation */
1884 ExecEvalJsonCoercion(state, op, econtext);
1885
1886 EEO_NEXT();
1887 }
1888
1890 {
1891 /* too complex for an inline implementation */
1893
1894 EEO_NEXT();
1895 }
1896
1898 {
1899 /*
1900 * Returns a Datum whose value is the precomputed aggregate value
1901 * found in the given expression context.
1902 */
1903 int aggno = op->d.aggref.aggno;
1904
1905 Assert(econtext->ecxt_aggvalues != NULL);
1906
1907 *op->resvalue = econtext->ecxt_aggvalues[aggno];
1908 *op->resnull = econtext->ecxt_aggnulls[aggno];
1909
1910 EEO_NEXT();
1911 }
1912
1914 {
1915 /* too complex/uncommon for an inline implementation */
1917
1918 EEO_NEXT();
1919 }
1920
1922 {
1923 /*
1924 * Like Aggref, just return a precomputed value from the econtext.
1925 */
1926 WindowFuncExprState *wfunc = op->d.window_func.wfstate;
1927
1928 Assert(econtext->ecxt_aggvalues != NULL);
1929
1930 *op->resvalue = econtext->ecxt_aggvalues[wfunc->wfuncno];
1931 *op->resnull = econtext->ecxt_aggnulls[wfunc->wfuncno];
1932
1933 EEO_NEXT();
1934 }
1935
1937 {
1938 /* too complex/uncommon for an inline implementation */
1939 ExecEvalMergeSupportFunc(state, op, econtext);
1940
1941 EEO_NEXT();
1942 }
1943
1945 {
1946 /* too complex for an inline implementation */
1947 ExecEvalSubPlan(state, op, econtext);
1948
1949 EEO_NEXT();
1950 }
1951
1952 /* evaluate a strict aggregate deserialization function */
1954 {
1955 /* Don't call a strict deserialization function with NULL input */
1956 if (op->d.agg_deserialize.fcinfo_data->args[0].isnull)
1957 EEO_JUMP(op->d.agg_deserialize.jumpnull);
1958
1959 /* fallthrough */
1960 }
1961
1962 /* evaluate aggregate deserialization function (non-strict portion) */
1964 {
1965 FunctionCallInfo fcinfo = op->d.agg_deserialize.fcinfo_data;
1966 AggState *aggstate = castNode(AggState, state->parent);
1967 MemoryContext oldContext;
1968
1969 /*
1970 * We run the deserialization functions in per-input-tuple memory
1971 * context.
1972 */
1974 fcinfo->isnull = false;
1975 *op->resvalue = FunctionCallInvoke(fcinfo);
1976 *op->resnull = fcinfo->isnull;
1977 MemoryContextSwitchTo(oldContext);
1978
1979 EEO_NEXT();
1980 }
1981
1982 /*
1983 * Check that a strict aggregate transition / combination function's
1984 * input is not NULL.
1985 */
1986
1988 {
1989 NullableDatum *args = op->d.agg_strict_input_check.args;
1990 int nargs = op->d.agg_strict_input_check.nargs;
1991
1992 for (int argno = 0; argno < nargs; argno++)
1993 {
1994 if (args[argno].isnull)
1995 EEO_JUMP(op->d.agg_strict_input_check.jumpnull);
1996 }
1997 EEO_NEXT();
1998 }
1999
2001 {
2002 bool *nulls = op->d.agg_strict_input_check.nulls;
2003 int nargs = op->d.agg_strict_input_check.nargs;
2004
2005 for (int argno = 0; argno < nargs; argno++)
2006 {
2007 if (nulls[argno])
2008 EEO_JUMP(op->d.agg_strict_input_check.jumpnull);
2009 }
2010 EEO_NEXT();
2011 }
2012
2013 /*
2014 * Check for a NULL pointer to the per-group states.
2015 */
2016
2018 {
2019 AggState *aggstate = castNode(AggState, state->parent);
2020 AggStatePerGroup pergroup_allaggs =
2021 aggstate->all_pergroups[op->d.agg_plain_pergroup_nullcheck.setoff];
2022
2023 if (pergroup_allaggs == NULL)
2024 EEO_JUMP(op->d.agg_plain_pergroup_nullcheck.jumpnull);
2025
2026 EEO_NEXT();
2027 }
2028
2029 /*
2030 * Different types of aggregate transition functions are implemented
2031 * as different types of steps, to avoid incurring unnecessary
2032 * overhead. There's a step type for each valid combination of having
2033 * a by value / by reference transition type, [not] needing to the
2034 * initialize the transition value for the first row in a group from
2035 * input, and [not] strict transition function.
2036 *
2037 * Could optimize further by splitting off by-reference for
2038 * fixed-length types, but currently that doesn't seem worth it.
2039 */
2040
2042 {
2043 AggState *aggstate = castNode(AggState, state->parent);
2044 AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
2045 AggStatePerGroup pergroup =
2046 &aggstate->all_pergroups[op->d.agg_trans.setoff][op->d.agg_trans.transno];
2047
2049
2050 if (pergroup->noTransValue)
2051 {
2052 /* If transValue has not yet been initialized, do so now. */
2053 ExecAggInitGroup(aggstate, pertrans, pergroup,
2054 op->d.agg_trans.aggcontext);
2055 /* copied trans value from input, done this round */
2056 }
2057 else if (likely(!pergroup->transValueIsNull))
2058 {
2059 /* invoke transition function, unless prevented by strictness */
2060 ExecAggPlainTransByVal(aggstate, pertrans, pergroup,
2061 op->d.agg_trans.aggcontext,
2062 op->d.agg_trans.setno);
2063 }
2064
2065 EEO_NEXT();
2066 }
2067
2068 /* see comments above EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL */
2070 {
2071 AggState *aggstate = castNode(AggState, state->parent);
2072 AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
2073 AggStatePerGroup pergroup =
2074 &aggstate->all_pergroups[op->d.agg_trans.setoff][op->d.agg_trans.transno];
2075
2077
2078 if (likely(!pergroup->transValueIsNull))
2079 ExecAggPlainTransByVal(aggstate, pertrans, pergroup,
2080 op->d.agg_trans.aggcontext,
2081 op->d.agg_trans.setno);
2082
2083 EEO_NEXT();
2084 }
2085
2086 /* see comments above EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL */
2088 {
2089 AggState *aggstate = castNode(AggState, state->parent);
2090 AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
2091 AggStatePerGroup pergroup =
2092 &aggstate->all_pergroups[op->d.agg_trans.setoff][op->d.agg_trans.transno];
2093
2095
2096 ExecAggPlainTransByVal(aggstate, pertrans, pergroup,
2097 op->d.agg_trans.aggcontext,
2098 op->d.agg_trans.setno);
2099
2100 EEO_NEXT();
2101 }
2102
2103 /* see comments above EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL */
2105 {
2106 AggState *aggstate = castNode(AggState, state->parent);
2107 AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
2108 AggStatePerGroup pergroup =
2109 &aggstate->all_pergroups[op->d.agg_trans.setoff][op->d.agg_trans.transno];
2110
2112
2113 if (pergroup->noTransValue)
2114 ExecAggInitGroup(aggstate, pertrans, pergroup,
2115 op->d.agg_trans.aggcontext);
2116 else if (likely(!pergroup->transValueIsNull))
2117 ExecAggPlainTransByRef(aggstate, pertrans, pergroup,
2118 op->d.agg_trans.aggcontext,
2119 op->d.agg_trans.setno);
2120
2121 EEO_NEXT();
2122 }
2123
2124 /* see comments above EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL */
2126 {
2127 AggState *aggstate = castNode(AggState, state->parent);
2128 AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
2129 AggStatePerGroup pergroup =
2130 &aggstate->all_pergroups[op->d.agg_trans.setoff][op->d.agg_trans.transno];
2131
2133
2134 if (likely(!pergroup->transValueIsNull))
2135 ExecAggPlainTransByRef(aggstate, pertrans, pergroup,
2136 op->d.agg_trans.aggcontext,
2137 op->d.agg_trans.setno);
2138 EEO_NEXT();
2139 }
2140
2141 /* see comments above EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL */
2143 {
2144 AggState *aggstate = castNode(AggState, state->parent);
2145 AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
2146 AggStatePerGroup pergroup =
2147 &aggstate->all_pergroups[op->d.agg_trans.setoff][op->d.agg_trans.transno];
2148
2150
2151 ExecAggPlainTransByRef(aggstate, pertrans, pergroup,
2152 op->d.agg_trans.aggcontext,
2153 op->d.agg_trans.setno);
2154
2155 EEO_NEXT();
2156 }
2157
2159 {
2160 AggStatePerTrans pertrans = op->d.agg_presorted_distinctcheck.pertrans;
2161 AggState *aggstate = castNode(AggState, state->parent);
2162
2164 EEO_NEXT();
2165 else
2166 EEO_JUMP(op->d.agg_presorted_distinctcheck.jumpdistinct);
2167 }
2168
2170 {
2171 AggState *aggstate = castNode(AggState, state->parent);
2172 AggStatePerTrans pertrans = op->d.agg_presorted_distinctcheck.pertrans;
2173
2175 EEO_NEXT();
2176 else
2177 EEO_JUMP(op->d.agg_presorted_distinctcheck.jumpdistinct);
2178 }
2179
2180 /* process single-column ordered aggregate datum */
2182 {
2183 /* too complex for an inline implementation */
2185
2186 EEO_NEXT();
2187 }
2188
2189 /* process multi-column ordered aggregate tuple */
2191 {
2192 /* too complex for an inline implementation */
2194
2195 EEO_NEXT();
2196 }
2197
2199 {
2200 /* unreachable */
2201 Assert(false);
2202 goto out;
2203 }
2204 }
2205
2206out:
2207 *isnull = state->resnull;
2208 return state->resvalue;
2209}
2210
2211/*
2212 * Expression evaluation callback that performs extra checks before executing
2213 * the expression. Declared extern so other methods of execution can use it
2214 * too.
2215 */
2216Datum
2218{
2219 /*
2220 * First time through, check whether attribute matches Var. Might not be
2221 * ok anymore, due to schema changes.
2222 */
2223 CheckExprStillValid(state, econtext);
2224
2225 /* skip the check during further executions */
2226 state->evalfunc = (ExprStateEvalFunc) state->evalfunc_private;
2227
2228 /* and actually execute */
2229 return state->evalfunc(state, econtext, isNull);
2230}
2231
2232/*
2233 * Check that an expression is still valid in the face of potential schema
2234 * changes since the plan has been created.
2235 */
2236void
2238{
2239 TupleTableSlot *innerslot;
2240 TupleTableSlot *outerslot;
2241 TupleTableSlot *scanslot;
2242 TupleTableSlot *oldslot;
2243 TupleTableSlot *newslot;
2244
2245 innerslot = econtext->ecxt_innertuple;
2246 outerslot = econtext->ecxt_outertuple;
2247 scanslot = econtext->ecxt_scantuple;
2248 oldslot = econtext->ecxt_oldtuple;
2249 newslot = econtext->ecxt_newtuple;
2250
2251 for (int i = 0; i < state->steps_len; i++)
2252 {
2253 ExprEvalStep *op = &state->steps[i];
2254
2255 switch (ExecEvalStepOp(state, op))
2256 {
2257 case EEOP_INNER_VAR:
2258 {
2259 int attnum = op->d.var.attnum;
2260
2261 CheckVarSlotCompatibility(innerslot, attnum + 1, op->d.var.vartype);
2262 break;
2263 }
2264
2265 case EEOP_OUTER_VAR:
2266 {
2267 int attnum = op->d.var.attnum;
2268
2269 CheckVarSlotCompatibility(outerslot, attnum + 1, op->d.var.vartype);
2270 break;
2271 }
2272
2273 case EEOP_SCAN_VAR:
2274 {
2275 int attnum = op->d.var.attnum;
2276
2277 CheckVarSlotCompatibility(scanslot, attnum + 1, op->d.var.vartype);
2278 break;
2279 }
2280
2281 case EEOP_OLD_VAR:
2282 {
2283 int attnum = op->d.var.attnum;
2284
2285 CheckVarSlotCompatibility(oldslot, attnum + 1, op->d.var.vartype);
2286 break;
2287 }
2288
2289 case EEOP_NEW_VAR:
2290 {
2291 int attnum = op->d.var.attnum;
2292
2293 CheckVarSlotCompatibility(newslot, attnum + 1, op->d.var.vartype);
2294 break;
2295 }
2296 default:
2297 break;
2298 }
2299 }
2300}
2301
2302/*
2303 * Check whether a user attribute in a slot can be referenced by a Var
2304 * expression. This should succeed unless there have been schema changes
2305 * since the expression tree has been created.
2306 */
2307static void
2309{
2310 /*
2311 * What we have to check for here is the possibility of an attribute
2312 * having been dropped or changed in type since the plan tree was created.
2313 * Ideally the plan will get invalidated and not re-used, but just in
2314 * case, we keep these defenses. Fortunately it's sufficient to check
2315 * once on the first time through.
2316 *
2317 * Note: ideally we'd check typmod as well as typid, but that seems
2318 * impractical at the moment: in many cases the tupdesc will have been
2319 * generated by ExecTypeFromTL(), and that can't guarantee to generate an
2320 * accurate typmod in all cases, because some expression node types don't
2321 * carry typmod. Fortunately, for precisely that reason, there should be
2322 * no places with a critical dependency on the typmod of a value.
2323 *
2324 * System attributes don't require checking since their types never
2325 * change.
2326 */
2327 if (attnum > 0)
2328 {
2329 TupleDesc slot_tupdesc = slot->tts_tupleDescriptor;
2330 Form_pg_attribute attr;
2331
2332 if (attnum > slot_tupdesc->natts) /* should never happen */
2333 elog(ERROR, "attribute number %d exceeds number of columns %d",
2334 attnum, slot_tupdesc->natts);
2335
2336 attr = TupleDescAttr(slot_tupdesc, attnum - 1);
2337
2338 if (attr->attisdropped)
2339 ereport(ERROR,
2340 (errcode(ERRCODE_UNDEFINED_COLUMN),
2341 errmsg("attribute %d of type %s has been dropped",
2342 attnum, format_type_be(slot_tupdesc->tdtypeid))));
2343
2344 if (vartype != attr->atttypid)
2345 ereport(ERROR,
2346 (errcode(ERRCODE_DATATYPE_MISMATCH),
2347 errmsg("attribute %d of type %s has wrong type",
2348 attnum, format_type_be(slot_tupdesc->tdtypeid)),
2349 errdetail("Table has type %s, but query expects %s.",
2350 format_type_be(attr->atttypid),
2352 }
2353}
2354
2355/*
2356 * Verify that the slot is compatible with a EEOP_*_FETCHSOME operation.
2357 */
2358static void
2360{
2361#ifdef USE_ASSERT_CHECKING
2362 /* there's nothing to check */
2363 if (!op->d.fetch.fixed)
2364 return;
2365
2366 /*
2367 * Should probably fixed at some point, but for now it's easier to allow
2368 * buffer and heap tuples to be used interchangeably.
2369 */
2370 if (slot->tts_ops == &TTSOpsBufferHeapTuple &&
2371 op->d.fetch.kind == &TTSOpsHeapTuple)
2372 return;
2373 if (slot->tts_ops == &TTSOpsHeapTuple &&
2374 op->d.fetch.kind == &TTSOpsBufferHeapTuple)
2375 return;
2376
2377 /*
2378 * At the moment we consider it OK if a virtual slot is used instead of a
2379 * specific type of slot, as a virtual slot never needs to be deformed.
2380 */
2381 if (slot->tts_ops == &TTSOpsVirtual)
2382 return;
2383
2384 Assert(op->d.fetch.kind == slot->tts_ops);
2385#endif
2386}
2387
2388/*
2389 * get_cached_rowtype: utility function to lookup a rowtype tupdesc
2390 *
2391 * type_id, typmod: identity of the rowtype
2392 * rowcache: space for caching identity info
2393 * (rowcache->cacheptr must be initialized to NULL)
2394 * changed: if not NULL, *changed is set to true on any update
2395 *
2396 * The returned TupleDesc is not guaranteed pinned; caller must pin it
2397 * to use it across any operation that might incur cache invalidation,
2398 * including for example detoasting of input tuples.
2399 * (The TupleDesc is always refcounted, so just use IncrTupleDescRefCount.)
2400 *
2401 * NOTE: because composite types can change contents, we must be prepared
2402 * to re-do this during any node execution; cannot call just once during
2403 * expression initialization.
2404 */
2405static TupleDesc
2408 bool *changed)
2409{
2410 if (type_id != RECORDOID)
2411 {
2412 /*
2413 * It's a named composite type, so use the regular typcache. Do a
2414 * lookup first time through, or if the composite type changed. Note:
2415 * "tupdesc_id == 0" may look redundant, but it protects against the
2416 * admittedly-theoretical possibility that type_id was RECORDOID the
2417 * last time through, so that the cacheptr isn't TypeCacheEntry *.
2418 */
2420
2421 if (unlikely(typentry == NULL ||
2422 rowcache->tupdesc_id == 0 ||
2423 typentry->tupDesc_identifier != rowcache->tupdesc_id))
2424 {
2425 typentry = lookup_type_cache(type_id, TYPECACHE_TUPDESC);
2426 if (typentry->tupDesc == NULL)
2427 ereport(ERROR,
2428 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2429 errmsg("type %s is not composite",
2430 format_type_be(type_id))));
2431 rowcache->cacheptr = typentry;
2433 if (changed)
2434 *changed = true;
2435 }
2436 return typentry->tupDesc;
2437 }
2438 else
2439 {
2440 /*
2441 * A RECORD type, once registered, doesn't change for the life of the
2442 * backend. So we don't need a typcache entry as such, which is good
2443 * because there isn't one. It's possible that the caller is asking
2444 * about a different type than before, though.
2445 */
2446 TupleDesc tupDesc = (TupleDesc) rowcache->cacheptr;
2447
2448 if (unlikely(tupDesc == NULL ||
2449 rowcache->tupdesc_id != 0 ||
2450 type_id != tupDesc->tdtypeid ||
2451 typmod != tupDesc->tdtypmod))
2452 {
2453 tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
2454 /* Drop pin acquired by lookup_rowtype_tupdesc */
2455 ReleaseTupleDesc(tupDesc);
2456 rowcache->cacheptr = tupDesc;
2457 rowcache->tupdesc_id = 0; /* not a valid value for non-RECORD */
2458 if (changed)
2459 *changed = true;
2460 }
2461 return tupDesc;
2462 }
2463}
2464
2465
2466/*
2467 * Fast-path functions, for very simple expressions
2468 */
2469
2470/* implementation of ExecJust(Inner|Outer|Scan)Var */
2473{
2474 ExprEvalStep *op = &state->steps[1];
2475 int attnum = op->d.var.attnum + 1;
2476
2477 CheckOpSlotCompatibility(&state->steps[0], slot);
2478
2479 /*
2480 * Since we use slot_getattr(), we don't need to implement the FETCHSOME
2481 * step explicitly, and we also needn't Assert that the attnum is in range
2482 * --- slot_getattr() will take care of any problems.
2483 */
2484 return slot_getattr(slot, attnum, isnull);
2485}
2486
2487/* Simple reference to inner Var */
2488static Datum
2490{
2491 return ExecJustVarImpl(state, econtext->ecxt_innertuple, isnull);
2492}
2493
2494/* Simple reference to outer Var */
2495static Datum
2497{
2498 return ExecJustVarImpl(state, econtext->ecxt_outertuple, isnull);
2499}
2500
2501/* Simple reference to scan Var */
2502static Datum
2504{
2505 return ExecJustVarImpl(state, econtext->ecxt_scantuple, isnull);
2506}
2507
2508/* implementation of ExecJustAssign(Inner|Outer|Scan)Var */
2511{
2512 ExprEvalStep *op = &state->steps[1];
2513 int attnum = op->d.assign_var.attnum + 1;
2514 int resultnum = op->d.assign_var.resultnum;
2515 TupleTableSlot *outslot = state->resultslot;
2516
2517 CheckOpSlotCompatibility(&state->steps[0], inslot);
2518
2519 /*
2520 * We do not need CheckVarSlotCompatibility here; that was taken care of
2521 * at compilation time.
2522 *
2523 * Since we use slot_getattr(), we don't need to implement the FETCHSOME
2524 * step explicitly, and we also needn't Assert that the attnum is in range
2525 * --- slot_getattr() will take care of any problems. Nonetheless, check
2526 * that resultnum is in range.
2527 */
2528 Assert(resultnum >= 0 && resultnum < outslot->tts_tupleDescriptor->natts);
2529 outslot->tts_values[resultnum] =
2530 slot_getattr(inslot, attnum, &outslot->tts_isnull[resultnum]);
2531 return 0;
2532}
2533
2534/* Evaluate inner Var and assign to appropriate column of result tuple */
2535static Datum
2537{
2539}
2540
2541/* Evaluate outer Var and assign to appropriate column of result tuple */
2542static Datum
2544{
2546}
2547
2548/* Evaluate scan Var and assign to appropriate column of result tuple */
2549static Datum
2551{
2553}
2554
2555/* Evaluate CASE_TESTVAL and apply a strict function to it */
2556static Datum
2558{
2559 ExprEvalStep *op = &state->steps[0];
2560 FunctionCallInfo fcinfo;
2562 int nargs;
2563 Datum d;
2564
2565 /*
2566 * XXX with some redesign of the CaseTestExpr mechanism, maybe we could
2567 * get rid of this data shuffling?
2568 */
2569 *op->resvalue = *op->d.casetest.value;
2570 *op->resnull = *op->d.casetest.isnull;
2571
2572 op++;
2573
2574 nargs = op->d.func.nargs;
2575 fcinfo = op->d.func.fcinfo_data;
2576 args = fcinfo->args;
2577
2578 /* strict function, so check for NULL args */
2579 for (int argno = 0; argno < nargs; argno++)
2580 {
2581 if (args[argno].isnull)
2582 {
2583 *isnull = true;
2584 return (Datum) 0;
2585 }
2586 }
2587 fcinfo->isnull = false;
2588 d = op->d.func.fn_addr(fcinfo);
2589 *isnull = fcinfo->isnull;
2590 return d;
2591}
2592
2593/* Simple Const expression */
2594static Datum
2596{
2597 ExprEvalStep *op = &state->steps[0];
2598
2599 *isnull = op->d.constval.isnull;
2600 return op->d.constval.value;
2601}
2602
2603/* implementation of ExecJust(Inner|Outer|Scan)VarVirt */
2606{
2607 ExprEvalStep *op = &state->steps[0];
2608 int attnum = op->d.var.attnum;
2609
2610 /*
2611 * As it is guaranteed that a virtual slot is used, there never is a need
2612 * to perform tuple deforming (nor would it be possible). Therefore
2613 * execExpr.c has not emitted an EEOP_*_FETCHSOME step. Verify, as much as
2614 * possible, that that determination was accurate.
2615 */
2616 Assert(TTS_IS_VIRTUAL(slot));
2617 Assert(TTS_FIXED(slot));
2618 Assert(attnum >= 0 && attnum < slot->tts_nvalid);
2619
2620 *isnull = slot->tts_isnull[attnum];
2621
2622 return slot->tts_values[attnum];
2623}
2624
2625/* Like ExecJustInnerVar, optimized for virtual slots */
2626static Datum
2628{
2629 return ExecJustVarVirtImpl(state, econtext->ecxt_innertuple, isnull);
2630}
2631
2632/* Like ExecJustOuterVar, optimized for virtual slots */
2633static Datum
2635{
2636 return ExecJustVarVirtImpl(state, econtext->ecxt_outertuple, isnull);
2637}
2638
2639/* Like ExecJustScanVar, optimized for virtual slots */
2640static Datum
2642{
2643 return ExecJustVarVirtImpl(state, econtext->ecxt_scantuple, isnull);
2644}
2645
2646/* implementation of ExecJustAssign(Inner|Outer|Scan)VarVirt */
2649{
2650 ExprEvalStep *op = &state->steps[0];
2651 int attnum = op->d.assign_var.attnum;
2652 int resultnum = op->d.assign_var.resultnum;
2653 TupleTableSlot *outslot = state->resultslot;
2654
2655 /* see ExecJustVarVirtImpl for comments */
2656
2657 Assert(TTS_IS_VIRTUAL(inslot));
2658 Assert(TTS_FIXED(inslot));
2659 Assert(attnum >= 0 && attnum < inslot->tts_nvalid);
2660 Assert(resultnum >= 0 && resultnum < outslot->tts_tupleDescriptor->natts);
2661
2662 outslot->tts_values[resultnum] = inslot->tts_values[attnum];
2663 outslot->tts_isnull[resultnum] = inslot->tts_isnull[attnum];
2664
2665 return 0;
2666}
2667
2668/* Like ExecJustAssignInnerVar, optimized for virtual slots */
2669static Datum
2671{
2673}
2674
2675/* Like ExecJustAssignOuterVar, optimized for virtual slots */
2676static Datum
2678{
2680}
2681
2682/* Like ExecJustAssignScanVar, optimized for virtual slots */
2683static Datum
2685{
2687}
2688
2689/*
2690 * implementation for hashing an inner Var, seeding with an initial value.
2691 */
2692static Datum
2694 bool *isnull)
2695{
2696 ExprEvalStep *fetchop = &state->steps[0];
2697 ExprEvalStep *setivop = &state->steps[1];
2698 ExprEvalStep *innervar = &state->steps[2];
2699 ExprEvalStep *hashop = &state->steps[3];
2700 FunctionCallInfo fcinfo = hashop->d.hashdatum.fcinfo_data;
2701 int attnum = innervar->d.var.attnum;
2702 uint32 hashkey;
2703
2704 CheckOpSlotCompatibility(fetchop, econtext->ecxt_innertuple);
2705 slot_getsomeattrs(econtext->ecxt_innertuple, fetchop->d.fetch.last_var);
2706
2707 fcinfo->args[0].value = econtext->ecxt_innertuple->tts_values[attnum];
2708 fcinfo->args[0].isnull = econtext->ecxt_innertuple->tts_isnull[attnum];
2709
2710 hashkey = DatumGetUInt32(setivop->d.hashdatum_initvalue.init_value);
2711 hashkey = pg_rotate_left32(hashkey, 1);
2712
2713 if (!fcinfo->args[0].isnull)
2714 {
2715 uint32 hashvalue;
2716
2717 hashvalue = DatumGetUInt32(hashop->d.hashdatum.fn_addr(fcinfo));
2718 hashkey = hashkey ^ hashvalue;
2719 }
2720
2721 *isnull = false;
2722 return UInt32GetDatum(hashkey);
2723}
2724
2725/* implementation of ExecJustHash(Inner|Outer)Var */
2728{
2729 ExprEvalStep *fetchop = &state->steps[0];
2730 ExprEvalStep *var = &state->steps[1];
2731 ExprEvalStep *hashop = &state->steps[2];
2732 FunctionCallInfo fcinfo = hashop->d.hashdatum.fcinfo_data;
2733 int attnum = var->d.var.attnum;
2734
2735 CheckOpSlotCompatibility(fetchop, slot);
2736 slot_getsomeattrs(slot, fetchop->d.fetch.last_var);
2737
2738 fcinfo->args[0].value = slot->tts_values[attnum];
2739 fcinfo->args[0].isnull = slot->tts_isnull[attnum];
2740
2741 *isnull = false;
2742
2743 if (!fcinfo->args[0].isnull)
2744 return DatumGetUInt32(hashop->d.hashdatum.fn_addr(fcinfo));
2745 else
2746 return (Datum) 0;
2747}
2748
2749/* implementation for hashing an outer Var */
2750static Datum
2752{
2753 return ExecJustHashVarImpl(state, econtext->ecxt_outertuple, isnull);
2754}
2755
2756/* implementation for hashing an inner Var */
2757static Datum
2759{
2760 return ExecJustHashVarImpl(state, econtext->ecxt_innertuple, isnull);
2761}
2762
2763/* implementation of ExecJustHash(Inner|Outer)VarVirt */
2766{
2767 ExprEvalStep *var = &state->steps[0];
2768 ExprEvalStep *hashop = &state->steps[1];
2769 FunctionCallInfo fcinfo = hashop->d.hashdatum.fcinfo_data;
2770 int attnum = var->d.var.attnum;
2771
2772 fcinfo->args[0].value = slot->tts_values[attnum];
2773 fcinfo->args[0].isnull = slot->tts_isnull[attnum];
2774
2775 *isnull = false;
2776
2777 if (!fcinfo->args[0].isnull)
2778 return DatumGetUInt32(hashop->d.hashdatum.fn_addr(fcinfo));
2779 else
2780 return (Datum) 0;
2781}
2782
2783/* Like ExecJustHashInnerVar, optimized for virtual slots */
2784static Datum
2786 bool *isnull)
2787{
2789}
2790
2791/* Like ExecJustHashOuterVar, optimized for virtual slots */
2792static Datum
2794 bool *isnull)
2795{
2797}
2798
2799/*
2800 * implementation for hashing an outer Var. Returns NULL on NULL input.
2801 */
2802static Datum
2804 bool *isnull)
2805{
2806 ExprEvalStep *fetchop = &state->steps[0];
2807 ExprEvalStep *var = &state->steps[1];
2808 ExprEvalStep *hashop = &state->steps[2];
2809 FunctionCallInfo fcinfo = hashop->d.hashdatum.fcinfo_data;
2810 int attnum = var->d.var.attnum;
2811
2812 CheckOpSlotCompatibility(fetchop, econtext->ecxt_outertuple);
2813 slot_getsomeattrs(econtext->ecxt_outertuple, fetchop->d.fetch.last_var);
2814
2815 fcinfo->args[0].value = econtext->ecxt_outertuple->tts_values[attnum];
2816 fcinfo->args[0].isnull = econtext->ecxt_outertuple->tts_isnull[attnum];
2817
2818 if (!fcinfo->args[0].isnull)
2819 {
2820 *isnull = false;
2821 return DatumGetUInt32(hashop->d.hashdatum.fn_addr(fcinfo));
2822 }
2823 else
2824 {
2825 /* return NULL on NULL input */
2826 *isnull = true;
2827 return (Datum) 0;
2828 }
2829}
2830
2831#if defined(EEO_USE_COMPUTED_GOTO)
2832/*
2833 * Comparator used when building address->opcode lookup table for
2834 * ExecEvalStepOp() in the threaded dispatch case.
2835 */
2836static int
2837dispatch_compare_ptr(const void *a, const void *b)
2838{
2839 const ExprEvalOpLookup *la = (const ExprEvalOpLookup *) a;
2840 const ExprEvalOpLookup *lb = (const ExprEvalOpLookup *) b;
2841
2842 if (la->opcode < lb->opcode)
2843 return -1;
2844 else if (la->opcode > lb->opcode)
2845 return 1;
2846 return 0;
2847}
2848#endif
2849
2850/*
2851 * Do one-time initialization of interpretation machinery.
2852 */
2853static void
2855{
2856#if defined(EEO_USE_COMPUTED_GOTO)
2857 /* Set up externally-visible pointer to dispatch table */
2858 if (dispatch_table == NULL)
2859 {
2860 dispatch_table = (const void **)
2861 DatumGetPointer(ExecInterpExpr(NULL, NULL, NULL));
2862
2863 /* build reverse lookup table */
2864 for (int i = 0; i < EEOP_LAST; i++)
2865 {
2866 reverse_dispatch_table[i].opcode = dispatch_table[i];
2867 reverse_dispatch_table[i].op = (ExprEvalOp) i;
2868 }
2869
2870 /* make it bsearch()able */
2871 qsort(reverse_dispatch_table,
2872 EEOP_LAST /* nmembers */ ,
2873 sizeof(ExprEvalOpLookup),
2874 dispatch_compare_ptr);
2875 }
2876#endif
2877}
2878
2879/*
2880 * Function to return the opcode of an expression step.
2881 *
2882 * When direct-threading is in use, ExprState->opcode isn't easily
2883 * decipherable. This function returns the appropriate enum member.
2884 */
2887{
2888#if defined(EEO_USE_COMPUTED_GOTO)
2889 if (state->flags & EEO_FLAG_DIRECT_THREADED)
2890 {
2891 ExprEvalOpLookup key;
2892 ExprEvalOpLookup *res;
2893
2894 key.opcode = (void *) op->opcode;
2895 res = bsearch(&key,
2896 reverse_dispatch_table,
2897 EEOP_LAST /* nmembers */ ,
2898 sizeof(ExprEvalOpLookup),
2899 dispatch_compare_ptr);
2900 Assert(res); /* unknown ops shouldn't get looked up */
2901 return res->op;
2902 }
2903#endif
2904 return (ExprEvalOp) op->opcode;
2905}
2906
2907
2908/*
2909 * Out-of-line helper functions for complex instructions.
2910 */
2911
2912/*
2913 * Evaluate EEOP_FUNCEXPR_FUSAGE
2914 */
2915void
2917 ExprContext *econtext)
2918{
2919 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
2921 Datum d;
2922
2923 pgstat_init_function_usage(fcinfo, &fcusage);
2924
2925 fcinfo->isnull = false;
2926 d = op->d.func.fn_addr(fcinfo);
2927 *op->resvalue = d;
2928 *op->resnull = fcinfo->isnull;
2929
2930 pgstat_end_function_usage(&fcusage, true);
2931}
2932
2933/*
2934 * Evaluate EEOP_FUNCEXPR_STRICT_FUSAGE
2935 */
2936void
2938 ExprContext *econtext)
2939{
2940
2941 FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
2943 NullableDatum *args = fcinfo->args;
2944 int nargs = op->d.func.nargs;
2945 Datum d;
2946
2947 /* strict function, so check for NULL args */
2948 for (int argno = 0; argno < nargs; argno++)
2949 {
2950 if (args[argno].isnull)
2951 {
2952 *op->resnull = true;
2953 return;
2954 }
2955 }
2956
2957 pgstat_init_function_usage(fcinfo, &fcusage);
2958
2959 fcinfo->isnull = false;
2960 d = op->d.func.fn_addr(fcinfo);
2961 *op->resvalue = d;
2962 *op->resnull = fcinfo->isnull;
2963
2964 pgstat_end_function_usage(&fcusage, true);
2965}
2966
2967/*
2968 * Evaluate a PARAM_EXEC parameter.
2969 *
2970 * PARAM_EXEC params (internal executor parameters) are stored in the
2971 * ecxt_param_exec_vals array, and can be accessed by array index.
2972 */
2973void
2975{
2976 ParamExecData *prm;
2977
2978 prm = &(econtext->ecxt_param_exec_vals[op->d.param.paramid]);
2979 if (unlikely(prm->execPlan != NULL))
2980 {
2981 /* Parameter not evaluated yet, so go do it */
2982 ExecSetParamPlan(prm->execPlan, econtext);
2983 /* ExecSetParamPlan should have processed this param... */
2984 Assert(prm->execPlan == NULL);
2985 }
2986 *op->resvalue = prm->value;
2987 *op->resnull = prm->isnull;
2988}
2989
2990/*
2991 * Evaluate a PARAM_EXTERN parameter.
2992 *
2993 * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
2994 */
2995void
2997{
2998 ParamListInfo paramInfo = econtext->ecxt_param_list_info;
2999 int paramId = op->d.param.paramid;
3000
3001 if (likely(paramInfo &&
3002 paramId > 0 && paramId <= paramInfo->numParams))
3003 {
3004 ParamExternData *prm;
3005 ParamExternData prmdata;
3006
3007 /* give hook a chance in case parameter is dynamic */
3008 if (paramInfo->paramFetch != NULL)
3009 prm = paramInfo->paramFetch(paramInfo, paramId, false, &prmdata);
3010 else
3011 prm = &paramInfo->params[paramId - 1];
3012
3013 if (likely(OidIsValid(prm->ptype)))
3014 {
3015 /* safety check in case hook did something unexpected */
3016 if (unlikely(prm->ptype != op->d.param.paramtype))
3017 ereport(ERROR,
3018 (errcode(ERRCODE_DATATYPE_MISMATCH),
3019 errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
3020 paramId,
3021 format_type_be(prm->ptype),
3022 format_type_be(op->d.param.paramtype))));
3023 *op->resvalue = prm->value;
3024 *op->resnull = prm->isnull;
3025 return;
3026 }
3027 }
3028
3029 ereport(ERROR,
3030 (errcode(ERRCODE_UNDEFINED_OBJECT),
3031 errmsg("no value found for parameter %d", paramId)));
3032}
3033
3034/*
3035 * Set value of a param (currently always PARAM_EXEC) from
3036 * state->res{value,null}.
3037 */
3038void
3040{
3041 ParamExecData *prm;
3042
3043 prm = &(econtext->ecxt_param_exec_vals[op->d.param.paramid]);
3044
3045 /* Shouldn't have a pending evaluation anymore */
3046 Assert(prm->execPlan == NULL);
3047
3048 prm->value = state->resvalue;
3049 prm->isnull = state->resnull;
3050}
3051
3052/*
3053 * Evaluate a CoerceViaIO node in soft-error mode.
3054 *
3055 * The source value is in op's result variable.
3056 *
3057 * Note: This implements EEOP_IOCOERCE_SAFE. If you change anything here,
3058 * also look at the inline code for EEOP_IOCOERCE.
3059 */
3060void
3062{
3063 char *str;
3064
3065 /* call output function (similar to OutputFunctionCall) */
3066 if (*op->resnull)
3067 {
3068 /* output functions are not called on nulls */
3069 str = NULL;
3070 }
3071 else
3072 {
3073 FunctionCallInfo fcinfo_out;
3074
3075 fcinfo_out = op->d.iocoerce.fcinfo_data_out;
3076 fcinfo_out->args[0].value = *op->resvalue;
3077 fcinfo_out->args[0].isnull = false;
3078
3079 fcinfo_out->isnull = false;
3080 str = DatumGetCString(FunctionCallInvoke(fcinfo_out));
3081
3082 /* OutputFunctionCall assumes result isn't null */
3083 Assert(!fcinfo_out->isnull);
3084 }
3085
3086 /* call input function (similar to InputFunctionCallSafe) */
3087 if (!op->d.iocoerce.finfo_in->fn_strict || str != NULL)
3088 {
3089 FunctionCallInfo fcinfo_in;
3090
3091 fcinfo_in = op->d.iocoerce.fcinfo_data_in;
3092 fcinfo_in->args[0].value = PointerGetDatum(str);
3093 fcinfo_in->args[0].isnull = *op->resnull;
3094 /* second and third arguments are already set up */
3095
3096 /* ErrorSaveContext must be present. */
3097 Assert(IsA(fcinfo_in->context, ErrorSaveContext));
3098
3099 fcinfo_in->isnull = false;
3100 *op->resvalue = FunctionCallInvoke(fcinfo_in);
3101
3102 if (SOFT_ERROR_OCCURRED(fcinfo_in->context))
3103 {
3104 *op->resnull = true;
3105 *op->resvalue = (Datum) 0;
3106 return;
3107 }
3108
3109 /* Should get null result if and only if str is NULL */
3110 if (str == NULL)
3111 Assert(*op->resnull);
3112 else
3113 Assert(!*op->resnull);
3114 }
3115}
3116
3117/*
3118 * Evaluate a SQLValueFunction expression.
3119 */
3120void
3122{
3123 LOCAL_FCINFO(fcinfo, 0);
3124 SQLValueFunction *svf = op->d.sqlvaluefunction.svf;
3125
3126 *op->resnull = false;
3127
3128 /*
3129 * Note: current_schema() can return NULL. current_user() etc currently
3130 * cannot, but might as well code those cases the same way for safety.
3131 */
3132 switch (svf->op)
3133 {
3134 case SVFOP_CURRENT_DATE:
3135 *op->resvalue = DateADTGetDatum(GetSQLCurrentDate());
3136 break;
3137 case SVFOP_CURRENT_TIME:
3140 break;
3144 break;
3145 case SVFOP_LOCALTIME:
3146 case SVFOP_LOCALTIME_N:
3148 break;
3152 break;
3153 case SVFOP_CURRENT_ROLE:
3154 case SVFOP_CURRENT_USER:
3155 case SVFOP_USER:
3156 InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
3157 *op->resvalue = current_user(fcinfo);
3158 *op->resnull = fcinfo->isnull;
3159 break;
3160 case SVFOP_SESSION_USER:
3161 InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
3162 *op->resvalue = session_user(fcinfo);
3163 *op->resnull = fcinfo->isnull;
3164 break;
3166 InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
3167 *op->resvalue = current_database(fcinfo);
3168 *op->resnull = fcinfo->isnull;
3169 break;
3171 InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
3172 *op->resvalue = current_schema(fcinfo);
3173 *op->resnull = fcinfo->isnull;
3174 break;
3175 }
3176}
3177
3178/*
3179 * Raise error if a CURRENT OF expression is evaluated.
3180 *
3181 * The planner should convert CURRENT OF into a TidScan qualification, or some
3182 * other special handling in a ForeignScan node. So we have to be able to do
3183 * ExecInitExpr on a CurrentOfExpr, but we shouldn't ever actually execute it.
3184 * If we get here, we suppose we must be dealing with CURRENT OF on a foreign
3185 * table whose FDW doesn't handle it, and complain accordingly.
3186 */
3187void
3189{
3190 ereport(ERROR,
3191 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3192 errmsg("WHERE CURRENT OF is not supported for this table type")));
3193}
3194
3195/*
3196 * Evaluate NextValueExpr.
3197 */
3198void
3200{
3201 int64 newval = nextval_internal(op->d.nextvalueexpr.seqid, false);
3202
3203 switch (op->d.nextvalueexpr.seqtypid)
3204 {
3205 case INT2OID:
3206 *op->resvalue = Int16GetDatum((int16) newval);
3207 break;
3208 case INT4OID:
3209 *op->resvalue = Int32GetDatum((int32) newval);
3210 break;
3211 case INT8OID:
3212 *op->resvalue = Int64GetDatum((int64) newval);
3213 break;
3214 default:
3215 elog(ERROR, "unsupported sequence type %u",
3216 op->d.nextvalueexpr.seqtypid);
3217 }
3218 *op->resnull = false;
3219}
3220
3221/*
3222 * Evaluate NullTest / IS NULL for rows.
3223 */
3224void
3226{
3227 ExecEvalRowNullInt(state, op, econtext, true);
3228}
3229
3230/*
3231 * Evaluate NullTest / IS NOT NULL for rows.
3232 */
3233void
3235{
3236 ExecEvalRowNullInt(state, op, econtext, false);
3237}
3238
3239/* Common code for IS [NOT] NULL on a row value */
3240static void
3242 ExprContext *econtext, bool checkisnull)
3243{
3244 Datum value = *op->resvalue;
3245 bool isnull = *op->resnull;
3246 HeapTupleHeader tuple;
3247 Oid tupType;
3248 int32 tupTypmod;
3249 TupleDesc tupDesc;
3250 HeapTupleData tmptup;
3251
3252 *op->resnull = false;
3253
3254 /* NULL row variables are treated just as NULL scalar columns */
3255 if (isnull)
3256 {
3257 *op->resvalue = BoolGetDatum(checkisnull);
3258 return;
3259 }
3260
3261 /*
3262 * The SQL standard defines IS [NOT] NULL for a non-null rowtype argument
3263 * as:
3264 *
3265 * "R IS NULL" is true if every field is the null value.
3266 *
3267 * "R IS NOT NULL" is true if no field is the null value.
3268 *
3269 * This definition is (apparently intentionally) not recursive; so our
3270 * tests on the fields are primitive attisnull tests, not recursive checks
3271 * to see if they are all-nulls or no-nulls rowtypes.
3272 *
3273 * The standard does not consider the possibility of zero-field rows, but
3274 * here we consider them to vacuously satisfy both predicates.
3275 */
3276
3278
3279 tupType = HeapTupleHeaderGetTypeId(tuple);
3280 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3281
3282 /* Lookup tupdesc if first time through or if type changes */
3283 tupDesc = get_cached_rowtype(tupType, tupTypmod,
3284 &op->d.nulltest_row.rowcache, NULL);
3285
3286 /*
3287 * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
3288 */
3289 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3290 tmptup.t_data = tuple;
3291
3292 for (int att = 1; att <= tupDesc->natts; att++)
3293 {
3294 /* ignore dropped columns */
3295 if (TupleDescCompactAttr(tupDesc, att - 1)->attisdropped)
3296 continue;
3297 if (heap_attisnull(&tmptup, att, tupDesc))
3298 {
3299 /* null field disproves IS NOT NULL */
3300 if (!checkisnull)
3301 {
3302 *op->resvalue = BoolGetDatum(false);
3303 return;
3304 }
3305 }
3306 else
3307 {
3308 /* non-null field disproves IS NULL */
3309 if (checkisnull)
3310 {
3311 *op->resvalue = BoolGetDatum(false);
3312 return;
3313 }
3314 }
3315 }
3316
3317 *op->resvalue = BoolGetDatum(true);
3318}
3319
3320/*
3321 * Evaluate an ARRAY[] expression.
3322 *
3323 * The individual array elements (or subarrays) have already been evaluated
3324 * into op->d.arrayexpr.elemvalues[]/elemnulls[].
3325 */
3326void
3328{
3329 ArrayType *result;
3330 Oid element_type = op->d.arrayexpr.elemtype;
3331 int nelems = op->d.arrayexpr.nelems;
3332 int ndims = 0;
3333 int dims[MAXDIM];
3334 int lbs[MAXDIM];
3335
3336 /* Set non-null as default */
3337 *op->resnull = false;
3338
3339 if (!op->d.arrayexpr.multidims)
3340 {
3341 /* Elements are presumably of scalar type */
3342 Datum *dvalues = op->d.arrayexpr.elemvalues;
3343 bool *dnulls = op->d.arrayexpr.elemnulls;
3344
3345 /* setup for 1-D array of the given length */
3346 ndims = 1;
3347 dims[0] = nelems;
3348 lbs[0] = 1;
3349
3350 result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
3352 op->d.arrayexpr.elemlength,
3353 op->d.arrayexpr.elembyval,
3354 op->d.arrayexpr.elemalign);
3355 }
3356 else
3357 {
3358 /* Must be nested array expressions */
3359 int nbytes = 0;
3360 int nitems;
3361 int outer_nelems = 0;
3362 int elem_ndims = 0;
3363 int *elem_dims = NULL;
3364 int *elem_lbs = NULL;
3365 bool firstone = true;
3366 bool havenulls = false;
3367 bool haveempty = false;
3368 char **subdata;
3369 bits8 **subbitmaps;
3370 int *subbytes;
3371 int *subnitems;
3372 int32 dataoffset;
3373 char *dat;
3374 int iitem;
3375
3376 subdata = (char **) palloc(nelems * sizeof(char *));
3377 subbitmaps = (bits8 **) palloc(nelems * sizeof(bits8 *));
3378 subbytes = (int *) palloc(nelems * sizeof(int));
3379 subnitems = (int *) palloc(nelems * sizeof(int));
3380
3381 /* loop through and get data area from each element */
3382 for (int elemoff = 0; elemoff < nelems; elemoff++)
3383 {
3384 Datum arraydatum;
3385 bool eisnull;
3386 ArrayType *array;
3387 int this_ndims;
3388
3389 arraydatum = op->d.arrayexpr.elemvalues[elemoff];
3390 eisnull = op->d.arrayexpr.elemnulls[elemoff];
3391
3392 /* temporarily ignore null subarrays */
3393 if (eisnull)
3394 {
3395 haveempty = true;
3396 continue;
3397 }
3398
3399 array = DatumGetArrayTypeP(arraydatum);
3400
3401 /* run-time double-check on element type */
3402 if (element_type != ARR_ELEMTYPE(array))
3403 ereport(ERROR,
3404 (errcode(ERRCODE_DATATYPE_MISMATCH),
3405 errmsg("cannot merge incompatible arrays"),
3406 errdetail("Array with element type %s cannot be "
3407 "included in ARRAY construct with element type %s.",
3410
3411 this_ndims = ARR_NDIM(array);
3412 /* temporarily ignore zero-dimensional subarrays */
3413 if (this_ndims <= 0)
3414 {
3415 haveempty = true;
3416 continue;
3417 }
3418
3419 if (firstone)
3420 {
3421 /* Get sub-array details from first member */
3422 elem_ndims = this_ndims;
3423 ndims = elem_ndims + 1;
3424 if (ndims <= 0 || ndims > MAXDIM)
3425 ereport(ERROR,
3426 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3427 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3428 ndims, MAXDIM)));
3429
3430 elem_dims = (int *) palloc(elem_ndims * sizeof(int));
3431 memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
3432 elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
3433 memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
3434
3435 firstone = false;
3436 }
3437 else
3438 {
3439 /* Check other sub-arrays are compatible */
3440 if (elem_ndims != this_ndims ||
3441 memcmp(elem_dims, ARR_DIMS(array),
3442 elem_ndims * sizeof(int)) != 0 ||
3443 memcmp(elem_lbs, ARR_LBOUND(array),
3444 elem_ndims * sizeof(int)) != 0)
3445 ereport(ERROR,
3446 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3447 errmsg("multidimensional arrays must have array "
3448 "expressions with matching dimensions")));
3449 }
3450
3451 subdata[outer_nelems] = ARR_DATA_PTR(array);
3452 subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
3453 subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
3454 nbytes += subbytes[outer_nelems];
3455 /* check for overflow of total request */
3456 if (!AllocSizeIsValid(nbytes))
3457 ereport(ERROR,
3458 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3459 errmsg("array size exceeds the maximum allowed (%d)",
3460 (int) MaxAllocSize)));
3461 subnitems[outer_nelems] = ArrayGetNItems(this_ndims,
3462 ARR_DIMS(array));
3463 havenulls |= ARR_HASNULL(array);
3464 outer_nelems++;
3465 }
3466
3467 /*
3468 * If all items were null or empty arrays, return an empty array;
3469 * otherwise, if some were and some weren't, raise error. (Note: we
3470 * must special-case this somehow to avoid trying to generate a 1-D
3471 * array formed from empty arrays. It's not ideal...)
3472 */
3473 if (haveempty)
3474 {
3475 if (ndims == 0) /* didn't find any nonempty array */
3476 {
3478 return;
3479 }
3480 ereport(ERROR,
3481 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3482 errmsg("multidimensional arrays must have array "
3483 "expressions with matching dimensions")));
3484 }
3485
3486 /* setup for multi-D array */
3487 dims[0] = outer_nelems;
3488 lbs[0] = 1;
3489 for (int i = 1; i < ndims; i++)
3490 {
3491 dims[i] = elem_dims[i - 1];
3492 lbs[i] = elem_lbs[i - 1];
3493 }
3494
3495 /* check for subscript overflow */
3496 nitems = ArrayGetNItems(ndims, dims);
3497 ArrayCheckBounds(ndims, dims, lbs);
3498
3499 if (havenulls)
3500 {
3501 dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
3502 nbytes += dataoffset;
3503 }
3504 else
3505 {
3506 dataoffset = 0; /* marker for no null bitmap */
3507 nbytes += ARR_OVERHEAD_NONULLS(ndims);
3508 }
3509
3510 result = (ArrayType *) palloc0(nbytes);
3511 SET_VARSIZE(result, nbytes);
3512 result->ndim = ndims;
3513 result->dataoffset = dataoffset;
3514 result->elemtype = element_type;
3515 memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
3516 memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
3517
3518 dat = ARR_DATA_PTR(result);
3519 iitem = 0;
3520 for (int i = 0; i < outer_nelems; i++)
3521 {
3522 memcpy(dat, subdata[i], subbytes[i]);
3523 dat += subbytes[i];
3524 if (havenulls)
3525 array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
3526 subbitmaps[i], 0,
3527 subnitems[i]);
3528 iitem += subnitems[i];
3529 }
3530 }
3531
3532 *op->resvalue = PointerGetDatum(result);
3533}
3534
3535/*
3536 * Evaluate an ArrayCoerceExpr expression.
3537 *
3538 * Source array is in step's result variable.
3539 */
3540void
3542{
3543 Datum arraydatum;
3544
3545 /* NULL array -> NULL result */
3546 if (*op->resnull)
3547 return;
3548
3549 arraydatum = *op->resvalue;
3550
3551 /*
3552 * If it's binary-compatible, modify the element type in the array header,
3553 * but otherwise leave the array as we received it.
3554 */
3555 if (op->d.arraycoerce.elemexprstate == NULL)
3556 {
3557 /* Detoast input array if necessary, and copy in any case */
3558 ArrayType *array = DatumGetArrayTypePCopy(arraydatum);
3559
3560 ARR_ELEMTYPE(array) = op->d.arraycoerce.resultelemtype;
3561 *op->resvalue = PointerGetDatum(array);
3562 return;
3563 }
3564
3565 /*
3566 * Use array_map to apply the sub-expression to each array element.
3567 */
3568 *op->resvalue = array_map(arraydatum,
3569 op->d.arraycoerce.elemexprstate,
3570 econtext,
3571 op->d.arraycoerce.resultelemtype,
3572 op->d.arraycoerce.amstate);
3573}
3574
3575/*
3576 * Evaluate a ROW() expression.
3577 *
3578 * The individual columns have already been evaluated into
3579 * op->d.row.elemvalues[]/elemnulls[].
3580 */
3581void
3583{
3584 HeapTuple tuple;
3585
3586 /* build tuple from evaluated field values */
3587 tuple = heap_form_tuple(op->d.row.tupdesc,
3588 op->d.row.elemvalues,
3589 op->d.row.elemnulls);
3590
3591 *op->resvalue = HeapTupleGetDatum(tuple);
3592 *op->resnull = false;
3593}
3594
3595/*
3596 * Evaluate GREATEST() or LEAST() expression (note this is *not* MIN()/MAX()).
3597 *
3598 * All of the to-be-compared expressions have already been evaluated into
3599 * op->d.minmax.values[]/nulls[].
3600 */
3601void
3603{
3604 Datum *values = op->d.minmax.values;
3605 bool *nulls = op->d.minmax.nulls;
3606 FunctionCallInfo fcinfo = op->d.minmax.fcinfo_data;
3607 MinMaxOp operator = op->d.minmax.op;
3608
3609 /* set at initialization */
3610 Assert(fcinfo->args[0].isnull == false);
3611 Assert(fcinfo->args[1].isnull == false);
3612
3613 /* default to null result */
3614 *op->resnull = true;
3615
3616 for (int off = 0; off < op->d.minmax.nelems; off++)
3617 {
3618 /* ignore NULL inputs */
3619 if (nulls[off])
3620 continue;
3621
3622 if (*op->resnull)
3623 {
3624 /* first nonnull input, adopt value */
3625 *op->resvalue = values[off];
3626 *op->resnull = false;
3627 }
3628 else
3629 {
3630 int cmpresult;
3631
3632 /* apply comparison function */
3633 fcinfo->args[0].value = *op->resvalue;
3634 fcinfo->args[1].value = values[off];
3635
3636 fcinfo->isnull = false;
3637 cmpresult = DatumGetInt32(FunctionCallInvoke(fcinfo));
3638 if (fcinfo->isnull) /* probably should not happen */
3639 continue;
3640
3641 if (cmpresult > 0 && operator == IS_LEAST)
3642 *op->resvalue = values[off];
3643 else if (cmpresult < 0 && operator == IS_GREATEST)
3644 *op->resvalue = values[off];
3645 }
3646 }
3647}
3648
3649/*
3650 * Evaluate a FieldSelect node.
3651 *
3652 * Source record is in step's result variable.
3653 */
3654void
3656{
3657 AttrNumber fieldnum = op->d.fieldselect.fieldnum;
3658 Datum tupDatum;
3659 HeapTupleHeader tuple;
3660 Oid tupType;
3661 int32 tupTypmod;
3662 TupleDesc tupDesc;
3663 Form_pg_attribute attr;
3664 HeapTupleData tmptup;
3665
3666 /* NULL record -> NULL result */
3667 if (*op->resnull)
3668 return;
3669
3670 tupDatum = *op->resvalue;
3671
3672 /* We can special-case expanded records for speed */
3674 {
3676
3677 Assert(erh->er_magic == ER_MAGIC);
3678
3679 /* Extract record's TupleDesc */
3680 tupDesc = expanded_record_get_tupdesc(erh);
3681
3682 /*
3683 * Find field's attr record. Note we don't support system columns
3684 * here: a datum tuple doesn't have valid values for most of the
3685 * interesting system columns anyway.
3686 */
3687 if (fieldnum <= 0) /* should never happen */
3688 elog(ERROR, "unsupported reference to system column %d in FieldSelect",
3689 fieldnum);
3690 if (fieldnum > tupDesc->natts) /* should never happen */
3691 elog(ERROR, "attribute number %d exceeds number of columns %d",
3692 fieldnum, tupDesc->natts);
3693 attr = TupleDescAttr(tupDesc, fieldnum - 1);
3694
3695 /* Check for dropped column, and force a NULL result if so */
3696 if (attr->attisdropped)
3697 {
3698 *op->resnull = true;
3699 return;
3700 }
3701
3702 /* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
3703 /* As in CheckVarSlotCompatibility, we should but can't check typmod */
3704 if (op->d.fieldselect.resulttype != attr->atttypid)
3705 ereport(ERROR,
3706 (errcode(ERRCODE_DATATYPE_MISMATCH),
3707 errmsg("attribute %d has wrong type", fieldnum),
3708 errdetail("Table has type %s, but query expects %s.",
3709 format_type_be(attr->atttypid),
3710 format_type_be(op->d.fieldselect.resulttype))));
3711
3712 /* extract the field */
3713 *op->resvalue = expanded_record_get_field(erh, fieldnum,
3714 op->resnull);
3715 }
3716 else
3717 {
3718 /* Get the composite datum and extract its type fields */
3719 tuple = DatumGetHeapTupleHeader(tupDatum);
3720
3721 tupType = HeapTupleHeaderGetTypeId(tuple);
3722 tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3723
3724 /* Lookup tupdesc if first time through or if type changes */
3725 tupDesc = get_cached_rowtype(tupType, tupTypmod,
3726 &op->d.fieldselect.rowcache, NULL);
3727
3728 /*
3729 * Find field's attr record. Note we don't support system columns
3730 * here: a datum tuple doesn't have valid values for most of the
3731 * interesting system columns anyway.
3732 */
3733 if (fieldnum <= 0) /* should never happen */
3734 elog(ERROR, "unsupported reference to system column %d in FieldSelect",
3735 fieldnum);
3736 if (fieldnum > tupDesc->natts) /* should never happen */
3737 elog(ERROR, "attribute number %d exceeds number of columns %d",
3738 fieldnum, tupDesc->natts);
3739 attr = TupleDescAttr(tupDesc, fieldnum - 1);
3740
3741 /* Check for dropped column, and force a NULL result if so */
3742 if (attr->attisdropped)
3743 {
3744 *op->resnull = true;
3745 return;
3746 }
3747
3748 /* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
3749 /* As in CheckVarSlotCompatibility, we should but can't check typmod */
3750 if (op->d.fieldselect.resulttype != attr->atttypid)
3751 ereport(ERROR,
3752 (errcode(ERRCODE_DATATYPE_MISMATCH),
3753 errmsg("attribute %d has wrong type", fieldnum),
3754 errdetail("Table has type %s, but query expects %s.",
3755 format_type_be(attr->atttypid),
3756 format_type_be(op->d.fieldselect.resulttype))));
3757
3758 /* heap_getattr needs a HeapTuple not a bare HeapTupleHeader */
3759 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3760 tmptup.t_data = tuple;
3761
3762 /* extract the field */
3763 *op->resvalue = heap_getattr(&tmptup,
3764 fieldnum,
3765 tupDesc,
3766 op->resnull);
3767 }
3768}
3769
3770/*
3771 * Deform source tuple, filling in the step's values/nulls arrays, before
3772 * evaluating individual new values as part of a FieldStore expression.
3773 * Subsequent steps will overwrite individual elements of the values/nulls
3774 * arrays with the new field values, and then FIELDSTORE_FORM will build the
3775 * new tuple value.
3776 *
3777 * Source record is in step's result variable.
3778 */
3779void
3781{
3782 if (*op->resnull)
3783 {
3784 /* Convert null input tuple into an all-nulls row */
3785 memset(op->d.fieldstore.nulls, true,
3786 op->d.fieldstore.ncolumns * sizeof(bool));
3787 }
3788 else
3789 {
3790 /*
3791 * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3792 * set all the fields in the struct just in case.
3793 */
3794 Datum tupDatum = *op->resvalue;
3795 HeapTupleHeader tuphdr;
3796 HeapTupleData tmptup;
3797 TupleDesc tupDesc;
3798
3799 tuphdr = DatumGetHeapTupleHeader(tupDatum);
3800 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3801 ItemPointerSetInvalid(&(tmptup.t_self));
3802 tmptup.t_tableOid = InvalidOid;
3803 tmptup.t_data = tuphdr;
3804
3805 /*
3806 * Lookup tupdesc if first time through or if type changes. Because
3807 * we don't pin the tupdesc, we must not do this lookup until after
3808 * doing DatumGetHeapTupleHeader: that could do database access while
3809 * detoasting the datum.
3810 */
3811 tupDesc = get_cached_rowtype(op->d.fieldstore.fstore->resulttype, -1,
3812 op->d.fieldstore.rowcache, NULL);
3813
3814 /* Check that current tupdesc doesn't have more fields than allocated */
3815 if (unlikely(tupDesc->natts > op->d.fieldstore.ncolumns))
3816 elog(ERROR, "too many columns in composite type %u",
3817 op->d.fieldstore.fstore->resulttype);
3818
3819 heap_deform_tuple(&tmptup, tupDesc,
3820 op->d.fieldstore.values,
3821 op->d.fieldstore.nulls);
3822 }
3823}
3824
3825/*
3826 * Compute the new composite datum after each individual field value of a
3827 * FieldStore expression has been evaluated.
3828 */
3829void
3831{
3832 TupleDesc tupDesc;
3833 HeapTuple tuple;
3834
3835 /* Lookup tupdesc (should be valid already) */
3836 tupDesc = get_cached_rowtype(op->d.fieldstore.fstore->resulttype, -1,
3837 op->d.fieldstore.rowcache, NULL);
3838
3839 tuple = heap_form_tuple(tupDesc,
3840 op->d.fieldstore.values,
3841 op->d.fieldstore.nulls);
3842
3843 *op->resvalue = HeapTupleGetDatum(tuple);
3844 *op->resnull = false;
3845}
3846
3847/*
3848 * Evaluate a rowtype coercion operation.
3849 * This may require rearranging field positions.
3850 *
3851 * Source record is in step's result variable.
3852 */
3853void
3855{
3856 HeapTuple result;
3857 Datum tupDatum;
3858 HeapTupleHeader tuple;
3859 HeapTupleData tmptup;
3860 TupleDesc indesc,
3861 outdesc;
3862 bool changed = false;
3863
3864 /* NULL in -> NULL out */
3865 if (*op->resnull)
3866 return;
3867
3868 tupDatum = *op->resvalue;
3869 tuple = DatumGetHeapTupleHeader(tupDatum);
3870
3871 /*
3872 * Lookup tupdescs if first time through or if type changes. We'd better
3873 * pin them since type conversion functions could do catalog lookups and
3874 * hence cause cache invalidation.
3875 */
3876 indesc = get_cached_rowtype(op->d.convert_rowtype.inputtype, -1,
3877 op->d.convert_rowtype.incache,
3878 &changed);
3879 IncrTupleDescRefCount(indesc);
3880 outdesc = get_cached_rowtype(op->d.convert_rowtype.outputtype, -1,
3881 op->d.convert_rowtype.outcache,
3882 &changed);
3883 IncrTupleDescRefCount(outdesc);
3884
3885 /*
3886 * We used to be able to assert that incoming tuples are marked with
3887 * exactly the rowtype of indesc. However, now that ExecEvalWholeRowVar
3888 * might change the tuples' marking to plain RECORD due to inserting
3889 * aliases, we can only make this weak test:
3890 */
3891 Assert(HeapTupleHeaderGetTypeId(tuple) == indesc->tdtypeid ||
3892 HeapTupleHeaderGetTypeId(tuple) == RECORDOID);
3893
3894 /* if first time through, or after change, initialize conversion map */
3895 if (changed)
3896 {
3897 MemoryContext old_cxt;
3898
3899 /* allocate map in long-lived memory context */
3900 old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
3901
3902 /* prepare map from old to new attribute numbers */
3903 op->d.convert_rowtype.map = convert_tuples_by_name(indesc, outdesc);
3904
3905 MemoryContextSwitchTo(old_cxt);
3906 }
3907
3908 /* Following steps need a HeapTuple not a bare HeapTupleHeader */
3909 tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3910 tmptup.t_data = tuple;
3911
3912 if (op->d.convert_rowtype.map != NULL)
3913 {
3914 /* Full conversion with attribute rearrangement needed */
3915 result = execute_attr_map_tuple(&tmptup, op->d.convert_rowtype.map);
3916 /* Result already has appropriate composite-datum header fields */
3917 *op->resvalue = HeapTupleGetDatum(result);
3918 }
3919 else
3920 {
3921 /*
3922 * The tuple is physically compatible as-is, but we need to insert the
3923 * destination rowtype OID in its composite-datum header field, so we
3924 * have to copy it anyway. heap_copy_tuple_as_datum() is convenient
3925 * for this since it will both make the physical copy and insert the
3926 * correct composite header fields. Note that we aren't expecting to
3927 * have to flatten any toasted fields: the input was a composite
3928 * datum, so it shouldn't contain any. So heap_copy_tuple_as_datum()
3929 * is overkill here, but its check for external fields is cheap.
3930 */
3931 *op->resvalue = heap_copy_tuple_as_datum(&tmptup, outdesc);
3932 }
3933
3934 DecrTupleDescRefCount(indesc);
3935 DecrTupleDescRefCount(outdesc);
3936}
3937
3938/*
3939 * Evaluate "scalar op ANY/ALL (array)".
3940 *
3941 * Source array is in our result area, scalar arg is already evaluated into
3942 * fcinfo->args[0].
3943 *
3944 * The operator always yields boolean, and we combine the results across all
3945 * array elements using OR and AND (for ANY and ALL respectively). Of course
3946 * we short-circuit as soon as the result is known.
3947 */
3948void
3950{
3951 FunctionCallInfo fcinfo = op->d.scalararrayop.fcinfo_data;
3952 bool useOr = op->d.scalararrayop.useOr;
3953 bool strictfunc = op->d.scalararrayop.finfo->fn_strict;
3954 ArrayType *arr;
3955 int nitems;
3956 Datum result;
3957 bool resultnull;
3958 int16 typlen;
3959 bool typbyval;
3960 char typalign;
3961 char *s;
3962 bits8 *bitmap;
3963 int bitmask;
3964
3965 /*
3966 * If the array is NULL then we return NULL --- it's not very meaningful
3967 * to do anything else, even if the operator isn't strict.
3968 */
3969 if (*op->resnull)
3970 return;
3971
3972 /* Else okay to fetch and detoast the array */
3973 arr = DatumGetArrayTypeP(*op->resvalue);
3974
3975 /*
3976 * If the array is empty, we return either FALSE or TRUE per the useOr
3977 * flag. This is correct even if the scalar is NULL; since we would
3978 * evaluate the operator zero times, it matters not whether it would want
3979 * to return NULL.
3980 */
3981 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
3982 if (nitems <= 0)
3983 {
3984 *op->resvalue = BoolGetDatum(!useOr);
3985 *op->resnull = false;
3986 return;
3987 }
3988
3989 /*
3990 * If the scalar is NULL, and the function is strict, return NULL; no
3991 * point in iterating the loop.
3992 */
3993 if (fcinfo->args[0].isnull && strictfunc)
3994 {
3995 *op->resnull = true;
3996 return;
3997 }
3998
3999 /*
4000 * We arrange to look up info about the element type only once per series
4001 * of calls, assuming the element type doesn't change underneath us.
4002 */
4003 if (op->d.scalararrayop.element_type != ARR_ELEMTYPE(arr))
4004 {
4006 &op->d.scalararrayop.typlen,
4007 &op->d.scalararrayop.typbyval,
4008 &op->d.scalararrayop.typalign);
4009 op->d.scalararrayop.element_type = ARR_ELEMTYPE(arr);
4010 }
4011
4012 typlen = op->d.scalararrayop.typlen;
4013 typbyval = op->d.scalararrayop.typbyval;
4014 typalign = op->d.scalararrayop.typalign;
4015
4016 /* Initialize result appropriately depending on useOr */
4017 result = BoolGetDatum(!useOr);
4018 resultnull = false;
4019
4020 /* Loop over the array elements */
4021 s = (char *) ARR_DATA_PTR(arr);
4022 bitmap = ARR_NULLBITMAP(arr);
4023 bitmask = 1;
4024
4025 for (int i = 0; i < nitems; i++)
4026 {
4027 Datum elt;
4028 Datum thisresult;
4029
4030 /* Get array element, checking for NULL */
4031 if (bitmap && (*bitmap & bitmask) == 0)
4032 {
4033 fcinfo->args[1].value = (Datum) 0;
4034 fcinfo->args[1].isnull = true;
4035 }
4036 else
4037 {
4038 elt = fetch_att(s, typbyval, typlen);
4039 s = att_addlength_pointer(s, typlen, s);
4040 s = (char *) att_align_nominal(s, typalign);
4041 fcinfo->args[1].value = elt;
4042 fcinfo->args[1].isnull = false;
4043 }
4044
4045 /* Call comparison function */
4046 if (fcinfo->args[1].isnull && strictfunc)
4047 {
4048 fcinfo->isnull = true;
4049 thisresult = (Datum) 0;
4050 }
4051 else
4052 {
4053 fcinfo->isnull = false;
4054 thisresult = op->d.scalararrayop.fn_addr(fcinfo);
4055 }
4056
4057 /* Combine results per OR or AND semantics */
4058 if (fcinfo->isnull)
4059 resultnull = true;
4060 else if (useOr)
4061 {
4062 if (DatumGetBool(thisresult))
4063 {
4064 result = BoolGetDatum(true);
4065 resultnull = false;
4066 break; /* needn't look at any more elements */
4067 }
4068 }
4069 else
4070 {
4071 if (!DatumGetBool(thisresult))
4072 {
4073 result = BoolGetDatum(false);
4074 resultnull = false;
4075 break; /* needn't look at any more elements */
4076 }
4077 }
4078
4079 /* advance bitmap pointer if any */
4080 if (bitmap)
4081 {
4082 bitmask <<= 1;
4083 if (bitmask == 0x100)
4084 {
4085 bitmap++;
4086 bitmask = 1;
4087 }
4088 }
4089 }
4090
4091 *op->resvalue = result;
4092 *op->resnull = resultnull;
4093}
4094
4095/*
4096 * Hash function for scalar array hash op elements.
4097 *
4098 * We use the element type's default hash opclass, and the column collation
4099 * if the type is collation-sensitive.
4100 */
4101static uint32
4102saop_element_hash(struct saophash_hash *tb, Datum key)
4103{
4106 Datum hash;
4107
4108 fcinfo->args[0].value = key;
4109 fcinfo->args[0].isnull = false;
4110
4112
4113 return DatumGetUInt32(hash);
4114}
4115
4116/*
4117 * Matching function for scalar array hash op elements, to be used in hashtable
4118 * lookups.
4119 */
4120static bool
4121saop_hash_element_match(struct saophash_hash *tb, Datum key1, Datum key2)
4122{
4123 Datum result;
4124
4127
4128 fcinfo->args[0].value = key1;
4129 fcinfo->args[0].isnull = false;
4130 fcinfo->args[1].value = key2;
4131 fcinfo->args[1].isnull = false;
4132
4133 result = elements_tab->op->d.hashedscalararrayop.finfo->fn_addr(fcinfo);
4134
4135 return DatumGetBool(result);
4136}
4137
4138/*
4139 * Evaluate "scalar op ANY (const array)".
4140 *
4141 * Similar to ExecEvalScalarArrayOp, but optimized for faster repeat lookups
4142 * by building a hashtable on the first lookup. This hashtable will be reused
4143 * by subsequent lookups. Unlike ExecEvalScalarArrayOp, this version only
4144 * supports OR semantics.
4145 *
4146 * Source array is in our result area, scalar arg is already evaluated into
4147 * fcinfo->args[0].
4148 *
4149 * The operator always yields boolean.
4150 */
4151void
4153{
4154 ScalarArrayOpExprHashTable *elements_tab = op->d.hashedscalararrayop.elements_tab;
4155 FunctionCallInfo fcinfo = op->d.hashedscalararrayop.fcinfo_data;
4156 bool inclause = op->d.hashedscalararrayop.inclause;
4157 bool strictfunc = op->d.hashedscalararrayop.finfo->fn_strict;
4158 Datum scalar = fcinfo->args[0].value;
4159 bool scalar_isnull = fcinfo->args[0].isnull;
4160 Datum result;
4161 bool resultnull;
4162 bool hashfound;
4163
4164 /* We don't setup a hashed scalar array op if the array const is null. */
4165 Assert(!*op->resnull);
4166
4167 /*
4168 * If the scalar is NULL, and the function is strict, return NULL; no
4169 * point in executing the search.
4170 */
4171 if (fcinfo->args[0].isnull && strictfunc)
4172 {
4173 *op->resnull = true;
4174 return;
4175 }
4176
4177 /* Build the hash table on first evaluation */
4178 if (elements_tab == NULL)
4179 {
4181 int16 typlen;
4182 bool typbyval;
4183 char typalign;
4184 int nitems;
4185 bool has_nulls = false;
4186 char *s;
4187 bits8 *bitmap;
4188 int bitmask;
4189 MemoryContext oldcontext;
4190 ArrayType *arr;
4191
4192 saop = op->d.hashedscalararrayop.saop;
4193
4194 arr = DatumGetArrayTypeP(*op->resvalue);
4195 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
4196
4198 &typlen,
4199 &typbyval,
4200 &typalign);
4201
4202 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
4203
4205 palloc0(offsetof(ScalarArrayOpExprHashTable, hash_fcinfo_data) +
4207 op->d.hashedscalararrayop.elements_tab = elements_tab;
4208 elements_tab->op = op;
4209
4210 fmgr_info(saop->hashfuncid, &elements_tab->hash_finfo);
4212
4215 1,
4216 saop->inputcollid,
4217 NULL,
4218 NULL);
4219
4220 /*
4221 * Create the hash table sizing it according to the number of elements
4222 * in the array. This does assume that the array has no duplicates.
4223 * If the array happens to contain many duplicate values then it'll
4224 * just mean that we sized the table a bit on the large side.
4225 */
4226 elements_tab->hashtab = saophash_create(CurrentMemoryContext, nitems,
4227 elements_tab);
4228
4229 MemoryContextSwitchTo(oldcontext);
4230
4231 s = (char *) ARR_DATA_PTR(arr);
4232 bitmap = ARR_NULLBITMAP(arr);
4233 bitmask = 1;
4234 for (int i = 0; i < nitems; i++)
4235 {
4236 /* Get array element, checking for NULL. */
4237 if (bitmap && (*bitmap & bitmask) == 0)
4238 {
4239 has_nulls = true;
4240 }
4241 else
4242 {
4243 Datum element;
4244
4246 s = att_addlength_pointer(s, typlen, s);
4247 s = (char *) att_align_nominal(s, typalign);
4248
4249 saophash_insert(elements_tab->hashtab, element, &hashfound);
4250 }
4251
4252 /* Advance bitmap pointer if any. */
4253 if (bitmap)
4254 {
4255 bitmask <<= 1;
4256 if (bitmask == 0x100)
4257 {
4258 bitmap++;
4259 bitmask = 1;
4260 }
4261 }
4262 }
4263
4264 /*
4265 * Remember if we had any nulls so that we know if we need to execute
4266 * non-strict functions with a null lhs value if no match is found.
4267 */
4268 op->d.hashedscalararrayop.has_nulls = has_nulls;
4269 }
4270
4271 /* Check the hash to see if we have a match. */
4272 hashfound = NULL != saophash_lookup(elements_tab->hashtab, scalar);
4273
4274 /* the result depends on if the clause is an IN or NOT IN clause */
4275 if (inclause)
4276 result = BoolGetDatum(hashfound); /* IN */
4277 else
4278 result = BoolGetDatum(!hashfound); /* NOT IN */
4279
4280 resultnull = false;
4281
4282 /*
4283 * If we didn't find a match in the array, we still might need to handle
4284 * the possibility of null values. We didn't put any NULLs into the
4285 * hashtable, but instead marked if we found any when building the table
4286 * in has_nulls.
4287 */
4288 if (!hashfound && op->d.hashedscalararrayop.has_nulls)
4289 {
4290 if (strictfunc)
4291 {
4292
4293 /*
4294 * We have nulls in the array so a non-null lhs and no match must
4295 * yield NULL.
4296 */
4297 result = (Datum) 0;
4298 resultnull = true;
4299 }
4300 else
4301 {
4302 /*
4303 * Execute function will null rhs just once.
4304 *
4305 * The hash lookup path will have scribbled on the lhs argument so
4306 * we need to set it up also (even though we entered this function
4307 * with it already set).
4308 */
4309 fcinfo->args[0].value = scalar;
4310 fcinfo->args[0].isnull = scalar_isnull;
4311 fcinfo->args[1].value = (Datum) 0;
4312 fcinfo->args[1].isnull = true;
4313
4314 result = op->d.hashedscalararrayop.finfo->fn_addr(fcinfo);
4315 resultnull = fcinfo->isnull;
4316
4317 /*
4318 * Reverse the result for NOT IN clauses since the above function
4319 * is the equality function and we need not-equals.
4320 */
4321 if (!inclause)
4322 result = !result;
4323 }
4324 }
4325
4326 *op->resvalue = result;
4327 *op->resnull = resultnull;
4328}
4329
4330/*
4331 * Evaluate a NOT NULL domain constraint.
4332 */
4333void
4335{
4336 if (*op->resnull)
4337 errsave((Node *) op->d.domaincheck.escontext,
4338 (errcode(ERRCODE_NOT_NULL_VIOLATION),
4339 errmsg("domain %s does not allow null values",
4340 format_type_be(op->d.domaincheck.resulttype)),
4341 errdatatype(op->d.domaincheck.resulttype)));
4342}
4343
4344/*
4345 * Evaluate a CHECK domain constraint.
4346 */
4347void
4349{
4350 if (!*op->d.domaincheck.checknull &&
4351 !DatumGetBool(*op->d.domaincheck.checkvalue))
4352 errsave((Node *) op->d.domaincheck.escontext,
4353 (errcode(ERRCODE_CHECK_VIOLATION),
4354 errmsg("value for domain %s violates check constraint \"%s\"",
4355 format_type_be(op->d.domaincheck.resulttype),
4356 op->d.domaincheck.constraintname),
4357 errdomainconstraint(op->d.domaincheck.resulttype,
4358 op->d.domaincheck.constraintname)));
4359}
4360
4361/*
4362 * Evaluate the various forms of XmlExpr.
4363 *
4364 * Arguments have been evaluated into named_argvalue/named_argnull
4365 * and/or argvalue/argnull arrays.
4366 */
4367void
4369{
4370 XmlExpr *xexpr = op->d.xmlexpr.xexpr;
4371 Datum value;
4372
4373 *op->resnull = true; /* until we get a result */
4374 *op->resvalue = (Datum) 0;
4375
4376 switch (xexpr->op)
4377 {
4378 case IS_XMLCONCAT:
4379 {
4380 Datum *argvalue = op->d.xmlexpr.argvalue;
4381 bool *argnull = op->d.xmlexpr.argnull;
4382 List *values = NIL;
4383
4384 for (int i = 0; i < list_length(xexpr->args); i++)
4385 {
4386 if (!argnull[i])
4388 }
4389
4390 if (values != NIL)
4391 {
4392 *op->resvalue = PointerGetDatum(xmlconcat(values));
4393 *op->resnull = false;
4394 }
4395 }
4396 break;
4397
4398 case IS_XMLFOREST:
4399 {
4400 Datum *argvalue = op->d.xmlexpr.named_argvalue;
4401 bool *argnull = op->d.xmlexpr.named_argnull;
4403 ListCell *lc;
4404 ListCell *lc2;
4405 int i;
4406
4408
4409 i = 0;
4410 forboth(lc, xexpr->named_args, lc2, xexpr->arg_names)
4411 {
4412 Expr *e = (Expr *) lfirst(lc);
4413 char *argname = strVal(lfirst(lc2));
4414
4415 if (!argnull[i])
4416 {
4417 value = argvalue[i];
4418 appendStringInfo(&buf, "<%s>%s</%s>",
4419 argname,
4421 exprType((Node *) e), true),
4422 argname);
4423 *op->resnull = false;
4424 }
4425 i++;
4426 }
4427
4428 if (!*op->resnull)
4429 {
4430 text *result;
4431
4432 result = cstring_to_text_with_len(buf.data, buf.len);
4433 *op->resvalue = PointerGetDatum(result);
4434 }
4435
4436 pfree(buf.data);
4437 }
4438 break;
4439
4440 case IS_XMLELEMENT:
4441 *op->resvalue = PointerGetDatum(xmlelement(xexpr,
4442 op->d.xmlexpr.named_argvalue,
4443 op->d.xmlexpr.named_argnull,
4444 op->d.xmlexpr.argvalue,
4445 op->d.xmlexpr.argnull));
4446 *op->resnull = false;
4447 break;
4448
4449 case IS_XMLPARSE:
4450 {
4451 Datum *argvalue = op->d.xmlexpr.argvalue;
4452 bool *argnull = op->d.xmlexpr.argnull;
4453 text *data;
4454 bool preserve_whitespace;
4455
4456 /* arguments are known to be text, bool */
4457 Assert(list_length(xexpr->args) == 2);
4458
4459 if (argnull[0])
4460 return;
4461 value = argvalue[0];
4463
4464 if (argnull[1]) /* probably can't happen */
4465 return;
4466 value = argvalue[1];
4467 preserve_whitespace = DatumGetBool(value);
4468
4469 *op->resvalue = PointerGetDatum(xmlparse(data,
4470 xexpr->xmloption,
4471 preserve_whitespace));
4472 *op->resnull = false;
4473 }
4474 break;
4475
4476 case IS_XMLPI:
4477 {
4478 text *arg;
4479 bool isnull;
4480
4481 /* optional argument is known to be text */
4482 Assert(list_length(xexpr->args) <= 1);
4483
4484 if (xexpr->args)
4485 {
4486 isnull = op->d.xmlexpr.argnull[0];
4487 if (isnull)
4488 arg = NULL;
4489 else
4490 arg = DatumGetTextPP(op->d.xmlexpr.argvalue[0]);
4491 }
4492 else
4493 {
4494 arg = NULL;
4495 isnull = false;
4496 }
4497
4498 *op->resvalue = PointerGetDatum(xmlpi(xexpr->name,
4499 arg,
4500 isnull,
4501 op->resnull));
4502 }
4503 break;
4504
4505 case IS_XMLROOT:
4506 {
4507 Datum *argvalue = op->d.xmlexpr.argvalue;
4508 bool *argnull = op->d.xmlexpr.argnull;
4509 xmltype *data;
4510 text *version;
4511 int standalone;
4512
4513 /* arguments are known to be xml, text, int */
4514 Assert(list_length(xexpr->args) == 3);
4515
4516 if (argnull[0])
4517 return;
4519
4520 if (argnull[1])
4521 version = NULL;
4522 else
4523 version = DatumGetTextPP(argvalue[1]);
4524
4525 Assert(!argnull[2]); /* always present */
4526 standalone = DatumGetInt32(argvalue[2]);
4527
4528 *op->resvalue = PointerGetDatum(xmlroot(data,
4529 version,
4530 standalone));
4531 *op->resnull = false;
4532 }
4533 break;
4534
4535 case IS_XMLSERIALIZE:
4536 {
4537 Datum *argvalue = op->d.xmlexpr.argvalue;
4538 bool *argnull = op->d.xmlexpr.argnull;
4539
4540 /* argument type is known to be xml */
4541 Assert(list_length(xexpr->args) == 1);
4542
4543 if (argnull[0])
4544 return;
4545 value = argvalue[0];
4546
4547 *op->resvalue =
4549 xexpr->xmloption,
4550 xexpr->indent));
4551 *op->resnull = false;
4552 }
4553 break;
4554
4555 case IS_DOCUMENT:
4556 {
4557 Datum *argvalue = op->d.xmlexpr.argvalue;
4558 bool *argnull = op->d.xmlexpr.argnull;
4559
4560 /* optional argument is known to be xml */
4561 Assert(list_length(xexpr->args) == 1);
4562
4563 if (argnull[0])
4564 return;
4565 value = argvalue[0];
4566
4567 *op->resvalue =
4569 *op->resnull = false;
4570 }
4571 break;
4572
4573 default:
4574 elog(ERROR, "unrecognized XML operation");
4575 break;
4576 }
4577}
4578
4579/*
4580 * Evaluate a JSON constructor expression.
4581 */
4582void
4584 ExprContext *econtext)
4585{
4586 Datum res;
4587 JsonConstructorExprState *jcstate = op->d.json_constructor.jcstate;
4589 bool is_jsonb = ctor->returning->format->format_type == JS_FORMAT_JSONB;
4590 bool isnull = false;
4591
4592 if (ctor->type == JSCTOR_JSON_ARRAY)
4593 res = (is_jsonb ?
4600 else if (ctor->type == JSCTOR_JSON_OBJECT)
4601 res = (is_jsonb ?
4609 else if (ctor->type == JSCTOR_JSON_SCALAR)
4610 {
4611 if (jcstate->arg_nulls[0])
4612 {
4613 res = (Datum) 0;
4614 isnull = true;
4615 }
4616 else
4617 {
4619 Oid outfuncid = jcstate->arg_type_cache[0].outfuncid;
4622
4623 if (is_jsonb)
4624 res = datum_to_jsonb(value, category, outfuncid);
4625 else
4626 res = datum_to_json(value, category, outfuncid);
4627 }
4628 }
4629 else if (ctor->type == JSCTOR_JSON_PARSE)
4630 {
4631 if (jcstate->arg_nulls[0])
4632 {
4633 res = (Datum) 0;
4634 isnull = true;
4635 }
4636 else
4637 {
4639 text *js = DatumGetTextP(value);
4640
4641 if (is_jsonb)
4642 res = jsonb_from_text(js, true);
4643 else
4644 {
4645 (void) json_validate(js, true, true);
4646 res = value;
4647 }
4648 }
4649 }
4650 else
4651 elog(ERROR, "invalid JsonConstructorExpr type %d", ctor->type);
4652
4653 *op->resvalue = res;
4654 *op->resnull = isnull;
4655}
4656
4657/*
4658 * Evaluate a IS JSON predicate.
4659 */
4660void
4662{
4663 JsonIsPredicate *pred = op->d.is_json.pred;
4664 Datum js = *op->resvalue;
4665 Oid exprtype;
4666 bool res;
4667
4668 if (*op->resnull)
4669 {
4670 *op->resvalue = BoolGetDatum(false);
4671 return;
4672 }
4673
4674 exprtype = exprType(pred->expr);
4675
4676 if (exprtype == TEXTOID || exprtype == JSONOID)
4677 {
4678 text *json = DatumGetTextP(js);
4679
4680 if (pred->item_type == JS_TYPE_ANY)
4681 res = true;
4682 else
4683 {
4684 switch (json_get_first_token(json, false))
4685 {
4688 break;
4691 break;
4692 case JSON_TOKEN_STRING:
4693 case JSON_TOKEN_NUMBER:
4694 case JSON_TOKEN_TRUE:
4695 case JSON_TOKEN_FALSE:
4696 case JSON_TOKEN_NULL:
4698 break;
4699 default:
4700 res = false;
4701 break;
4702 }
4703 }
4704
4705 /*
4706 * Do full parsing pass only for uniqueness check or for JSON text
4707 * validation.
4708 */
4709 if (res && (pred->unique_keys || exprtype == TEXTOID))
4710 res = json_validate(json, pred->unique_keys, false);
4711 }
4712 else if (exprtype == JSONBOID)
4713 {
4714 if (pred->item_type == JS_TYPE_ANY)
4715 res = true;
4716 else
4717 {
4718 Jsonb *jb = DatumGetJsonbP(js);
4719
4720 switch (pred->item_type)
4721 {
4722 case JS_TYPE_OBJECT:
4723 res = JB_ROOT_IS_OBJECT(jb);
4724 break;
4725 case JS_TYPE_ARRAY:
4727 break;
4728 case JS_TYPE_SCALAR:
4730 break;
4731 default:
4732 res = false;
4733 break;
4734 }
4735 }
4736
4737 /* Key uniqueness check is redundant for jsonb */
4738 }
4739 else
4740 res = false;
4741
4742 *op->resvalue = BoolGetDatum(res);
4743}
4744
4745/*
4746 * Evaluate a jsonpath against a document, both of which must have been
4747 * evaluated and their values saved in op->d.jsonexpr.jsestate.
4748 *
4749 * If an error occurs during JsonPath* evaluation or when coercing its result
4750 * to the RETURNING type, JsonExprState.error is set to true, provided the
4751 * ON ERROR behavior is not ERROR. Similarly, if JsonPath{Query|Value}() found
4752 * no matching items, JsonExprState.empty is set to true, provided the ON EMPTY
4753 * behavior is not ERROR. That is to signal to the subsequent steps that check
4754 * those flags to return the ON ERROR / ON EMPTY expression.
4755 *
4756 * Return value is the step address to be performed next. It will be one of
4757 * jump_error, jump_empty, jump_eval_coercion, or jump_end, all given in
4758 * op->d.jsonexpr.jsestate.
4759 */
4760int
4762 ExprContext *econtext)
4763{
4764 JsonExprState *jsestate = op->d.jsonexpr.jsestate;
4765 JsonExpr *jsexpr = jsestate->jsexpr;
4766 Datum item;
4767 JsonPath *path;
4768 bool throw_error = jsexpr->on_error->btype == JSON_BEHAVIOR_ERROR;
4769 bool error = false,
4770 empty = false;
4771 int jump_eval_coercion = jsestate->jump_eval_coercion;
4772 char *val_string = NULL;
4773
4776
4777 /* Set error/empty to false. */
4778 memset(&jsestate->error, 0, sizeof(NullableDatum));
4779 memset(&jsestate->empty, 0, sizeof(NullableDatum));
4780
4781 /* Also reset ErrorSaveContext contents for the next row. */
4783 {
4786 }
4788
4789 switch (jsexpr->op)
4790 {
4791 case JSON_EXISTS_OP:
4792 {
4793 bool exists = JsonPathExists(item, path,
4794 !throw_error ? &error : NULL,
4795 jsestate->args);
4796
4797 if (!error)
4798 {
4799 *op->resnull = false;
4800 *op->resvalue = BoolGetDatum(exists);
4801 }
4802 }
4803 break;
4804
4805 case JSON_QUERY_OP:
4806 *op->resvalue = JsonPathQuery(item, path, jsexpr->wrapper, &empty,
4807 !throw_error ? &error : NULL,
4808 jsestate->args,
4809 jsexpr->column_name);
4810
4811 *op->resnull = (DatumGetPointer(*op->resvalue) == NULL);
4812 break;
4813
4814 case JSON_VALUE_OP:
4815 {
4816 JsonbValue *jbv = JsonPathValue(item, path, &empty,
4817 !throw_error ? &error : NULL,
4818 jsestate->args,
4819 jsexpr->column_name);
4820
4821 if (jbv == NULL)
4822 {
4823 /* Will be coerced with json_populate_type(), if needed. */
4824 *op->resvalue = (Datum) 0;
4825 *op->resnull = true;
4826 }
4827 else if (!error && !empty)
4828 {
4829 if (jsexpr->returning->typid == JSONOID ||
4830 jsexpr->returning->typid == JSONBOID)
4831 {
4834 }
4835 else if (jsexpr->use_json_coercion)
4836 {
4837 *op->resvalue = JsonbPGetDatum(JsonbValueToJsonb(jbv));
4838 *op->resnull = false;
4839 }
4840 else
4841 {
4842 val_string = ExecGetJsonValueItemString(jbv, op->resnull);
4843
4844 /*
4845 * Simply convert to the default RETURNING type (text)
4846 * if no coercion needed.
4847 */
4848 if (!jsexpr->use_io_coercion)
4849 *op->resvalue = DirectFunctionCall1(textin,
4851 }
4852 }
4853 break;
4854 }
4855
4856 /* JSON_TABLE_OP can't happen here */
4857
4858 default:
4859 elog(ERROR, "unrecognized SQL/JSON expression op %d",
4860 (int) jsexpr->op);
4861 return false;
4862 }
4863
4864 /*
4865 * Coerce the result value to the RETURNING type by calling its input
4866 * function.
4867 */
4868 if (!*op->resnull && jsexpr->use_io_coercion)
4869 {
4870 FunctionCallInfo fcinfo;
4871
4872 Assert(jump_eval_coercion == -1);
4873 fcinfo = jsestate->input_fcinfo;
4874 Assert(fcinfo != NULL);
4875 Assert(val_string != NULL);
4876 fcinfo->args[0].value = PointerGetDatum(val_string);
4877 fcinfo->args[0].isnull = *op->resnull;
4878
4879 /*
4880 * Second and third arguments are already set up in
4881 * ExecInitJsonExpr().
4882 */
4883
4884 fcinfo->isnull = false;
4885 *op->resvalue = FunctionCallInvoke(fcinfo);
4887 error = true;
4888 }
4889
4890 /*
4891 * When setting up the ErrorSaveContext (if needed) for capturing the
4892 * errors that occur when coercing the JsonBehavior expression, set
4893 * details_wanted to be able to show the actual error message as the
4894 * DETAIL of the error message that tells that it is the JsonBehavior
4895 * expression that caused the error; see ExecEvalJsonCoercionFinish().
4896 */
4897
4898 /* Handle ON EMPTY. */
4899 if (empty)
4900 {
4901 *op->resvalue = (Datum) 0;
4902 *op->resnull = true;
4903 if (jsexpr->on_empty)
4904 {
4905 if (jsexpr->on_empty->btype != JSON_BEHAVIOR_ERROR)
4906 {
4908 /* Set up to catch coercion errors of the ON EMPTY value. */
4911 /* Jump to end if the ON EMPTY behavior is to return NULL */
4913 }
4914 }
4915 else if (jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR)
4916 {
4918 /* Set up to catch coercion errors of the ON ERROR value. */
4921 Assert(!throw_error);
4922 /* Jump to end if the ON ERROR behavior is to return NULL */
4924 }
4925
4926 if (jsexpr->column_name)
4927 ereport(ERROR,
4928 errcode(ERRCODE_NO_SQL_JSON_ITEM),
4929 errmsg("no SQL/JSON item found for specified path of column \"%s\"",
4930 jsexpr->column_name));
4931 else
4932 ereport(ERROR,
4933 errcode(ERRCODE_NO_SQL_JSON_ITEM),
4934 errmsg("no SQL/JSON item found for specified path"));
4935 }
4936
4937 /*
4938 * ON ERROR. Wouldn't get here if the behavior is ERROR, because they
4939 * would have already been thrown.
4940 */
4941 if (error)
4942 {
4943 Assert(!throw_error);
4944 *op->resvalue = (Datum) 0;
4945 *op->resnull = true;
4947 /* Set up to catch coercion errors of the ON ERROR value. */
4950 /* Jump to end if the ON ERROR behavior is to return NULL */
4952 }
4953
4954 return jump_eval_coercion >= 0 ? jump_eval_coercion : jsestate->jump_end;
4955}
4956
4957/*
4958 * Convert the given JsonbValue to its C string representation
4