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