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-2019, 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 "utils/array.h"
66 #include "utils/memutils.h"
67 #include "miscadmin.h"
68 #include "nodes/nodeFuncs.h"
69 #include "parser/parsetree.h"
70 #include "pgstat.h"
71 #include "utils/builtins.h"
72 #include "utils/date.h"
73 #include "utils/datum.h"
74 #include "utils/expandedrecord.h"
75 #include "utils/lsyscache.h"
76 #include "utils/timestamp.h"
77 #include "utils/typcache.h"
78 #include "utils/xml.h"
79 
80 
81 /*
82  * Use computed-goto-based opcode dispatch when computed gotos are available.
83  * But use a separate symbol so that it's easy to adjust locally in this file
84  * for development and testing.
85  */
86 #ifdef HAVE_COMPUTED_GOTO
87 #define EEO_USE_COMPUTED_GOTO
88 #endif /* HAVE_COMPUTED_GOTO */
89 
90 /*
91  * Macros for opcode dispatch.
92  *
93  * EEO_SWITCH - just hides the switch if not in use.
94  * EEO_CASE - labels the implementation of named expression step type.
95  * EEO_DISPATCH - jump to the implementation of the step type for 'op'.
96  * EEO_OPCODE - compute opcode required by used expression evaluation method.
97  * EEO_NEXT - increment 'op' and jump to correct next step type.
98  * EEO_JUMP - jump to the specified step number within the current expression.
99  */
100 #if defined(EEO_USE_COMPUTED_GOTO)
101 
102 /* struct for jump target -> opcode lookup table */
103 typedef struct ExprEvalOpLookup
104 {
105  const void *opcode;
106  ExprEvalOp op;
107 } ExprEvalOpLookup;
108 
109 /* to make dispatch_table accessible outside ExecInterpExpr() */
110 static const void **dispatch_table = NULL;
111 
112 /* jump target -> opcode lookup table */
113 static ExprEvalOpLookup reverse_dispatch_table[EEOP_LAST];
114 
115 #define EEO_SWITCH()
116 #define EEO_CASE(name) CASE_##name:
117 #define EEO_DISPATCH() goto *((void *) op->opcode)
118 #define EEO_OPCODE(opcode) ((intptr_t) dispatch_table[opcode])
119 
120 #else /* !EEO_USE_COMPUTED_GOTO */
121 
122 #define EEO_SWITCH() starteval: switch ((ExprEvalOp) op->opcode)
123 #define EEO_CASE(name) case name:
124 #define EEO_DISPATCH() goto starteval
125 #define EEO_OPCODE(opcode) (opcode)
126 
127 #endif /* EEO_USE_COMPUTED_GOTO */
128 
129 #define EEO_NEXT() \
130  do { \
131  op++; \
132  EEO_DISPATCH(); \
133  } while (0)
134 
135 #define EEO_JUMP(stepno) \
136  do { \
137  op = &state->steps[stepno]; \
138  EEO_DISPATCH(); \
139  } while (0)
140 
141 
142 static Datum ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull);
143 static void ExecInitInterpreter(void);
144 
145 /* support functions */
146 static void CheckVarSlotCompatibility(TupleTableSlot *slot, int attnum, Oid vartype);
148 static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod,
149  TupleDesc *cache_field, ExprContext *econtext);
150 static void ShutdownTupleDescRef(Datum arg);
152  ExprContext *econtext, bool checkisnull);
153 
154 /* fast-path evaluation functions */
155 static Datum ExecJustInnerVar(ExprState *state, ExprContext *econtext, bool *isnull);
156 static Datum ExecJustOuterVar(ExprState *state, ExprContext *econtext, bool *isnull);
157 static Datum ExecJustScanVar(ExprState *state, ExprContext *econtext, bool *isnull);
158 static Datum ExecJustAssignInnerVar(ExprState *state, ExprContext *econtext, bool *isnull);
159 static Datum ExecJustAssignOuterVar(ExprState *state, ExprContext *econtext, bool *isnull);
160 static Datum ExecJustAssignScanVar(ExprState *state, ExprContext *econtext, bool *isnull);
161 static Datum ExecJustApplyFuncToCase(ExprState *state, ExprContext *econtext, bool *isnull);
162 static Datum ExecJustConst(ExprState *state, ExprContext *econtext, bool *isnull);
163 static Datum ExecJustInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
164 static Datum ExecJustOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
165 static Datum ExecJustScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
166 static Datum ExecJustAssignInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
167 static Datum ExecJustAssignOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
168 static Datum ExecJustAssignScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull);
169 
170 
171 /*
172  * Prepare ExprState for interpreted execution.
173  */
174 void
176 {
177  /* Ensure one-time interpreter setup has been done */
179 
180  /* Simple validity checks on expression */
181  Assert(state->steps_len >= 1);
182  Assert(state->steps[state->steps_len - 1].opcode == EEOP_DONE);
183 
184  /*
185  * Don't perform redundant initialization. This is unreachable in current
186  * cases, but might be hit if there's additional expression evaluation
187  * methods that rely on interpreted execution to work.
188  */
190  return;
191 
192  /*
193  * First time through, check whether attribute matches Var. Might not be
194  * ok anymore, due to schema changes. We do that by setting up a callback
195  * that does checking on the first call, which then sets the evalfunc
196  * callback to the actual method of execution.
197  */
199 
200  /* DIRECT_THREADED should not already be set */
201  Assert((state->flags & EEO_FLAG_DIRECT_THREADED) == 0);
202 
203  /*
204  * There shouldn't be any errors before the expression is fully
205  * initialized, and even if so, it'd lead to the expression being
206  * abandoned. So we can set the flag now and save some code.
207  */
209 
210  /*
211  * Select fast-path evalfuncs for very simple expressions. "Starting up"
212  * the full interpreter is a measurable overhead for these, and these
213  * patterns occur often enough to be worth optimizing.
214  */
215  if (state->steps_len == 3)
216  {
217  ExprEvalOp step0 = state->steps[0].opcode;
218  ExprEvalOp step1 = state->steps[1].opcode;
219 
220  if (step0 == EEOP_INNER_FETCHSOME &&
221  step1 == EEOP_INNER_VAR)
222  {
223  state->evalfunc_private = (void *) ExecJustInnerVar;
224  return;
225  }
226  else if (step0 == EEOP_OUTER_FETCHSOME &&
227  step1 == EEOP_OUTER_VAR)
228  {
229  state->evalfunc_private = (void *) ExecJustOuterVar;
230  return;
231  }
232  else if (step0 == EEOP_SCAN_FETCHSOME &&
233  step1 == EEOP_SCAN_VAR)
234  {
235  state->evalfunc_private = (void *) ExecJustScanVar;
236  return;
237  }
238  else if (step0 == EEOP_INNER_FETCHSOME &&
239  step1 == EEOP_ASSIGN_INNER_VAR)
240  {
241  state->evalfunc_private = (void *) ExecJustAssignInnerVar;
242  return;
243  }
244  else if (step0 == EEOP_OUTER_FETCHSOME &&
245  step1 == EEOP_ASSIGN_OUTER_VAR)
246  {
247  state->evalfunc_private = (void *) ExecJustAssignOuterVar;
248  return;
249  }
250  else if (step0 == EEOP_SCAN_FETCHSOME &&
251  step1 == EEOP_ASSIGN_SCAN_VAR)
252  {
253  state->evalfunc_private = (void *) ExecJustAssignScanVar;
254  return;
255  }
256  else if (step0 == EEOP_CASE_TESTVAL &&
257  step1 == EEOP_FUNCEXPR_STRICT &&
258  state->steps[0].d.casetest.value)
259  {
260  state->evalfunc_private = (void *) ExecJustApplyFuncToCase;
261  return;
262  }
263  }
264  else if (state->steps_len == 2)
265  {
266  ExprEvalOp step0 = state->steps[0].opcode;
267 
268  if (step0 == EEOP_CONST)
269  {
270  state->evalfunc_private = (void *) ExecJustConst;
271  return;
272  }
273  else if (step0 == EEOP_INNER_VAR)
274  {
275  state->evalfunc_private = (void *) ExecJustInnerVarVirt;
276  return;
277  }
278  else if (step0 == EEOP_OUTER_VAR)
279  {
280  state->evalfunc_private = (void *) ExecJustOuterVarVirt;
281  return;
282  }
283  else if (step0 == EEOP_SCAN_VAR)
284  {
285  state->evalfunc_private = (void *) ExecJustScanVarVirt;
286  return;
287  }
288  else if (step0 == EEOP_ASSIGN_INNER_VAR)
289  {
291  return;
292  }
293  else if (step0 == EEOP_ASSIGN_OUTER_VAR)
294  {
296  return;
297  }
298  else if (step0 == EEOP_ASSIGN_SCAN_VAR)
299  {
301  return;
302  }
303  }
304 
305 #if defined(EEO_USE_COMPUTED_GOTO)
306 
307  /*
308  * In the direct-threaded implementation, replace each opcode with the
309  * address to jump to. (Use ExecEvalStepOp() to get back the opcode.)
310  */
311  {
312  int off;
313 
314  for (off = 0; off < state->steps_len; off++)
315  {
316  ExprEvalStep *op = &state->steps[off];
317 
318  op->opcode = EEO_OPCODE(op->opcode);
319  }
320 
322  }
323 #endif /* EEO_USE_COMPUTED_GOTO */
324 
325  state->evalfunc_private = (void *) ExecInterpExpr;
326 }
327 
328 
329 /*
330  * Evaluate expression identified by "state" in the execution context
331  * given by "econtext". *isnull is set to the is-null flag for the result,
332  * and the Datum value is the function result.
333  *
334  * As a special case, return the dispatch table's address if state is NULL.
335  * This is used by ExecInitInterpreter to set up the dispatch_table global.
336  * (Only applies when EEO_USE_COMPUTED_GOTO is defined.)
337  */
338 static Datum
339 ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
340 {
341  ExprEvalStep *op;
342  TupleTableSlot *resultslot;
343  TupleTableSlot *innerslot;
344  TupleTableSlot *outerslot;
345  TupleTableSlot *scanslot;
346 
347  /*
348  * This array has to be in the same order as enum ExprEvalOp.
349  */
350 #if defined(EEO_USE_COMPUTED_GOTO)
351  static const void *const dispatch_table[] = {
352  &&CASE_EEOP_DONE,
353  &&CASE_EEOP_INNER_FETCHSOME,
354  &&CASE_EEOP_OUTER_FETCHSOME,
355  &&CASE_EEOP_SCAN_FETCHSOME,
356  &&CASE_EEOP_INNER_VAR,
357  &&CASE_EEOP_OUTER_VAR,
358  &&CASE_EEOP_SCAN_VAR,
359  &&CASE_EEOP_INNER_SYSVAR,
360  &&CASE_EEOP_OUTER_SYSVAR,
361  &&CASE_EEOP_SCAN_SYSVAR,
362  &&CASE_EEOP_WHOLEROW,
363  &&CASE_EEOP_ASSIGN_INNER_VAR,
364  &&CASE_EEOP_ASSIGN_OUTER_VAR,
365  &&CASE_EEOP_ASSIGN_SCAN_VAR,
366  &&CASE_EEOP_ASSIGN_TMP,
367  &&CASE_EEOP_ASSIGN_TMP_MAKE_RO,
368  &&CASE_EEOP_CONST,
369  &&CASE_EEOP_FUNCEXPR,
370  &&CASE_EEOP_FUNCEXPR_STRICT,
371  &&CASE_EEOP_FUNCEXPR_FUSAGE,
372  &&CASE_EEOP_FUNCEXPR_STRICT_FUSAGE,
373  &&CASE_EEOP_BOOL_AND_STEP_FIRST,
374  &&CASE_EEOP_BOOL_AND_STEP,
375  &&CASE_EEOP_BOOL_AND_STEP_LAST,
376  &&CASE_EEOP_BOOL_OR_STEP_FIRST,
377  &&CASE_EEOP_BOOL_OR_STEP,
378  &&CASE_EEOP_BOOL_OR_STEP_LAST,
379  &&CASE_EEOP_BOOL_NOT_STEP,
380  &&CASE_EEOP_QUAL,
381  &&CASE_EEOP_JUMP,
382  &&CASE_EEOP_JUMP_IF_NULL,
383  &&CASE_EEOP_JUMP_IF_NOT_NULL,
384  &&CASE_EEOP_JUMP_IF_NOT_TRUE,
385  &&CASE_EEOP_NULLTEST_ISNULL,
386  &&CASE_EEOP_NULLTEST_ISNOTNULL,
387  &&CASE_EEOP_NULLTEST_ROWISNULL,
388  &&CASE_EEOP_NULLTEST_ROWISNOTNULL,
389  &&CASE_EEOP_BOOLTEST_IS_TRUE,
390  &&CASE_EEOP_BOOLTEST_IS_NOT_TRUE,
391  &&CASE_EEOP_BOOLTEST_IS_FALSE,
392  &&CASE_EEOP_BOOLTEST_IS_NOT_FALSE,
393  &&CASE_EEOP_PARAM_EXEC,
394  &&CASE_EEOP_PARAM_EXTERN,
395  &&CASE_EEOP_PARAM_CALLBACK,
396  &&CASE_EEOP_CASE_TESTVAL,
397  &&CASE_EEOP_MAKE_READONLY,
398  &&CASE_EEOP_IOCOERCE,
399  &&CASE_EEOP_DISTINCT,
400  &&CASE_EEOP_NOT_DISTINCT,
401  &&CASE_EEOP_NULLIF,
402  &&CASE_EEOP_SQLVALUEFUNCTION,
403  &&CASE_EEOP_CURRENTOFEXPR,
404  &&CASE_EEOP_NEXTVALUEEXPR,
405  &&CASE_EEOP_ARRAYEXPR,
406  &&CASE_EEOP_ARRAYCOERCE,
407  &&CASE_EEOP_ROW,
408  &&CASE_EEOP_ROWCOMPARE_STEP,
409  &&CASE_EEOP_ROWCOMPARE_FINAL,
410  &&CASE_EEOP_MINMAX,
411  &&CASE_EEOP_FIELDSELECT,
412  &&CASE_EEOP_FIELDSTORE_DEFORM,
413  &&CASE_EEOP_FIELDSTORE_FORM,
414  &&CASE_EEOP_SBSREF_SUBSCRIPT,
415  &&CASE_EEOP_SBSREF_OLD,
416  &&CASE_EEOP_SBSREF_ASSIGN,
417  &&CASE_EEOP_SBSREF_FETCH,
418  &&CASE_EEOP_DOMAIN_TESTVAL,
419  &&CASE_EEOP_DOMAIN_NOTNULL,
420  &&CASE_EEOP_DOMAIN_CHECK,
421  &&CASE_EEOP_CONVERT_ROWTYPE,
422  &&CASE_EEOP_SCALARARRAYOP,
423  &&CASE_EEOP_XMLEXPR,
424  &&CASE_EEOP_AGGREF,
425  &&CASE_EEOP_GROUPING_FUNC,
426  &&CASE_EEOP_WINDOW_FUNC,
427  &&CASE_EEOP_SUBPLAN,
428  &&CASE_EEOP_ALTERNATIVE_SUBPLAN,
429  &&CASE_EEOP_AGG_STRICT_DESERIALIZE,
430  &&CASE_EEOP_AGG_DESERIALIZE,
431  &&CASE_EEOP_AGG_STRICT_INPUT_CHECK_ARGS,
432  &&CASE_EEOP_AGG_STRICT_INPUT_CHECK_NULLS,
433  &&CASE_EEOP_AGG_INIT_TRANS,
434  &&CASE_EEOP_AGG_STRICT_TRANS_CHECK,
435  &&CASE_EEOP_AGG_PLAIN_TRANS_BYVAL,
436  &&CASE_EEOP_AGG_PLAIN_TRANS,
437  &&CASE_EEOP_AGG_ORDERED_TRANS_DATUM,
438  &&CASE_EEOP_AGG_ORDERED_TRANS_TUPLE,
439  &&CASE_EEOP_LAST
440  };
441 
442  StaticAssertStmt(EEOP_LAST + 1 == lengthof(dispatch_table),
443  "dispatch_table out of whack with ExprEvalOp");
444 
445  if (unlikely(state == NULL))
446  return PointerGetDatum(dispatch_table);
447 #else
448  Assert(state != NULL);
449 #endif /* EEO_USE_COMPUTED_GOTO */
450 
451  /* setup state */
452  op = state->steps;
453  resultslot = state->resultslot;
454  innerslot = econtext->ecxt_innertuple;
455  outerslot = econtext->ecxt_outertuple;
456  scanslot = econtext->ecxt_scantuple;
457 
458 #if defined(EEO_USE_COMPUTED_GOTO)
459  EEO_DISPATCH();
460 #endif
461 
462  EEO_SWITCH()
463  {
465  {
466  goto out;
467  }
468 
470  {
471  CheckOpSlotCompatibility(op, innerslot);
472 
473  slot_getsomeattrs(innerslot, op->d.fetch.last_var);
474 
475  EEO_NEXT();
476  }
477 
479  {
480  CheckOpSlotCompatibility(op, outerslot);
481 
482  slot_getsomeattrs(outerslot, op->d.fetch.last_var);
483 
484  EEO_NEXT();
485  }
486 
488  {
489  CheckOpSlotCompatibility(op, scanslot);
490 
491  slot_getsomeattrs(scanslot, op->d.fetch.last_var);
492 
493  EEO_NEXT();
494  }
495 
497  {
498  int attnum = op->d.var.attnum;
499 
500  /*
501  * Since we already extracted all referenced columns from the
502  * tuple with a FETCHSOME step, we can just grab the value
503  * directly out of the slot's decomposed-data arrays. But let's
504  * have an Assert to check that that did happen.
505  */
506  Assert(attnum >= 0 && attnum < innerslot->tts_nvalid);
507  *op->resvalue = innerslot->tts_values[attnum];
508  *op->resnull = innerslot->tts_isnull[attnum];
509 
510  EEO_NEXT();
511  }
512 
514  {
515  int attnum = op->d.var.attnum;
516 
517  /* See EEOP_INNER_VAR comments */
518 
519  Assert(attnum >= 0 && attnum < outerslot->tts_nvalid);
520  *op->resvalue = outerslot->tts_values[attnum];
521  *op->resnull = outerslot->tts_isnull[attnum];
522 
523  EEO_NEXT();
524  }
525 
527  {
528  int attnum = op->d.var.attnum;
529 
530  /* See EEOP_INNER_VAR comments */
531 
532  Assert(attnum >= 0 && attnum < scanslot->tts_nvalid);
533  *op->resvalue = scanslot->tts_values[attnum];
534  *op->resnull = scanslot->tts_isnull[attnum];
535 
536  EEO_NEXT();
537  }
538 
540  {
541  ExecEvalSysVar(state, op, econtext, innerslot);
542  EEO_NEXT();
543  }
544 
546  {
547  ExecEvalSysVar(state, op, econtext, outerslot);
548  EEO_NEXT();
549  }
550 
552  {
553  ExecEvalSysVar(state, op, econtext, scanslot);
554  EEO_NEXT();
555  }
556 
558  {
559  /* too complex for an inline implementation */
560  ExecEvalWholeRowVar(state, op, econtext);
561 
562  EEO_NEXT();
563  }
564 
566  {
567  int resultnum = op->d.assign_var.resultnum;
568  int attnum = op->d.assign_var.attnum;
569 
570  /*
571  * We do not need CheckVarSlotCompatibility here; that was taken
572  * care of at compilation time. But see EEOP_INNER_VAR comments.
573  */
574  Assert(attnum >= 0 && attnum < innerslot->tts_nvalid);
575  resultslot->tts_values[resultnum] = innerslot->tts_values[attnum];
576  resultslot->tts_isnull[resultnum] = innerslot->tts_isnull[attnum];
577 
578  EEO_NEXT();
579  }
580 
582  {
583  int resultnum = op->d.assign_var.resultnum;
584  int attnum = op->d.assign_var.attnum;
585 
586  /*
587  * We do not need CheckVarSlotCompatibility here; that was taken
588  * care of at compilation time. But see EEOP_INNER_VAR comments.
589  */
590  Assert(attnum >= 0 && attnum < outerslot->tts_nvalid);
591  resultslot->tts_values[resultnum] = outerslot->tts_values[attnum];
592  resultslot->tts_isnull[resultnum] = outerslot->tts_isnull[attnum];
593 
594  EEO_NEXT();
595  }
596 
598  {
599  int resultnum = op->d.assign_var.resultnum;
600  int attnum = op->d.assign_var.attnum;
601 
602  /*
603  * We do not need CheckVarSlotCompatibility here; that was taken
604  * care of at compilation time. But see EEOP_INNER_VAR comments.
605  */
606  Assert(attnum >= 0 && attnum < scanslot->tts_nvalid);
607  resultslot->tts_values[resultnum] = scanslot->tts_values[attnum];
608  resultslot->tts_isnull[resultnum] = scanslot->tts_isnull[attnum];
609 
610  EEO_NEXT();
611  }
612 
614  {
615  int resultnum = op->d.assign_tmp.resultnum;
616 
617  resultslot->tts_values[resultnum] = state->resvalue;
618  resultslot->tts_isnull[resultnum] = state->resnull;
619 
620  EEO_NEXT();
621  }
622 
624  {
625  int resultnum = op->d.assign_tmp.resultnum;
626 
627  resultslot->tts_isnull[resultnum] = state->resnull;
628  if (!resultslot->tts_isnull[resultnum])
629  resultslot->tts_values[resultnum] =
631  else
632  resultslot->tts_values[resultnum] = state->resvalue;
633 
634  EEO_NEXT();
635  }
636 
638  {
639  *op->resnull = op->d.constval.isnull;
640  *op->resvalue = op->d.constval.value;
641 
642  EEO_NEXT();
643  }
644 
645  /*
646  * Function-call implementations. Arguments have previously been
647  * evaluated directly into fcinfo->args.
648  *
649  * As both STRICT checks and function-usage are noticeable performance
650  * wise, and function calls are a very hot-path (they also back
651  * operators!), it's worth having so many separate opcodes.
652  *
653  * Note: the reason for using a temporary variable "d", here and in
654  * other places, is that some compilers think "*op->resvalue = f();"
655  * requires them to evaluate op->resvalue into a register before
656  * calling f(), just in case f() is able to modify op->resvalue
657  * somehow. The extra line of code can save a useless register spill
658  * and reload across the function call.
659  */
661  {
662  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
663  Datum d;
664 
665  fcinfo->isnull = false;
666  d = op->d.func.fn_addr(fcinfo);
667  *op->resvalue = d;
668  *op->resnull = fcinfo->isnull;
669 
670  EEO_NEXT();
671  }
672 
674  {
675  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
676  NullableDatum *args = fcinfo->args;
677  int argno;
678  Datum d;
679 
680  /* strict function, so check for NULL args */
681  for (argno = 0; argno < op->d.func.nargs; argno++)
682  {
683  if (args[argno].isnull)
684  {
685  *op->resnull = true;
686  goto strictfail;
687  }
688  }
689  fcinfo->isnull = false;
690  d = op->d.func.fn_addr(fcinfo);
691  *op->resvalue = d;
692  *op->resnull = fcinfo->isnull;
693 
694  strictfail:
695  EEO_NEXT();
696  }
697 
699  {
700  /* not common enough to inline */
701  ExecEvalFuncExprFusage(state, op, econtext);
702 
703  EEO_NEXT();
704  }
705 
707  {
708  /* not common enough to inline */
709  ExecEvalFuncExprStrictFusage(state, op, econtext);
710 
711  EEO_NEXT();
712  }
713 
714  /*
715  * If any of its clauses is FALSE, an AND's result is FALSE regardless
716  * of the states of the rest of the clauses, so we can stop evaluating
717  * and return FALSE immediately. If none are FALSE and one or more is
718  * NULL, we return NULL; otherwise we return TRUE. This makes sense
719  * when you interpret NULL as "don't know": perhaps one of the "don't
720  * knows" would have been FALSE if we'd known its value. Only when
721  * all the inputs are known to be TRUE can we state confidently that
722  * the AND's result is TRUE.
723  */
725  {
726  *op->d.boolexpr.anynull = false;
727 
728  /*
729  * EEOP_BOOL_AND_STEP_FIRST resets anynull, otherwise it's the
730  * same as EEOP_BOOL_AND_STEP - so fall through to that.
731  */
732 
733  /* FALL THROUGH */
734  }
735 
737  {
738  if (*op->resnull)
739  {
740  *op->d.boolexpr.anynull = true;
741  }
742  else if (!DatumGetBool(*op->resvalue))
743  {
744  /* result is already set to FALSE, need not change it */
745  /* bail out early */
746  EEO_JUMP(op->d.boolexpr.jumpdone);
747  }
748 
749  EEO_NEXT();
750  }
751 
753  {
754  if (*op->resnull)
755  {
756  /* result is already set to NULL, need not change it */
757  }
758  else if (!DatumGetBool(*op->resvalue))
759  {
760  /* result is already set to FALSE, need not change it */
761 
762  /*
763  * No point jumping early to jumpdone - would be same target
764  * (as this is the last argument to the AND expression),
765  * except more expensive.
766  */
767  }
768  else if (*op->d.boolexpr.anynull)
769  {
770  *op->resvalue = (Datum) 0;
771  *op->resnull = true;
772  }
773  else
774  {
775  /* result is already set to TRUE, need not change it */
776  }
777 
778  EEO_NEXT();
779  }
780 
781  /*
782  * If any of its clauses is TRUE, an OR's result is TRUE regardless of
783  * the states of the rest of the clauses, so we can stop evaluating
784  * and return TRUE immediately. If none are TRUE and one or more is
785  * NULL, we return NULL; otherwise we return FALSE. This makes sense
786  * when you interpret NULL as "don't know": perhaps one of the "don't
787  * knows" would have been TRUE if we'd known its value. Only when all
788  * the inputs are known to be FALSE can we state confidently that the
789  * OR's result is FALSE.
790  */
792  {
793  *op->d.boolexpr.anynull = false;
794 
795  /*
796  * EEOP_BOOL_OR_STEP_FIRST resets anynull, otherwise it's the same
797  * as EEOP_BOOL_OR_STEP - so fall through to that.
798  */
799 
800  /* FALL THROUGH */
801  }
802 
804  {
805  if (*op->resnull)
806  {
807  *op->d.boolexpr.anynull = true;
808  }
809  else if (DatumGetBool(*op->resvalue))
810  {
811  /* result is already set to TRUE, need not change it */
812  /* bail out early */
813  EEO_JUMP(op->d.boolexpr.jumpdone);
814  }
815 
816  EEO_NEXT();
817  }
818 
820  {
821  if (*op->resnull)
822  {
823  /* result is already set to NULL, need not change it */
824  }
825  else if (DatumGetBool(*op->resvalue))
826  {
827  /* result is already set to TRUE, need not change it */
828 
829  /*
830  * No point jumping to jumpdone - would be same target (as
831  * this is the last argument to the AND expression), except
832  * more expensive.
833  */
834  }
835  else if (*op->d.boolexpr.anynull)
836  {
837  *op->resvalue = (Datum) 0;
838  *op->resnull = true;
839  }
840  else
841  {
842  /* result is already set to FALSE, need not change it */
843  }
844 
845  EEO_NEXT();
846  }
847 
849  {
850  /*
851  * Evaluation of 'not' is simple... if expr is false, then return
852  * 'true' and vice versa. It's safe to do this even on a
853  * nominally null value, so we ignore resnull; that means that
854  * NULL in produces NULL out, which is what we want.
855  */
857 
858  EEO_NEXT();
859  }
860 
862  {
863  /* simplified version of BOOL_AND_STEP for use by ExecQual() */
864 
865  /* If argument (also result) is false or null ... */
866  if (*op->resnull ||
867  !DatumGetBool(*op->resvalue))
868  {
869  /* ... bail out early, returning FALSE */
870  *op->resnull = false;
871  *op->resvalue = BoolGetDatum(false);
872  EEO_JUMP(op->d.qualexpr.jumpdone);
873  }
874 
875  /*
876  * Otherwise, leave the TRUE value in place, in case this is the
877  * last qual. Then, TRUE is the correct answer.
878  */
879 
880  EEO_NEXT();
881  }
882 
884  {
885  /* Unconditionally jump to target step */
886  EEO_JUMP(op->d.jump.jumpdone);
887  }
888 
890  {
891  /* Transfer control if current result is null */
892  if (*op->resnull)
893  EEO_JUMP(op->d.jump.jumpdone);
894 
895  EEO_NEXT();
896  }
897 
899  {
900  /* Transfer control if current result is non-null */
901  if (!*op->resnull)
902  EEO_JUMP(op->d.jump.jumpdone);
903 
904  EEO_NEXT();
905  }
906 
908  {
909  /* Transfer control if current result is null or false */
910  if (*op->resnull || !DatumGetBool(*op->resvalue))
911  EEO_JUMP(op->d.jump.jumpdone);
912 
913  EEO_NEXT();
914  }
915 
917  {
918  *op->resvalue = BoolGetDatum(*op->resnull);
919  *op->resnull = false;
920 
921  EEO_NEXT();
922  }
923 
925  {
926  *op->resvalue = BoolGetDatum(!*op->resnull);
927  *op->resnull = false;
928 
929  EEO_NEXT();
930  }
931 
933  {
934  /* out of line implementation: too large */
935  ExecEvalRowNull(state, op, econtext);
936 
937  EEO_NEXT();
938  }
939 
941  {
942  /* out of line implementation: too large */
943  ExecEvalRowNotNull(state, op, econtext);
944 
945  EEO_NEXT();
946  }
947 
948  /* BooleanTest implementations for all booltesttypes */
949 
951  {
952  if (*op->resnull)
953  {
954  *op->resvalue = BoolGetDatum(false);
955  *op->resnull = false;
956  }
957  /* else, input value is the correct output as well */
958 
959  EEO_NEXT();
960  }
961 
963  {
964  if (*op->resnull)
965  {
966  *op->resvalue = BoolGetDatum(true);
967  *op->resnull = false;
968  }
969  else
971 
972  EEO_NEXT();
973  }
974 
976  {
977  if (*op->resnull)
978  {
979  *op->resvalue = BoolGetDatum(false);
980  *op->resnull = false;
981  }
982  else
984 
985  EEO_NEXT();
986  }
987 
989  {
990  if (*op->resnull)
991  {
992  *op->resvalue = BoolGetDatum(true);
993  *op->resnull = false;
994  }
995  /* else, input value is the correct output as well */
996 
997  EEO_NEXT();
998  }
999 
1001  {
1002  /* out of line implementation: too large */
1003  ExecEvalParamExec(state, op, econtext);
1004 
1005  EEO_NEXT();
1006  }
1007 
1009  {
1010  /* out of line implementation: too large */
1011  ExecEvalParamExtern(state, op, econtext);
1012  EEO_NEXT();
1013  }
1014 
1016  {
1017  /* allow an extension module to supply a PARAM_EXTERN value */
1018  op->d.cparam.paramfunc(state, op, econtext);
1019  EEO_NEXT();
1020  }
1021 
1023  {
1024  /*
1025  * Normally upper parts of the expression tree have setup the
1026  * values to be returned here, but some parts of the system
1027  * currently misuse {caseValue,domainValue}_{datum,isNull} to set
1028  * run-time data. So if no values have been set-up, use
1029  * ExprContext's. This isn't pretty, but also not *that* ugly,
1030  * and this is unlikely to be performance sensitive enough to
1031  * worry about an extra branch.
1032  */
1033  if (op->d.casetest.value)
1034  {
1035  *op->resvalue = *op->d.casetest.value;
1036  *op->resnull = *op->d.casetest.isnull;
1037  }
1038  else
1039  {
1040  *op->resvalue = econtext->caseValue_datum;
1041  *op->resnull = econtext->caseValue_isNull;
1042  }
1043 
1044  EEO_NEXT();
1045  }
1046 
1048  {
1049  /*
1050  * See EEOP_CASE_TESTVAL comment.
1051  */
1052  if (op->d.casetest.value)
1053  {
1054  *op->resvalue = *op->d.casetest.value;
1055  *op->resnull = *op->d.casetest.isnull;
1056  }
1057  else
1058  {
1059  *op->resvalue = econtext->domainValue_datum;
1060  *op->resnull = econtext->domainValue_isNull;
1061  }
1062 
1063  EEO_NEXT();
1064  }
1065 
1067  {
1068  /*
1069  * Force a varlena value that might be read multiple times to R/O
1070  */
1071  if (!*op->d.make_readonly.isnull)
1072  *op->resvalue =
1074  *op->resnull = *op->d.make_readonly.isnull;
1075 
1076  EEO_NEXT();
1077  }
1078 
1080  {
1081  /*
1082  * Evaluate a CoerceViaIO node. This can be quite a hot path, so
1083  * inline as much work as possible. The source value is in our
1084  * result variable.
1085  */
1086  char *str;
1087 
1088  /* call output function (similar to OutputFunctionCall) */
1089  if (*op->resnull)
1090  {
1091  /* output functions are not called on nulls */
1092  str = NULL;
1093  }
1094  else
1095  {
1096  FunctionCallInfo fcinfo_out;
1097 
1098  fcinfo_out = op->d.iocoerce.fcinfo_data_out;
1099  fcinfo_out->args[0].value = *op->resvalue;
1100  fcinfo_out->args[0].isnull = false;
1101 
1102  fcinfo_out->isnull = false;
1103  str = DatumGetCString(FunctionCallInvoke(fcinfo_out));
1104 
1105  /* OutputFunctionCall assumes result isn't null */
1106  Assert(!fcinfo_out->isnull);
1107  }
1108 
1109  /* call input function (similar to InputFunctionCall) */
1110  if (!op->d.iocoerce.finfo_in->fn_strict || str != NULL)
1111  {
1112  FunctionCallInfo fcinfo_in;
1113  Datum d;
1114 
1115  fcinfo_in = op->d.iocoerce.fcinfo_data_in;
1116  fcinfo_in->args[0].value = PointerGetDatum(str);
1117  fcinfo_in->args[0].isnull = *op->resnull;
1118  /* second and third arguments are already set up */
1119 
1120  fcinfo_in->isnull = false;
1121  d = FunctionCallInvoke(fcinfo_in);
1122  *op->resvalue = d;
1123 
1124  /* Should get null result if and only if str is NULL */
1125  if (str == NULL)
1126  {
1127  Assert(*op->resnull);
1128  Assert(fcinfo_in->isnull);
1129  }
1130  else
1131  {
1132  Assert(!*op->resnull);
1133  Assert(!fcinfo_in->isnull);
1134  }
1135  }
1136 
1137  EEO_NEXT();
1138  }
1139 
1141  {
1142  /*
1143  * IS DISTINCT FROM must evaluate arguments (already done into
1144  * fcinfo->args) to determine whether they are NULL; if either is
1145  * NULL then the result is determined. If neither is NULL, then
1146  * proceed to evaluate the comparison function, which is just the
1147  * type's standard equality operator. We need not care whether
1148  * that function is strict. Because the handling of nulls is
1149  * different, we can't just reuse EEOP_FUNCEXPR.
1150  */
1151  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
1152 
1153  /* check function arguments for NULLness */
1154  if (fcinfo->args[0].isnull && fcinfo->args[1].isnull)
1155  {
1156  /* Both NULL? Then is not distinct... */
1157  *op->resvalue = BoolGetDatum(false);
1158  *op->resnull = false;
1159  }
1160  else if (fcinfo->args[0].isnull || fcinfo->args[1].isnull)
1161  {
1162  /* Only one is NULL? Then is distinct... */
1163  *op->resvalue = BoolGetDatum(true);
1164  *op->resnull = false;
1165  }
1166  else
1167  {
1168  /* Neither null, so apply the equality function */
1169  Datum eqresult;
1170 
1171  fcinfo->isnull = false;
1172  eqresult = op->d.func.fn_addr(fcinfo);
1173  /* Must invert result of "="; safe to do even if null */
1174  *op->resvalue = BoolGetDatum(!DatumGetBool(eqresult));
1175  *op->resnull = fcinfo->isnull;
1176  }
1177 
1178  EEO_NEXT();
1179  }
1180 
1181  /* see EEOP_DISTINCT for comments, this is just inverted */
1183  {
1184  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
1185 
1186  if (fcinfo->args[0].isnull && fcinfo->args[1].isnull)
1187  {
1188  *op->resvalue = BoolGetDatum(true);
1189  *op->resnull = false;
1190  }
1191  else if (fcinfo->args[0].isnull || fcinfo->args[1].isnull)
1192  {
1193  *op->resvalue = BoolGetDatum(false);
1194  *op->resnull = false;
1195  }
1196  else
1197  {
1198  Datum eqresult;
1199 
1200  fcinfo->isnull = false;
1201  eqresult = op->d.func.fn_addr(fcinfo);
1202  *op->resvalue = eqresult;
1203  *op->resnull = fcinfo->isnull;
1204  }
1205 
1206  EEO_NEXT();
1207  }
1208 
1210  {
1211  /*
1212  * The arguments are already evaluated into fcinfo->args.
1213  */
1214  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
1215 
1216  /* if either argument is NULL they can't be equal */
1217  if (!fcinfo->args[0].isnull && !fcinfo->args[1].isnull)
1218  {
1219  Datum result;
1220 
1221  fcinfo->isnull = false;
1222  result = op->d.func.fn_addr(fcinfo);
1223 
1224  /* if the arguments are equal return null */
1225  if (!fcinfo->isnull && DatumGetBool(result))
1226  {
1227  *op->resvalue = (Datum) 0;
1228  *op->resnull = true;
1229 
1230  EEO_NEXT();
1231  }
1232  }
1233 
1234  /* Arguments aren't equal, so return the first one */
1235  *op->resvalue = fcinfo->args[0].value;
1236  *op->resnull = fcinfo->args[0].isnull;
1237 
1238  EEO_NEXT();
1239  }
1240 
1242  {
1243  /*
1244  * Doesn't seem worthwhile to have an inline implementation
1245  * efficiency-wise.
1246  */
1247  ExecEvalSQLValueFunction(state, op);
1248 
1249  EEO_NEXT();
1250  }
1251 
1253  {
1254  /* error invocation uses space, and shouldn't ever occur */
1255  ExecEvalCurrentOfExpr(state, op);
1256 
1257  EEO_NEXT();
1258  }
1259 
1261  {
1262  /*
1263  * Doesn't seem worthwhile to have an inline implementation
1264  * efficiency-wise.
1265  */
1266  ExecEvalNextValueExpr(state, op);
1267 
1268  EEO_NEXT();
1269  }
1270 
1272  {
1273  /* too complex for an inline implementation */
1274  ExecEvalArrayExpr(state, op);
1275 
1276  EEO_NEXT();
1277  }
1278 
1280  {
1281  /* too complex for an inline implementation */
1282  ExecEvalArrayCoerce(state, op, econtext);
1283 
1284  EEO_NEXT();
1285  }
1286 
1288  {
1289  /* too complex for an inline implementation */
1290  ExecEvalRow(state, op);
1291 
1292  EEO_NEXT();
1293  }
1294 
1296  {
1297  FunctionCallInfo fcinfo = op->d.rowcompare_step.fcinfo_data;
1298  Datum d;
1299 
1300  /* force NULL result if strict fn and NULL input */
1301  if (op->d.rowcompare_step.finfo->fn_strict &&
1302  (fcinfo->args[0].isnull || fcinfo->args[1].isnull))
1303  {
1304  *op->resnull = true;
1305  EEO_JUMP(op->d.rowcompare_step.jumpnull);
1306  }
1307 
1308  /* Apply comparison function */
1309  fcinfo->isnull = false;
1310  d = op->d.rowcompare_step.fn_addr(fcinfo);
1311  *op->resvalue = d;
1312 
1313  /* force NULL result if NULL function result */
1314  if (fcinfo->isnull)
1315  {
1316  *op->resnull = true;
1317  EEO_JUMP(op->d.rowcompare_step.jumpnull);
1318  }
1319  *op->resnull = false;
1320 
1321  /* If unequal, no need to compare remaining columns */
1322  if (DatumGetInt32(*op->resvalue) != 0)
1323  {
1324  EEO_JUMP(op->d.rowcompare_step.jumpdone);
1325  }
1326 
1327  EEO_NEXT();
1328  }
1329 
1331  {
1332  int32 cmpresult = DatumGetInt32(*op->resvalue);
1333  RowCompareType rctype = op->d.rowcompare_final.rctype;
1334 
1335  *op->resnull = false;
1336  switch (rctype)
1337  {
1338  /* EQ and NE cases aren't allowed here */
1339  case ROWCOMPARE_LT:
1340  *op->resvalue = BoolGetDatum(cmpresult < 0);
1341  break;
1342  case ROWCOMPARE_LE:
1343  *op->resvalue = BoolGetDatum(cmpresult <= 0);
1344  break;
1345  case ROWCOMPARE_GE:
1346  *op->resvalue = BoolGetDatum(cmpresult >= 0);
1347  break;
1348  case ROWCOMPARE_GT:
1349  *op->resvalue = BoolGetDatum(cmpresult > 0);
1350  break;
1351  default:
1352  Assert(false);
1353  break;
1354  }
1355 
1356  EEO_NEXT();
1357  }
1358 
1360  {
1361  /* too complex for an inline implementation */
1362  ExecEvalMinMax(state, op);
1363 
1364  EEO_NEXT();
1365  }
1366 
1368  {
1369  /* too complex for an inline implementation */
1370  ExecEvalFieldSelect(state, op, econtext);
1371 
1372  EEO_NEXT();
1373  }
1374 
1376  {
1377  /* too complex for an inline implementation */
1378  ExecEvalFieldStoreDeForm(state, op, econtext);
1379 
1380  EEO_NEXT();
1381  }
1382 
1384  {
1385  /* too complex for an inline implementation */
1386  ExecEvalFieldStoreForm(state, op, econtext);
1387 
1388  EEO_NEXT();
1389  }
1390 
1392  {
1393  /* Process an array subscript */
1394 
1395  /* too complex for an inline implementation */
1396  if (ExecEvalSubscriptingRef(state, op))
1397  {
1398  EEO_NEXT();
1399  }
1400  else
1401  {
1402  /* Subscript is null, short-circuit SubscriptingRef to NULL */
1403  EEO_JUMP(op->d.sbsref_subscript.jumpdone);
1404  }
1405  }
1406 
1408  {
1409  /*
1410  * Fetch the old value in an sbsref assignment, in case it's
1411  * referenced (via a CaseTestExpr) inside the assignment
1412  * expression.
1413  */
1414 
1415  /* too complex for an inline implementation */
1416  ExecEvalSubscriptingRefOld(state, op);
1417 
1418  EEO_NEXT();
1419  }
1420 
1421  /*
1422  * Perform SubscriptingRef assignment
1423  */
1425  {
1426  /* too complex for an inline implementation */
1427  ExecEvalSubscriptingRefAssign(state, op);
1428 
1429  EEO_NEXT();
1430  }
1431 
1432  /*
1433  * Fetch subset of an array.
1434  */
1436  {
1437  /* too complex for an inline implementation */
1438  ExecEvalSubscriptingRefFetch(state, op);
1439 
1440  EEO_NEXT();
1441  }
1442 
1444  {
1445  /* too complex for an inline implementation */
1446  ExecEvalConvertRowtype(state, op, econtext);
1447 
1448  EEO_NEXT();
1449  }
1450 
1452  {
1453  /* too complex for an inline implementation */
1454  ExecEvalScalarArrayOp(state, op);
1455 
1456  EEO_NEXT();
1457  }
1458 
1460  {
1461  /* too complex for an inline implementation */
1462  ExecEvalConstraintNotNull(state, op);
1463 
1464  EEO_NEXT();
1465  }
1466 
1468  {
1469  /* too complex for an inline implementation */
1470  ExecEvalConstraintCheck(state, op);
1471 
1472  EEO_NEXT();
1473  }
1474 
1476  {
1477  /* too complex for an inline implementation */
1478  ExecEvalXmlExpr(state, op);
1479 
1480  EEO_NEXT();
1481  }
1482 
1484  {
1485  /*
1486  * Returns a Datum whose value is the precomputed aggregate value
1487  * found in the given expression context.
1488  */
1489  AggrefExprState *aggref = op->d.aggref.astate;
1490 
1491  Assert(econtext->ecxt_aggvalues != NULL);
1492 
1493  *op->resvalue = econtext->ecxt_aggvalues[aggref->aggno];
1494  *op->resnull = econtext->ecxt_aggnulls[aggref->aggno];
1495 
1496  EEO_NEXT();
1497  }
1498 
1500  {
1501  /* too complex/uncommon for an inline implementation */
1502  ExecEvalGroupingFunc(state, op);
1503 
1504  EEO_NEXT();
1505  }
1506 
1508  {
1509  /*
1510  * Like Aggref, just return a precomputed value from the econtext.
1511  */
1512  WindowFuncExprState *wfunc = op->d.window_func.wfstate;
1513 
1514  Assert(econtext->ecxt_aggvalues != NULL);
1515 
1516  *op->resvalue = econtext->ecxt_aggvalues[wfunc->wfuncno];
1517  *op->resnull = econtext->ecxt_aggnulls[wfunc->wfuncno];
1518 
1519  EEO_NEXT();
1520  }
1521 
1523  {
1524  /* too complex for an inline implementation */
1525  ExecEvalSubPlan(state, op, econtext);
1526 
1527  EEO_NEXT();
1528  }
1529 
1531  {
1532  /* too complex for an inline implementation */
1533  ExecEvalAlternativeSubPlan(state, op, econtext);
1534 
1535  EEO_NEXT();
1536  }
1537 
1538  /* evaluate a strict aggregate deserialization function */
1540  {
1541  /* Don't call a strict deserialization function with NULL input */
1542  if (op->d.agg_deserialize.fcinfo_data->args[0].isnull)
1543  EEO_JUMP(op->d.agg_deserialize.jumpnull);
1544 
1545  /* fallthrough */
1546  }
1547 
1548  /* evaluate aggregate deserialization function (non-strict portion) */
1550  {
1551  FunctionCallInfo fcinfo = op->d.agg_deserialize.fcinfo_data;
1552  AggState *aggstate = op->d.agg_deserialize.aggstate;
1553  MemoryContext oldContext;
1554 
1555  /*
1556  * We run the deserialization functions in per-input-tuple memory
1557  * context.
1558  */
1559  oldContext = MemoryContextSwitchTo(aggstate->tmpcontext->ecxt_per_tuple_memory);
1560  fcinfo->isnull = false;
1561  *op->resvalue = FunctionCallInvoke(fcinfo);
1562  *op->resnull = fcinfo->isnull;
1563  MemoryContextSwitchTo(oldContext);
1564 
1565  EEO_NEXT();
1566  }
1567 
1568  /*
1569  * Check that a strict aggregate transition / combination function's
1570  * input is not NULL.
1571  */
1573  {
1574  int argno;
1575  bool *nulls = op->d.agg_strict_input_check.nulls;
1576  int nargs = op->d.agg_strict_input_check.nargs;
1577 
1578  for (argno = 0; argno < nargs; argno++)
1579  {
1580  if (nulls[argno])
1581  EEO_JUMP(op->d.agg_strict_input_check.jumpnull);
1582  }
1583  EEO_NEXT();
1584  }
1585 
1587  {
1588  int argno;
1590  int nargs = op->d.agg_strict_input_check.nargs;
1591 
1592  for (argno = 0; argno < nargs; argno++)
1593  {
1594  if (args[argno].isnull)
1595  EEO_JUMP(op->d.agg_strict_input_check.jumpnull);
1596  }
1597  EEO_NEXT();
1598  }
1599 
1600  /*
1601  * Initialize an aggregate's first value if necessary.
1602  */
1604  {
1605  AggState *aggstate;
1606  AggStatePerGroup pergroup;
1607 
1608  aggstate = op->d.agg_init_trans.aggstate;
1609  pergroup = &aggstate->all_pergroups
1610  [op->d.agg_init_trans.setoff]
1611  [op->d.agg_init_trans.transno];
1612 
1613  /* If transValue has not yet been initialized, do so now. */
1614  if (pergroup->noTransValue)
1615  {
1616  AggStatePerTrans pertrans = op->d.agg_init_trans.pertrans;
1617 
1618  aggstate->curaggcontext = op->d.agg_init_trans.aggcontext;
1619  aggstate->current_set = op->d.agg_init_trans.setno;
1620 
1621  ExecAggInitGroup(aggstate, pertrans, pergroup);
1622 
1623  /* copied trans value from input, done this round */
1624  EEO_JUMP(op->d.agg_init_trans.jumpnull);
1625  }
1626 
1627  EEO_NEXT();
1628  }
1629 
1630  /* check that a strict aggregate's input isn't NULL */
1632  {
1633  AggState *aggstate;
1634  AggStatePerGroup pergroup;
1635 
1636  aggstate = op->d.agg_strict_trans_check.aggstate;
1637  pergroup = &aggstate->all_pergroups
1638  [op->d.agg_strict_trans_check.setoff]
1639  [op->d.agg_strict_trans_check.transno];
1640 
1641  if (unlikely(pergroup->transValueIsNull))
1642  EEO_JUMP(op->d.agg_strict_trans_check.jumpnull);
1643 
1644  EEO_NEXT();
1645  }
1646 
1647  /*
1648  * Evaluate aggregate transition / combine function that has a
1649  * by-value transition type. That's a separate case from the
1650  * by-reference implementation because it's a bit simpler.
1651  */
1653  {
1654  AggState *aggstate;
1655  AggStatePerTrans pertrans;
1656  AggStatePerGroup pergroup;
1657  FunctionCallInfo fcinfo;
1658  MemoryContext oldContext;
1659  Datum newVal;
1660 
1661  aggstate = op->d.agg_trans.aggstate;
1662  pertrans = op->d.agg_trans.pertrans;
1663 
1664  pergroup = &aggstate->all_pergroups
1665  [op->d.agg_trans.setoff]
1666  [op->d.agg_trans.transno];
1667 
1668  Assert(pertrans->transtypeByVal);
1669 
1670  fcinfo = pertrans->transfn_fcinfo;
1671 
1672  /* cf. select_current_set() */
1673  aggstate->curaggcontext = op->d.agg_trans.aggcontext;
1674  aggstate->current_set = op->d.agg_trans.setno;
1675 
1676  /* set up aggstate->curpertrans for AggGetAggref() */
1677  aggstate->curpertrans = pertrans;
1678 
1679  /* invoke transition function in per-tuple context */
1680  oldContext = MemoryContextSwitchTo(aggstate->tmpcontext->ecxt_per_tuple_memory);
1681 
1682  fcinfo->args[0].value = pergroup->transValue;
1683  fcinfo->args[0].isnull = pergroup->transValueIsNull;
1684  fcinfo->isnull = false; /* just in case transfn doesn't set it */
1685 
1686  newVal = FunctionCallInvoke(fcinfo);
1687 
1688  pergroup->transValue = newVal;
1689  pergroup->transValueIsNull = fcinfo->isnull;
1690 
1691  MemoryContextSwitchTo(oldContext);
1692 
1693  EEO_NEXT();
1694  }
1695 
1696  /*
1697  * Evaluate aggregate transition / combine function that has a
1698  * by-reference transition type.
1699  *
1700  * Could optimize a bit further by splitting off by-reference
1701  * fixed-length types, but currently that doesn't seem worth it.
1702  */
1704  {
1705  AggState *aggstate;
1706  AggStatePerTrans pertrans;
1707  AggStatePerGroup pergroup;
1708  FunctionCallInfo fcinfo;
1709  MemoryContext oldContext;
1710  Datum newVal;
1711 
1712  aggstate = op->d.agg_trans.aggstate;
1713  pertrans = op->d.agg_trans.pertrans;
1714 
1715  pergroup = &aggstate->all_pergroups
1716  [op->d.agg_trans.setoff]
1717  [op->d.agg_trans.transno];
1718 
1719  Assert(!pertrans->transtypeByVal);
1720 
1721  fcinfo = pertrans->transfn_fcinfo;
1722 
1723  /* cf. select_current_set() */
1724  aggstate->curaggcontext = op->d.agg_trans.aggcontext;
1725  aggstate->current_set = op->d.agg_trans.setno;
1726 
1727  /* set up aggstate->curpertrans for AggGetAggref() */
1728  aggstate->curpertrans = pertrans;
1729 
1730  /* invoke transition function in per-tuple context */
1731  oldContext = MemoryContextSwitchTo(aggstate->tmpcontext->ecxt_per_tuple_memory);
1732 
1733  fcinfo->args[0].value = pergroup->transValue;
1734  fcinfo->args[0].isnull = pergroup->transValueIsNull;
1735  fcinfo->isnull = false; /* just in case transfn doesn't set it */
1736 
1737  newVal = FunctionCallInvoke(fcinfo);
1738 
1739  /*
1740  * For pass-by-ref datatype, must copy the new value into
1741  * aggcontext and free the prior transValue. But if transfn
1742  * returned a pointer to its first input, we don't need to do
1743  * anything. Also, if transfn returned a pointer to a R/W
1744  * expanded object that is already a child of the aggcontext,
1745  * assume we can adopt that value without copying it.
1746  */
1747  if (DatumGetPointer(newVal) != DatumGetPointer(pergroup->transValue))
1748  newVal = ExecAggTransReparent(aggstate, pertrans,
1749  newVal, fcinfo->isnull,
1750  pergroup->transValue,
1751  pergroup->transValueIsNull);
1752 
1753  pergroup->transValue = newVal;
1754  pergroup->transValueIsNull = fcinfo->isnull;
1755 
1756  MemoryContextSwitchTo(oldContext);
1757 
1758  EEO_NEXT();
1759  }
1760 
1761  /* process single-column ordered aggregate datum */
1763  {
1764  /* too complex for an inline implementation */
1765  ExecEvalAggOrderedTransDatum(state, op, econtext);
1766 
1767  EEO_NEXT();
1768  }
1769 
1770  /* process multi-column ordered aggregate tuple */
1772  {
1773  /* too complex for an inline implementation */
1774  ExecEvalAggOrderedTransTuple(state, op, econtext);
1775 
1776  EEO_NEXT();
1777  }
1778 
1780  {
1781  /* unreachable */
1782  Assert(false);
1783  goto out;
1784  }
1785  }
1786 
1787 out:
1788  *isnull = state->resnull;
1789  return state->resvalue;
1790 }
1791 
1792 /*
1793  * Expression evaluation callback that performs extra checks before executing
1794  * the expression. Declared extern so other methods of execution can use it
1795  * too.
1796  */
1797 Datum
1799 {
1800  /*
1801  * First time through, check whether attribute matches Var. Might not be
1802  * ok anymore, due to schema changes.
1803  */
1804  CheckExprStillValid(state, econtext);
1805 
1806  /* skip the check during further executions */
1807  state->evalfunc = (ExprStateEvalFunc) state->evalfunc_private;
1808 
1809  /* and actually execute */
1810  return state->evalfunc(state, econtext, isNull);
1811 }
1812 
1813 /*
1814  * Check that an expression is still valid in the face of potential schema
1815  * changes since the plan has been created.
1816  */
1817 void
1819 {
1820  int i = 0;
1821  TupleTableSlot *innerslot;
1822  TupleTableSlot *outerslot;
1823  TupleTableSlot *scanslot;
1824 
1825  innerslot = econtext->ecxt_innertuple;
1826  outerslot = econtext->ecxt_outertuple;
1827  scanslot = econtext->ecxt_scantuple;
1828 
1829  for (i = 0; i < state->steps_len; i++)
1830  {
1831  ExprEvalStep *op = &state->steps[i];
1832 
1833  switch (ExecEvalStepOp(state, op))
1834  {
1835  case EEOP_INNER_VAR:
1836  {
1837  int attnum = op->d.var.attnum;
1838 
1839  CheckVarSlotCompatibility(innerslot, attnum + 1, op->d.var.vartype);
1840  break;
1841  }
1842 
1843  case EEOP_OUTER_VAR:
1844  {
1845  int attnum = op->d.var.attnum;
1846 
1847  CheckVarSlotCompatibility(outerslot, attnum + 1, op->d.var.vartype);
1848  break;
1849  }
1850 
1851  case EEOP_SCAN_VAR:
1852  {
1853  int attnum = op->d.var.attnum;
1854 
1855  CheckVarSlotCompatibility(scanslot, attnum + 1, op->d.var.vartype);
1856  break;
1857  }
1858  default:
1859  break;
1860  }
1861  }
1862 }
1863 
1864 /*
1865  * Check whether a user attribute in a slot can be referenced by a Var
1866  * expression. This should succeed unless there have been schema changes
1867  * since the expression tree has been created.
1868  */
1869 static void
1871 {
1872  /*
1873  * What we have to check for here is the possibility of an attribute
1874  * having been dropped or changed in type since the plan tree was created.
1875  * Ideally the plan will get invalidated and not re-used, but just in
1876  * case, we keep these defenses. Fortunately it's sufficient to check
1877  * once on the first time through.
1878  *
1879  * Note: ideally we'd check typmod as well as typid, but that seems
1880  * impractical at the moment: in many cases the tupdesc will have been
1881  * generated by ExecTypeFromTL(), and that can't guarantee to generate an
1882  * accurate typmod in all cases, because some expression node types don't
1883  * carry typmod. Fortunately, for precisely that reason, there should be
1884  * no places with a critical dependency on the typmod of a value.
1885  *
1886  * System attributes don't require checking since their types never
1887  * change.
1888  */
1889  if (attnum > 0)
1890  {
1891  TupleDesc slot_tupdesc = slot->tts_tupleDescriptor;
1892  Form_pg_attribute attr;
1893 
1894  if (attnum > slot_tupdesc->natts) /* should never happen */
1895  elog(ERROR, "attribute number %d exceeds number of columns %d",
1896  attnum, slot_tupdesc->natts);
1897 
1898  attr = TupleDescAttr(slot_tupdesc, attnum - 1);
1899 
1900  if (attr->attisdropped)
1901  ereport(ERROR,
1902  (errcode(ERRCODE_UNDEFINED_COLUMN),
1903  errmsg("attribute %d of type %s has been dropped",
1904  attnum, format_type_be(slot_tupdesc->tdtypeid))));
1905 
1906  if (vartype != attr->atttypid)
1907  ereport(ERROR,
1908  (errcode(ERRCODE_DATATYPE_MISMATCH),
1909  errmsg("attribute %d of type %s has wrong type",
1910  attnum, format_type_be(slot_tupdesc->tdtypeid)),
1911  errdetail("Table has type %s, but query expects %s.",
1912  format_type_be(attr->atttypid),
1913  format_type_be(vartype))));
1914  }
1915 }
1916 
1917 /*
1918  * Verify that the slot is compatible with a EEOP_*_FETCHSOME operation.
1919  */
1920 static void
1922 {
1923 #ifdef USE_ASSERT_CHECKING
1924  /* there's nothing to check */
1925  if (!op->d.fetch.fixed)
1926  return;
1927 
1928  /*
1929  * Should probably fixed at some point, but for now it's easier to allow
1930  * buffer and heap tuples to be used interchangeably.
1931  */
1932  if (slot->tts_ops == &TTSOpsBufferHeapTuple &&
1933  op->d.fetch.kind == &TTSOpsHeapTuple)
1934  return;
1935  if (slot->tts_ops == &TTSOpsHeapTuple &&
1936  op->d.fetch.kind == &TTSOpsBufferHeapTuple)
1937  return;
1938 
1939  /*
1940  * At the moment we consider it OK if a virtual slot is used instead of a
1941  * specific type of slot, as a virtual slot never needs to be deformed.
1942  */
1943  if (slot->tts_ops == &TTSOpsVirtual)
1944  return;
1945 
1946  Assert(op->d.fetch.kind == slot->tts_ops);
1947 #endif
1948 }
1949 
1950 /*
1951  * get_cached_rowtype: utility function to lookup a rowtype tupdesc
1952  *
1953  * type_id, typmod: identity of the rowtype
1954  * cache_field: where to cache the TupleDesc pointer in expression state node
1955  * (field must be initialized to NULL)
1956  * econtext: expression context we are executing in
1957  *
1958  * NOTE: because the shutdown callback will be called during plan rescan,
1959  * must be prepared to re-do this during any node execution; cannot call
1960  * just once during expression initialization.
1961  */
1962 static TupleDesc
1963 get_cached_rowtype(Oid type_id, int32 typmod,
1964  TupleDesc *cache_field, ExprContext *econtext)
1965 {
1966  TupleDesc tupDesc = *cache_field;
1967 
1968  /* Do lookup if no cached value or if requested type changed */
1969  if (tupDesc == NULL ||
1970  type_id != tupDesc->tdtypeid ||
1971  typmod != tupDesc->tdtypmod)
1972  {
1973  tupDesc = lookup_rowtype_tupdesc(type_id, typmod);
1974 
1975  if (*cache_field)
1976  {
1977  /* Release old tupdesc; but callback is already registered */
1978  ReleaseTupleDesc(*cache_field);
1979  }
1980  else
1981  {
1982  /* Need to register shutdown callback to release tupdesc */
1983  RegisterExprContextCallback(econtext,
1985  PointerGetDatum(cache_field));
1986  }
1987  *cache_field = tupDesc;
1988  }
1989  return tupDesc;
1990 }
1991 
1992 /*
1993  * Callback function to release a tupdesc refcount at econtext shutdown
1994  */
1995 static void
1997 {
1998  TupleDesc *cache_field = (TupleDesc *) DatumGetPointer(arg);
1999 
2000  if (*cache_field)
2001  ReleaseTupleDesc(*cache_field);
2002  *cache_field = NULL;
2003 }
2004 
2005 /*
2006  * Fast-path functions, for very simple expressions
2007  */
2008 
2009 /* implementation of ExecJust(Inner|Outer|Scan)Var */
2012 {
2013  ExprEvalStep *op = &state->steps[1];
2014  int attnum = op->d.var.attnum + 1;
2015 
2016  CheckOpSlotCompatibility(&state->steps[0], slot);
2017 
2018  /*
2019  * Since we use slot_getattr(), we don't need to implement the FETCHSOME
2020  * step explicitly, and we also needn't Assert that the attnum is in range
2021  * --- slot_getattr() will take care of any problems.
2022  */
2023  return slot_getattr(slot, attnum, isnull);
2024 }
2025 
2026 /* Simple reference to inner Var */
2027 static Datum
2028 ExecJustInnerVar(ExprState *state, ExprContext *econtext, bool *isnull)
2029 {
2030  return ExecJustVarImpl(state, econtext->ecxt_innertuple, isnull);
2031 }
2032 
2033 /* Simple reference to outer Var */
2034 static Datum
2035 ExecJustOuterVar(ExprState *state, ExprContext *econtext, bool *isnull)
2036 {
2037  return ExecJustVarImpl(state, econtext->ecxt_outertuple, isnull);
2038 }
2039 
2040 /* Simple reference to scan Var */
2041 static Datum
2042 ExecJustScanVar(ExprState *state, ExprContext *econtext, bool *isnull)
2043 {
2044  return ExecJustVarImpl(state, econtext->ecxt_scantuple, isnull);
2045 }
2046 
2047 /* implementation of ExecJustAssign(Inner|Outer|Scan)Var */
2050 {
2051  ExprEvalStep *op = &state->steps[1];
2052  int attnum = op->d.assign_var.attnum + 1;
2053  int resultnum = op->d.assign_var.resultnum;
2054  TupleTableSlot *outslot = state->resultslot;
2055 
2056  CheckOpSlotCompatibility(&state->steps[0], inslot);
2057 
2058  /*
2059  * We do not need CheckVarSlotCompatibility here; that was taken care of
2060  * at compilation time.
2061  *
2062  * Since we use slot_getattr(), we don't need to implement the FETCHSOME
2063  * step explicitly, and we also needn't Assert that the attnum is in range
2064  * --- slot_getattr() will take care of any problems.
2065  */
2066  outslot->tts_values[resultnum] =
2067  slot_getattr(inslot, attnum, &outslot->tts_isnull[resultnum]);
2068  return 0;
2069 }
2070 
2071 /* Evaluate inner Var and assign to appropriate column of result tuple */
2072 static Datum
2074 {
2075  return ExecJustAssignVarImpl(state, econtext->ecxt_innertuple, isnull);
2076 }
2077 
2078 /* Evaluate outer Var and assign to appropriate column of result tuple */
2079 static Datum
2081 {
2082  return ExecJustAssignVarImpl(state, econtext->ecxt_outertuple, isnull);
2083 }
2084 
2085 /* Evaluate scan Var and assign to appropriate column of result tuple */
2086 static Datum
2088 {
2089  return ExecJustAssignVarImpl(state, econtext->ecxt_scantuple, isnull);
2090 }
2091 
2092 /* Evaluate CASE_TESTVAL and apply a strict function to it */
2093 static Datum
2095 {
2096  ExprEvalStep *op = &state->steps[0];
2097  FunctionCallInfo fcinfo;
2099  int argno;
2100  Datum d;
2101 
2102  /*
2103  * XXX with some redesign of the CaseTestExpr mechanism, maybe we could
2104  * get rid of this data shuffling?
2105  */
2106  *op->resvalue = *op->d.casetest.value;
2107  *op->resnull = *op->d.casetest.isnull;
2108 
2109  op++;
2110 
2111  fcinfo = op->d.func.fcinfo_data;
2112  args = fcinfo->args;
2113 
2114  /* strict function, so check for NULL args */
2115  for (argno = 0; argno < op->d.func.nargs; argno++)
2116  {
2117  if (args[argno].isnull)
2118  {
2119  *isnull = true;
2120  return (Datum) 0;
2121  }
2122  }
2123  fcinfo->isnull = false;
2124  d = op->d.func.fn_addr(fcinfo);
2125  *isnull = fcinfo->isnull;
2126  return d;
2127 }
2128 
2129 /* Simple Const expression */
2130 static Datum
2131 ExecJustConst(ExprState *state, ExprContext *econtext, bool *isnull)
2132 {
2133  ExprEvalStep *op = &state->steps[0];
2134 
2135  *isnull = op->d.constval.isnull;
2136  return op->d.constval.value;
2137 }
2138 
2139 /* implementation of ExecJust(Inner|Outer|Scan)VarVirt */
2142 {
2143  ExprEvalStep *op = &state->steps[0];
2144  int attnum = op->d.var.attnum;
2145 
2146  /*
2147  * As it is guaranteed that a virtual slot is used, there never is a need
2148  * to perform tuple deforming (nor would it be possible). Therefore
2149  * execExpr.c has not emitted an EEOP_*_FETCHSOME step. Verify, as much as
2150  * possible, that that determination was accurate.
2151  */
2152  Assert(TTS_IS_VIRTUAL(slot));
2153  Assert(TTS_FIXED(slot));
2154  Assert(attnum >= 0 && attnum < slot->tts_nvalid);
2155 
2156  *isnull = slot->tts_isnull[attnum];
2157 
2158  return slot->tts_values[attnum];
2159 }
2160 
2161 /* Like ExecJustInnerVar, optimized for virtual slots */
2162 static Datum
2164 {
2165  return ExecJustVarVirtImpl(state, econtext->ecxt_innertuple, isnull);
2166 }
2167 
2168 /* Like ExecJustOuterVar, optimized for virtual slots */
2169 static Datum
2171 {
2172  return ExecJustVarVirtImpl(state, econtext->ecxt_outertuple, isnull);
2173 }
2174 
2175 /* Like ExecJustScanVar, optimized for virtual slots */
2176 static Datum
2178 {
2179  return ExecJustVarVirtImpl(state, econtext->ecxt_scantuple, isnull);
2180 }
2181 
2182 /* implementation of ExecJustAssign(Inner|Outer|Scan)VarVirt */
2185 {
2186  ExprEvalStep *op = &state->steps[0];
2187  int attnum = op->d.assign_var.attnum;
2188  int resultnum = op->d.assign_var.resultnum;
2189  TupleTableSlot *outslot = state->resultslot;
2190 
2191  /* see ExecJustVarVirtImpl for comments */
2192 
2193  Assert(TTS_IS_VIRTUAL(inslot));
2194  Assert(TTS_FIXED(inslot));
2195  Assert(attnum >= 0 && attnum < inslot->tts_nvalid);
2196 
2197  outslot->tts_values[resultnum] = inslot->tts_values[attnum];
2198  outslot->tts_isnull[resultnum] = inslot->tts_isnull[attnum];
2199 
2200  return 0;
2201 }
2202 
2203 /* Like ExecJustAssignInnerVar, optimized for virtual slots */
2204 static Datum
2206 {
2207  return ExecJustAssignVarVirtImpl(state, econtext->ecxt_innertuple, isnull);
2208 }
2209 
2210 /* Like ExecJustAssignOuterVar, optimized for virtual slots */
2211 static Datum
2213 {
2214  return ExecJustAssignVarVirtImpl(state, econtext->ecxt_outertuple, isnull);
2215 }
2216 
2217 /* Like ExecJustAssignScanVar, optimized for virtual slots */
2218 static Datum
2220 {
2221  return ExecJustAssignVarVirtImpl(state, econtext->ecxt_scantuple, isnull);
2222 }
2223 
2224 #if defined(EEO_USE_COMPUTED_GOTO)
2225 /*
2226  * Comparator used when building address->opcode lookup table for
2227  * ExecEvalStepOp() in the threaded dispatch case.
2228  */
2229 static int
2230 dispatch_compare_ptr(const void *a, const void *b)
2231 {
2232  const ExprEvalOpLookup *la = (const ExprEvalOpLookup *) a;
2233  const ExprEvalOpLookup *lb = (const ExprEvalOpLookup *) b;
2234 
2235  if (la->opcode < lb->opcode)
2236  return -1;
2237  else if (la->opcode > lb->opcode)
2238  return 1;
2239  return 0;
2240 }
2241 #endif
2242 
2243 /*
2244  * Do one-time initialization of interpretation machinery.
2245  */
2246 static void
2248 {
2249 #if defined(EEO_USE_COMPUTED_GOTO)
2250  /* Set up externally-visible pointer to dispatch table */
2251  if (dispatch_table == NULL)
2252  {
2253  int i;
2254 
2255  dispatch_table = (const void **)
2256  DatumGetPointer(ExecInterpExpr(NULL, NULL, NULL));
2257 
2258  /* build reverse lookup table */
2259  for (i = 0; i < EEOP_LAST; i++)
2260  {
2261  reverse_dispatch_table[i].opcode = dispatch_table[i];
2262  reverse_dispatch_table[i].op = (ExprEvalOp) i;
2263  }
2264 
2265  /* make it bsearch()able */
2266  qsort(reverse_dispatch_table,
2267  EEOP_LAST /* nmembers */ ,
2268  sizeof(ExprEvalOpLookup),
2269  dispatch_compare_ptr);
2270  }
2271 #endif
2272 }
2273 
2274 /*
2275  * Function to return the opcode of an expression step.
2276  *
2277  * When direct-threading is in use, ExprState->opcode isn't easily
2278  * decipherable. This function returns the appropriate enum member.
2279  */
2280 ExprEvalOp
2282 {
2283 #if defined(EEO_USE_COMPUTED_GOTO)
2284  if (state->flags & EEO_FLAG_DIRECT_THREADED)
2285  {
2286  ExprEvalOpLookup key;
2287  ExprEvalOpLookup *res;
2288 
2289  key.opcode = (void *) op->opcode;
2290  res = bsearch(&key,
2291  reverse_dispatch_table,
2292  EEOP_LAST /* nmembers */ ,
2293  sizeof(ExprEvalOpLookup),
2294  dispatch_compare_ptr);
2295  Assert(res); /* unknown ops shouldn't get looked up */
2296  return res->op;
2297  }
2298 #endif
2299  return (ExprEvalOp) op->opcode;
2300 }
2301 
2302 
2303 /*
2304  * Out-of-line helper functions for complex instructions.
2305  */
2306 
2307 /*
2308  * Evaluate EEOP_FUNCEXPR_FUSAGE
2309  */
2310 void
2312  ExprContext *econtext)
2313 {
2314  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
2315  PgStat_FunctionCallUsage fcusage;
2316  Datum d;
2317 
2318  pgstat_init_function_usage(fcinfo, &fcusage);
2319 
2320  fcinfo->isnull = false;
2321  d = op->d.func.fn_addr(fcinfo);
2322  *op->resvalue = d;
2323  *op->resnull = fcinfo->isnull;
2324 
2325  pgstat_end_function_usage(&fcusage, true);
2326 }
2327 
2328 /*
2329  * Evaluate EEOP_FUNCEXPR_STRICT_FUSAGE
2330  */
2331 void
2333  ExprContext *econtext)
2334 {
2335 
2336  FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
2337  PgStat_FunctionCallUsage fcusage;
2338  NullableDatum *args = fcinfo->args;
2339  int argno;
2340  Datum d;
2341 
2342  /* strict function, so check for NULL args */
2343  for (argno = 0; argno < op->d.func.nargs; argno++)
2344  {
2345  if (args[argno].isnull)
2346  {
2347  *op->resnull = true;
2348  return;
2349  }
2350  }
2351 
2352  pgstat_init_function_usage(fcinfo, &fcusage);
2353 
2354  fcinfo->isnull = false;
2355  d = op->d.func.fn_addr(fcinfo);
2356  *op->resvalue = d;
2357  *op->resnull = fcinfo->isnull;
2358 
2359  pgstat_end_function_usage(&fcusage, true);
2360 }
2361 
2362 /*
2363  * Evaluate a PARAM_EXEC parameter.
2364  *
2365  * PARAM_EXEC params (internal executor parameters) are stored in the
2366  * ecxt_param_exec_vals array, and can be accessed by array index.
2367  */
2368 void
2370 {
2371  ParamExecData *prm;
2372 
2373  prm = &(econtext->ecxt_param_exec_vals[op->d.param.paramid]);
2374  if (unlikely(prm->execPlan != NULL))
2375  {
2376  /* Parameter not evaluated yet, so go do it */
2377  ExecSetParamPlan(prm->execPlan, econtext);
2378  /* ExecSetParamPlan should have processed this param... */
2379  Assert(prm->execPlan == NULL);
2380  }
2381  *op->resvalue = prm->value;
2382  *op->resnull = prm->isnull;
2383 }
2384 
2385 /*
2386  * Evaluate a PARAM_EXTERN parameter.
2387  *
2388  * PARAM_EXTERN parameters must be sought in ecxt_param_list_info.
2389  */
2390 void
2392 {
2393  ParamListInfo paramInfo = econtext->ecxt_param_list_info;
2394  int paramId = op->d.param.paramid;
2395 
2396  if (likely(paramInfo &&
2397  paramId > 0 && paramId <= paramInfo->numParams))
2398  {
2399  ParamExternData *prm;
2400  ParamExternData prmdata;
2401 
2402  /* give hook a chance in case parameter is dynamic */
2403  if (paramInfo->paramFetch != NULL)
2404  prm = paramInfo->paramFetch(paramInfo, paramId, false, &prmdata);
2405  else
2406  prm = &paramInfo->params[paramId - 1];
2407 
2408  if (likely(OidIsValid(prm->ptype)))
2409  {
2410  /* safety check in case hook did something unexpected */
2411  if (unlikely(prm->ptype != op->d.param.paramtype))
2412  ereport(ERROR,
2413  (errcode(ERRCODE_DATATYPE_MISMATCH),
2414  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
2415  paramId,
2416  format_type_be(prm->ptype),
2417  format_type_be(op->d.param.paramtype))));
2418  *op->resvalue = prm->value;
2419  *op->resnull = prm->isnull;
2420  return;
2421  }
2422  }
2423 
2424  ereport(ERROR,
2425  (errcode(ERRCODE_UNDEFINED_OBJECT),
2426  errmsg("no value found for parameter %d", paramId)));
2427 }
2428 
2429 /*
2430  * Evaluate a SQLValueFunction expression.
2431  */
2432 void
2434 {
2435  LOCAL_FCINFO(fcinfo, 0);
2436  SQLValueFunction *svf = op->d.sqlvaluefunction.svf;
2437 
2438  *op->resnull = false;
2439 
2440  /*
2441  * Note: current_schema() can return NULL. current_user() etc currently
2442  * cannot, but might as well code those cases the same way for safety.
2443  */
2444  switch (svf->op)
2445  {
2446  case SVFOP_CURRENT_DATE:
2448  break;
2449  case SVFOP_CURRENT_TIME:
2450  case SVFOP_CURRENT_TIME_N:
2452  break;
2456  break;
2457  case SVFOP_LOCALTIME:
2458  case SVFOP_LOCALTIME_N:
2460  break;
2461  case SVFOP_LOCALTIMESTAMP:
2464  break;
2465  case SVFOP_CURRENT_ROLE:
2466  case SVFOP_CURRENT_USER:
2467  case SVFOP_USER:
2468  InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
2469  *op->resvalue = current_user(fcinfo);
2470  *op->resnull = fcinfo->isnull;
2471  break;
2472  case SVFOP_SESSION_USER:
2473  InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
2474  *op->resvalue = session_user(fcinfo);
2475  *op->resnull = fcinfo->isnull;
2476  break;
2477  case SVFOP_CURRENT_CATALOG:
2478  InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
2479  *op->resvalue = current_database(fcinfo);
2480  *op->resnull = fcinfo->isnull;
2481  break;
2482  case SVFOP_CURRENT_SCHEMA:
2483  InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
2484  *op->resvalue = current_schema(fcinfo);
2485  *op->resnull = fcinfo->isnull;
2486  break;
2487  }
2488 }
2489 
2490 /*
2491  * Raise error if a CURRENT OF expression is evaluated.
2492  *
2493  * The planner should convert CURRENT OF into a TidScan qualification, or some
2494  * other special handling in a ForeignScan node. So we have to be able to do
2495  * ExecInitExpr on a CurrentOfExpr, but we shouldn't ever actually execute it.
2496  * If we get here, we suppose we must be dealing with CURRENT OF on a foreign
2497  * table whose FDW doesn't handle it, and complain accordingly.
2498  */
2499 void
2501 {
2502  ereport(ERROR,
2503  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2504  errmsg("WHERE CURRENT OF is not supported for this table type")));
2505 }
2506 
2507 /*
2508  * Evaluate NextValueExpr.
2509  */
2510 void
2512 {
2513  int64 newval = nextval_internal(op->d.nextvalueexpr.seqid, false);
2514 
2515  switch (op->d.nextvalueexpr.seqtypid)
2516  {
2517  case INT2OID:
2518  *op->resvalue = Int16GetDatum((int16) newval);
2519  break;
2520  case INT4OID:
2521  *op->resvalue = Int32GetDatum((int32) newval);
2522  break;
2523  case INT8OID:
2524  *op->resvalue = Int64GetDatum((int64) newval);
2525  break;
2526  default:
2527  elog(ERROR, "unsupported sequence type %u",
2528  op->d.nextvalueexpr.seqtypid);
2529  }
2530  *op->resnull = false;
2531 }
2532 
2533 /*
2534  * Evaluate NullTest / IS NULL for rows.
2535  */
2536 void
2538 {
2539  ExecEvalRowNullInt(state, op, econtext, true);
2540 }
2541 
2542 /*
2543  * Evaluate NullTest / IS NOT NULL for rows.
2544  */
2545 void
2547 {
2548  ExecEvalRowNullInt(state, op, econtext, false);
2549 }
2550 
2551 /* Common code for IS [NOT] NULL on a row value */
2552 static void
2554  ExprContext *econtext, bool checkisnull)
2555 {
2556  Datum value = *op->resvalue;
2557  bool isnull = *op->resnull;
2558  HeapTupleHeader tuple;
2559  Oid tupType;
2560  int32 tupTypmod;
2561  TupleDesc tupDesc;
2562  HeapTupleData tmptup;
2563  int att;
2564 
2565  *op->resnull = false;
2566 
2567  /* NULL row variables are treated just as NULL scalar columns */
2568  if (isnull)
2569  {
2570  *op->resvalue = BoolGetDatum(checkisnull);
2571  return;
2572  }
2573 
2574  /*
2575  * The SQL standard defines IS [NOT] NULL for a non-null rowtype argument
2576  * as:
2577  *
2578  * "R IS NULL" is true if every field is the null value.
2579  *
2580  * "R IS NOT NULL" is true if no field is the null value.
2581  *
2582  * This definition is (apparently intentionally) not recursive; so our
2583  * tests on the fields are primitive attisnull tests, not recursive checks
2584  * to see if they are all-nulls or no-nulls rowtypes.
2585  *
2586  * The standard does not consider the possibility of zero-field rows, but
2587  * here we consider them to vacuously satisfy both predicates.
2588  */
2589 
2590  tuple = DatumGetHeapTupleHeader(value);
2591 
2592  tupType = HeapTupleHeaderGetTypeId(tuple);
2593  tupTypmod = HeapTupleHeaderGetTypMod(tuple);
2594 
2595  /* Lookup tupdesc if first time through or if type changes */
2596  tupDesc = get_cached_rowtype(tupType, tupTypmod,
2597  &op->d.nulltest_row.argdesc,
2598  econtext);
2599 
2600  /*
2601  * heap_attisnull needs a HeapTuple not a bare HeapTupleHeader.
2602  */
2603  tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
2604  tmptup.t_data = tuple;
2605 
2606  for (att = 1; att <= tupDesc->natts; att++)
2607  {
2608  /* ignore dropped columns */
2609  if (TupleDescAttr(tupDesc, att - 1)->attisdropped)
2610  continue;
2611  if (heap_attisnull(&tmptup, att, tupDesc))
2612  {
2613  /* null field disproves IS NOT NULL */
2614  if (!checkisnull)
2615  {
2616  *op->resvalue = BoolGetDatum(false);
2617  return;
2618  }
2619  }
2620  else
2621  {
2622  /* non-null field disproves IS NULL */
2623  if (checkisnull)
2624  {
2625  *op->resvalue = BoolGetDatum(false);
2626  return;
2627  }
2628  }
2629  }
2630 
2631  *op->resvalue = BoolGetDatum(true);
2632 }
2633 
2634 /*
2635  * Evaluate an ARRAY[] expression.
2636  *
2637  * The individual array elements (or subarrays) have already been evaluated
2638  * into op->d.arrayexpr.elemvalues[]/elemnulls[].
2639  */
2640 void
2642 {
2643  ArrayType *result;
2644  Oid element_type = op->d.arrayexpr.elemtype;
2645  int nelems = op->d.arrayexpr.nelems;
2646  int ndims = 0;
2647  int dims[MAXDIM];
2648  int lbs[MAXDIM];
2649 
2650  /* Set non-null as default */
2651  *op->resnull = false;
2652 
2653  if (!op->d.arrayexpr.multidims)
2654  {
2655  /* Elements are presumably of scalar type */
2656  Datum *dvalues = op->d.arrayexpr.elemvalues;
2657  bool *dnulls = op->d.arrayexpr.elemnulls;
2658 
2659  /* setup for 1-D array of the given length */
2660  ndims = 1;
2661  dims[0] = nelems;
2662  lbs[0] = 1;
2663 
2664  result = construct_md_array(dvalues, dnulls, ndims, dims, lbs,
2665  element_type,
2666  op->d.arrayexpr.elemlength,
2667  op->d.arrayexpr.elembyval,
2668  op->d.arrayexpr.elemalign);
2669  }
2670  else
2671  {
2672  /* Must be nested array expressions */
2673  int nbytes = 0;
2674  int nitems = 0;
2675  int outer_nelems = 0;
2676  int elem_ndims = 0;
2677  int *elem_dims = NULL;
2678  int *elem_lbs = NULL;
2679  bool firstone = true;
2680  bool havenulls = false;
2681  bool haveempty = false;
2682  char **subdata;
2683  bits8 **subbitmaps;
2684  int *subbytes;
2685  int *subnitems;
2686  int32 dataoffset;
2687  char *dat;
2688  int iitem;
2689  int elemoff;
2690  int i;
2691 
2692  subdata = (char **) palloc(nelems * sizeof(char *));
2693  subbitmaps = (bits8 **) palloc(nelems * sizeof(bits8 *));
2694  subbytes = (int *) palloc(nelems * sizeof(int));
2695  subnitems = (int *) palloc(nelems * sizeof(int));
2696 
2697  /* loop through and get data area from each element */
2698  for (elemoff = 0; elemoff < nelems; elemoff++)
2699  {
2700  Datum arraydatum;
2701  bool eisnull;
2702  ArrayType *array;
2703  int this_ndims;
2704 
2705  arraydatum = op->d.arrayexpr.elemvalues[elemoff];
2706  eisnull = op->d.arrayexpr.elemnulls[elemoff];
2707 
2708  /* temporarily ignore null subarrays */
2709  if (eisnull)
2710  {
2711  haveempty = true;
2712  continue;
2713  }
2714 
2715  array = DatumGetArrayTypeP(arraydatum);
2716 
2717  /* run-time double-check on element type */
2718  if (element_type != ARR_ELEMTYPE(array))
2719  ereport(ERROR,
2720  (errcode(ERRCODE_DATATYPE_MISMATCH),
2721  errmsg("cannot merge incompatible arrays"),
2722  errdetail("Array with element type %s cannot be "
2723  "included in ARRAY construct with element type %s.",
2724  format_type_be(ARR_ELEMTYPE(array)),
2725  format_type_be(element_type))));
2726 
2727  this_ndims = ARR_NDIM(array);
2728  /* temporarily ignore zero-dimensional subarrays */
2729  if (this_ndims <= 0)
2730  {
2731  haveempty = true;
2732  continue;
2733  }
2734 
2735  if (firstone)
2736  {
2737  /* Get sub-array details from first member */
2738  elem_ndims = this_ndims;
2739  ndims = elem_ndims + 1;
2740  if (ndims <= 0 || ndims > MAXDIM)
2741  ereport(ERROR,
2742  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2743  errmsg("number of array dimensions (%d) exceeds " \
2744  "the maximum allowed (%d)", ndims, MAXDIM)));
2745 
2746  elem_dims = (int *) palloc(elem_ndims * sizeof(int));
2747  memcpy(elem_dims, ARR_DIMS(array), elem_ndims * sizeof(int));
2748  elem_lbs = (int *) palloc(elem_ndims * sizeof(int));
2749  memcpy(elem_lbs, ARR_LBOUND(array), elem_ndims * sizeof(int));
2750 
2751  firstone = false;
2752  }
2753  else
2754  {
2755  /* Check other sub-arrays are compatible */
2756  if (elem_ndims != this_ndims ||
2757  memcmp(elem_dims, ARR_DIMS(array),
2758  elem_ndims * sizeof(int)) != 0 ||
2759  memcmp(elem_lbs, ARR_LBOUND(array),
2760  elem_ndims * sizeof(int)) != 0)
2761  ereport(ERROR,
2762  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2763  errmsg("multidimensional arrays must have array "
2764  "expressions with matching dimensions")));
2765  }
2766 
2767  subdata[outer_nelems] = ARR_DATA_PTR(array);
2768  subbitmaps[outer_nelems] = ARR_NULLBITMAP(array);
2769  subbytes[outer_nelems] = ARR_SIZE(array) - ARR_DATA_OFFSET(array);
2770  nbytes += subbytes[outer_nelems];
2771  subnitems[outer_nelems] = ArrayGetNItems(this_ndims,
2772  ARR_DIMS(array));
2773  nitems += subnitems[outer_nelems];
2774  havenulls |= ARR_HASNULL(array);
2775  outer_nelems++;
2776  }
2777 
2778  /*
2779  * If all items were null or empty arrays, return an empty array;
2780  * otherwise, if some were and some weren't, raise error. (Note: we
2781  * must special-case this somehow to avoid trying to generate a 1-D
2782  * array formed from empty arrays. It's not ideal...)
2783  */
2784  if (haveempty)
2785  {
2786  if (ndims == 0) /* didn't find any nonempty array */
2787  {
2788  *op->resvalue = PointerGetDatum(construct_empty_array(element_type));
2789  return;
2790  }
2791  ereport(ERROR,
2792  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2793  errmsg("multidimensional arrays must have array "
2794  "expressions with matching dimensions")));
2795  }
2796 
2797  /* setup for multi-D array */
2798  dims[0] = outer_nelems;
2799  lbs[0] = 1;
2800  for (i = 1; i < ndims; i++)
2801  {
2802  dims[i] = elem_dims[i - 1];
2803  lbs[i] = elem_lbs[i - 1];
2804  }
2805 
2806  if (havenulls)
2807  {
2808  dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
2809  nbytes += dataoffset;
2810  }
2811  else
2812  {
2813  dataoffset = 0; /* marker for no null bitmap */
2814  nbytes += ARR_OVERHEAD_NONULLS(ndims);
2815  }
2816 
2817  result = (ArrayType *) palloc(nbytes);
2818  SET_VARSIZE(result, nbytes);
2819  result->ndim = ndims;
2820  result->dataoffset = dataoffset;
2821  result->elemtype = element_type;
2822  memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
2823  memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
2824 
2825  dat = ARR_DATA_PTR(result);
2826  iitem = 0;
2827  for (i = 0; i < outer_nelems; i++)
2828  {
2829  memcpy(dat, subdata[i], subbytes[i]);
2830  dat += subbytes[i];
2831  if (havenulls)
2832  array_bitmap_copy(ARR_NULLBITMAP(result), iitem,
2833  subbitmaps[i], 0,
2834  subnitems[i]);
2835  iitem += subnitems[i];
2836  }
2837  }
2838 
2839  *op->resvalue = PointerGetDatum(result);
2840 }
2841 
2842 /*
2843  * Evaluate an ArrayCoerceExpr expression.
2844  *
2845  * Source array is in step's result variable.
2846  */
2847 void
2849 {
2850  Datum arraydatum;
2851 
2852  /* NULL array -> NULL result */
2853  if (*op->resnull)
2854  return;
2855 
2856  arraydatum = *op->resvalue;
2857 
2858  /*
2859  * If it's binary-compatible, modify the element type in the array header,
2860  * but otherwise leave the array as we received it.
2861  */
2862  if (op->d.arraycoerce.elemexprstate == NULL)
2863  {
2864  /* Detoast input array if necessary, and copy in any case */
2865  ArrayType *array = DatumGetArrayTypePCopy(arraydatum);
2866 
2867  ARR_ELEMTYPE(array) = op->d.arraycoerce.resultelemtype;
2868  *op->resvalue = PointerGetDatum(array);
2869  return;
2870  }
2871 
2872  /*
2873  * Use array_map to apply the sub-expression to each array element.
2874  */
2875  *op->resvalue = array_map(arraydatum,
2876  op->d.arraycoerce.elemexprstate,
2877  econtext,
2878  op->d.arraycoerce.resultelemtype,
2879  op->d.arraycoerce.amstate);
2880 }
2881 
2882 /*
2883  * Evaluate a ROW() expression.
2884  *
2885  * The individual columns have already been evaluated into
2886  * op->d.row.elemvalues[]/elemnulls[].
2887  */
2888 void
2890 {
2891  HeapTuple tuple;
2892 
2893  /* build tuple from evaluated field values */
2894  tuple = heap_form_tuple(op->d.row.tupdesc,
2895  op->d.row.elemvalues,
2896  op->d.row.elemnulls);
2897 
2898  *op->resvalue = HeapTupleGetDatum(tuple);
2899  *op->resnull = false;
2900 }
2901 
2902 /*
2903  * Evaluate GREATEST() or LEAST() expression (note this is *not* MIN()/MAX()).
2904  *
2905  * All of the to-be-compared expressions have already been evaluated into
2906  * op->d.minmax.values[]/nulls[].
2907  */
2908 void
2910 {
2911  Datum *values = op->d.minmax.values;
2912  bool *nulls = op->d.minmax.nulls;
2913  FunctionCallInfo fcinfo = op->d.minmax.fcinfo_data;
2914  MinMaxOp operator = op->d.minmax.op;
2915  int off;
2916 
2917  /* set at initialization */
2918  Assert(fcinfo->args[0].isnull == false);
2919  Assert(fcinfo->args[1].isnull == false);
2920 
2921  /* default to null result */
2922  *op->resnull = true;
2923 
2924  for (off = 0; off < op->d.minmax.nelems; off++)
2925  {
2926  /* ignore NULL inputs */
2927  if (nulls[off])
2928  continue;
2929 
2930  if (*op->resnull)
2931  {
2932  /* first nonnull input, adopt value */
2933  *op->resvalue = values[off];
2934  *op->resnull = false;
2935  }
2936  else
2937  {
2938  int cmpresult;
2939 
2940  /* apply comparison function */
2941  fcinfo->args[0].value = *op->resvalue;
2942  fcinfo->args[1].value = values[off];
2943 
2944  fcinfo->isnull = false;
2945  cmpresult = DatumGetInt32(FunctionCallInvoke(fcinfo));
2946  if (fcinfo->isnull) /* probably should not happen */
2947  continue;
2948 
2949  if (cmpresult > 0 && operator == IS_LEAST)
2950  *op->resvalue = values[off];
2951  else if (cmpresult < 0 && operator == IS_GREATEST)
2952  *op->resvalue = values[off];
2953  }
2954  }
2955 }
2956 
2957 /*
2958  * Evaluate a FieldSelect node.
2959  *
2960  * Source record is in step's result variable.
2961  */
2962 void
2964 {
2965  AttrNumber fieldnum = op->d.fieldselect.fieldnum;
2966  Datum tupDatum;
2967  HeapTupleHeader tuple;
2968  Oid tupType;
2969  int32 tupTypmod;
2970  TupleDesc tupDesc;
2971  Form_pg_attribute attr;
2972  HeapTupleData tmptup;
2973 
2974  /* NULL record -> NULL result */
2975  if (*op->resnull)
2976  return;
2977 
2978  tupDatum = *op->resvalue;
2979 
2980  /* We can special-case expanded records for speed */
2982  {
2984 
2985  Assert(erh->er_magic == ER_MAGIC);
2986 
2987  /* Extract record's TupleDesc */
2988  tupDesc = expanded_record_get_tupdesc(erh);
2989 
2990  /*
2991  * Find field's attr record. Note we don't support system columns
2992  * here: a datum tuple doesn't have valid values for most of the
2993  * interesting system columns anyway.
2994  */
2995  if (fieldnum <= 0) /* should never happen */
2996  elog(ERROR, "unsupported reference to system column %d in FieldSelect",
2997  fieldnum);
2998  if (fieldnum > tupDesc->natts) /* should never happen */
2999  elog(ERROR, "attribute number %d exceeds number of columns %d",
3000  fieldnum, tupDesc->natts);
3001  attr = TupleDescAttr(tupDesc, fieldnum - 1);
3002 
3003  /* Check for dropped column, and force a NULL result if so */
3004  if (attr->attisdropped)
3005  {
3006  *op->resnull = true;
3007  return;
3008  }
3009 
3010  /* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
3011  /* As in CheckVarSlotCompatibility, we should but can't check typmod */
3012  if (op->d.fieldselect.resulttype != attr->atttypid)
3013  ereport(ERROR,
3014  (errcode(ERRCODE_DATATYPE_MISMATCH),
3015  errmsg("attribute %d has wrong type", fieldnum),
3016  errdetail("Table has type %s, but query expects %s.",
3017  format_type_be(attr->atttypid),
3018  format_type_be(op->d.fieldselect.resulttype))));
3019 
3020  /* extract the field */
3021  *op->resvalue = expanded_record_get_field(erh, fieldnum,
3022  op->resnull);
3023  }
3024  else
3025  {
3026  /* Get the composite datum and extract its type fields */
3027  tuple = DatumGetHeapTupleHeader(tupDatum);
3028 
3029  tupType = HeapTupleHeaderGetTypeId(tuple);
3030  tupTypmod = HeapTupleHeaderGetTypMod(tuple);
3031 
3032  /* Lookup tupdesc if first time through or if type changes */
3033  tupDesc = get_cached_rowtype(tupType, tupTypmod,
3034  &op->d.fieldselect.argdesc,
3035  econtext);
3036 
3037  /*
3038  * Find field's attr record. Note we don't support system columns
3039  * here: a datum tuple doesn't have valid values for most of the
3040  * interesting system columns anyway.
3041  */
3042  if (fieldnum <= 0) /* should never happen */
3043  elog(ERROR, "unsupported reference to system column %d in FieldSelect",
3044  fieldnum);
3045  if (fieldnum > tupDesc->natts) /* should never happen */
3046  elog(ERROR, "attribute number %d exceeds number of columns %d",
3047  fieldnum, tupDesc->natts);
3048  attr = TupleDescAttr(tupDesc, fieldnum - 1);
3049 
3050  /* Check for dropped column, and force a NULL result if so */
3051  if (attr->attisdropped)
3052  {
3053  *op->resnull = true;
3054  return;
3055  }
3056 
3057  /* Check for type mismatch --- possible after ALTER COLUMN TYPE? */
3058  /* As in CheckVarSlotCompatibility, we should but can't check typmod */
3059  if (op->d.fieldselect.resulttype != attr->atttypid)
3060  ereport(ERROR,
3061  (errcode(ERRCODE_DATATYPE_MISMATCH),
3062  errmsg("attribute %d has wrong type", fieldnum),
3063  errdetail("Table has type %s, but query expects %s.",
3064  format_type_be(attr->atttypid),
3065  format_type_be(op->d.fieldselect.resulttype))));
3066 
3067  /* heap_getattr needs a HeapTuple not a bare HeapTupleHeader */
3068  tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3069  tmptup.t_data = tuple;
3070 
3071  /* extract the field */
3072  *op->resvalue = heap_getattr(&tmptup,
3073  fieldnum,
3074  tupDesc,
3075  op->resnull);
3076  }
3077 }
3078 
3079 /*
3080  * Deform source tuple, filling in the step's values/nulls arrays, before
3081  * evaluating individual new values as part of a FieldStore expression.
3082  * Subsequent steps will overwrite individual elements of the values/nulls
3083  * arrays with the new field values, and then FIELDSTORE_FORM will build the
3084  * new tuple value.
3085  *
3086  * Source record is in step's result variable.
3087  */
3088 void
3090 {
3091  TupleDesc tupDesc;
3092 
3093  /* Lookup tupdesc if first time through or after rescan */
3094  tupDesc = get_cached_rowtype(op->d.fieldstore.fstore->resulttype, -1,
3095  op->d.fieldstore.argdesc, econtext);
3096 
3097  /* Check that current tupdesc doesn't have more fields than we allocated */
3098  if (unlikely(tupDesc->natts > op->d.fieldstore.ncolumns))
3099  elog(ERROR, "too many columns in composite type %u",
3100  op->d.fieldstore.fstore->resulttype);
3101 
3102  if (*op->resnull)
3103  {
3104  /* Convert null input tuple into an all-nulls row */
3105  memset(op->d.fieldstore.nulls, true,
3106  op->d.fieldstore.ncolumns * sizeof(bool));
3107  }
3108  else
3109  {
3110  /*
3111  * heap_deform_tuple needs a HeapTuple not a bare HeapTupleHeader. We
3112  * set all the fields in the struct just in case.
3113  */
3114  Datum tupDatum = *op->resvalue;
3115  HeapTupleHeader tuphdr;
3116  HeapTupleData tmptup;
3117 
3118  tuphdr = DatumGetHeapTupleHeader(tupDatum);
3119  tmptup.t_len = HeapTupleHeaderGetDatumLength(tuphdr);
3120  ItemPointerSetInvalid(&(tmptup.t_self));
3121  tmptup.t_tableOid = InvalidOid;
3122  tmptup.t_data = tuphdr;
3123 
3124  heap_deform_tuple(&tmptup, tupDesc,
3125  op->d.fieldstore.values,
3126  op->d.fieldstore.nulls);
3127  }
3128 }
3129 
3130 /*
3131  * Compute the new composite datum after each individual field value of a
3132  * FieldStore expression has been evaluated.
3133  */
3134 void
3136 {
3137  HeapTuple tuple;
3138 
3139  /* argdesc should already be valid from the DeForm step */
3140  tuple = heap_form_tuple(*op->d.fieldstore.argdesc,
3141  op->d.fieldstore.values,
3142  op->d.fieldstore.nulls);
3143 
3144  *op->resvalue = HeapTupleGetDatum(tuple);
3145  *op->resnull = false;
3146 }
3147 
3148 /*
3149  * Process a subscript in a SubscriptingRef expression.
3150  *
3151  * If subscript is NULL, throw error in assignment case, or in fetch case
3152  * set result to NULL and return false (instructing caller to skip the rest
3153  * of the SubscriptingRef sequence).
3154  *
3155  * Subscript expression result is in subscriptvalue/subscriptnull.
3156  * On success, integer subscript value has been saved in upperindex[] or
3157  * lowerindex[] for use later.
3158  */
3159 bool
3161 {
3162  SubscriptingRefState *sbsrefstate = op->d.sbsref_subscript.state;
3163  int *indexes;
3164  int off;
3165 
3166  /* If any index expr yields NULL, result is NULL or error */
3167  if (sbsrefstate->subscriptnull)
3168  {
3169  if (sbsrefstate->isassignment)
3170  ereport(ERROR,
3171  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3172  errmsg("array subscript in assignment must not be null")));
3173  *op->resnull = true;
3174  return false;
3175  }
3176 
3177  /* Convert datum to int, save in appropriate place */
3178  if (op->d.sbsref_subscript.isupper)
3179  indexes = sbsrefstate->upperindex;
3180  else
3181  indexes = sbsrefstate->lowerindex;
3182  off = op->d.sbsref_subscript.off;
3183 
3184  indexes[off] = DatumGetInt32(sbsrefstate->subscriptvalue);
3185 
3186  return true;
3187 }
3188 
3189 /*
3190  * Evaluate SubscriptingRef fetch.
3191  *
3192  * Source container is in step's result variable.
3193  */
3194 void
3196 {
3197  SubscriptingRefState *sbsrefstate = op->d.sbsref.state;
3198 
3199  /* Should not get here if source container (or any subscript) is null */
3200  Assert(!(*op->resnull));
3201 
3202  if (sbsrefstate->numlower == 0)
3203  {
3204  /* Scalar case */
3205  *op->resvalue = array_get_element(*op->resvalue,
3206  sbsrefstate->numupper,
3207  sbsrefstate->upperindex,
3208  sbsrefstate->refattrlength,
3209  sbsrefstate->refelemlength,
3210  sbsrefstate->refelembyval,
3211  sbsrefstate->refelemalign,
3212  op->resnull);
3213  }
3214  else
3215  {
3216  /* Slice case */
3217  *op->resvalue = array_get_slice(*op->resvalue,
3218  sbsrefstate->numupper,
3219  sbsrefstate->upperindex,
3220  sbsrefstate->lowerindex,
3221  sbsrefstate->upperprovided,
3222  sbsrefstate->lowerprovided,
3223  sbsrefstate->refattrlength,
3224  sbsrefstate->refelemlength,
3225  sbsrefstate->refelembyval,
3226  sbsrefstate->refelemalign);
3227  }
3228 }
3229 
3230 /*
3231  * Compute old container element/slice value for a SubscriptingRef assignment
3232  * expression. Will only be generated if the new-value subexpression
3233  * contains SubscriptingRef or FieldStore. The value is stored into the
3234  * SubscriptingRefState's prevvalue/prevnull fields.
3235  */
3236 void
3238 {
3239  SubscriptingRefState *sbsrefstate = op->d.sbsref.state;
3240 
3241  if (*op->resnull)
3242  {
3243  /* whole array is null, so any element or slice is too */
3244  sbsrefstate->prevvalue = (Datum) 0;
3245  sbsrefstate->prevnull = true;
3246  }
3247  else if (sbsrefstate->numlower == 0)
3248  {
3249  /* Scalar case */
3250  sbsrefstate->prevvalue = array_get_element(*op->resvalue,
3251  sbsrefstate->numupper,
3252  sbsrefstate->upperindex,
3253  sbsrefstate->refattrlength,
3254  sbsrefstate->refelemlength,
3255  sbsrefstate->refelembyval,
3256  sbsrefstate->refelemalign,
3257  &sbsrefstate->prevnull);
3258  }
3259  else
3260  {
3261  /* Slice case */
3262  /* this is currently unreachable */
3263  sbsrefstate->prevvalue = array_get_slice(*op->resvalue,
3264  sbsrefstate->numupper,
3265  sbsrefstate->upperindex,
3266  sbsrefstate->lowerindex,
3267  sbsrefstate->upperprovided,
3268  sbsrefstate->lowerprovided,
3269  sbsrefstate->refattrlength,
3270  sbsrefstate->refelemlength,
3271  sbsrefstate->refelembyval,
3272  sbsrefstate->refelemalign);
3273  sbsrefstate->prevnull = false;
3274  }
3275 }
3276 
3277 /*
3278  * Evaluate SubscriptingRef assignment.
3279  *
3280  * Input container (possibly null) is in result area, replacement value is in
3281  * SubscriptingRefState's replacevalue/replacenull.
3282  */
3283 void
3285 {
3286  SubscriptingRefState *sbsrefstate = op->d.sbsref_subscript.state;
3287 
3288  /*
3289  * For an assignment to a fixed-length container type, both the original
3290  * container and the value to be assigned into it must be non-NULL, else
3291  * we punt and return the original container.
3292  */
3293  if (sbsrefstate->refattrlength > 0)
3294  {
3295  if (*op->resnull || sbsrefstate->replacenull)
3296  return;
3297  }
3298 
3299  /*
3300  * For assignment to varlena arrays, we handle a NULL original array by
3301  * substituting an empty (zero-dimensional) array; insertion of the new
3302  * element will result in a singleton array value. It does not matter
3303  * whether the new element is NULL.
3304  */
3305  if (*op->resnull)
3306  {
3308  *op->resnull = false;
3309  }
3310 
3311  if (sbsrefstate->numlower == 0)
3312  {
3313  /* Scalar case */
3314  *op->resvalue = array_set_element(*op->resvalue,
3315  sbsrefstate->numupper,
3316  sbsrefstate->upperindex,
3317  sbsrefstate->replacevalue,
3318  sbsrefstate->replacenull,
3319  sbsrefstate->refattrlength,
3320  sbsrefstate->refelemlength,
3321  sbsrefstate->refelembyval,
3322  sbsrefstate->refelemalign);
3323  }
3324  else
3325  {
3326  /* Slice case */
3327  *op->resvalue = array_set_slice(*op->resvalue,
3328  sbsrefstate->numupper,
3329  sbsrefstate->upperindex,
3330  sbsrefstate->lowerindex,
3331  sbsrefstate->upperprovided,
3332  sbsrefstate->lowerprovided,
3333  sbsrefstate->replacevalue,
3334  sbsrefstate->replacenull,
3335  sbsrefstate->refattrlength,
3336  sbsrefstate->refelemlength,
3337  sbsrefstate->refelembyval,
3338  sbsrefstate->refelemalign);
3339  }
3340 }
3341 
3342 /*
3343  * Evaluate a rowtype coercion operation.
3344  * This may require rearranging field positions.
3345  *
3346  * Source record is in step's result variable.
3347  */
3348 void
3350 {
3352  HeapTuple result;
3353  Datum tupDatum;
3354  HeapTupleHeader tuple;
3355  HeapTupleData tmptup;
3356  TupleDesc indesc,
3357  outdesc;
3358 
3359  /* NULL in -> NULL out */
3360  if (*op->resnull)
3361  return;
3362 
3363  tupDatum = *op->resvalue;
3364  tuple = DatumGetHeapTupleHeader(tupDatum);
3365 
3366  /* Lookup tupdescs if first time through or after rescan */
3367  if (op->d.convert_rowtype.indesc == NULL)
3368  {
3369  get_cached_rowtype(exprType((Node *) convert->arg), -1,
3370  &op->d.convert_rowtype.indesc,
3371  econtext);
3372  op->d.convert_rowtype.initialized = false;
3373  }
3374  if (op->d.convert_rowtype.outdesc == NULL)
3375  {
3376  get_cached_rowtype(convert->resulttype, -1,
3377  &op->d.convert_rowtype.outdesc,
3378  econtext);
3379  op->d.convert_rowtype.initialized = false;
3380  }
3381 
3382  indesc = op->d.convert_rowtype.indesc;
3383  outdesc = op->d.convert_rowtype.outdesc;
3384 
3385  /*
3386  * We used to be able to assert that incoming tuples are marked with
3387  * exactly the rowtype of indesc. However, now that ExecEvalWholeRowVar
3388  * might change the tuples' marking to plain RECORD due to inserting
3389  * aliases, we can only make this weak test:
3390  */
3391  Assert(HeapTupleHeaderGetTypeId(tuple) == indesc->tdtypeid ||
3392  HeapTupleHeaderGetTypeId(tuple) == RECORDOID);
3393 
3394  /* if first time through, initialize conversion map */
3395  if (!op->d.convert_rowtype.initialized)
3396  {
3397  MemoryContext old_cxt;
3398 
3399  /* allocate map in long-lived memory context */
3400  old_cxt = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
3401 
3402  /* prepare map from old to new attribute numbers */
3403  op->d.convert_rowtype.map = convert_tuples_by_name(indesc, outdesc);
3404  op->d.convert_rowtype.initialized = true;
3405 
3406  MemoryContextSwitchTo(old_cxt);
3407  }
3408 
3409  /* Following steps need a HeapTuple not a bare HeapTupleHeader */
3410  tmptup.t_len = HeapTupleHeaderGetDatumLength(tuple);
3411  tmptup.t_data = tuple;
3412 
3413  if (op->d.convert_rowtype.map != NULL)
3414  {
3415  /* Full conversion with attribute rearrangement needed */
3416  result = execute_attr_map_tuple(&tmptup, op->d.convert_rowtype.map);
3417  /* Result already has appropriate composite-datum header fields */
3418  *op->resvalue = HeapTupleGetDatum(result);
3419  }
3420  else
3421  {
3422  /*
3423  * The tuple is physically compatible as-is, but we need to insert the
3424  * destination rowtype OID in its composite-datum header field, so we
3425  * have to copy it anyway. heap_copy_tuple_as_datum() is convenient
3426  * for this since it will both make the physical copy and insert the
3427  * correct composite header fields. Note that we aren't expecting to
3428  * have to flatten any toasted fields: the input was a composite
3429  * datum, so it shouldn't contain any. So heap_copy_tuple_as_datum()
3430  * is overkill here, but its check for external fields is cheap.
3431  */
3432  *op->resvalue = heap_copy_tuple_as_datum(&tmptup, outdesc);
3433  }
3434 }
3435 
3436 /*
3437  * Evaluate "scalar op ANY/ALL (array)".
3438  *
3439  * Source array is in our result area, scalar arg is already evaluated into
3440  * fcinfo->args[0].
3441  *
3442  * The operator always yields boolean, and we combine the results across all
3443  * array elements using OR and AND (for ANY and ALL respectively). Of course
3444  * we short-circuit as soon as the result is known.
3445  */
3446 void
3448 {
3449  FunctionCallInfo fcinfo = op->d.scalararrayop.fcinfo_data;
3450  bool useOr = op->d.scalararrayop.useOr;
3451  bool strictfunc = op->d.scalararrayop.finfo->fn_strict;
3452  ArrayType *arr;
3453  int nitems;
3454  Datum result;
3455  bool resultnull;
3456  int i;
3457  int16 typlen;
3458  bool typbyval;
3459  char typalign;
3460  char *s;
3461  bits8 *bitmap;
3462  int bitmask;
3463 
3464  /*
3465  * If the array is NULL then we return NULL --- it's not very meaningful
3466  * to do anything else, even if the operator isn't strict.
3467  */
3468  if (*op->resnull)
3469  return;
3470 
3471  /* Else okay to fetch and detoast the array */
3472  arr = DatumGetArrayTypeP(*op->resvalue);
3473 
3474  /*
3475  * If the array is empty, we return either FALSE or TRUE per the useOr
3476  * flag. This is correct even if the scalar is NULL; since we would
3477  * evaluate the operator zero times, it matters not whether it would want
3478  * to return NULL.
3479  */
3480  nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
3481  if (nitems <= 0)
3482  {
3483  *op->resvalue = BoolGetDatum(!useOr);
3484  *op->resnull = false;
3485  return;
3486  }
3487 
3488  /*
3489  * If the scalar is NULL, and the function is strict, return NULL; no
3490  * point in iterating the loop.
3491  */
3492  if (fcinfo->args[0].isnull && strictfunc)
3493  {
3494  *op->resnull = true;
3495  return;
3496  }
3497 
3498  /*
3499  * We arrange to look up info about the element type only once per series
3500  * of calls, assuming the element type doesn't change underneath us.
3501  */
3502  if (op->d.scalararrayop.element_type != ARR_ELEMTYPE(arr))
3503  {
3505  &op->d.scalararrayop.typlen,
3506  &op->d.scalararrayop.typbyval,
3507  &op->d.scalararrayop.typalign);
3508  op->d.scalararrayop.element_type = ARR_ELEMTYPE(arr);
3509  }
3510 
3511  typlen = op->d.scalararrayop.typlen;
3512  typbyval = op->d.scalararrayop.typbyval;
3513  typalign = op->d.scalararrayop.typalign;
3514 
3515  /* Initialize result appropriately depending on useOr */
3516  result = BoolGetDatum(!useOr);
3517  resultnull = false;
3518 
3519  /* Loop over the array elements */
3520  s = (char *) ARR_DATA_PTR(arr);
3521  bitmap = ARR_NULLBITMAP(arr);
3522  bitmask = 1;
3523 
3524  for (i = 0; i < nitems; i++)
3525  {
3526  Datum elt;
3527  Datum thisresult;
3528 
3529  /* Get array element, checking for NULL */
3530  if (bitmap && (*bitmap & bitmask) == 0)
3531  {
3532  fcinfo->args[1].value = (Datum) 0;
3533  fcinfo->args[1].isnull = true;
3534  }
3535  else
3536  {
3537  elt = fetch_att(s, typbyval, typlen);
3538  s = att_addlength_pointer(s, typlen, s);
3539  s = (char *) att_align_nominal(s, typalign);
3540  fcinfo->args[1].value = elt;
3541  fcinfo->args[1].isnull = false;
3542  }
3543 
3544  /* Call comparison function */
3545  if (fcinfo->args[1].isnull && strictfunc)
3546  {
3547  fcinfo->isnull = true;
3548  thisresult = (Datum) 0;
3549  }
3550  else
3551  {
3552  fcinfo->isnull = false;
3553  thisresult = op->d.scalararrayop.fn_addr(fcinfo);
3554  }
3555 
3556  /* Combine results per OR or AND semantics */
3557  if (fcinfo->isnull)
3558  resultnull = true;
3559  else if (useOr)
3560  {
3561  if (DatumGetBool(thisresult))
3562  {
3563  result = BoolGetDatum(true);
3564  resultnull = false;
3565  break; /* needn't look at any more elements */
3566  }
3567  }
3568  else
3569  {
3570  if (!DatumGetBool(thisresult))
3571  {
3572  result = BoolGetDatum(false);
3573  resultnull = false;
3574  break; /* needn't look at any more elements */
3575  }
3576  }
3577 
3578  /* advance bitmap pointer if any */
3579  if (bitmap)
3580  {
3581  bitmask <<= 1;
3582  if (bitmask == 0x100)
3583  {
3584  bitmap++;
3585  bitmask = 1;
3586  }
3587  }
3588  }
3589 
3590  *op->resvalue = result;
3591  *op->resnull = resultnull;
3592 }
3593 
3594 /*
3595  * Evaluate a NOT NULL domain constraint.
3596  */
3597 void
3599 {
3600  if (*op->resnull)
3601  ereport(ERROR,
3602  (errcode(ERRCODE_NOT_NULL_VIOLATION),
3603  errmsg("domain %s does not allow null values",
3604  format_type_be(op->d.domaincheck.resulttype)),
3605  errdatatype(op->d.domaincheck.resulttype)));
3606 }
3607 
3608 /*
3609  * Evaluate a CHECK domain constraint.
3610  */
3611 void
3613 {
3614  if (!*op->d.domaincheck.checknull &&
3615  !DatumGetBool(*op->d.domaincheck.checkvalue))
3616  ereport(ERROR,
3617  (errcode(ERRCODE_CHECK_VIOLATION),
3618  errmsg("value for domain %s violates check constraint \"%s\"",
3619  format_type_be(op->d.domaincheck.resulttype),
3620  op->d.domaincheck.constraintname),
3621  errdomainconstraint(op->d.domaincheck.resulttype,
3622  op->d.domaincheck.constraintname)));
3623 }
3624 
3625 /*
3626  * Evaluate the various forms of XmlExpr.
3627  *
3628  * Arguments have been evaluated into named_argvalue/named_argnull
3629  * and/or argvalue/argnull arrays.
3630  */
3631 void
3633 {
3634  XmlExpr *xexpr = op->d.xmlexpr.xexpr;
3635  Datum value;
3636  int i;
3637 
3638  *op->resnull = true; /* until we get a result */
3639  *op->resvalue = (Datum) 0;
3640 
3641  switch (xexpr->op)
3642  {
3643  case IS_XMLCONCAT:
3644  {
3645  Datum *argvalue = op->d.xmlexpr.argvalue;
3646  bool *argnull = op->d.xmlexpr.argnull;
3647  List *values = NIL;
3648 
3649  for (i = 0; i < list_length(xexpr->args); i++)
3650  {
3651  if (!argnull[i])
3652  values = lappend(values, DatumGetPointer(argvalue[i]));
3653  }
3654 
3655  if (values != NIL)
3656  {
3657  *op->resvalue = PointerGetDatum(xmlconcat(values));
3658  *op->resnull = false;
3659  }
3660  }
3661  break;
3662 
3663  case IS_XMLFOREST:
3664  {
3665  Datum *argvalue = op->d.xmlexpr.named_argvalue;
3666  bool *argnull = op->d.xmlexpr.named_argnull;
3668  ListCell *lc;
3669  ListCell *lc2;
3670 
3671  initStringInfo(&buf);
3672 
3673  i = 0;
3674  forboth(lc, xexpr->named_args, lc2, xexpr->arg_names)
3675  {
3676  Expr *e = (Expr *) lfirst(lc);
3677  char *argname = strVal(lfirst(lc2));
3678 
3679  if (!argnull[i])
3680  {
3681  value = argvalue[i];
3682  appendStringInfo(&buf, "<%s>%s</%s>",
3683  argname,
3685  exprType((Node *) e), true),
3686  argname);
3687  *op->resnull = false;
3688  }
3689  i++;
3690  }
3691 
3692  if (!*op->resnull)
3693  {
3694  text *result;
3695 
3696  result = cstring_to_text_with_len(buf.data, buf.len);
3697  *op->resvalue = PointerGetDatum(result);
3698  }
3699 
3700  pfree(buf.data);
3701  }
3702  break;
3703 
3704  case IS_XMLELEMENT:
3705  *op->resvalue = PointerGetDatum(xmlelement(xexpr,
3706  op->d.xmlexpr.named_argvalue,
3707  op->d.xmlexpr.named_argnull,
3708  op->d.xmlexpr.argvalue,
3709  op->d.xmlexpr.argnull));
3710  *op->resnull = false;
3711  break;
3712 
3713  case IS_XMLPARSE:
3714  {
3715  Datum *argvalue = op->d.xmlexpr.argvalue;
3716  bool *argnull = op->d.xmlexpr.argnull;
3717  text *data;
3718  bool preserve_whitespace;
3719 
3720  /* arguments are known to be text, bool */
3721  Assert(list_length(xexpr->args) == 2);
3722 
3723  if (argnull[0])
3724  return;
3725  value = argvalue[0];
3726  data = DatumGetTextPP(value);
3727 
3728  if (argnull[1]) /* probably can't happen */
3729  return;
3730  value = argvalue[1];
3731  preserve_whitespace = DatumGetBool(value);
3732 
3733  *op->resvalue = PointerGetDatum(xmlparse(data,
3734  xexpr->xmloption,
3735  preserve_whitespace));
3736  *op->resnull = false;
3737  }
3738  break;
3739 
3740  case IS_XMLPI:
3741  {
3742  text *arg;
3743  bool isnull;
3744 
3745  /* optional argument is known to be text */
3746  Assert(list_length(xexpr->args) <= 1);
3747 
3748  if (xexpr->args)
3749  {
3750  isnull = op->d.xmlexpr.argnull[0];
3751  if (isnull)
3752  arg = NULL;
3753  else
3754  arg = DatumGetTextPP(op->d.xmlexpr.argvalue[0]);
3755  }
3756  else
3757  {
3758  arg = NULL;
3759  isnull = false;
3760  }
3761 
3762  *op->resvalue = PointerGetDatum(xmlpi(xexpr->name,
3763  arg,
3764  isnull,
3765  op->resnull));
3766  }
3767  break;
3768 
3769  case IS_XMLROOT:
3770  {
3771  Datum *argvalue = op->d.xmlexpr.argvalue;
3772  bool *argnull = op->d.xmlexpr.argnull;
3773  xmltype *data;
3774  text *version;
3775  int standalone;
3776 
3777  /* arguments are known to be xml, text, int */
3778  Assert(list_length(xexpr->args) == 3);
3779 
3780  if (argnull[0])
3781  return;
3782  data = DatumGetXmlP(argvalue[0]);
3783 
3784  if (argnull[1])
3785  version = NULL;
3786  else
3787  version = DatumGetTextPP(argvalue[1]);
3788 
3789  Assert(!argnull[2]); /* always present */
3790  standalone = DatumGetInt32(argvalue[2]);
3791 
3792  *op->resvalue = PointerGetDatum(xmlroot(data,
3793  version,
3794  standalone));
3795  *op->resnull = false;
3796  }
3797  break;
3798 
3799  case IS_XMLSERIALIZE:
3800  {
3801  Datum *argvalue = op->d.xmlexpr.argvalue;
3802  bool *argnull = op->d.xmlexpr.argnull;
3803 
3804  /* argument type is known to be xml */
3805  Assert(list_length(xexpr->args) == 1);
3806 
3807  if (argnull[0])
3808  return;
3809  value = argvalue[0];
3810 
3811  *op->resvalue = PointerGetDatum(
3813  xexpr->xmloption));
3814  *op->resnull = false;
3815  }
3816  break;
3817 
3818  case IS_DOCUMENT:
3819  {
3820  Datum *argvalue = op->d.xmlexpr.argvalue;
3821  bool *argnull = op->d.xmlexpr.argnull;
3822 
3823  /* optional argument is known to be xml */
3824  Assert(list_length(xexpr->args) == 1);
3825 
3826  if (argnull[0])
3827  return;
3828  value = argvalue[0];
3829 
3830  *op->resvalue =
3832  *op->resnull = false;
3833  }
3834  break;
3835 
3836  default:
3837  elog(ERROR, "unrecognized XML operation");
3838  break;
3839  }
3840 }
3841 
3842 /*
3843  * ExecEvalGroupingFunc
3844  *
3845  * Computes a bitmask with a bit for each (unevaluated) argument expression
3846  * (rightmost arg is least significant bit).
3847  *
3848  * A bit is set if the corresponding expression is NOT part of the set of
3849  * grouping expressions in the current grouping set.
3850  */
3851 void
3853 {
3854  int result = 0;
3855  Bitmapset *grouped_cols = op->d.grouping_func.parent->grouped_cols;
3856  ListCell *lc;
3857 
3858  foreach(lc, op->d.grouping_func.clauses)
3859  {
3860  int attnum = lfirst_int(lc);
3861 
3862  result <<= 1;
3863 
3864  if (!bms_is_member(attnum, grouped_cols))
3865  result |= 1;
3866  }
3867 
3868  *op->resvalue = Int32GetDatum(result);
3869  *op->resnull = false;
3870 }
3871 
3872 /*
3873  * Hand off evaluation of a subplan to nodeSubplan.c
3874  */
3875 void
3877 {
3878  SubPlanState *sstate = op->d.subplan.sstate;
3879 
3880  /* could potentially be nested, so make sure there's enough stack */
3882 
3883  *op->resvalue = ExecSubPlan(sstate, econtext, op->resnull);
3884 }
3885 
3886 /*
3887  * Hand off evaluation of an alternative subplan to nodeSubplan.c
3888  */
3889 void
3891 {
3892  AlternativeSubPlanState *asstate = op->d.alternative_subplan.asstate;
3893 
3894  /* could potentially be nested, so make sure there's enough stack */
3896 
3897  *op->resvalue = ExecAlternativeSubPlan(asstate, econtext, op->resnull);
3898 }
3899 
3900 /*
3901  * Evaluate a wholerow Var expression.
3902  *
3903  * Returns a Datum whose value is the value of a whole-row range variable
3904  * with respect to given expression context.
3905  */
3906 void
3908 {
3909  Var *variable = op->d.wholerow.var;
3910  TupleTableSlot *slot;
3911  TupleDesc output_tupdesc;
3912  MemoryContext oldcontext;
3913  HeapTupleHeader dtuple;
3914  HeapTuple tuple;
3915 
3916  /* This was checked by ExecInitExpr */
3917  Assert(variable->varattno == InvalidAttrNumber);
3918 
3919  /* Get the input slot we want */
3920  switch (variable->varno)
3921  {
3922  case INNER_VAR:
3923  /* get the tuple from the inner node */
3924  slot = econtext->ecxt_innertuple;
3925  break;
3926 
3927  case OUTER_VAR:
3928  /* get the tuple from the outer node */
3929  slot = econtext->ecxt_outertuple;
3930  break;
3931 
3932  /* INDEX_VAR is handled by default case */
3933 
3934  default:
3935  /* get the tuple from the relation being scanned */
3936  slot = econtext->ecxt_scantuple;
3937  break;
3938  }
3939 
3940  /* Apply the junkfilter if any */
3941  if (op->d.wholerow.junkFilter != NULL)
3942  slot = ExecFilterJunk(op->d.wholerow.junkFilter, slot);
3943 
3944  /*
3945  * If first time through, obtain tuple descriptor and check compatibility.
3946  *
3947  * XXX: It'd be great if this could be moved to the expression
3948  * initialization phase, but due to using slots that's currently not
3949  * feasible.
3950  */
3951  if (op->d.wholerow.first)
3952  {
3953  /* optimistically assume we don't need slow path */
3954  op->d.wholerow.slow = false;
3955 
3956  /*
3957  * If the Var identifies a named composite type, we must check that
3958  * the actual tuple type is compatible with it.
3959  */
3960  if (variable->vartype != RECORDOID)
3961  {
3962  TupleDesc var_tupdesc;
3963  TupleDesc slot_tupdesc;
3964  int i;
3965 
3966  /*
3967  * We really only care about numbers of attributes and data types.
3968  * Also, we can ignore type mismatch on columns that are dropped
3969  * in the destination type, so long as (1) the physical storage
3970  * matches or (2) the actual column value is NULL. Case (1) is
3971  * helpful in some cases involving out-of-date cached plans, while
3972  * case (2) is expected behavior in situations such as an INSERT
3973  * into a table with dropped columns (the planner typically
3974  * generates an INT4 NULL regardless of the dropped column type).
3975  * If we find a dropped column and cannot verify that case (1)
3976  * holds, we have to use the slow path to check (2) for each row.
3977  *
3978  * If vartype is a domain over composite, just look through that
3979  * to the base composite type.
3980  */
3981  var_tupdesc = lookup_rowtype_tupdesc_domain(variable->vartype,
3982  -1, false);
3983 
3984  slot_tupdesc = slot->tts_tupleDescriptor;
3985 
3986  if (var_tupdesc->natts != slot_tupdesc->natts)
3987  ereport(ERROR,
3988  (errcode(ERRCODE_DATATYPE_MISMATCH),
3989  errmsg("table row type and query-specified row type do not match"),
3990  errdetail_plural("Table row contains %d attribute, but query expects %d.",
3991  "Table row contains %d attributes, but query expects %d.",
3992  slot_tupdesc->natts,
3993  slot_tupdesc->natts,
3994  var_tupdesc->natts)));
3995 
3996  for (i = 0; i < var_tupdesc->natts; i++)
3997  {
3998  Form_pg_attribute vattr = TupleDescAttr(var_tupdesc, i);
3999  Form_pg_attribute sattr = TupleDescAttr(slot_tupdesc, i);
4000 
4001  if (vattr->atttypid == sattr->atttypid)
4002  continue; /* no worries */
4003  if (!vattr->attisdropped)
4004  ereport(ERROR,
4005  (errcode(ERRCODE_DATATYPE_MISMATCH),
4006  errmsg("table row type and query-specified row type do not match"),
4007  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
4008  format_type_be(sattr->atttypid),
4009  i + 1,
4010  format_type_be(vattr->atttypid))));
4011 
4012  if (vattr->attlen != sattr->attlen ||
4013  vattr->attalign != sattr->attalign)
4014  op->d.wholerow.slow = true; /* need to check for nulls */
4015  }
4016 
4017  /*
4018  * Use the variable's declared rowtype as the descriptor for the
4019  * output values, modulo possibly assigning new column names
4020  * below. In particular, we *must* absorb any attisdropped
4021  * markings.
4022  */
4023  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
4024  output_tupdesc = CreateTupleDescCopy(var_tupdesc);
4025  MemoryContextSwitchTo(oldcontext);
4026 
4027  ReleaseTupleDesc(var_tupdesc);
4028  }
4029  else
4030  {
4031  /*
4032  * In the RECORD case, we use the input slot's rowtype as the
4033  * descriptor for the output values, modulo possibly assigning new
4034  * column names below.
4035  */
4036  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
4037  output_tupdesc = CreateTupleDescCopy(slot->tts_tupleDescriptor);
4038  MemoryContextSwitchTo(oldcontext);
4039  }
4040 
4041  /*
4042  * Construct a tuple descriptor for the composite values we'll
4043  * produce, and make sure its record type is "blessed". The main
4044  * reason to do this is to be sure that operations such as
4045  * row_to_json() will see the desired column names when they look up
4046  * the descriptor from the type information embedded in the composite
4047  * values.
4048  *
4049  * We already got the correct physical datatype info above, but now we
4050  * should try to find the source RTE and adopt its column aliases, in
4051  * case they are different from the original rowtype's names. For
4052  * example, in "SELECT foo(t) FROM tab t(x,y)", the first two columns
4053  * in the composite output should be named "x" and "y" regardless of
4054  * tab's column names.
4055  *
4056  * If we can't locate the RTE, assume the column names we've got are
4057  * OK. (As of this writing, the only cases where we can't locate the
4058  * RTE are in execution of trigger WHEN clauses, and then the Var will
4059  * have the trigger's relation's rowtype, so its names are fine.)
4060  * Also, if the creator of the RTE didn't bother to fill in an eref
4061  * field, assume our column names are OK. (This happens in COPY, and
4062  * perhaps other places.)
4063  */
4064  if (econtext->ecxt_estate &&
4065  variable->varno <= econtext->ecxt_estate->es_range_table_size)
4066  {
4067  RangeTblEntry *rte = exec_rt_fetch(variable->varno,
4068  econtext->ecxt_estate);
4069 
4070  if (rte->eref)
4071  ExecTypeSetColNames(output_tupdesc, rte->eref->colnames);
4072  }
4073 
4074  /* Bless the tupdesc if needed, and save it in the execution state */
4075  op->d.wholerow.tupdesc = BlessTupleDesc(output_tupdesc);
4076 
4077  op->d.wholerow.first = false;
4078  }
4079 
4080  /*
4081  * Make sure all columns of the slot are accessible in the slot's
4082  * Datum/isnull arrays.
4083  */
4084  slot_getallattrs(slot);
4085 
4086  if (op->d.wholerow.slow)
4087  {
4088  /* Check to see if any dropped attributes are non-null */
4089  TupleDesc tupleDesc = slot->tts_tupleDescriptor;
4090  TupleDesc var_tupdesc = op->d.wholerow.tupdesc;
4091  int i;
4092 
4093  Assert(var_tupdesc->natts == tupleDesc->natts);
4094 
4095  for (i = 0; i < var_tupdesc->natts; i++)
4096  {
4097  Form_pg_attribute vattr = TupleDescAttr(var_tupdesc, i);
4098  Form_pg_attribute sattr = TupleDescAttr(tupleDesc, i);
4099 
4100  if (!vattr->attisdropped)
4101  continue; /* already checked non-dropped cols */
4102  if (slot->tts_isnull[i])
4103  continue; /* null is always okay */
4104  if (vattr->attlen != sattr->attlen ||
4105  vattr->attalign != sattr->attalign)
4106  ereport(ERROR,
4107  (errcode(ERRCODE_DATATYPE_MISMATCH),
4108  errmsg("table row type and query-specified row type do not match"),
4109  errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.",
4110  i + 1)));
4111  }
4112  }
4113 
4114  /*
4115  * Build a composite datum, making sure any toasted fields get detoasted.
4116  *
4117  * (Note: it is critical that we not change the slot's state here.)
4118  */
4120  slot->tts_values,
4121  slot->tts_isnull);
4122  dtuple = tuple->t_data;
4123 
4124  /*
4125  * Label the datum with the composite type info we identified before.
4126  *
4127  * (Note: we could skip doing this by passing op->d.wholerow.tupdesc to
4128  * the tuple build step; but that seems a tad risky so let's not.)
4129  */
4130  HeapTupleHeaderSetTypeId(dtuple, op->d.wholerow.tupdesc->tdtypeid);
4131  HeapTupleHeaderSetTypMod(dtuple, op->d.wholerow.tupdesc->tdtypmod);
4132 
4133  *op->resvalue = PointerGetDatum(dtuple);
4134  *op->resnull = false;
4135 }
4136 
4137 void
4139  TupleTableSlot *slot)
4140 {
4141  Datum d;
4142 
4143  /* slot_getsysattr has sufficient defenses against bad attnums */
4144  d = slot_getsysattr(slot,
4145  op->d.var.attnum,
4146  op->resnull);
4147  *op->resvalue = d;
4148  /* this ought to be unreachable, but it's cheap enough to check */
4149  if (unlikely(*op->resnull))
4150  elog(ERROR, "failed to fetch attribute from slot");
4151 }
4152 
4153 /*
4154  * Transition value has not been initialized. This is the first non-NULL input
4155  * value for a group. We use it as the initial value for transValue.
4156  */
4157 void
4159 {
4160  FunctionCallInfo fcinfo = pertrans->transfn_fcinfo;
4161  MemoryContext oldContext;
4162 
4163  /*
4164  * We must copy the datum into aggcontext if it is pass-by-ref. We do not
4165  * need to pfree the old transValue, since it's NULL. (We already checked
4166  * that the agg's input type is binary-compatible with its transtype, so
4167  * straight copy here is OK.)
4168  */
4169  oldContext = MemoryContextSwitchTo(
4171  pergroup->transValue = datumCopy(fcinfo->args[1].value,
4172  pertrans->transtypeByVal,
4173  pertrans->transtypeLen);
4174  pergroup->transValueIsNull = false;
4175  pergroup->noTransValue = false;
4176  MemoryContextSwitchTo(oldContext);
4177 }
4178 
4179 /*
4180  * Ensure that the current transition value is a child of the aggcontext,
4181  * rather than the per-tuple context.
4182  *
4183  * NB: This can change the current memory context.
4184  */
4185 Datum
4187  Datum newValue, bool newValueIsNull,
4188  Datum oldValue, bool oldValueIsNull)
4189 {
4190  if (!newValueIsNull)
4191  {
4193  if (DatumIsReadWriteExpandedObject(newValue,
4194  false,
4195  pertrans->transtypeLen) &&
4196  MemoryContextGetParent(DatumGetEOHP(newValue)->eoh_context) == CurrentMemoryContext)
4197  /* do nothing */ ;
4198  else
4199  newValue = datumCopy(newValue,
4200  pertrans->transtypeByVal,
4201  pertrans->transtypeLen);
4202  }
4203  if (!oldValueIsNull)
4204  {
4205  if (DatumIsReadWriteExpandedObject(oldValue,
4206  false,
4207  pertrans->transtypeLen))
4208  DeleteExpandedObject(oldValue);
4209  else
4210  pfree(DatumGetPointer(oldValue));
4211  }
4212 
4213  return newValue;
4214 }
4215 
4216 /*
4217  * Invoke ordered transition function, with a datum argument.
4218  */
4219 void
4221  ExprContext *econtext)
4222 {
4223  AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
4224  int setno = op->d.agg_trans.setno;
4225 
4226  tuplesort_putdatum(pertrans->sortstates[setno],
4227  *op->resvalue, *op->resnull);
4228 }
4229 
4230 /*
4231  * Invoke ordered transition function, with a tuple argument.
4232  */
4233 void
4235  ExprContext *econtext)
4236 {
4237  AggStatePerTrans pertrans = op->d.agg_trans.pertrans;
4238  int setno = op->d.agg_trans.setno;
4239 
4240  ExecClearTuple(pertrans->sortslot);
4241  pertrans->sortslot->tts_nvalid = pertrans->numInputs;
4242  ExecStoreVirtualTuple(pertrans->sortslot);
4243  tuplesort_puttupleslot(pertrans->sortstates[setno], pertrans->sortslot);
4244 }
#define TTS_FIXED(slot)
Definition: tuptable.h:109
signed short int16
Definition: c.h:345
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:124
#define NIL
Definition: pg_list.h:65
void ExecEvalScalarArrayOp(ExprState *state, ExprEvalStep *op)
Datum value
Definition: params.h:92
Datum ExecInterpExprStillValid(ExprState *state, ExprContext *econtext, bool *isNull)
Datum array_get_slice(Datum arraydatum, int nSubscripts, int *upperIndx, int *lowerIndx, bool *upperProvided, bool *lowerProvided, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:2028
struct ExprEvalStep::@52::@94 agg_trans
struct ExprEvalStep::@52::@80 sbsref
void * execPlan
Definition: params.h:147
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
struct ExprEvalStep::@52::@84 xmlexpr
Datum * ecxt_aggvalues
Definition: execnodes.h:243
void ExecAggInitGroup(AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroup)
Datum MakeExpandedObjectReadOnlyInternal(Datum d)
Definition: expandeddatum.c:95
#define HeapTupleHeaderSetTypeId(tup, typeid)
Definition: htup_details.h:463
#define likely(x)
Definition: c.h:207
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:298
void tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
Definition: tuplesort.c:1556
Datum current_schema(PG_FUNCTION_ARGS)
Definition: name.c:319
struct ExprEvalStep::@52::@88 subplan
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:146
static Datum ExecJustOuterVar(ExprState *state, ExprContext *econtext, bool *isnull)
char * name
Definition: primnodes.h:1168
struct ExprEvalStep::@52::@54 var
#define ARR_SIZE(a)
Definition: array.h:277
#define VARATT_IS_EXTERNAL_EXPANDED(PTR)
Definition: postgres.h:322
static void ShutdownTupleDescRef(Datum arg)
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1652
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:426
static Datum ExecJustScanVar(ExprState *state, ExprContext *econtext, bool *isnull)
Datum * resvalue
Definition: execExpr.h:250
List * colnames
Definition: primnodes.h:43
#define DatumGetInt32(X)
Definition: postgres.h:472
MemoryContext MemoryContextGetParent(MemoryContext context)
Definition: mcxt.c:439
#define MAXDIM
Definition: c.h:529
static Datum ExecJustInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
struct ExprEvalStep::@52::@92 agg_init_trans
static Datum expanded_record_get_field(ExpandedRecordHeader *erh, int fnumber, bool *isnull)
#define EEO_SWITCH()
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2049
#define PointerGetDatum(X)
Definition: postgres.h:556
struct ExprEvalStep * steps
Definition: execnodes.h:86
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void ExecReadyInterpretedExpr(ExprState *state)
const TupleTableSlotOps TTSOpsBufferHeapTuple
Definition: execTuples.c:87
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:232
struct ExprEvalStep::@52::@85 aggref
#define EEO_JUMP(stepno)
void array_bitmap_copy(bits8 *destbitmap, int destoffset, const bits8 *srcbitmap, int srcoffset, int nitems)
Definition: arrayfuncs.c:4687
int64 nextval_internal(Oid relid, bool check_permissions)
Definition: sequence.c:579
int32 dataoffset
Definition: array.h:84
#define DatumGetTextPP(X)
Definition: fmgr.h:286
void ExecEvalParamExec(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
bool * resnull
Definition: execExpr.h:251
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define TimeTzADTPGetDatum(X)
Definition: date.h:59
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Int16GetDatum(X)
Definition: postgres.h:451
ExprEvalOp
Definition: execExpr.h:44
Datum ExecAlternativeSubPlan(AlternativeSubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:1377
xmltype * xmlconcat(List *args)
Definition: xml.c:512
static struct @145 value
static void slot_getsomeattrs(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:342
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
const TupleTableSlotOps *const tts_ops
Definition: tuptable.h:122
TimestampTz GetSQLCurrentTimestamp(int32 typmod)
Definition: timestamp.c:1601
int errcode(int sqlerrcode)
Definition: elog.c:570
void ExecEvalConvertRowtype(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
#define DateADTGetDatum(X)
Definition: date.h:57
AttrNumber varattno
Definition: primnodes.h:172
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
Datum array_set_element(Datum arraydatum, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:2199
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359
Datum * tts_values
Definition: tuptable.h:126
void ExecEvalSubscriptingRefAssign(ExprState *state, ExprEvalStep *op)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
static pg_attribute_always_inline Datum ExecJustAssignVarImpl(ExprState *state, TupleTableSlot *inslot, bool *isnull)
bool ExecEvalSubscriptingRef(ExprState *state, ExprEvalStep *op)
#define lengthof(array)
Definition: c.h:662
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3410
DateADT GetSQLCurrentDate(void)
Definition: date.c:299
TupleTableSlot * resultslot
Definition: execnodes.h:81
unsigned int Oid
Definition: postgres_ext.h:31
Datum domainValue_datum
Definition: execnodes.h:255
union ExprEvalStep::@52 d
List * arg_names
Definition: primnodes.h:1170
Definition: primnodes.h:167
#define DatumGetXmlP(X)
Definition: xml.h:50
int current_set
Definition: execnodes.h:2059
#define OidIsValid(objectId)
Definition: c.h:638
void ExecEvalFieldStoreForm(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:289
FunctionCallInfo transfn_fcinfo
Definition: nodeAgg.h:161
Datum(* ExprStateEvalFunc)(struct ExprState *expression, struct ExprContext *econtext, bool *isNull)
Definition: execnodes.h:54
#define ARR_OVERHEAD_WITHNULLS(ndims, nitems)
Definition: array.h:300
struct ExprEvalStep::@52::@65 cparam
struct ExprEvalStep::@52::@61 qualexpr
Datum ExecAggTransReparent(AggState *aggstate, AggStatePerTrans pertrans, Datum newValue, bool newValueIsNull, Datum oldValue, bool oldValueIsNull)
SQLValueFunctionOp op
Definition: primnodes.h:1129
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition: typcache.c:1708
struct ExprEvalStep::@52::@81 domaincheck
ExprContext * tmpcontext
Definition: execnodes.h:2049
signed int int32
Definition: c.h:346
struct ExprEvalStep::@52::@90 agg_deserialize
Datum current_database(PG_FUNCTION_ARGS)
Definition: misc.c:170
xmltype * xmlpi(const char *target, text *arg, bool arg_is_null, bool *result_is_null)
Definition: xml.c:770
void ExecEvalRow(ExprState *state, ExprEvalStep *op)
#define ARR_DATA_OFFSET(a)
Definition: array.h:304
#define ARR_LBOUND(a)
Definition: array.h:284
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:468
static pg_attribute_always_inline Datum ExecJustVarVirtImpl(ExprState *state, TupleTableSlot *slot, bool *isnull)
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:842
void ExecEvalMinMax(ExprState *state, ExprEvalStep *op)
Datum array_set_slice(Datum arraydatum, int nSubscripts, int *upperIndx, int *lowerIndx, bool *upperProvided, bool *lowerProvided, Datum srcArrayDatum, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:2759
static void CheckVarSlotCompatibility(TupleTableSlot *slot, int attnum, Oid vartype)
struct ExprEvalStep::@52::@86 grouping_func
ParamFetchHook paramFetch
Definition: params.h:112
void pfree(void *pointer)
Definition: mcxt.c:1056
ExprEvalOp ExecEvalStepOp(ExprState *state, ExprEvalStep *op)
MinMaxOp
Definition: primnodes.h:1079
static void convert(const int32 val, char *const buf)
Definition: zic.c:1959
char typalign
Definition: pg_type.h:170
struct ExprEvalStep::@52::@73 row
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
static Datum ExecJustConst(ExprState *state, ExprContext *econtext, bool *isnull)
struct ExprEvalStep::@52::@63 nulltest_row
struct ExprEvalStep::@52::@53 fetch
#define ERROR
Definition: elog.h:43
int errdomainconstraint(Oid datatypeOid, const char *conname)
Definition: domains.c:384
bool resnull
Definition: execnodes.h:73
#define DatumGetCString(X)
Definition: postgres.h:566
void pgstat_init_function_usage(FunctionCallInfo fcinfo, PgStat_FunctionCallUsage *fcu)
Definition: pgstat.c:1622
Oid elemtype
Definition: array.h:85
#define lfirst_int(lc)
Definition: pg_list.h:191
void ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
Definition: nodeSubplan.c:1051
bool isnull
Definition: params.h:149
Oid vartype
Definition: primnodes.h:174
Datum caseValue_datum
Definition: execnodes.h:249
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
text * xmltotext_with_xmloption(xmltype *data, XmlOptionType xmloption_arg)
Definition: xml.c:615
int32 tdtypmod
Definition: tupdesc.h:83
NullableDatum args[FLEXIBLE_ARRAY_MEMBER]
Definition: fmgr.h:95
#define ARR_DIMS(a)
Definition: array.h:282
struct ExprEvalStep::@52::@67 make_readonly
TimeTzADT * GetSQLCurrentTime(int32 typmod)
Definition: date.c:321
ItemPointerData t_self
Definition: htup.h:65
struct ExprEvalStep::@52::@78 fieldstore
void ExecEvalSubscriptingRefFetch(ExprState *state, ExprEvalStep *op)
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:355
struct ExprEvalStep::@52::@72 arraycoerce
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2048
struct ExprEvalStep::@52::@89 alternative_subplan
uint32 t_len
Definition: htup.h:64
#define EEO_NEXT()
#define ARR_DATA_PTR(a)
Definition: array.h:310
void ExecEvalRowNull(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:205
Tuplesortstate ** sortstates
Definition: nodeAgg.h:153
ExprStateEvalFunc evalfunc
Definition: execnodes.h:92
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:167
static void ExecEvalRowNullInt(ExprState *state, ExprEvalStep *op, ExprContext *econtext, bool checkisnull)
static char * buf
Definition: pg_test_fsync.c:68
Datum current_user(PG_FUNCTION_ARGS)
Definition: name.c:303
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:183
HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptoast.c:556
bool * tts_isnull
Definition: tuptable.h:128
void ExecEvalSysVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext, TupleTableSlot *slot)
static Datum ExecJustInnerVar(ExprState *state, ExprContext *econtext, bool *isnull)
void check_stack_depth(void)
Definition: postgres.c:3262
struct ExprEvalStep::@52::@66 casetest
int errdetail(const char *fmt,...)
Definition: elog.c:860
xmltype * xmlroot(xmltype *data, text *version, int standalone)
Definition: xml.c:822
#define DatumGetBool(X)
Definition: postgres.h:393
bool upperprovided[MAXDIM]
Definition: execExpr.h:675
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:226
void ExecEvalGroupingFunc(ExprState *state, ExprEvalStep *op)
ParamExecData * ecxt_param_exec_vals
Definition: execnodes.h:235
struct ExprEvalStep::@52::@58 constval
struct EState * ecxt_estate
Definition: execnodes.h:260
static Datum ExecJustAssignOuterVar(ExprState *state, ExprContext *econtext, bool *isnull)
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:537
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
Oid t_tableOid
Definition: htup.h:66
#define ARR_HASNULL(a)
Definition: array.h:279
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
struct ExprEvalStep::@52::@60 boolexpr
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1699
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:387
#define EEO_DISPATCH()
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:174
#define ereport(elevel, rest)
Definition: elog.h:141
Datum value
Definition: postgres.h:378
struct ExprEvalStep::@52::@71 arrayexpr
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
#define TimestampGetDatum(X)
Definition: timestamp.h:31
static pg_attribute_always_inline Datum ExecJustAssignVarVirtImpl(ExprState *state, TupleTableSlot *inslot, bool *isnull)
void * evalfunc_private
Definition: execnodes.h:98
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition: heaptuple.c:984
struct ExprEvalStep::@52::@64 param
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
TimeADT GetSQLLocalTime(int32 typmod)
Definition: date.c:347
List * lappend(List *list, void *datum)
Definition: list.c:322
static Datum ExecJustApplyFuncToCase(ExprState *state, ExprContext *econtext, bool *isnull)
bool xml_is_document(xmltype *arg)
Definition: xml.c:888
static Datum ExecJustAssignOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
struct ExprEvalStep::@52::@93 agg_strict_trans_check
Index varno
Definition: primnodes.h:170
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
bool domainValue_isNull
Definition: execnodes.h:257
XmlExprOp op
Definition: primnodes.h:1167
Datum session_user(PG_FUNCTION_ARGS)
Definition: name.c:309
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
ExprContext * curaggcontext
Definition: execnodes.h:2051
struct ExprEvalStep::@52::@87 window_func
bool * ecxt_aggnulls
Definition: execnodes.h:245
uint8 bits8
Definition: c.h:365
static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod, TupleDesc *cache_field, ExprContext *econtext)
#define TTS_IS_VIRTUAL(slot)
Definition: tuptable.h:228
uintptr_t Datum
Definition: postgres.h:367
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:261
#define ER_MAGIC
void ExecEvalXmlExpr(ExprState *state, ExprEvalStep *op)
#define HeapTupleHeaderSetTypMod(tup, typmod)
Definition: htup_details.h:473
bool lowerprovided[MAXDIM]
Definition: execExpr.h:680
void ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
#define DatumGetArrayTypePCopy(X)
Definition: array.h:250
#define TimeADTGetDatum(X)
Definition: date.h:58
int errdatatype(Oid datatypeOid)
Definition: domains.c:360
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:458
Timestamp GetSQLLocalTimestamp(int32 typmod)
Definition: timestamp.c:1615
#define BoolGetDatum(X)
Definition: postgres.h:402
void ExecEvalParamExtern(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
void DeleteExpandedObject(Datum d)
#define InvalidOid
Definition: postgres_ext.h:36
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:382
struct ExprEvalStep::@52::@62 jump
int16 attnum
Definition: pg_attribute.h:79
List * named_args
Definition: primnodes.h:1169
RowCompareType
Definition: primnodes.h:1042
struct ExprEvalStep::@52::@56 assign_var
static Datum ExecJustScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
struct ExprEvalStep::@52::@82 convert_rowtype
#define INNER_VAR
Definition: primnodes.h:157
List * args
Definition: primnodes.h:1171
Datum array_get_element(Datum arraydatum, int nSubscripts, int *indx, int arraytyplen, int elmlen, bool elmbyval, char elmalign, bool *isNull)
Definition: arrayfuncs.c:1819
struct ExprEvalStep::@52::@59 func
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
Datum array_map(Datum arrayd, ExprState *exprstate, ExprContext *econtext, Oid retType, ArrayMapState *amstate)
Definition: arrayfuncs.c:3131
struct ExprEvalStep::@52::@74 rowcompare_step
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:228
static Datum ExecJustAssignScanVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
void RegisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:863
Definition: regguts.h:298
intptr_t opcode
Definition: execExpr.h:247
static Datum ExecJustAssignScanVar(ExprState *state, ExprContext *econtext, bool *isnull)
#define DatumIsReadWriteExpandedObject(d, isnull, typlen)
XmlOptionType xmloption
Definition: primnodes.h:1172
int lowerindex[MAXDIM]
Definition: execExpr.h:681
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static void ExecInitInterpreter(void)
struct ExprEvalStep::@52::@70 nextvalueexpr
static int list_length(const List *l)
Definition: pg_list.h:169
#define newval
struct ExprEvalStep::@52::@91 agg_strict_input_check
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:952
void ExecEvalArrayCoerce(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:224
Index es_range_table_size
Definition: execnodes.h:506
void ExecEvalFuncExprStrictFusage(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
void ExecEvalSubscriptingRefOld(ExprState *state, ExprEvalStep *op)
static pg_attribute_always_inline Datum ExecJustVarImpl(ExprState *state, TupleTableSlot *slot, bool *isnull)
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:231
#define ARR_NDIM(a)
Definition: array.h:278
#define InvalidAttrNumber
Definition: attnum.h:23
static Datum ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
struct ExprEvalStep::@52::@76 minmax
void ExecEvalAggOrderedTransDatum(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
#define DatumGetPointer(X)
Definition: postgres.h:549
void pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
Definition: pgstat.c:1694
int upperindex[MAXDIM]
Definition: execExpr.h:676
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
void ExecEvalFieldStoreDeForm(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
static Datum values[MAXATTR]
Definition: bootstrap.c:167
struct ExprEvalStep::@52::@79 sbsref_subscript
Oid tdtypeid
Definition: tupdesc.h:82
struct ExprEvalStep::@52::@69 sqlvaluefunction
void ExecEvalConstraintCheck(ExprState *state, ExprEvalStep *op)
#define Int32GetDatum(X)
Definition: postgres.h:479
e
Definition: preproc-init.c:82
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
static Datum ExecJustOuterVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
bool caseValue_isNull
Definition: execnodes.h:251
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define fetch_att(T, attbyval, attlen)
Definition: tupmacs.h:73
int steps_len
Definition: execnodes.h:105
void ExecEvalRowNotNull(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
struct ExprEvalStep::@52::@68 iocoerce
void ExecEvalConstraintNotNull(ExprState *state, ExprEvalStep *op)
#define elog(elevel,...)
Definition: elog.h:226
static Datum ExecJustAssignInnerVarVirt(ExprState *state, ExprContext *econtext, bool *isnull)
Datum ExecSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:63
int i
xmltype * xmlelement(XmlExpr *xexpr, Datum *named_argvalue, bool *named_argnull, Datum *argvalue, bool *argnull)
Definition: xml.c:628
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:85
Datum value
Definition: params.h:148
static Datum ExecJustAssignInnerVar(ExprState *state, ExprContext *econtext, bool *isnull)
uint8 flags
Definition: execnodes.h:66
#define pg_attribute_always_inline
Definition: c.h:164
void * arg
AggStatePerTrans curpertrans
Definition: execnodes.h:2054
#define unlikely(x)
Definition: c.h:208
struct ExprEvalStep::@52::@77 fieldselect
Definition: c.h:549
void ExecEvalSubPlan(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
void ExecEvalFuncExprFusage(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
AttrNumber tts_nvalid
Definition: tuptable.h:121
struct ExprEvalStep::@52::@83 scalararrayop
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
TupleTableSlot * sortslot
Definition: nodeAgg.h:135
struct ExprEvalStep::@52::@55 wholerow
Alias * eref
Definition: parsenodes.h:1092
#define qsort(a, b, c, d)
Definition: port.h:492
void CheckExprStillValid(ExprState *state, ExprContext *econtext)
#define EEO_OPCODE(opcode)
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:403
void ExecEvalCurrentOfExpr(ExprState *state, ExprEvalStep *op)
static void CheckOpSlotCompatibility(ExprEvalStep *op, TupleTableSlot *slot)
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:3326
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
char * map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
Definition: xml.c:2154
ParamListInfo ecxt_param_list_info
Definition: execnodes.h:236
void ExecEvalAlternativeSubPlan(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
Definition: pg_list.h:50
void ExecEvalNextValueExpr(ExprState *state, ExprEvalStep *op)
bool isnull
Definition: params.h:93
#define EEO_CASE(name)
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
#define ARR_ELEMTYPE(a)
Definition: array.h:280
Datum resvalue
Definition: execnodes.h:75
#define EEO_FLAG_INTERPRETER_INITIALIZED
Definition: execExpr.h:26
int16 AttrNumber
Definition: attnum.h:21
#define ARR_NULLBITMAP(a)
Definition: array.h:288
#define OUTER_VAR
Definition: primnodes.h:158
void ExecTypeSetColNames(TupleDesc typeInfo, List *namesList)
Definition: execTuples.c:2002
void ExecEvalAggOrderedTransTuple(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
void ExecEvalFieldSelect(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
xmltype * xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace)
Definition: xml.c:752
int ndim
Definition: array.h:83
#define EEO_FLAG_DIRECT_THREADED
Definition: execExpr.h:28
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1517
void tuplesort_puttupleslot(Tuplesortstate *state, TupleTableSlot *slot)
Definition: tuplesort.c:1435
void ExecEvalSQLValueFunction(ExprState *state, ExprEvalStep *op)
struct ExprEvalStep::@52::@75 rowcompare_final
AggStatePerGroup * all_pergroups
Definition: execnodes.h:2081
void ExecEvalArrayExpr(ExprState *state, ExprEvalStep *op)
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:452
#define DatumGetArrayTypeP(X)
Definition: array.h:249
struct ExprEvalStep::@52::@57 assign_tmp