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