Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * clauses.c
4 : * routines to manipulate qualification clauses
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/optimizer/util/clauses.c
12 : *
13 : * HISTORY
14 : * AUTHOR DATE MAJOR EVENT
15 : * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
16 : *
17 : *-------------------------------------------------------------------------
18 : */
19 :
20 : #include "postgres.h"
21 :
22 : #include "access/htup_details.h"
23 : #include "catalog/pg_language.h"
24 : #include "catalog/pg_operator.h"
25 : #include "catalog/pg_proc.h"
26 : #include "catalog/pg_type.h"
27 : #include "executor/executor.h"
28 : #include "executor/functions.h"
29 : #include "funcapi.h"
30 : #include "miscadmin.h"
31 : #include "nodes/makefuncs.h"
32 : #include "nodes/multibitmapset.h"
33 : #include "nodes/nodeFuncs.h"
34 : #include "nodes/subscripting.h"
35 : #include "nodes/supportnodes.h"
36 : #include "optimizer/clauses.h"
37 : #include "optimizer/cost.h"
38 : #include "optimizer/optimizer.h"
39 : #include "optimizer/plancat.h"
40 : #include "optimizer/planmain.h"
41 : #include "parser/analyze.h"
42 : #include "parser/parse_coerce.h"
43 : #include "parser/parse_collate.h"
44 : #include "parser/parse_func.h"
45 : #include "parser/parse_oper.h"
46 : #include "rewrite/rewriteHandler.h"
47 : #include "rewrite/rewriteManip.h"
48 : #include "tcop/tcopprot.h"
49 : #include "utils/acl.h"
50 : #include "utils/builtins.h"
51 : #include "utils/datum.h"
52 : #include "utils/fmgroids.h"
53 : #include "utils/json.h"
54 : #include "utils/jsonb.h"
55 : #include "utils/jsonpath.h"
56 : #include "utils/lsyscache.h"
57 : #include "utils/memutils.h"
58 : #include "utils/syscache.h"
59 : #include "utils/typcache.h"
60 :
61 : typedef struct
62 : {
63 : ParamListInfo boundParams;
64 : PlannerInfo *root;
65 : List *active_fns;
66 : Node *case_val;
67 : bool estimate;
68 : } eval_const_expressions_context;
69 :
70 : typedef struct
71 : {
72 : int nargs;
73 : List *args;
74 : int *usecounts;
75 : } substitute_actual_parameters_context;
76 :
77 : typedef struct
78 : {
79 : int nargs;
80 : List *args;
81 : int sublevels_up;
82 : } substitute_actual_srf_parameters_context;
83 :
84 : typedef struct
85 : {
86 : char *proname;
87 : char *prosrc;
88 : } inline_error_callback_arg;
89 :
90 : typedef struct
91 : {
92 : char max_hazard; /* worst proparallel hazard found so far */
93 : char max_interesting; /* worst proparallel hazard of interest */
94 : List *safe_param_ids; /* PARAM_EXEC Param IDs to treat as safe */
95 : } max_parallel_hazard_context;
96 :
97 : static bool contain_agg_clause_walker(Node *node, void *context);
98 : static bool find_window_functions_walker(Node *node, WindowFuncLists *lists);
99 : static bool contain_subplans_walker(Node *node, void *context);
100 : static bool contain_mutable_functions_walker(Node *node, void *context);
101 : static bool contain_volatile_functions_walker(Node *node, void *context);
102 : static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context);
103 : static bool max_parallel_hazard_walker(Node *node,
104 : max_parallel_hazard_context *context);
105 : static bool contain_nonstrict_functions_walker(Node *node, void *context);
106 : static bool contain_exec_param_walker(Node *node, List *param_ids);
107 : static bool contain_context_dependent_node(Node *clause);
108 : static bool contain_context_dependent_node_walker(Node *node, int *flags);
109 : static bool contain_leaked_vars_walker(Node *node, void *context);
110 : static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
111 : static List *find_nonnullable_vars_walker(Node *node, bool top_level);
112 : static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
113 : static bool convert_saop_to_hashed_saop_walker(Node *node, void *context);
114 : static Node *eval_const_expressions_mutator(Node *node,
115 : eval_const_expressions_context *context);
116 : static bool contain_non_const_walker(Node *node, void *context);
117 : static bool ece_function_is_safe(Oid funcid,
118 : eval_const_expressions_context *context);
119 : static List *simplify_or_arguments(List *args,
120 : eval_const_expressions_context *context,
121 : bool *haveNull, bool *forceTrue);
122 : static List *simplify_and_arguments(List *args,
123 : eval_const_expressions_context *context,
124 : bool *haveNull, bool *forceFalse);
125 : static Node *simplify_boolean_equality(Oid opno, List *args);
126 : static Expr *simplify_function(Oid funcid,
127 : Oid result_type, int32 result_typmod,
128 : Oid result_collid, Oid input_collid, List **args_p,
129 : bool funcvariadic, bool process_args, bool allow_non_const,
130 : eval_const_expressions_context *context);
131 : static List *reorder_function_arguments(List *args, int pronargs,
132 : HeapTuple func_tuple);
133 : static List *add_function_defaults(List *args, int pronargs,
134 : HeapTuple func_tuple);
135 : static List *fetch_function_defaults(HeapTuple func_tuple);
136 : static void recheck_cast_function_args(List *args, Oid result_type,
137 : Oid *proargtypes, int pronargs,
138 : HeapTuple func_tuple);
139 : static Expr *evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
140 : Oid result_collid, Oid input_collid, List *args,
141 : bool funcvariadic,
142 : HeapTuple func_tuple,
143 : eval_const_expressions_context *context);
144 : static Expr *inline_function(Oid funcid, Oid result_type, Oid result_collid,
145 : Oid input_collid, List *args,
146 : bool funcvariadic,
147 : HeapTuple func_tuple,
148 : eval_const_expressions_context *context);
149 : static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
150 : int *usecounts);
151 : static Node *substitute_actual_parameters_mutator(Node *node,
152 : substitute_actual_parameters_context *context);
153 : static void sql_inline_error_callback(void *arg);
154 : static Query *substitute_actual_srf_parameters(Query *expr,
155 : int nargs, List *args);
156 : static Node *substitute_actual_srf_parameters_mutator(Node *node,
157 : substitute_actual_srf_parameters_context *context);
158 : static bool pull_paramids_walker(Node *node, Bitmapset **context);
159 :
160 :
161 : /*****************************************************************************
162 : * Aggregate-function clause manipulation
163 : *****************************************************************************/
164 :
165 : /*
166 : * contain_agg_clause
167 : * Recursively search for Aggref/GroupingFunc nodes within a clause.
168 : *
169 : * Returns true if any aggregate found.
170 : *
171 : * This does not descend into subqueries, and so should be used only after
172 : * reduction of sublinks to subplans, or in contexts where it's known there
173 : * are no subqueries. There mustn't be outer-aggregate references either.
174 : *
175 : * (If you want something like this but able to deal with subqueries,
176 : * see rewriteManip.c's contain_aggs_of_level().)
177 : */
178 : bool
179 10006 : contain_agg_clause(Node *clause)
180 : {
181 10006 : return contain_agg_clause_walker(clause, NULL);
182 : }
183 :
184 : static bool
185 11958 : contain_agg_clause_walker(Node *node, void *context)
186 : {
187 11958 : if (node == NULL)
188 30 : return false;
189 11928 : if (IsA(node, Aggref))
190 : {
191 : Assert(((Aggref *) node)->agglevelsup == 0);
192 968 : return true; /* abort the tree traversal and return true */
193 : }
194 10960 : if (IsA(node, GroupingFunc))
195 : {
196 : Assert(((GroupingFunc *) node)->agglevelsup == 0);
197 30 : return true; /* abort the tree traversal and return true */
198 : }
199 : Assert(!IsA(node, SubLink));
200 10930 : return expression_tree_walker(node, contain_agg_clause_walker, context);
201 : }
202 :
203 : /*****************************************************************************
204 : * Window-function clause manipulation
205 : *****************************************************************************/
206 :
207 : /*
208 : * contain_window_function
209 : * Recursively search for WindowFunc nodes within a clause.
210 : *
211 : * Since window functions don't have level fields, but are hard-wired to
212 : * be associated with the current query level, this is just the same as
213 : * rewriteManip.c's function.
214 : */
215 : bool
216 8672 : contain_window_function(Node *clause)
217 : {
218 8672 : return contain_windowfuncs(clause);
219 : }
220 :
221 : /*
222 : * find_window_functions
223 : * Locate all the WindowFunc nodes in an expression tree, and organize
224 : * them by winref ID number.
225 : *
226 : * Caller must provide an upper bound on the winref IDs expected in the tree.
227 : */
228 : WindowFuncLists *
229 2384 : find_window_functions(Node *clause, Index maxWinRef)
230 : {
231 2384 : WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
232 :
233 2384 : lists->numWindowFuncs = 0;
234 2384 : lists->maxWinRef = maxWinRef;
235 2384 : lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
236 2384 : (void) find_window_functions_walker(clause, lists);
237 2384 : return lists;
238 : }
239 :
240 : static bool
241 20776 : find_window_functions_walker(Node *node, WindowFuncLists *lists)
242 : {
243 20776 : if (node == NULL)
244 218 : return false;
245 20558 : if (IsA(node, WindowFunc))
246 : {
247 3260 : WindowFunc *wfunc = (WindowFunc *) node;
248 :
249 : /* winref is unsigned, so one-sided test is OK */
250 3260 : if (wfunc->winref > lists->maxWinRef)
251 0 : elog(ERROR, "WindowFunc contains out-of-range winref %u",
252 : wfunc->winref);
253 : /* eliminate duplicates, so that we avoid repeated computation */
254 3260 : if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
255 : {
256 6496 : lists->windowFuncs[wfunc->winref] =
257 3248 : lappend(lists->windowFuncs[wfunc->winref], wfunc);
258 3248 : lists->numWindowFuncs++;
259 : }
260 :
261 : /*
262 : * We assume that the parser checked that there are no window
263 : * functions in the arguments or filter clause. Hence, we need not
264 : * recurse into them. (If either the parser or the planner screws up
265 : * on this point, the executor will still catch it; see ExecInitExpr.)
266 : */
267 3260 : return false;
268 : }
269 : Assert(!IsA(node, SubLink));
270 17298 : return expression_tree_walker(node, find_window_functions_walker, lists);
271 : }
272 :
273 :
274 : /*****************************************************************************
275 : * Support for expressions returning sets
276 : *****************************************************************************/
277 :
278 : /*
279 : * expression_returns_set_rows
280 : * Estimate the number of rows returned by a set-returning expression.
281 : * The result is 1 if it's not a set-returning expression.
282 : *
283 : * We should only examine the top-level function or operator; it used to be
284 : * appropriate to recurse, but not anymore. (Even if there are more SRFs in
285 : * the function's inputs, their multipliers are accounted for separately.)
286 : *
287 : * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
288 : */
289 : double
290 454806 : expression_returns_set_rows(PlannerInfo *root, Node *clause)
291 : {
292 454806 : if (clause == NULL)
293 0 : return 1.0;
294 454806 : if (IsA(clause, FuncExpr))
295 : {
296 65502 : FuncExpr *expr = (FuncExpr *) clause;
297 :
298 65502 : if (expr->funcretset)
299 56414 : return clamp_row_est(get_function_rows(root, expr->funcid, clause));
300 : }
301 398392 : if (IsA(clause, OpExpr))
302 : {
303 3302 : OpExpr *expr = (OpExpr *) clause;
304 :
305 3302 : if (expr->opretset)
306 : {
307 6 : set_opfuncid(expr);
308 6 : return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
309 : }
310 : }
311 398386 : return 1.0;
312 : }
313 :
314 :
315 : /*****************************************************************************
316 : * Subplan clause manipulation
317 : *****************************************************************************/
318 :
319 : /*
320 : * contain_subplans
321 : * Recursively search for subplan nodes within a clause.
322 : *
323 : * If we see a SubLink node, we will return true. This is only possible if
324 : * the expression tree hasn't yet been transformed by subselect.c. We do not
325 : * know whether the node will produce a true subplan or just an initplan,
326 : * but we make the conservative assumption that it will be a subplan.
327 : *
328 : * Returns true if any subplan found.
329 : */
330 : bool
331 49460 : contain_subplans(Node *clause)
332 : {
333 49460 : return contain_subplans_walker(clause, NULL);
334 : }
335 :
336 : static bool
337 181064 : contain_subplans_walker(Node *node, void *context)
338 : {
339 181064 : if (node == NULL)
340 7298 : return false;
341 173766 : if (IsA(node, SubPlan) ||
342 173664 : IsA(node, AlternativeSubPlan) ||
343 173664 : IsA(node, SubLink))
344 358 : return true; /* abort the tree traversal and return true */
345 173408 : return expression_tree_walker(node, contain_subplans_walker, context);
346 : }
347 :
348 :
349 : /*****************************************************************************
350 : * Check clauses for mutable functions
351 : *****************************************************************************/
352 :
353 : /*
354 : * contain_mutable_functions
355 : * Recursively search for mutable functions within a clause.
356 : *
357 : * Returns true if any mutable function (or operator implemented by a
358 : * mutable function) is found. This test is needed so that we don't
359 : * mistakenly think that something like "WHERE random() < 0.5" can be treated
360 : * as a constant qualification.
361 : *
362 : * This will give the right answer only for clauses that have been put
363 : * through expression preprocessing. Callers outside the planner typically
364 : * should use contain_mutable_functions_after_planning() instead, for the
365 : * reasons given there.
366 : *
367 : * We will recursively look into Query nodes (i.e., SubLink sub-selects)
368 : * but not into SubPlans. See comments for contain_volatile_functions().
369 : */
370 : bool
371 166998 : contain_mutable_functions(Node *clause)
372 : {
373 166998 : return contain_mutable_functions_walker(clause, NULL);
374 : }
375 :
376 : static bool
377 121596 : contain_mutable_functions_checker(Oid func_id, void *context)
378 : {
379 121596 : return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
380 : }
381 :
382 : static bool
383 439302 : contain_mutable_functions_walker(Node *node, void *context)
384 : {
385 439302 : if (node == NULL)
386 2228 : return false;
387 : /* Check for mutable functions in node itself */
388 437074 : if (check_functions_in_node(node, contain_mutable_functions_checker,
389 : context))
390 6428 : return true;
391 :
392 430646 : if (IsA(node, JsonConstructorExpr))
393 : {
394 0 : const JsonConstructorExpr *ctor = (JsonConstructorExpr *) node;
395 : ListCell *lc;
396 : bool is_jsonb;
397 :
398 0 : is_jsonb = ctor->returning->format->format_type == JS_FORMAT_JSONB;
399 :
400 : /*
401 : * Check argument_type => json[b] conversions specifically. We still
402 : * recurse to check 'args' below, but here we want to specifically
403 : * check whether or not the emitted clause would fail to be immutable
404 : * because of TimeZone, for example.
405 : */
406 0 : foreach(lc, ctor->args)
407 : {
408 0 : Oid typid = exprType(lfirst(lc));
409 :
410 0 : if (is_jsonb ?
411 0 : !to_jsonb_is_immutable(typid) :
412 0 : !to_json_is_immutable(typid))
413 0 : return true;
414 : }
415 :
416 : /* Check all subnodes */
417 : }
418 :
419 430646 : if (IsA(node, JsonExpr))
420 : {
421 234 : JsonExpr *jexpr = castNode(JsonExpr, node);
422 : Const *cnst;
423 :
424 234 : if (!IsA(jexpr->path_spec, Const))
425 0 : return true;
426 :
427 234 : cnst = castNode(Const, jexpr->path_spec);
428 :
429 : Assert(cnst->consttype == JSONPATHOID);
430 234 : if (cnst->constisnull)
431 0 : return false;
432 :
433 234 : if (jspIsMutable(DatumGetJsonPathP(cnst->constvalue),
434 : jexpr->passing_names, jexpr->passing_values))
435 162 : return true;
436 : }
437 :
438 430484 : if (IsA(node, SQLValueFunction))
439 : {
440 : /* all variants of SQLValueFunction are stable */
441 432 : return true;
442 : }
443 :
444 430052 : if (IsA(node, NextValueExpr))
445 : {
446 : /* NextValueExpr is volatile */
447 0 : return true;
448 : }
449 :
450 : /*
451 : * It should be safe to treat MinMaxExpr as immutable, because it will
452 : * depend on a non-cross-type btree comparison function, and those should
453 : * always be immutable. Treating XmlExpr as immutable is more dubious,
454 : * and treating CoerceToDomain as immutable is outright dangerous. But we
455 : * have done so historically, and changing this would probably cause more
456 : * problems than it would fix. In practice, if you have a non-immutable
457 : * domain constraint you are in for pain anyhow.
458 : */
459 :
460 : /* Recurse to check arguments */
461 430052 : if (IsA(node, Query))
462 : {
463 : /* Recurse into subselects */
464 0 : return query_tree_walker((Query *) node,
465 : contain_mutable_functions_walker,
466 : context, 0);
467 : }
468 430052 : return expression_tree_walker(node, contain_mutable_functions_walker,
469 : context);
470 : }
471 :
472 : /*
473 : * contain_mutable_functions_after_planning
474 : * Test whether given expression contains mutable functions.
475 : *
476 : * This is a wrapper for contain_mutable_functions() that is safe to use from
477 : * outside the planner. The difference is that it first runs the expression
478 : * through expression_planner(). There are two key reasons why we need that:
479 : *
480 : * First, function default arguments will get inserted, which may affect
481 : * volatility (consider "default now()").
482 : *
483 : * Second, inline-able functions will get inlined, which may allow us to
484 : * conclude that the function is really less volatile than it's marked.
485 : * As an example, polymorphic functions must be marked with the most volatile
486 : * behavior that they have for any input type, but once we inline the
487 : * function we may be able to conclude that it's not so volatile for the
488 : * particular input type we're dealing with.
489 : */
490 : bool
491 3348 : contain_mutable_functions_after_planning(Expr *expr)
492 : {
493 : /* We assume here that expression_planner() won't scribble on its input */
494 3348 : expr = expression_planner(expr);
495 :
496 : /* Now we can search for non-immutable functions */
497 3348 : return contain_mutable_functions((Node *) expr);
498 : }
499 :
500 :
501 : /*****************************************************************************
502 : * Check clauses for volatile functions
503 : *****************************************************************************/
504 :
505 : /*
506 : * contain_volatile_functions
507 : * Recursively search for volatile functions within a clause.
508 : *
509 : * Returns true if any volatile function (or operator implemented by a
510 : * volatile function) is found. This test prevents, for example,
511 : * invalid conversions of volatile expressions into indexscan quals.
512 : *
513 : * This will give the right answer only for clauses that have been put
514 : * through expression preprocessing. Callers outside the planner typically
515 : * should use contain_volatile_functions_after_planning() instead, for the
516 : * reasons given there.
517 : *
518 : * We will recursively look into Query nodes (i.e., SubLink sub-selects)
519 : * but not into SubPlans. This is a bit odd, but intentional. If we are
520 : * looking at a SubLink, we are probably deciding whether a query tree
521 : * transformation is safe, and a contained sub-select should affect that;
522 : * for example, duplicating a sub-select containing a volatile function
523 : * would be bad. However, once we've got to the stage of having SubPlans,
524 : * subsequent planning need not consider volatility within those, since
525 : * the executor won't change its evaluation rules for a SubPlan based on
526 : * volatility.
527 : *
528 : * For some node types, for example, RestrictInfo and PathTarget, we cache
529 : * whether we found any volatile functions or not and reuse that value in any
530 : * future checks for that node. All of the logic for determining if the
531 : * cached value should be set to VOLATILITY_NOVOLATILE or VOLATILITY_VOLATILE
532 : * belongs in this function. Any code which makes changes to these nodes
533 : * which could change the outcome this function must set the cached value back
534 : * to VOLATILITY_UNKNOWN. That allows this function to redetermine the
535 : * correct value during the next call, should we need to redetermine if the
536 : * node contains any volatile functions again in the future.
537 : */
538 : bool
539 3413858 : contain_volatile_functions(Node *clause)
540 : {
541 3413858 : return contain_volatile_functions_walker(clause, NULL);
542 : }
543 :
544 : static bool
545 847082 : contain_volatile_functions_checker(Oid func_id, void *context)
546 : {
547 847082 : return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
548 : }
549 :
550 : static bool
551 7489192 : contain_volatile_functions_walker(Node *node, void *context)
552 : {
553 7489192 : if (node == NULL)
554 215596 : return false;
555 : /* Check for volatile functions in node itself */
556 7273596 : if (check_functions_in_node(node, contain_volatile_functions_checker,
557 : context))
558 1906 : return true;
559 :
560 7271690 : if (IsA(node, NextValueExpr))
561 : {
562 : /* NextValueExpr is volatile */
563 42 : return true;
564 : }
565 :
566 7271648 : if (IsA(node, RestrictInfo))
567 : {
568 1355156 : RestrictInfo *rinfo = (RestrictInfo *) node;
569 :
570 : /*
571 : * For RestrictInfo, check if we've checked the volatility of it
572 : * before. If so, we can just use the cached value and not bother
573 : * checking it again. Otherwise, check it and cache if whether we
574 : * found any volatile functions.
575 : */
576 1355156 : if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
577 857252 : return false;
578 497904 : else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
579 8 : return true;
580 : else
581 : {
582 : bool hasvolatile;
583 :
584 497896 : hasvolatile = contain_volatile_functions_walker((Node *) rinfo->clause,
585 : context);
586 497896 : if (hasvolatile)
587 64 : rinfo->has_volatile = VOLATILITY_VOLATILE;
588 : else
589 497832 : rinfo->has_volatile = VOLATILITY_NOVOLATILE;
590 :
591 497896 : return hasvolatile;
592 : }
593 : }
594 :
595 5916492 : if (IsA(node, PathTarget))
596 : {
597 400124 : PathTarget *target = (PathTarget *) node;
598 :
599 : /*
600 : * We also do caching for PathTarget the same as we do above for
601 : * RestrictInfos.
602 : */
603 400124 : if (target->has_volatile_expr == VOLATILITY_NOVOLATILE)
604 335348 : return false;
605 64776 : else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
606 0 : return true;
607 : else
608 : {
609 : bool hasvolatile;
610 :
611 64776 : hasvolatile = contain_volatile_functions_walker((Node *) target->exprs,
612 : context);
613 :
614 64776 : if (hasvolatile)
615 0 : target->has_volatile_expr = VOLATILITY_VOLATILE;
616 : else
617 64776 : target->has_volatile_expr = VOLATILITY_NOVOLATILE;
618 :
619 64776 : return hasvolatile;
620 : }
621 : }
622 :
623 : /*
624 : * See notes in contain_mutable_functions_walker about why we treat
625 : * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
626 : * SQLValueFunction is stable. Hence, none of them are of interest here.
627 : */
628 :
629 : /* Recurse to check arguments */
630 5516368 : if (IsA(node, Query))
631 : {
632 : /* Recurse into subselects */
633 6932 : return query_tree_walker((Query *) node,
634 : contain_volatile_functions_walker,
635 : context, 0);
636 : }
637 5509436 : return expression_tree_walker(node, contain_volatile_functions_walker,
638 : context);
639 : }
640 :
641 : /*
642 : * contain_volatile_functions_after_planning
643 : * Test whether given expression contains volatile functions.
644 : *
645 : * This is a wrapper for contain_volatile_functions() that is safe to use from
646 : * outside the planner. The difference is that it first runs the expression
647 : * through expression_planner(). There are two key reasons why we need that:
648 : *
649 : * First, function default arguments will get inserted, which may affect
650 : * volatility (consider "default random()").
651 : *
652 : * Second, inline-able functions will get inlined, which may allow us to
653 : * conclude that the function is really less volatile than it's marked.
654 : * As an example, polymorphic functions must be marked with the most volatile
655 : * behavior that they have for any input type, but once we inline the
656 : * function we may be able to conclude that it's not so volatile for the
657 : * particular input type we're dealing with.
658 : */
659 : bool
660 0 : contain_volatile_functions_after_planning(Expr *expr)
661 : {
662 : /* We assume here that expression_planner() won't scribble on its input */
663 0 : expr = expression_planner(expr);
664 :
665 : /* Now we can search for volatile functions */
666 0 : return contain_volatile_functions((Node *) expr);
667 : }
668 :
669 : /*
670 : * Special purpose version of contain_volatile_functions() for use in COPY:
671 : * ignore nextval(), but treat all other functions normally.
672 : */
673 : bool
674 252 : contain_volatile_functions_not_nextval(Node *clause)
675 : {
676 252 : return contain_volatile_functions_not_nextval_walker(clause, NULL);
677 : }
678 :
679 : static bool
680 64 : contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
681 : {
682 104 : return (func_id != F_NEXTVAL &&
683 40 : func_volatile(func_id) == PROVOLATILE_VOLATILE);
684 : }
685 :
686 : static bool
687 312 : contain_volatile_functions_not_nextval_walker(Node *node, void *context)
688 : {
689 312 : if (node == NULL)
690 0 : return false;
691 : /* Check for volatile functions in node itself */
692 312 : if (check_functions_in_node(node,
693 : contain_volatile_functions_not_nextval_checker,
694 : context))
695 6 : return true;
696 :
697 : /*
698 : * See notes in contain_mutable_functions_walker about why we treat
699 : * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
700 : * SQLValueFunction is stable. Hence, none of them are of interest here.
701 : * Also, since we're intentionally ignoring nextval(), presumably we
702 : * should ignore NextValueExpr.
703 : */
704 :
705 : /* Recurse to check arguments */
706 306 : if (IsA(node, Query))
707 : {
708 : /* Recurse into subselects */
709 0 : return query_tree_walker((Query *) node,
710 : contain_volatile_functions_not_nextval_walker,
711 : context, 0);
712 : }
713 306 : return expression_tree_walker(node,
714 : contain_volatile_functions_not_nextval_walker,
715 : context);
716 : }
717 :
718 :
719 : /*****************************************************************************
720 : * Check queries for parallel unsafe and/or restricted constructs
721 : *****************************************************************************/
722 :
723 : /*
724 : * max_parallel_hazard
725 : * Find the worst parallel-hazard level in the given query
726 : *
727 : * Returns the worst function hazard property (the earliest in this list:
728 : * PROPARALLEL_UNSAFE, PROPARALLEL_RESTRICTED, PROPARALLEL_SAFE) that can
729 : * be found in the given parsetree. We use this to find out whether the query
730 : * can be parallelized at all. The caller will also save the result in
731 : * PlannerGlobal so as to short-circuit checks of portions of the querytree
732 : * later, in the common case where everything is SAFE.
733 : */
734 : char
735 343656 : max_parallel_hazard(Query *parse)
736 : {
737 : max_parallel_hazard_context context;
738 :
739 343656 : context.max_hazard = PROPARALLEL_SAFE;
740 343656 : context.max_interesting = PROPARALLEL_UNSAFE;
741 343656 : context.safe_param_ids = NIL;
742 343656 : (void) max_parallel_hazard_walker((Node *) parse, &context);
743 343656 : return context.max_hazard;
744 : }
745 :
746 : /*
747 : * is_parallel_safe
748 : * Detect whether the given expr contains only parallel-safe functions
749 : *
750 : * root->glob->maxParallelHazard must previously have been set to the
751 : * result of max_parallel_hazard() on the whole query.
752 : */
753 : bool
754 2320124 : is_parallel_safe(PlannerInfo *root, Node *node)
755 : {
756 : max_parallel_hazard_context context;
757 : PlannerInfo *proot;
758 : ListCell *l;
759 :
760 : /*
761 : * Even if the original querytree contained nothing unsafe, we need to
762 : * search the expression if we have generated any PARAM_EXEC Params while
763 : * planning, because those are parallel-restricted and there might be one
764 : * in this expression. But otherwise we don't need to look.
765 : */
766 2320124 : if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
767 1366504 : root->glob->paramExecTypes == NIL)
768 1327496 : return true;
769 : /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
770 992628 : context.max_hazard = PROPARALLEL_SAFE;
771 992628 : context.max_interesting = PROPARALLEL_RESTRICTED;
772 992628 : context.safe_param_ids = NIL;
773 :
774 : /*
775 : * The params that refer to the same or parent query level are considered
776 : * parallel-safe. The idea is that we compute such params at Gather or
777 : * Gather Merge node and pass their value to workers.
778 : */
779 2389130 : for (proot = root; proot != NULL; proot = proot->parent_root)
780 : {
781 1474592 : foreach(l, proot->init_plans)
782 : {
783 78090 : SubPlan *initsubplan = (SubPlan *) lfirst(l);
784 :
785 78090 : context.safe_param_ids = list_concat(context.safe_param_ids,
786 78090 : initsubplan->setParam);
787 : }
788 : }
789 :
790 992628 : return !max_parallel_hazard_walker(node, &context);
791 : }
792 :
793 : /* core logic for all parallel-hazard checks */
794 : static bool
795 1596350 : max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
796 : {
797 1596350 : switch (proparallel)
798 : {
799 1311562 : case PROPARALLEL_SAFE:
800 : /* nothing to see here, move along */
801 1311562 : break;
802 208898 : case PROPARALLEL_RESTRICTED:
803 : /* increase max_hazard to RESTRICTED */
804 : Assert(context->max_hazard != PROPARALLEL_UNSAFE);
805 208898 : context->max_hazard = proparallel;
806 : /* done if we are not expecting any unsafe functions */
807 208898 : if (context->max_interesting == proparallel)
808 108316 : return true;
809 100582 : break;
810 75890 : case PROPARALLEL_UNSAFE:
811 75890 : context->max_hazard = proparallel;
812 : /* we're always done at the first unsafe construct */
813 75890 : return true;
814 0 : default:
815 0 : elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
816 : break;
817 : }
818 1412144 : return false;
819 : }
820 :
821 : /* check_functions_in_node callback */
822 : static bool
823 1453298 : max_parallel_hazard_checker(Oid func_id, void *context)
824 : {
825 1453298 : return max_parallel_hazard_test(func_parallel(func_id),
826 : (max_parallel_hazard_context *) context);
827 : }
828 :
829 : static bool
830 20824940 : max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
831 : {
832 20824940 : if (node == NULL)
833 5554040 : return false;
834 :
835 : /* Check for hazardous functions in node itself */
836 15270900 : if (check_functions_in_node(node, max_parallel_hazard_checker,
837 : context))
838 104522 : return true;
839 :
840 : /*
841 : * It should be OK to treat MinMaxExpr as parallel-safe, since btree
842 : * opclass support functions are generally parallel-safe. XmlExpr is a
843 : * bit more dubious but we can probably get away with it. We err on the
844 : * side of caution by treating CoerceToDomain as parallel-restricted.
845 : * (Note: in principle that's wrong because a domain constraint could
846 : * contain a parallel-unsafe function; but useful constraints probably
847 : * never would have such, and assuming they do would cripple use of
848 : * parallel query in the presence of domain types.) SQLValueFunction
849 : * should be safe in all cases. NextValueExpr is parallel-unsafe.
850 : */
851 15166378 : if (IsA(node, CoerceToDomain))
852 : {
853 19530 : if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
854 6310 : return true;
855 : }
856 :
857 15146848 : else if (IsA(node, NextValueExpr))
858 : {
859 350 : if (max_parallel_hazard_test(PROPARALLEL_UNSAFE, context))
860 350 : return true;
861 : }
862 :
863 : /*
864 : * Treat window functions as parallel-restricted because we aren't sure
865 : * whether the input row ordering is fully deterministic, and the output
866 : * of window functions might vary across workers if not. (In some cases,
867 : * like where the window frame orders by a primary key, we could relax
868 : * this restriction. But it doesn't currently seem worth expending extra
869 : * effort to do so.)
870 : */
871 15146498 : else if (IsA(node, WindowFunc))
872 : {
873 5532 : if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
874 2456 : return true;
875 : }
876 :
877 : /*
878 : * As a notational convenience for callers, look through RestrictInfo.
879 : */
880 15140966 : else if (IsA(node, RestrictInfo))
881 : {
882 265496 : RestrictInfo *rinfo = (RestrictInfo *) node;
883 :
884 265496 : return max_parallel_hazard_walker((Node *) rinfo->clause, context);
885 : }
886 :
887 : /*
888 : * Really we should not see SubLink during a max_interesting == restricted
889 : * scan, but if we do, return true.
890 : */
891 14875470 : else if (IsA(node, SubLink))
892 : {
893 42432 : if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
894 0 : return true;
895 : }
896 :
897 : /*
898 : * Only parallel-safe SubPlans can be sent to workers. Within the
899 : * testexpr of the SubPlan, Params representing the output columns of the
900 : * subplan can be treated as parallel-safe, so temporarily add their IDs
901 : * to the safe_param_ids list while examining the testexpr.
902 : */
903 14833038 : else if (IsA(node, SubPlan))
904 : {
905 32600 : SubPlan *subplan = (SubPlan *) node;
906 : List *save_safe_param_ids;
907 :
908 64882 : if (!subplan->parallel_safe &&
909 32282 : max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
910 32282 : return true;
911 318 : save_safe_param_ids = context->safe_param_ids;
912 636 : context->safe_param_ids = list_concat_copy(context->safe_param_ids,
913 318 : subplan->paramIds);
914 318 : if (max_parallel_hazard_walker(subplan->testexpr, context))
915 6 : return true; /* no need to restore safe_param_ids */
916 312 : list_free(context->safe_param_ids);
917 312 : context->safe_param_ids = save_safe_param_ids;
918 : /* we must also check args, but no special Param treatment there */
919 312 : if (max_parallel_hazard_walker((Node *) subplan->args, context))
920 0 : return true;
921 : /* don't want to recurse normally, so we're done */
922 312 : return false;
923 : }
924 :
925 : /*
926 : * We can't pass Params to workers at the moment either, so they are also
927 : * parallel-restricted, unless they are PARAM_EXTERN Params or are
928 : * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
929 : * either generated within workers or can be computed by the leader and
930 : * then their value can be passed to workers.
931 : */
932 14800438 : else if (IsA(node, Param))
933 : {
934 110794 : Param *param = (Param *) node;
935 :
936 110794 : if (param->paramkind == PARAM_EXTERN)
937 56766 : return false;
938 :
939 54028 : if (param->paramkind != PARAM_EXEC ||
940 49322 : !list_member_int(context->safe_param_ids, param->paramid))
941 : {
942 42926 : if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
943 38286 : return true;
944 : }
945 15742 : return false; /* nothing to recurse to */
946 : }
947 :
948 : /*
949 : * When we're first invoked on a completely unplanned tree, we must
950 : * recurse into subqueries so to as to locate parallel-unsafe constructs
951 : * anywhere in the tree.
952 : */
953 14689644 : else if (IsA(node, Query))
954 : {
955 438860 : Query *query = (Query *) node;
956 :
957 : /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
958 438860 : if (query->rowMarks != NULL)
959 : {
960 1804 : context->max_hazard = PROPARALLEL_UNSAFE;
961 1804 : return true;
962 : }
963 :
964 : /* Recurse into subselects */
965 437056 : return query_tree_walker(query,
966 : max_parallel_hazard_walker,
967 : context, 0);
968 : }
969 :
970 : /* Recurse to check arguments */
971 14309512 : return expression_tree_walker(node,
972 : max_parallel_hazard_walker,
973 : context);
974 : }
975 :
976 :
977 : /*****************************************************************************
978 : * Check clauses for nonstrict functions
979 : *****************************************************************************/
980 :
981 : /*
982 : * contain_nonstrict_functions
983 : * Recursively search for nonstrict functions within a clause.
984 : *
985 : * Returns true if any nonstrict construct is found --- ie, anything that
986 : * could produce non-NULL output with a NULL input.
987 : *
988 : * The idea here is that the caller has verified that the expression contains
989 : * one or more Var or Param nodes (as appropriate for the caller's need), and
990 : * now wishes to prove that the expression result will be NULL if any of these
991 : * inputs is NULL. If we return false, then the proof succeeded.
992 : */
993 : bool
994 2340 : contain_nonstrict_functions(Node *clause)
995 : {
996 2340 : return contain_nonstrict_functions_walker(clause, NULL);
997 : }
998 :
999 : static bool
1000 2418 : contain_nonstrict_functions_checker(Oid func_id, void *context)
1001 : {
1002 2418 : return !func_strict(func_id);
1003 : }
1004 :
1005 : static bool
1006 8174 : contain_nonstrict_functions_walker(Node *node, void *context)
1007 : {
1008 8174 : if (node == NULL)
1009 0 : return false;
1010 8174 : if (IsA(node, Aggref))
1011 : {
1012 : /* an aggregate could return non-null with null input */
1013 0 : return true;
1014 : }
1015 8174 : if (IsA(node, GroupingFunc))
1016 : {
1017 : /*
1018 : * A GroupingFunc doesn't evaluate its arguments, and therefore must
1019 : * be treated as nonstrict.
1020 : */
1021 0 : return true;
1022 : }
1023 8174 : if (IsA(node, WindowFunc))
1024 : {
1025 : /* a window function could return non-null with null input */
1026 0 : return true;
1027 : }
1028 8174 : if (IsA(node, SubscriptingRef))
1029 : {
1030 0 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
1031 : const SubscriptRoutines *sbsroutines;
1032 :
1033 : /* Subscripting assignment is always presumed nonstrict */
1034 0 : if (sbsref->refassgnexpr != NULL)
1035 0 : return true;
1036 : /* Otherwise we must look up the subscripting support methods */
1037 0 : sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
1038 0 : if (!(sbsroutines && sbsroutines->fetch_strict))
1039 0 : return true;
1040 : /* else fall through to check args */
1041 : }
1042 8174 : if (IsA(node, DistinctExpr))
1043 : {
1044 : /* IS DISTINCT FROM is inherently non-strict */
1045 0 : return true;
1046 : }
1047 8174 : if (IsA(node, NullIfExpr))
1048 : {
1049 : /* NULLIF is inherently non-strict */
1050 0 : return true;
1051 : }
1052 8174 : if (IsA(node, BoolExpr))
1053 : {
1054 18 : BoolExpr *expr = (BoolExpr *) node;
1055 :
1056 18 : switch (expr->boolop)
1057 : {
1058 18 : case AND_EXPR:
1059 : case OR_EXPR:
1060 : /* AND, OR are inherently non-strict */
1061 18 : return true;
1062 0 : default:
1063 0 : break;
1064 : }
1065 : }
1066 8156 : if (IsA(node, SubLink))
1067 : {
1068 : /* In some cases a sublink might be strict, but in general not */
1069 12 : return true;
1070 : }
1071 8144 : if (IsA(node, SubPlan))
1072 0 : return true;
1073 8144 : if (IsA(node, AlternativeSubPlan))
1074 0 : return true;
1075 8144 : if (IsA(node, FieldStore))
1076 0 : return true;
1077 8144 : if (IsA(node, CoerceViaIO))
1078 : {
1079 : /*
1080 : * CoerceViaIO is strict regardless of whether the I/O functions are,
1081 : * so just go look at its argument; asking check_functions_in_node is
1082 : * useless expense and could deliver the wrong answer.
1083 : */
1084 1062 : return contain_nonstrict_functions_walker((Node *) ((CoerceViaIO *) node)->arg,
1085 : context);
1086 : }
1087 7082 : if (IsA(node, ArrayCoerceExpr))
1088 : {
1089 : /*
1090 : * ArrayCoerceExpr is strict at the array level, regardless of what
1091 : * the per-element expression is; so we should ignore elemexpr and
1092 : * recurse only into the arg.
1093 : */
1094 0 : return contain_nonstrict_functions_walker((Node *) ((ArrayCoerceExpr *) node)->arg,
1095 : context);
1096 : }
1097 7082 : if (IsA(node, CaseExpr))
1098 64 : return true;
1099 7018 : if (IsA(node, ArrayExpr))
1100 0 : return true;
1101 7018 : if (IsA(node, RowExpr))
1102 4 : return true;
1103 7014 : if (IsA(node, RowCompareExpr))
1104 0 : return true;
1105 7014 : if (IsA(node, CoalesceExpr))
1106 254 : return true;
1107 6760 : if (IsA(node, MinMaxExpr))
1108 60 : return true;
1109 6700 : if (IsA(node, XmlExpr))
1110 0 : return true;
1111 6700 : if (IsA(node, NullTest))
1112 24 : return true;
1113 6676 : if (IsA(node, BooleanTest))
1114 0 : return true;
1115 :
1116 : /* Check other function-containing nodes */
1117 6676 : if (check_functions_in_node(node, contain_nonstrict_functions_checker,
1118 : context))
1119 0 : return true;
1120 :
1121 6676 : return expression_tree_walker(node, contain_nonstrict_functions_walker,
1122 : context);
1123 : }
1124 :
1125 : /*****************************************************************************
1126 : * Check clauses for Params
1127 : *****************************************************************************/
1128 :
1129 : /*
1130 : * contain_exec_param
1131 : * Recursively search for PARAM_EXEC Params within a clause.
1132 : *
1133 : * Returns true if the clause contains any PARAM_EXEC Param with a paramid
1134 : * appearing in the given list of Param IDs. Does not descend into
1135 : * subqueries!
1136 : */
1137 : bool
1138 3052 : contain_exec_param(Node *clause, List *param_ids)
1139 : {
1140 3052 : return contain_exec_param_walker(clause, param_ids);
1141 : }
1142 :
1143 : static bool
1144 3262 : contain_exec_param_walker(Node *node, List *param_ids)
1145 : {
1146 3262 : if (node == NULL)
1147 18 : return false;
1148 3244 : if (IsA(node, Param))
1149 : {
1150 12 : Param *p = (Param *) node;
1151 :
1152 24 : if (p->paramkind == PARAM_EXEC &&
1153 12 : list_member_int(param_ids, p->paramid))
1154 12 : return true;
1155 : }
1156 3232 : return expression_tree_walker(node, contain_exec_param_walker, param_ids);
1157 : }
1158 :
1159 : /*****************************************************************************
1160 : * Check clauses for context-dependent nodes
1161 : *****************************************************************************/
1162 :
1163 : /*
1164 : * contain_context_dependent_node
1165 : * Recursively search for context-dependent nodes within a clause.
1166 : *
1167 : * CaseTestExpr nodes must appear directly within the corresponding CaseExpr,
1168 : * not nested within another one, or they'll see the wrong test value. If one
1169 : * appears "bare" in the arguments of a SQL function, then we can't inline the
1170 : * SQL function for fear of creating such a situation. The same applies for
1171 : * CaseTestExpr used within the elemexpr of an ArrayCoerceExpr.
1172 : *
1173 : * CoerceToDomainValue would have the same issue if domain CHECK expressions
1174 : * could get inlined into larger expressions, but presently that's impossible.
1175 : * Still, it might be allowed in future, or other node types with similar
1176 : * issues might get invented. So give this function a generic name, and set
1177 : * up the recursion state to allow multiple flag bits.
1178 : */
1179 : static bool
1180 3232 : contain_context_dependent_node(Node *clause)
1181 : {
1182 3232 : int flags = 0;
1183 :
1184 3232 : return contain_context_dependent_node_walker(clause, &flags);
1185 : }
1186 :
1187 : #define CCDN_CASETESTEXPR_OK 0x0001 /* CaseTestExpr okay here? */
1188 :
1189 : static bool
1190 9850 : contain_context_dependent_node_walker(Node *node, int *flags)
1191 : {
1192 9850 : if (node == NULL)
1193 194 : return false;
1194 9656 : if (IsA(node, CaseTestExpr))
1195 6 : return !(*flags & CCDN_CASETESTEXPR_OK);
1196 9650 : else if (IsA(node, CaseExpr))
1197 : {
1198 0 : CaseExpr *caseexpr = (CaseExpr *) node;
1199 :
1200 : /*
1201 : * If this CASE doesn't have a test expression, then it doesn't create
1202 : * a context in which CaseTestExprs should appear, so just fall
1203 : * through and treat it as a generic expression node.
1204 : */
1205 0 : if (caseexpr->arg)
1206 : {
1207 0 : int save_flags = *flags;
1208 : bool res;
1209 :
1210 : /*
1211 : * Note: in principle, we could distinguish the various sub-parts
1212 : * of a CASE construct and set the flag bit only for some of them,
1213 : * since we are only expecting CaseTestExprs to appear in the
1214 : * "expr" subtree of the CaseWhen nodes. But it doesn't really
1215 : * seem worth any extra code. If there are any bare CaseTestExprs
1216 : * elsewhere in the CASE, something's wrong already.
1217 : */
1218 0 : *flags |= CCDN_CASETESTEXPR_OK;
1219 0 : res = expression_tree_walker(node,
1220 : contain_context_dependent_node_walker,
1221 : flags);
1222 0 : *flags = save_flags;
1223 0 : return res;
1224 : }
1225 : }
1226 9650 : else if (IsA(node, ArrayCoerceExpr))
1227 : {
1228 0 : ArrayCoerceExpr *ac = (ArrayCoerceExpr *) node;
1229 : int save_flags;
1230 : bool res;
1231 :
1232 : /* Check the array expression */
1233 0 : if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1234 0 : return true;
1235 :
1236 : /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1237 0 : save_flags = *flags;
1238 0 : *flags |= CCDN_CASETESTEXPR_OK;
1239 0 : res = contain_context_dependent_node_walker((Node *) ac->elemexpr,
1240 : flags);
1241 0 : *flags = save_flags;
1242 0 : return res;
1243 : }
1244 9650 : return expression_tree_walker(node, contain_context_dependent_node_walker,
1245 : flags);
1246 : }
1247 :
1248 : /*****************************************************************************
1249 : * Check clauses for Vars passed to non-leakproof functions
1250 : *****************************************************************************/
1251 :
1252 : /*
1253 : * contain_leaked_vars
1254 : * Recursively scan a clause to discover whether it contains any Var
1255 : * nodes (of the current query level) that are passed as arguments to
1256 : * leaky functions.
1257 : *
1258 : * Returns true if the clause contains any non-leakproof functions that are
1259 : * passed Var nodes of the current query level, and which might therefore leak
1260 : * data. Such clauses must be applied after any lower-level security barrier
1261 : * clauses.
1262 : */
1263 : bool
1264 5726 : contain_leaked_vars(Node *clause)
1265 : {
1266 5726 : return contain_leaked_vars_walker(clause, NULL);
1267 : }
1268 :
1269 : static bool
1270 5692 : contain_leaked_vars_checker(Oid func_id, void *context)
1271 : {
1272 5692 : return !get_func_leakproof(func_id);
1273 : }
1274 :
1275 : static bool
1276 12508 : contain_leaked_vars_walker(Node *node, void *context)
1277 : {
1278 12508 : if (node == NULL)
1279 0 : return false;
1280 :
1281 12508 : switch (nodeTag(node))
1282 : {
1283 6744 : case T_Var:
1284 : case T_Const:
1285 : case T_Param:
1286 : case T_ArrayExpr:
1287 : case T_FieldSelect:
1288 : case T_FieldStore:
1289 : case T_NamedArgExpr:
1290 : case T_BoolExpr:
1291 : case T_RelabelType:
1292 : case T_CollateExpr:
1293 : case T_CaseExpr:
1294 : case T_CaseTestExpr:
1295 : case T_RowExpr:
1296 : case T_SQLValueFunction:
1297 : case T_NullTest:
1298 : case T_BooleanTest:
1299 : case T_NextValueExpr:
1300 : case T_ReturningExpr:
1301 : case T_List:
1302 :
1303 : /*
1304 : * We know these node types don't contain function calls; but
1305 : * something further down in the node tree might.
1306 : */
1307 6744 : break;
1308 :
1309 5692 : case T_FuncExpr:
1310 : case T_OpExpr:
1311 : case T_DistinctExpr:
1312 : case T_NullIfExpr:
1313 : case T_ScalarArrayOpExpr:
1314 : case T_CoerceViaIO:
1315 : case T_ArrayCoerceExpr:
1316 :
1317 : /*
1318 : * If node contains a leaky function call, and there's any Var
1319 : * underneath it, reject.
1320 : */
1321 5692 : if (check_functions_in_node(node, contain_leaked_vars_checker,
1322 2270 : context) &&
1323 2270 : contain_var_clause(node))
1324 2214 : return true;
1325 3478 : break;
1326 :
1327 0 : case T_SubscriptingRef:
1328 : {
1329 0 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
1330 : const SubscriptRoutines *sbsroutines;
1331 :
1332 : /* Consult the subscripting support method info */
1333 0 : sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1334 : NULL);
1335 0 : if (!sbsroutines ||
1336 0 : !(sbsref->refassgnexpr != NULL ?
1337 0 : sbsroutines->store_leakproof :
1338 0 : sbsroutines->fetch_leakproof))
1339 : {
1340 : /* Node is leaky, so reject if it contains Vars */
1341 0 : if (contain_var_clause(node))
1342 0 : return true;
1343 : }
1344 : }
1345 0 : break;
1346 :
1347 0 : case T_RowCompareExpr:
1348 : {
1349 : /*
1350 : * It's worth special-casing this because a leaky comparison
1351 : * function only compromises one pair of row elements, which
1352 : * might not contain Vars while others do.
1353 : */
1354 0 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1355 : ListCell *opid;
1356 : ListCell *larg;
1357 : ListCell *rarg;
1358 :
1359 0 : forthree(opid, rcexpr->opnos,
1360 : larg, rcexpr->largs,
1361 : rarg, rcexpr->rargs)
1362 : {
1363 0 : Oid funcid = get_opcode(lfirst_oid(opid));
1364 :
1365 0 : if (!get_func_leakproof(funcid) &&
1366 0 : (contain_var_clause((Node *) lfirst(larg)) ||
1367 0 : contain_var_clause((Node *) lfirst(rarg))))
1368 0 : return true;
1369 : }
1370 : }
1371 0 : break;
1372 :
1373 0 : case T_MinMaxExpr:
1374 : {
1375 : /*
1376 : * MinMaxExpr is leakproof if the comparison function it calls
1377 : * is leakproof.
1378 : */
1379 0 : MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1380 : TypeCacheEntry *typentry;
1381 : bool leakproof;
1382 :
1383 : /* Look up the btree comparison function for the datatype */
1384 0 : typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1385 : TYPECACHE_CMP_PROC);
1386 0 : if (OidIsValid(typentry->cmp_proc))
1387 0 : leakproof = get_func_leakproof(typentry->cmp_proc);
1388 : else
1389 : {
1390 : /*
1391 : * The executor will throw an error, but here we just
1392 : * treat the missing function as leaky.
1393 : */
1394 0 : leakproof = false;
1395 : }
1396 :
1397 0 : if (!leakproof &&
1398 0 : contain_var_clause((Node *) minmaxexpr->args))
1399 0 : return true;
1400 : }
1401 0 : break;
1402 :
1403 42 : case T_CurrentOfExpr:
1404 :
1405 : /*
1406 : * WHERE CURRENT OF doesn't contain leaky function calls.
1407 : * Moreover, it is essential that this is considered non-leaky,
1408 : * since the planner must always generate a TID scan when CURRENT
1409 : * OF is present -- cf. cost_tidscan.
1410 : */
1411 42 : return false;
1412 :
1413 30 : default:
1414 :
1415 : /*
1416 : * If we don't recognize the node tag, assume it might be leaky.
1417 : * This prevents an unexpected security hole if someone adds a new
1418 : * node type that can call a function.
1419 : */
1420 30 : return true;
1421 : }
1422 10222 : return expression_tree_walker(node, contain_leaked_vars_walker,
1423 : context);
1424 : }
1425 :
1426 : /*
1427 : * find_nonnullable_rels
1428 : * Determine which base rels are forced nonnullable by given clause.
1429 : *
1430 : * Returns the set of all Relids that are referenced in the clause in such
1431 : * a way that the clause cannot possibly return TRUE if any of these Relids
1432 : * is an all-NULL row. (It is OK to err on the side of conservatism; hence
1433 : * the analysis here is simplistic.)
1434 : *
1435 : * The semantics here are subtly different from contain_nonstrict_functions:
1436 : * that function is concerned with NULL results from arbitrary expressions,
1437 : * but here we assume that the input is a Boolean expression, and wish to
1438 : * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1439 : * the expression to have been AND/OR flattened and converted to implicit-AND
1440 : * format.
1441 : *
1442 : * Note: this function is largely duplicative of find_nonnullable_vars().
1443 : * The reason not to simplify this function into a thin wrapper around
1444 : * find_nonnullable_vars() is that the tested conditions really are different:
1445 : * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1446 : * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1447 : * as a whole can't be all-NULL. Also, the behavior for PHVs is different.
1448 : *
1449 : * top_level is true while scanning top-level AND/OR structure; here, showing
1450 : * the result is either FALSE or NULL is good enough. top_level is false when
1451 : * we have descended below a NOT or a strict function: now we must be able to
1452 : * prove that the subexpression goes to NULL.
1453 : *
1454 : * We don't use expression_tree_walker here because we don't want to descend
1455 : * through very many kinds of nodes; only the ones we can be sure are strict.
1456 : */
1457 : Relids
1458 105862 : find_nonnullable_rels(Node *clause)
1459 : {
1460 105862 : return find_nonnullable_rels_walker(clause, true);
1461 : }
1462 :
1463 : static Relids
1464 702406 : find_nonnullable_rels_walker(Node *node, bool top_level)
1465 : {
1466 702406 : Relids result = NULL;
1467 : ListCell *l;
1468 :
1469 702406 : if (node == NULL)
1470 6224 : return NULL;
1471 696182 : if (IsA(node, Var))
1472 : {
1473 224830 : Var *var = (Var *) node;
1474 :
1475 224830 : if (var->varlevelsup == 0)
1476 224830 : result = bms_make_singleton(var->varno);
1477 : }
1478 471352 : else if (IsA(node, List))
1479 : {
1480 : /*
1481 : * At top level, we are examining an implicit-AND list: if any of the
1482 : * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1483 : * not at top level, we are examining the arguments of a strict
1484 : * function: if any of them produce NULL then the result of the
1485 : * function must be NULL. So in both cases, the set of nonnullable
1486 : * rels is the union of those found in the arms, and we pass down the
1487 : * top_level flag unmodified.
1488 : */
1489 679022 : foreach(l, (List *) node)
1490 : {
1491 432278 : result = bms_join(result,
1492 432278 : find_nonnullable_rels_walker(lfirst(l),
1493 : top_level));
1494 : }
1495 : }
1496 224608 : else if (IsA(node, FuncExpr))
1497 : {
1498 7148 : FuncExpr *expr = (FuncExpr *) node;
1499 :
1500 7148 : if (func_strict(expr->funcid))
1501 6956 : result = find_nonnullable_rels_walker((Node *) expr->args, false);
1502 : }
1503 217460 : else if (IsA(node, OpExpr))
1504 : {
1505 127046 : OpExpr *expr = (OpExpr *) node;
1506 :
1507 127046 : set_opfuncid(expr);
1508 127046 : if (func_strict(expr->opfuncid))
1509 127046 : result = find_nonnullable_rels_walker((Node *) expr->args, false);
1510 : }
1511 90414 : else if (IsA(node, ScalarArrayOpExpr))
1512 : {
1513 9096 : ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1514 :
1515 9096 : if (is_strict_saop(expr, true))
1516 9096 : result = find_nonnullable_rels_walker((Node *) expr->args, false);
1517 : }
1518 81318 : else if (IsA(node, BoolExpr))
1519 : {
1520 8434 : BoolExpr *expr = (BoolExpr *) node;
1521 :
1522 8434 : switch (expr->boolop)
1523 : {
1524 562 : case AND_EXPR:
1525 : /* At top level we can just recurse (to the List case) */
1526 562 : if (top_level)
1527 : {
1528 562 : result = find_nonnullable_rels_walker((Node *) expr->args,
1529 : top_level);
1530 562 : break;
1531 : }
1532 :
1533 : /*
1534 : * Below top level, even if one arm produces NULL, the result
1535 : * could be FALSE (hence not NULL). However, if *all* the
1536 : * arms produce NULL then the result is NULL, so we can take
1537 : * the intersection of the sets of nonnullable rels, just as
1538 : * for OR. Fall through to share code.
1539 : */
1540 : /* FALL THRU */
1541 : case OR_EXPR:
1542 :
1543 : /*
1544 : * OR is strict if all of its arms are, so we can take the
1545 : * intersection of the sets of nonnullable rels for each arm.
1546 : * This works for both values of top_level.
1547 : */
1548 9994 : foreach(l, expr->args)
1549 : {
1550 : Relids subresult;
1551 :
1552 8774 : subresult = find_nonnullable_rels_walker(lfirst(l),
1553 : top_level);
1554 8774 : if (result == NULL) /* first subresult? */
1555 4426 : result = subresult;
1556 : else
1557 4348 : result = bms_int_members(result, subresult);
1558 :
1559 : /*
1560 : * If the intersection is empty, we can stop looking. This
1561 : * also justifies the test for first-subresult above.
1562 : */
1563 8774 : if (bms_is_empty(result))
1564 3206 : break;
1565 : }
1566 4426 : break;
1567 3446 : case NOT_EXPR:
1568 : /* NOT will return null if its arg is null */
1569 3446 : result = find_nonnullable_rels_walker((Node *) expr->args,
1570 : false);
1571 3446 : break;
1572 0 : default:
1573 0 : elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1574 : break;
1575 : }
1576 : }
1577 72884 : else if (IsA(node, RelabelType))
1578 : {
1579 4152 : RelabelType *expr = (RelabelType *) node;
1580 :
1581 4152 : result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1582 : }
1583 68732 : else if (IsA(node, CoerceViaIO))
1584 : {
1585 : /* not clear this is useful, but it can't hurt */
1586 190 : CoerceViaIO *expr = (CoerceViaIO *) node;
1587 :
1588 190 : result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1589 : }
1590 68542 : else if (IsA(node, ArrayCoerceExpr))
1591 : {
1592 : /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1593 0 : ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1594 :
1595 0 : result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1596 : }
1597 68542 : else if (IsA(node, ConvertRowtypeExpr))
1598 : {
1599 : /* not clear this is useful, but it can't hurt */
1600 0 : ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1601 :
1602 0 : result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1603 : }
1604 68542 : else if (IsA(node, CollateExpr))
1605 : {
1606 0 : CollateExpr *expr = (CollateExpr *) node;
1607 :
1608 0 : result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1609 : }
1610 68542 : else if (IsA(node, NullTest))
1611 : {
1612 : /* IS NOT NULL can be considered strict, but only at top level */
1613 5234 : NullTest *expr = (NullTest *) node;
1614 :
1615 5234 : if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1616 3388 : result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1617 : }
1618 63308 : else if (IsA(node, BooleanTest))
1619 : {
1620 : /* Boolean tests that reject NULL are strict at top level */
1621 92 : BooleanTest *expr = (BooleanTest *) node;
1622 :
1623 92 : if (top_level &&
1624 92 : (expr->booltesttype == IS_TRUE ||
1625 92 : expr->booltesttype == IS_FALSE ||
1626 6 : expr->booltesttype == IS_NOT_UNKNOWN))
1627 86 : result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1628 : }
1629 63216 : else if (IsA(node, SubPlan))
1630 : {
1631 114 : SubPlan *splan = (SubPlan *) node;
1632 :
1633 : /*
1634 : * For some types of SubPlan, we can infer strictness from Vars in the
1635 : * testexpr (the LHS of the original SubLink).
1636 : *
1637 : * For ANY_SUBLINK, if the subquery produces zero rows, the result is
1638 : * always FALSE. If the subquery produces more than one row, the
1639 : * per-row results of the testexpr are combined using OR semantics.
1640 : * Hence ANY_SUBLINK can be strict only at top level, but there it's
1641 : * as strict as the testexpr is.
1642 : *
1643 : * For ROWCOMPARE_SUBLINK, if the subquery produces zero rows, the
1644 : * result is always NULL. Otherwise, the result is as strict as the
1645 : * testexpr is. So we can check regardless of top_level.
1646 : *
1647 : * We can't prove anything for other sublink types (in particular,
1648 : * note that ALL_SUBLINK will return TRUE if the subquery is empty).
1649 : */
1650 114 : if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1651 72 : splan->subLinkType == ROWCOMPARE_SUBLINK)
1652 42 : result = find_nonnullable_rels_walker(splan->testexpr, top_level);
1653 : }
1654 63102 : else if (IsA(node, PlaceHolderVar))
1655 : {
1656 528 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
1657 :
1658 : /*
1659 : * If the contained expression forces any rels non-nullable, so does
1660 : * the PHV.
1661 : */
1662 528 : result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1663 :
1664 : /*
1665 : * If the PHV's syntactic scope is exactly one rel, it will be forced
1666 : * to be evaluated at that rel, and so it will behave like a Var of
1667 : * that rel: if the rel's entire output goes to null, so will the PHV.
1668 : * (If the syntactic scope is a join, we know that the PHV will go to
1669 : * null if the whole join does; but that is AND semantics while we
1670 : * need OR semantics for find_nonnullable_rels' result, so we can't do
1671 : * anything with the knowledge.)
1672 : */
1673 1056 : if (phv->phlevelsup == 0 &&
1674 528 : bms_membership(phv->phrels) == BMS_SINGLETON)
1675 336 : result = bms_add_members(result, phv->phrels);
1676 : }
1677 696182 : return result;
1678 : }
1679 :
1680 : /*
1681 : * find_nonnullable_vars
1682 : * Determine which Vars are forced nonnullable by given clause.
1683 : *
1684 : * Returns the set of all level-zero Vars that are referenced in the clause in
1685 : * such a way that the clause cannot possibly return TRUE if any of these Vars
1686 : * is NULL. (It is OK to err on the side of conservatism; hence the analysis
1687 : * here is simplistic.)
1688 : *
1689 : * The semantics here are subtly different from contain_nonstrict_functions:
1690 : * that function is concerned with NULL results from arbitrary expressions,
1691 : * but here we assume that the input is a Boolean expression, and wish to
1692 : * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1693 : * the expression to have been AND/OR flattened and converted to implicit-AND
1694 : * format.
1695 : *
1696 : * Attnos of the identified Vars are returned in a multibitmapset (a List of
1697 : * Bitmapsets). List indexes correspond to relids (varnos), while the per-rel
1698 : * Bitmapsets hold varattnos offset by FirstLowInvalidHeapAttributeNumber.
1699 : *
1700 : * top_level is true while scanning top-level AND/OR structure; here, showing
1701 : * the result is either FALSE or NULL is good enough. top_level is false when
1702 : * we have descended below a NOT or a strict function: now we must be able to
1703 : * prove that the subexpression goes to NULL.
1704 : *
1705 : * We don't use expression_tree_walker here because we don't want to descend
1706 : * through very many kinds of nodes; only the ones we can be sure are strict.
1707 : */
1708 : List *
1709 46424 : find_nonnullable_vars(Node *clause)
1710 : {
1711 46424 : return find_nonnullable_vars_walker(clause, true);
1712 : }
1713 :
1714 : static List *
1715 304506 : find_nonnullable_vars_walker(Node *node, bool top_level)
1716 : {
1717 304506 : List *result = NIL;
1718 : ListCell *l;
1719 :
1720 304506 : if (node == NULL)
1721 524 : return NIL;
1722 303982 : if (IsA(node, Var))
1723 : {
1724 112382 : Var *var = (Var *) node;
1725 :
1726 112382 : if (var->varlevelsup == 0)
1727 112382 : result = mbms_add_member(result,
1728 : var->varno,
1729 112382 : var->varattno - FirstLowInvalidHeapAttributeNumber);
1730 : }
1731 191600 : else if (IsA(node, List))
1732 : {
1733 : /*
1734 : * At top level, we are examining an implicit-AND list: if any of the
1735 : * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1736 : * not at top level, we are examining the arguments of a strict
1737 : * function: if any of them produce NULL then the result of the
1738 : * function must be NULL. So in both cases, the set of nonnullable
1739 : * vars is the union of those found in the arms, and we pass down the
1740 : * top_level flag unmodified.
1741 : */
1742 302386 : foreach(l, (List *) node)
1743 : {
1744 192074 : result = mbms_add_members(result,
1745 192074 : find_nonnullable_vars_walker(lfirst(l),
1746 : top_level));
1747 : }
1748 : }
1749 81288 : else if (IsA(node, FuncExpr))
1750 : {
1751 438 : FuncExpr *expr = (FuncExpr *) node;
1752 :
1753 438 : if (func_strict(expr->funcid))
1754 414 : result = find_nonnullable_vars_walker((Node *) expr->args, false);
1755 : }
1756 80850 : else if (IsA(node, OpExpr))
1757 : {
1758 62018 : OpExpr *expr = (OpExpr *) node;
1759 :
1760 62018 : set_opfuncid(expr);
1761 62018 : if (func_strict(expr->opfuncid))
1762 62018 : result = find_nonnullable_vars_walker((Node *) expr->args, false);
1763 : }
1764 18832 : else if (IsA(node, ScalarArrayOpExpr))
1765 : {
1766 1916 : ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1767 :
1768 1916 : if (is_strict_saop(expr, true))
1769 1916 : result = find_nonnullable_vars_walker((Node *) expr->args, false);
1770 : }
1771 16916 : else if (IsA(node, BoolExpr))
1772 : {
1773 394 : BoolExpr *expr = (BoolExpr *) node;
1774 :
1775 394 : switch (expr->boolop)
1776 : {
1777 0 : case AND_EXPR:
1778 :
1779 : /*
1780 : * At top level we can just recurse (to the List case), since
1781 : * the result should be the union of what we can prove in each
1782 : * arm.
1783 : */
1784 0 : if (top_level)
1785 : {
1786 0 : result = find_nonnullable_vars_walker((Node *) expr->args,
1787 : top_level);
1788 0 : break;
1789 : }
1790 :
1791 : /*
1792 : * Below top level, even if one arm produces NULL, the result
1793 : * could be FALSE (hence not NULL). However, if *all* the
1794 : * arms produce NULL then the result is NULL, so we can take
1795 : * the intersection of the sets of nonnullable vars, just as
1796 : * for OR. Fall through to share code.
1797 : */
1798 : /* FALL THRU */
1799 : case OR_EXPR:
1800 :
1801 : /*
1802 : * OR is strict if all of its arms are, so we can take the
1803 : * intersection of the sets of nonnullable vars for each arm.
1804 : * This works for both values of top_level.
1805 : */
1806 856 : foreach(l, expr->args)
1807 : {
1808 : List *subresult;
1809 :
1810 694 : subresult = find_nonnullable_vars_walker(lfirst(l),
1811 : top_level);
1812 694 : if (result == NIL) /* first subresult? */
1813 330 : result = subresult;
1814 : else
1815 364 : result = mbms_int_members(result, subresult);
1816 :
1817 : /*
1818 : * If the intersection is empty, we can stop looking. This
1819 : * also justifies the test for first-subresult above.
1820 : */
1821 694 : if (result == NIL)
1822 168 : break;
1823 : }
1824 330 : break;
1825 64 : case NOT_EXPR:
1826 : /* NOT will return null if its arg is null */
1827 64 : result = find_nonnullable_vars_walker((Node *) expr->args,
1828 : false);
1829 64 : break;
1830 0 : default:
1831 0 : elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1832 : break;
1833 : }
1834 : }
1835 16522 : else if (IsA(node, RelabelType))
1836 : {
1837 592 : RelabelType *expr = (RelabelType *) node;
1838 :
1839 592 : result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1840 : }
1841 15930 : else if (IsA(node, CoerceViaIO))
1842 : {
1843 : /* not clear this is useful, but it can't hurt */
1844 100 : CoerceViaIO *expr = (CoerceViaIO *) node;
1845 :
1846 100 : result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1847 : }
1848 15830 : else if (IsA(node, ArrayCoerceExpr))
1849 : {
1850 : /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1851 0 : ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1852 :
1853 0 : result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1854 : }
1855 15830 : else if (IsA(node, ConvertRowtypeExpr))
1856 : {
1857 : /* not clear this is useful, but it can't hurt */
1858 0 : ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1859 :
1860 0 : result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1861 : }
1862 15830 : else if (IsA(node, CollateExpr))
1863 : {
1864 0 : CollateExpr *expr = (CollateExpr *) node;
1865 :
1866 0 : result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1867 : }
1868 15830 : else if (IsA(node, NullTest))
1869 : {
1870 : /* IS NOT NULL can be considered strict, but only at top level */
1871 318 : NullTest *expr = (NullTest *) node;
1872 :
1873 318 : if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1874 126 : result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1875 : }
1876 15512 : else if (IsA(node, BooleanTest))
1877 : {
1878 : /* Boolean tests that reject NULL are strict at top level */
1879 0 : BooleanTest *expr = (BooleanTest *) node;
1880 :
1881 0 : if (top_level &&
1882 0 : (expr->booltesttype == IS_TRUE ||
1883 0 : expr->booltesttype == IS_FALSE ||
1884 0 : expr->booltesttype == IS_NOT_UNKNOWN))
1885 0 : result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1886 : }
1887 15512 : else if (IsA(node, SubPlan))
1888 : {
1889 24 : SubPlan *splan = (SubPlan *) node;
1890 :
1891 : /* See analysis in find_nonnullable_rels_walker */
1892 24 : if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1893 0 : splan->subLinkType == ROWCOMPARE_SUBLINK)
1894 24 : result = find_nonnullable_vars_walker(splan->testexpr, top_level);
1895 : }
1896 15488 : else if (IsA(node, PlaceHolderVar))
1897 : {
1898 60 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
1899 :
1900 60 : result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1901 : }
1902 303982 : return result;
1903 : }
1904 :
1905 : /*
1906 : * find_forced_null_vars
1907 : * Determine which Vars must be NULL for the given clause to return TRUE.
1908 : *
1909 : * This is the complement of find_nonnullable_vars: find the level-zero Vars
1910 : * that must be NULL for the clause to return TRUE. (It is OK to err on the
1911 : * side of conservatism; hence the analysis here is simplistic. In fact,
1912 : * we only detect simple "var IS NULL" tests at the top level.)
1913 : *
1914 : * As with find_nonnullable_vars, we return the varattnos of the identified
1915 : * Vars in a multibitmapset.
1916 : */
1917 : List *
1918 124564 : find_forced_null_vars(Node *node)
1919 : {
1920 124564 : List *result = NIL;
1921 : Var *var;
1922 : ListCell *l;
1923 :
1924 124564 : if (node == NULL)
1925 5568 : return NIL;
1926 : /* Check single-clause cases using subroutine */
1927 118996 : var = find_forced_null_var(node);
1928 118996 : if (var)
1929 : {
1930 1384 : result = mbms_add_member(result,
1931 : var->varno,
1932 1384 : var->varattno - FirstLowInvalidHeapAttributeNumber);
1933 : }
1934 : /* Otherwise, handle AND-conditions */
1935 117612 : else if (IsA(node, List))
1936 : {
1937 : /*
1938 : * At top level, we are examining an implicit-AND list: if any of the
1939 : * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1940 : */
1941 118996 : foreach(l, (List *) node)
1942 : {
1943 72804 : result = mbms_add_members(result,
1944 72804 : find_forced_null_vars((Node *) lfirst(l)));
1945 : }
1946 : }
1947 71420 : else if (IsA(node, BoolExpr))
1948 : {
1949 6112 : BoolExpr *expr = (BoolExpr *) node;
1950 :
1951 : /*
1952 : * We don't bother considering the OR case, because it's fairly
1953 : * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1954 : * the NOT case isn't worth expending code on.
1955 : */
1956 6112 : if (expr->boolop == AND_EXPR)
1957 : {
1958 : /* At top level we can just recurse (to the List case) */
1959 0 : result = find_forced_null_vars((Node *) expr->args);
1960 : }
1961 : }
1962 118996 : return result;
1963 : }
1964 :
1965 : /*
1966 : * find_forced_null_var
1967 : * Return the Var forced null by the given clause, or NULL if it's
1968 : * not an IS NULL-type clause. For success, the clause must enforce
1969 : * *only* nullness of the particular Var, not any other conditions.
1970 : *
1971 : * This is just the single-clause case of find_forced_null_vars(), without
1972 : * any allowance for AND conditions. It's used by initsplan.c on individual
1973 : * qual clauses. The reason for not just applying find_forced_null_vars()
1974 : * is that if an AND of an IS NULL clause with something else were to somehow
1975 : * survive AND/OR flattening, initsplan.c might get fooled into discarding
1976 : * the whole clause when only the IS NULL part of it had been proved redundant.
1977 : */
1978 : Var *
1979 599998 : find_forced_null_var(Node *node)
1980 : {
1981 599998 : if (node == NULL)
1982 0 : return NULL;
1983 599998 : if (IsA(node, NullTest))
1984 : {
1985 : /* check for var IS NULL */
1986 11834 : NullTest *expr = (NullTest *) node;
1987 :
1988 11834 : if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1989 : {
1990 4234 : Var *var = (Var *) expr->arg;
1991 :
1992 4234 : if (var && IsA(var, Var) &&
1993 4120 : var->varlevelsup == 0)
1994 4120 : return var;
1995 : }
1996 : }
1997 588164 : else if (IsA(node, BooleanTest))
1998 : {
1999 : /* var IS UNKNOWN is equivalent to var IS NULL */
2000 572 : BooleanTest *expr = (BooleanTest *) node;
2001 :
2002 572 : if (expr->booltesttype == IS_UNKNOWN)
2003 : {
2004 42 : Var *var = (Var *) expr->arg;
2005 :
2006 42 : if (var && IsA(var, Var) &&
2007 42 : var->varlevelsup == 0)
2008 42 : return var;
2009 : }
2010 : }
2011 595836 : return NULL;
2012 : }
2013 :
2014 : /*
2015 : * Can we treat a ScalarArrayOpExpr as strict?
2016 : *
2017 : * If "falseOK" is true, then a "false" result can be considered strict,
2018 : * else we need to guarantee an actual NULL result for NULL input.
2019 : *
2020 : * "foo op ALL array" is strict if the op is strict *and* we can prove
2021 : * that the array input isn't an empty array. We can check that
2022 : * for the cases of an array constant and an ARRAY[] construct.
2023 : *
2024 : * "foo op ANY array" is strict in the falseOK sense if the op is strict.
2025 : * If not falseOK, the test is the same as for "foo op ALL array".
2026 : */
2027 : static bool
2028 11012 : is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
2029 : {
2030 : Node *rightop;
2031 :
2032 : /* The contained operator must be strict. */
2033 11012 : set_sa_opfuncid(expr);
2034 11012 : if (!func_strict(expr->opfuncid))
2035 0 : return false;
2036 : /* If ANY and falseOK, that's all we need to check. */
2037 11012 : if (expr->useOr && falseOK)
2038 10866 : return true;
2039 : /* Else, we have to see if the array is provably non-empty. */
2040 : Assert(list_length(expr->args) == 2);
2041 146 : rightop = (Node *) lsecond(expr->args);
2042 146 : if (rightop && IsA(rightop, Const))
2043 0 : {
2044 146 : Datum arraydatum = ((Const *) rightop)->constvalue;
2045 146 : bool arrayisnull = ((Const *) rightop)->constisnull;
2046 : ArrayType *arrayval;
2047 : int nitems;
2048 :
2049 146 : if (arrayisnull)
2050 0 : return false;
2051 146 : arrayval = DatumGetArrayTypeP(arraydatum);
2052 146 : nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2053 146 : if (nitems > 0)
2054 146 : return true;
2055 : }
2056 0 : else if (rightop && IsA(rightop, ArrayExpr))
2057 : {
2058 0 : ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2059 :
2060 0 : if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2061 0 : return true;
2062 : }
2063 0 : return false;
2064 : }
2065 :
2066 :
2067 : /*****************************************************************************
2068 : * Check for "pseudo-constant" clauses
2069 : *****************************************************************************/
2070 :
2071 : /*
2072 : * is_pseudo_constant_clause
2073 : * Detect whether an expression is "pseudo constant", ie, it contains no
2074 : * variables of the current query level and no uses of volatile functions.
2075 : * Such an expr is not necessarily a true constant: it can still contain
2076 : * Params and outer-level Vars, not to mention functions whose results
2077 : * may vary from one statement to the next. However, the expr's value
2078 : * will be constant over any one scan of the current query, so it can be
2079 : * used as, eg, an indexscan key. (Actually, the condition for indexscan
2080 : * keys is weaker than this; see is_pseudo_constant_for_index().)
2081 : *
2082 : * CAUTION: this function omits to test for one very important class of
2083 : * not-constant expressions, namely aggregates (Aggrefs). In current usage
2084 : * this is only applied to WHERE clauses and so a check for Aggrefs would be
2085 : * a waste of cycles; but be sure to also check contain_agg_clause() if you
2086 : * want to know about pseudo-constness in other contexts. The same goes
2087 : * for window functions (WindowFuncs).
2088 : */
2089 : bool
2090 5832 : is_pseudo_constant_clause(Node *clause)
2091 : {
2092 : /*
2093 : * We could implement this check in one recursive scan. But since the
2094 : * check for volatile functions is both moderately expensive and unlikely
2095 : * to fail, it seems better to look for Vars first and only check for
2096 : * volatile functions if we find no Vars.
2097 : */
2098 5832 : if (!contain_var_clause(clause) &&
2099 5832 : !contain_volatile_functions(clause))
2100 5832 : return true;
2101 0 : return false;
2102 : }
2103 :
2104 : /*
2105 : * is_pseudo_constant_clause_relids
2106 : * Same as above, except caller already has available the var membership
2107 : * of the expression; this lets us avoid the contain_var_clause() scan.
2108 : */
2109 : bool
2110 463080 : is_pseudo_constant_clause_relids(Node *clause, Relids relids)
2111 : {
2112 463080 : if (bms_is_empty(relids) &&
2113 455350 : !contain_volatile_functions(clause))
2114 455350 : return true;
2115 7730 : return false;
2116 : }
2117 :
2118 :
2119 : /*****************************************************************************
2120 : * *
2121 : * General clause-manipulating routines *
2122 : * *
2123 : *****************************************************************************/
2124 :
2125 : /*
2126 : * NumRelids
2127 : * (formerly clause_relids)
2128 : *
2129 : * Returns the number of different base relations referenced in 'clause'.
2130 : */
2131 : int
2132 1782 : NumRelids(PlannerInfo *root, Node *clause)
2133 : {
2134 : int result;
2135 1782 : Relids varnos = pull_varnos(root, clause);
2136 :
2137 1782 : varnos = bms_del_members(varnos, root->outer_join_rels);
2138 1782 : result = bms_num_members(varnos);
2139 1782 : bms_free(varnos);
2140 1782 : return result;
2141 : }
2142 :
2143 : /*
2144 : * CommuteOpExpr: commute a binary operator clause
2145 : *
2146 : * XXX the clause is destructively modified!
2147 : */
2148 : void
2149 18746 : CommuteOpExpr(OpExpr *clause)
2150 : {
2151 : Oid opoid;
2152 : Node *temp;
2153 :
2154 : /* Sanity checks: caller is at fault if these fail */
2155 37492 : if (!is_opclause(clause) ||
2156 18746 : list_length(clause->args) != 2)
2157 0 : elog(ERROR, "cannot commute non-binary-operator clause");
2158 :
2159 18746 : opoid = get_commutator(clause->opno);
2160 :
2161 18746 : if (!OidIsValid(opoid))
2162 0 : elog(ERROR, "could not find commutator for operator %u",
2163 : clause->opno);
2164 :
2165 : /*
2166 : * modify the clause in-place!
2167 : */
2168 18746 : clause->opno = opoid;
2169 18746 : clause->opfuncid = InvalidOid;
2170 : /* opresulttype, opretset, opcollid, inputcollid need not change */
2171 :
2172 18746 : temp = linitial(clause->args);
2173 18746 : linitial(clause->args) = lsecond(clause->args);
2174 18746 : lsecond(clause->args) = temp;
2175 18746 : }
2176 :
2177 : /*
2178 : * Helper for eval_const_expressions: check that datatype of an attribute
2179 : * is still what it was when the expression was parsed. This is needed to
2180 : * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
2181 : * may well need to make similar checks elsewhere?)
2182 : *
2183 : * rowtypeid may come from a whole-row Var, and therefore it can be a domain
2184 : * over composite, but for this purpose we only care about checking the type
2185 : * of a contained field.
2186 : */
2187 : static bool
2188 706 : rowtype_field_matches(Oid rowtypeid, int fieldnum,
2189 : Oid expectedtype, int32 expectedtypmod,
2190 : Oid expectedcollation)
2191 : {
2192 : TupleDesc tupdesc;
2193 : Form_pg_attribute attr;
2194 :
2195 : /* No issue for RECORD, since there is no way to ALTER such a type */
2196 706 : if (rowtypeid == RECORDOID)
2197 42 : return true;
2198 664 : tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2199 664 : if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2200 : {
2201 0 : ReleaseTupleDesc(tupdesc);
2202 0 : return false;
2203 : }
2204 664 : attr = TupleDescAttr(tupdesc, fieldnum - 1);
2205 664 : if (attr->attisdropped ||
2206 664 : attr->atttypid != expectedtype ||
2207 664 : attr->atttypmod != expectedtypmod ||
2208 664 : attr->attcollation != expectedcollation)
2209 : {
2210 0 : ReleaseTupleDesc(tupdesc);
2211 0 : return false;
2212 : }
2213 664 : ReleaseTupleDesc(tupdesc);
2214 664 : return true;
2215 : }
2216 :
2217 :
2218 : /*--------------------
2219 : * eval_const_expressions
2220 : *
2221 : * Reduce any recognizably constant subexpressions of the given
2222 : * expression tree, for example "2 + 2" => "4". More interestingly,
2223 : * we can reduce certain boolean expressions even when they contain
2224 : * non-constant subexpressions: "x OR true" => "true" no matter what
2225 : * the subexpression x is. (XXX We assume that no such subexpression
2226 : * will have important side-effects, which is not necessarily a good
2227 : * assumption in the presence of user-defined functions; do we need a
2228 : * pg_proc flag that prevents discarding the execution of a function?)
2229 : *
2230 : * We do understand that certain functions may deliver non-constant
2231 : * results even with constant inputs, "nextval()" being the classic
2232 : * example. Functions that are not marked "immutable" in pg_proc
2233 : * will not be pre-evaluated here, although we will reduce their
2234 : * arguments as far as possible.
2235 : *
2236 : * Whenever a function is eliminated from the expression by means of
2237 : * constant-expression evaluation or inlining, we add the function to
2238 : * root->glob->invalItems. This ensures the plan is known to depend on
2239 : * such functions, even though they aren't referenced anymore.
2240 : *
2241 : * We assume that the tree has already been type-checked and contains
2242 : * only operators and functions that are reasonable to try to execute.
2243 : *
2244 : * NOTE: "root" can be passed as NULL if the caller never wants to do any
2245 : * Param substitutions nor receive info about inlined functions.
2246 : *
2247 : * NOTE: the planner assumes that this will always flatten nested AND and
2248 : * OR clauses into N-argument form. See comments in prepqual.c.
2249 : *
2250 : * NOTE: another critical effect is that any function calls that require
2251 : * default arguments will be expanded, and named-argument calls will be
2252 : * converted to positional notation. The executor won't handle either.
2253 : *--------------------
2254 : */
2255 : Node *
2256 1220356 : eval_const_expressions(PlannerInfo *root, Node *node)
2257 : {
2258 : eval_const_expressions_context context;
2259 :
2260 1220356 : if (root)
2261 965468 : context.boundParams = root->glob->boundParams; /* bound Params */
2262 : else
2263 254888 : context.boundParams = NULL;
2264 1220356 : context.root = root; /* for inlined-function dependencies */
2265 1220356 : context.active_fns = NIL; /* nothing being recursively simplified */
2266 1220356 : context.case_val = NULL; /* no CASE being examined */
2267 1220356 : context.estimate = false; /* safe transformations only */
2268 1220356 : return eval_const_expressions_mutator(node, &context);
2269 : }
2270 :
2271 : #define MIN_ARRAY_SIZE_FOR_HASHED_SAOP 9
2272 : /*--------------------
2273 : * convert_saop_to_hashed_saop
2274 : *
2275 : * Recursively search 'node' for ScalarArrayOpExprs and fill in the hash
2276 : * function for any ScalarArrayOpExpr that looks like it would be useful to
2277 : * evaluate using a hash table rather than a linear search.
2278 : *
2279 : * We'll use a hash table if all of the following conditions are met:
2280 : * 1. The 2nd argument of the array contain only Consts.
2281 : * 2. useOr is true or there is a valid negator operator for the
2282 : * ScalarArrayOpExpr's opno.
2283 : * 3. There's valid hash function for both left and righthand operands and
2284 : * these hash functions are the same.
2285 : * 4. If the array contains enough elements for us to consider it to be
2286 : * worthwhile using a hash table rather than a linear search.
2287 : */
2288 : void
2289 841350 : convert_saop_to_hashed_saop(Node *node)
2290 : {
2291 841350 : (void) convert_saop_to_hashed_saop_walker(node, NULL);
2292 841350 : }
2293 :
2294 : static bool
2295 6077468 : convert_saop_to_hashed_saop_walker(Node *node, void *context)
2296 : {
2297 6077468 : if (node == NULL)
2298 135256 : return false;
2299 :
2300 5942212 : if (IsA(node, ScalarArrayOpExpr))
2301 : {
2302 33052 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2303 33052 : Expr *arrayarg = (Expr *) lsecond(saop->args);
2304 : Oid lefthashfunc;
2305 : Oid righthashfunc;
2306 :
2307 33052 : if (arrayarg && IsA(arrayarg, Const) &&
2308 17638 : !((Const *) arrayarg)->constisnull)
2309 : {
2310 17608 : if (saop->useOr)
2311 : {
2312 15124 : if (get_op_hash_functions(saop->opno, &lefthashfunc, &righthashfunc) &&
2313 14790 : lefthashfunc == righthashfunc)
2314 : {
2315 14764 : Datum arrdatum = ((Const *) arrayarg)->constvalue;
2316 14764 : ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2317 : int nitems;
2318 :
2319 : /*
2320 : * Only fill in the hash functions if the array looks
2321 : * large enough for it to be worth hashing instead of
2322 : * doing a linear search.
2323 : */
2324 14764 : nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2325 :
2326 14764 : if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2327 : {
2328 : /* Looks good. Fill in the hash functions */
2329 458 : saop->hashfuncid = lefthashfunc;
2330 : }
2331 17078 : return false;
2332 : }
2333 : }
2334 : else /* !saop->useOr */
2335 : {
2336 2484 : Oid negator = get_negator(saop->opno);
2337 :
2338 : /*
2339 : * Check if this is a NOT IN using an operator whose negator
2340 : * is hashable. If so we can still build a hash table and
2341 : * just ensure the lookup items are not in the hash table.
2342 : */
2343 4968 : if (OidIsValid(negator) &&
2344 2484 : get_op_hash_functions(negator, &lefthashfunc, &righthashfunc) &&
2345 2314 : lefthashfunc == righthashfunc)
2346 : {
2347 2314 : Datum arrdatum = ((Const *) arrayarg)->constvalue;
2348 2314 : ArrayType *arr = (ArrayType *) DatumGetPointer(arrdatum);
2349 : int nitems;
2350 :
2351 : /*
2352 : * Only fill in the hash functions if the array looks
2353 : * large enough for it to be worth hashing instead of
2354 : * doing a linear search.
2355 : */
2356 2314 : nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2357 :
2358 2314 : if (nitems >= MIN_ARRAY_SIZE_FOR_HASHED_SAOP)
2359 : {
2360 : /* Looks good. Fill in the hash functions */
2361 70 : saop->hashfuncid = lefthashfunc;
2362 :
2363 : /*
2364 : * Also set the negfuncid. The executor will need
2365 : * that to perform hashtable lookups.
2366 : */
2367 70 : saop->negfuncid = get_opcode(negator);
2368 : }
2369 2314 : return false;
2370 : }
2371 : }
2372 : }
2373 : }
2374 :
2375 5925134 : return expression_tree_walker(node, convert_saop_to_hashed_saop_walker, NULL);
2376 : }
2377 :
2378 :
2379 : /*--------------------
2380 : * estimate_expression_value
2381 : *
2382 : * This function attempts to estimate the value of an expression for
2383 : * planning purposes. It is in essence a more aggressive version of
2384 : * eval_const_expressions(): we will perform constant reductions that are
2385 : * not necessarily 100% safe, but are reasonable for estimation purposes.
2386 : *
2387 : * Currently the extra steps that are taken in this mode are:
2388 : * 1. Substitute values for Params, where a bound Param value has been made
2389 : * available by the caller of planner(), even if the Param isn't marked
2390 : * constant. This effectively means that we plan using the first supplied
2391 : * value of the Param.
2392 : * 2. Fold stable, as well as immutable, functions to constants.
2393 : * 3. Reduce PlaceHolderVar nodes to their contained expressions.
2394 : *--------------------
2395 : */
2396 : Node *
2397 843994 : estimate_expression_value(PlannerInfo *root, Node *node)
2398 : {
2399 : eval_const_expressions_context context;
2400 :
2401 843994 : context.boundParams = root->glob->boundParams; /* bound Params */
2402 : /* we do not need to mark the plan as depending on inlined functions */
2403 843994 : context.root = NULL;
2404 843994 : context.active_fns = NIL; /* nothing being recursively simplified */
2405 843994 : context.case_val = NULL; /* no CASE being examined */
2406 843994 : context.estimate = true; /* unsafe transformations OK */
2407 843994 : return eval_const_expressions_mutator(node, &context);
2408 : }
2409 :
2410 : /*
2411 : * The generic case in eval_const_expressions_mutator is to recurse using
2412 : * expression_tree_mutator, which will copy the given node unchanged but
2413 : * const-simplify its arguments (if any) as far as possible. If the node
2414 : * itself does immutable processing, and each of its arguments were reduced
2415 : * to a Const, we can then reduce it to a Const using evaluate_expr. (Some
2416 : * node types need more complicated logic; for example, a CASE expression
2417 : * might be reducible to a constant even if not all its subtrees are.)
2418 : */
2419 : #define ece_generic_processing(node) \
2420 : expression_tree_mutator((Node *) (node), eval_const_expressions_mutator, \
2421 : context)
2422 :
2423 : /*
2424 : * Check whether all arguments of the given node were reduced to Consts.
2425 : * By going directly to expression_tree_walker, contain_non_const_walker
2426 : * is not applied to the node itself, only to its children.
2427 : */
2428 : #define ece_all_arguments_const(node) \
2429 : (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
2430 :
2431 : /* Generic macro for applying evaluate_expr */
2432 : #define ece_evaluate_expr(node) \
2433 : ((Node *) evaluate_expr((Expr *) (node), \
2434 : exprType((Node *) (node)), \
2435 : exprTypmod((Node *) (node)), \
2436 : exprCollation((Node *) (node))))
2437 :
2438 : /*
2439 : * Recursive guts of eval_const_expressions/estimate_expression_value
2440 : */
2441 : static Node *
2442 8984556 : eval_const_expressions_mutator(Node *node,
2443 : eval_const_expressions_context *context)
2444 : {
2445 :
2446 : /* since this function recurses, it could be driven to stack overflow */
2447 8984556 : check_stack_depth();
2448 :
2449 8984556 : if (node == NULL)
2450 375754 : return NULL;
2451 8608802 : switch (nodeTag(node))
2452 : {
2453 148632 : case T_Param:
2454 : {
2455 148632 : Param *param = (Param *) node;
2456 148632 : ParamListInfo paramLI = context->boundParams;
2457 :
2458 : /* Look to see if we've been given a value for this Param */
2459 148632 : if (param->paramkind == PARAM_EXTERN &&
2460 53440 : paramLI != NULL &&
2461 53440 : param->paramid > 0 &&
2462 53440 : param->paramid <= paramLI->numParams)
2463 : {
2464 : ParamExternData *prm;
2465 : ParamExternData prmdata;
2466 :
2467 : /*
2468 : * Give hook a chance in case parameter is dynamic. Tell
2469 : * it that this fetch is speculative, so it should avoid
2470 : * erroring out if parameter is unavailable.
2471 : */
2472 53440 : if (paramLI->paramFetch != NULL)
2473 7244 : prm = paramLI->paramFetch(paramLI, param->paramid,
2474 : true, &prmdata);
2475 : else
2476 46196 : prm = ¶mLI->params[param->paramid - 1];
2477 :
2478 : /*
2479 : * We don't just check OidIsValid, but insist that the
2480 : * fetched type match the Param, just in case the hook did
2481 : * something unexpected. No need to throw an error here
2482 : * though; leave that for runtime.
2483 : */
2484 53440 : if (OidIsValid(prm->ptype) &&
2485 53440 : prm->ptype == param->paramtype)
2486 : {
2487 : /* OK to substitute parameter value? */
2488 53438 : if (context->estimate ||
2489 53438 : (prm->pflags & PARAM_FLAG_CONST))
2490 : {
2491 : /*
2492 : * Return a Const representing the param value.
2493 : * Must copy pass-by-ref datatypes, since the
2494 : * Param might be in a memory context
2495 : * shorter-lived than our output plan should be.
2496 : */
2497 : int16 typLen;
2498 : bool typByVal;
2499 : Datum pval;
2500 : Const *con;
2501 :
2502 53438 : get_typlenbyval(param->paramtype,
2503 : &typLen, &typByVal);
2504 53438 : if (prm->isnull || typByVal)
2505 35556 : pval = prm->value;
2506 : else
2507 17882 : pval = datumCopy(prm->value, typByVal, typLen);
2508 53438 : con = makeConst(param->paramtype,
2509 : param->paramtypmod,
2510 : param->paramcollid,
2511 : (int) typLen,
2512 : pval,
2513 53438 : prm->isnull,
2514 : typByVal);
2515 53438 : con->location = param->location;
2516 53438 : return (Node *) con;
2517 : }
2518 : }
2519 : }
2520 :
2521 : /*
2522 : * Not replaceable, so just copy the Param (no need to
2523 : * recurse)
2524 : */
2525 95194 : return (Node *) copyObject(param);
2526 : }
2527 3260 : case T_WindowFunc:
2528 : {
2529 3260 : WindowFunc *expr = (WindowFunc *) node;
2530 3260 : Oid funcid = expr->winfnoid;
2531 : List *args;
2532 : Expr *aggfilter;
2533 : HeapTuple func_tuple;
2534 : WindowFunc *newexpr;
2535 :
2536 : /*
2537 : * We can't really simplify a WindowFunc node, but we mustn't
2538 : * just fall through to the default processing, because we
2539 : * have to apply expand_function_arguments to its argument
2540 : * list. That takes care of inserting default arguments and
2541 : * expanding named-argument notation.
2542 : */
2543 3260 : func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2544 3260 : if (!HeapTupleIsValid(func_tuple))
2545 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
2546 :
2547 3260 : args = expand_function_arguments(expr->args,
2548 : false, expr->wintype,
2549 : func_tuple);
2550 :
2551 3260 : ReleaseSysCache(func_tuple);
2552 :
2553 : /* Now, recursively simplify the args (which are a List) */
2554 : args = (List *)
2555 3260 : expression_tree_mutator((Node *) args,
2556 : eval_const_expressions_mutator,
2557 : context);
2558 : /* ... and the filter expression, which isn't */
2559 : aggfilter = (Expr *)
2560 3260 : eval_const_expressions_mutator((Node *) expr->aggfilter,
2561 : context);
2562 :
2563 : /* And build the replacement WindowFunc node */
2564 3260 : newexpr = makeNode(WindowFunc);
2565 3260 : newexpr->winfnoid = expr->winfnoid;
2566 3260 : newexpr->wintype = expr->wintype;
2567 3260 : newexpr->wincollid = expr->wincollid;
2568 3260 : newexpr->inputcollid = expr->inputcollid;
2569 3260 : newexpr->args = args;
2570 3260 : newexpr->aggfilter = aggfilter;
2571 3260 : newexpr->runCondition = expr->runCondition;
2572 3260 : newexpr->winref = expr->winref;
2573 3260 : newexpr->winstar = expr->winstar;
2574 3260 : newexpr->winagg = expr->winagg;
2575 3260 : newexpr->location = expr->location;
2576 :
2577 3260 : return (Node *) newexpr;
2578 : }
2579 542450 : case T_FuncExpr:
2580 : {
2581 542450 : FuncExpr *expr = (FuncExpr *) node;
2582 542450 : List *args = expr->args;
2583 : Expr *simple;
2584 : FuncExpr *newexpr;
2585 :
2586 : /*
2587 : * Code for op/func reduction is pretty bulky, so split it out
2588 : * as a separate function. Note: exprTypmod normally returns
2589 : * -1 for a FuncExpr, but not when the node is recognizably a
2590 : * length coercion; we want to preserve the typmod in the
2591 : * eventual Const if so.
2592 : */
2593 542450 : simple = simplify_function(expr->funcid,
2594 : expr->funcresulttype,
2595 : exprTypmod(node),
2596 : expr->funccollid,
2597 : expr->inputcollid,
2598 : &args,
2599 542450 : expr->funcvariadic,
2600 : true,
2601 : true,
2602 : context);
2603 539720 : if (simple) /* successfully simplified it */
2604 154598 : return (Node *) simple;
2605 :
2606 : /*
2607 : * The expression cannot be simplified any further, so build
2608 : * and return a replacement FuncExpr node using the
2609 : * possibly-simplified arguments. Note that we have also
2610 : * converted the argument list to positional notation.
2611 : */
2612 385122 : newexpr = makeNode(FuncExpr);
2613 385122 : newexpr->funcid = expr->funcid;
2614 385122 : newexpr->funcresulttype = expr->funcresulttype;
2615 385122 : newexpr->funcretset = expr->funcretset;
2616 385122 : newexpr->funcvariadic = expr->funcvariadic;
2617 385122 : newexpr->funcformat = expr->funcformat;
2618 385122 : newexpr->funccollid = expr->funccollid;
2619 385122 : newexpr->inputcollid = expr->inputcollid;
2620 385122 : newexpr->args = args;
2621 385122 : newexpr->location = expr->location;
2622 385122 : return (Node *) newexpr;
2623 : }
2624 684320 : case T_OpExpr:
2625 : {
2626 684320 : OpExpr *expr = (OpExpr *) node;
2627 684320 : List *args = expr->args;
2628 : Expr *simple;
2629 : OpExpr *newexpr;
2630 :
2631 : /*
2632 : * Need to get OID of underlying function. Okay to scribble
2633 : * on input to this extent.
2634 : */
2635 684320 : set_opfuncid(expr);
2636 :
2637 : /*
2638 : * Code for op/func reduction is pretty bulky, so split it out
2639 : * as a separate function.
2640 : */
2641 684320 : simple = simplify_function(expr->opfuncid,
2642 : expr->opresulttype, -1,
2643 : expr->opcollid,
2644 : expr->inputcollid,
2645 : &args,
2646 : false,
2647 : true,
2648 : true,
2649 : context);
2650 683138 : if (simple) /* successfully simplified it */
2651 22432 : return (Node *) simple;
2652 :
2653 : /*
2654 : * If the operator is boolean equality or inequality, we know
2655 : * how to simplify cases involving one constant and one
2656 : * non-constant argument.
2657 : */
2658 660706 : if (expr->opno == BooleanEqualOperator ||
2659 659596 : expr->opno == BooleanNotEqualOperator)
2660 : {
2661 1278 : simple = (Expr *) simplify_boolean_equality(expr->opno,
2662 : args);
2663 1278 : if (simple) /* successfully simplified it */
2664 1046 : return (Node *) simple;
2665 : }
2666 :
2667 : /*
2668 : * The expression cannot be simplified any further, so build
2669 : * and return a replacement OpExpr node using the
2670 : * possibly-simplified arguments.
2671 : */
2672 659660 : newexpr = makeNode(OpExpr);
2673 659660 : newexpr->opno = expr->opno;
2674 659660 : newexpr->opfuncid = expr->opfuncid;
2675 659660 : newexpr->opresulttype = expr->opresulttype;
2676 659660 : newexpr->opretset = expr->opretset;
2677 659660 : newexpr->opcollid = expr->opcollid;
2678 659660 : newexpr->inputcollid = expr->inputcollid;
2679 659660 : newexpr->args = args;
2680 659660 : newexpr->location = expr->location;
2681 659660 : return (Node *) newexpr;
2682 : }
2683 1356 : case T_DistinctExpr:
2684 : {
2685 1356 : DistinctExpr *expr = (DistinctExpr *) node;
2686 : List *args;
2687 : ListCell *arg;
2688 1356 : bool has_null_input = false;
2689 1356 : bool all_null_input = true;
2690 1356 : bool has_nonconst_input = false;
2691 : Expr *simple;
2692 : DistinctExpr *newexpr;
2693 :
2694 : /*
2695 : * Reduce constants in the DistinctExpr's arguments. We know
2696 : * args is either NIL or a List node, so we can call
2697 : * expression_tree_mutator directly rather than recursing to
2698 : * self.
2699 : */
2700 1356 : args = (List *) expression_tree_mutator((Node *) expr->args,
2701 : eval_const_expressions_mutator,
2702 : context);
2703 :
2704 : /*
2705 : * We must do our own check for NULLs because DistinctExpr has
2706 : * different results for NULL input than the underlying
2707 : * operator does.
2708 : */
2709 4068 : foreach(arg, args)
2710 : {
2711 2712 : if (IsA(lfirst(arg), Const))
2712 : {
2713 310 : has_null_input |= ((Const *) lfirst(arg))->constisnull;
2714 310 : all_null_input &= ((Const *) lfirst(arg))->constisnull;
2715 : }
2716 : else
2717 2402 : has_nonconst_input = true;
2718 : }
2719 :
2720 : /* all constants? then can optimize this out */
2721 1356 : if (!has_nonconst_input)
2722 : {
2723 : /* all nulls? then not distinct */
2724 54 : if (all_null_input)
2725 12 : return makeBoolConst(false, false);
2726 :
2727 : /* one null? then distinct */
2728 42 : if (has_null_input)
2729 18 : return makeBoolConst(true, false);
2730 :
2731 : /* otherwise try to evaluate the '=' operator */
2732 : /* (NOT okay to try to inline it, though!) */
2733 :
2734 : /*
2735 : * Need to get OID of underlying function. Okay to
2736 : * scribble on input to this extent.
2737 : */
2738 24 : set_opfuncid((OpExpr *) expr); /* rely on struct
2739 : * equivalence */
2740 :
2741 : /*
2742 : * Code for op/func reduction is pretty bulky, so split it
2743 : * out as a separate function.
2744 : */
2745 24 : simple = simplify_function(expr->opfuncid,
2746 : expr->opresulttype, -1,
2747 : expr->opcollid,
2748 : expr->inputcollid,
2749 : &args,
2750 : false,
2751 : false,
2752 : false,
2753 : context);
2754 24 : if (simple) /* successfully simplified it */
2755 : {
2756 : /*
2757 : * Since the underlying operator is "=", must negate
2758 : * its result
2759 : */
2760 24 : Const *csimple = castNode(Const, simple);
2761 :
2762 24 : csimple->constvalue =
2763 24 : BoolGetDatum(!DatumGetBool(csimple->constvalue));
2764 24 : return (Node *) csimple;
2765 : }
2766 : }
2767 :
2768 : /*
2769 : * The expression cannot be simplified any further, so build
2770 : * and return a replacement DistinctExpr node using the
2771 : * possibly-simplified arguments.
2772 : */
2773 1302 : newexpr = makeNode(DistinctExpr);
2774 1302 : newexpr->opno = expr->opno;
2775 1302 : newexpr->opfuncid = expr->opfuncid;
2776 1302 : newexpr->opresulttype = expr->opresulttype;
2777 1302 : newexpr->opretset = expr->opretset;
2778 1302 : newexpr->opcollid = expr->opcollid;
2779 1302 : newexpr->inputcollid = expr->inputcollid;
2780 1302 : newexpr->args = args;
2781 1302 : newexpr->location = expr->location;
2782 1302 : return (Node *) newexpr;
2783 : }
2784 794 : case T_NullIfExpr:
2785 : {
2786 : NullIfExpr *expr;
2787 : ListCell *arg;
2788 794 : bool has_nonconst_input = false;
2789 :
2790 : /* Copy the node and const-simplify its arguments */
2791 794 : expr = (NullIfExpr *) ece_generic_processing(node);
2792 :
2793 : /* If either argument is NULL they can't be equal */
2794 2376 : foreach(arg, expr->args)
2795 : {
2796 1588 : if (!IsA(lfirst(arg), Const))
2797 762 : has_nonconst_input = true;
2798 826 : else if (((Const *) lfirst(arg))->constisnull)
2799 6 : return (Node *) linitial(expr->args);
2800 : }
2801 :
2802 : /*
2803 : * Need to get OID of underlying function before checking if
2804 : * the function is OK to evaluate.
2805 : */
2806 788 : set_opfuncid((OpExpr *) expr);
2807 :
2808 826 : if (!has_nonconst_input &&
2809 38 : ece_function_is_safe(expr->opfuncid, context))
2810 38 : return ece_evaluate_expr(expr);
2811 :
2812 750 : return (Node *) expr;
2813 : }
2814 38144 : case T_ScalarArrayOpExpr:
2815 : {
2816 : ScalarArrayOpExpr *saop;
2817 :
2818 : /* Copy the node and const-simplify its arguments */
2819 38144 : saop = (ScalarArrayOpExpr *) ece_generic_processing(node);
2820 :
2821 : /* Make sure we know underlying function */
2822 38144 : set_sa_opfuncid(saop);
2823 :
2824 : /*
2825 : * If all arguments are Consts, and it's a safe function, we
2826 : * can fold to a constant
2827 : */
2828 38482 : if (ece_all_arguments_const(saop) &&
2829 338 : ece_function_is_safe(saop->opfuncid, context))
2830 338 : return ece_evaluate_expr(saop);
2831 37806 : return (Node *) saop;
2832 : }
2833 170004 : case T_BoolExpr:
2834 : {
2835 170004 : BoolExpr *expr = (BoolExpr *) node;
2836 :
2837 170004 : switch (expr->boolop)
2838 : {
2839 13250 : case OR_EXPR:
2840 : {
2841 : List *newargs;
2842 13250 : bool haveNull = false;
2843 13250 : bool forceTrue = false;
2844 :
2845 13250 : newargs = simplify_or_arguments(expr->args,
2846 : context,
2847 : &haveNull,
2848 : &forceTrue);
2849 13250 : if (forceTrue)
2850 160 : return makeBoolConst(true, false);
2851 13090 : if (haveNull)
2852 30 : newargs = lappend(newargs,
2853 30 : makeBoolConst(false, true));
2854 : /* If all the inputs are FALSE, result is FALSE */
2855 13090 : if (newargs == NIL)
2856 22 : return makeBoolConst(false, false);
2857 :
2858 : /*
2859 : * If only one nonconst-or-NULL input, it's the
2860 : * result
2861 : */
2862 13068 : if (list_length(newargs) == 1)
2863 102 : return (Node *) linitial(newargs);
2864 : /* Else we still need an OR node */
2865 12966 : return (Node *) make_orclause(newargs);
2866 : }
2867 141726 : case AND_EXPR:
2868 : {
2869 : List *newargs;
2870 141726 : bool haveNull = false;
2871 141726 : bool forceFalse = false;
2872 :
2873 141726 : newargs = simplify_and_arguments(expr->args,
2874 : context,
2875 : &haveNull,
2876 : &forceFalse);
2877 141726 : if (forceFalse)
2878 1548 : return makeBoolConst(false, false);
2879 140178 : if (haveNull)
2880 6 : newargs = lappend(newargs,
2881 6 : makeBoolConst(false, true));
2882 : /* If all the inputs are TRUE, result is TRUE */
2883 140178 : if (newargs == NIL)
2884 370 : return makeBoolConst(true, false);
2885 :
2886 : /*
2887 : * If only one nonconst-or-NULL input, it's the
2888 : * result
2889 : */
2890 139808 : if (list_length(newargs) == 1)
2891 26 : return (Node *) linitial(newargs);
2892 : /* Else we still need an AND node */
2893 139782 : return (Node *) make_andclause(newargs);
2894 : }
2895 15028 : case NOT_EXPR:
2896 : {
2897 : Node *arg;
2898 :
2899 : Assert(list_length(expr->args) == 1);
2900 15028 : arg = eval_const_expressions_mutator(linitial(expr->args),
2901 : context);
2902 :
2903 : /*
2904 : * Use negate_clause() to see if we can simplify
2905 : * away the NOT.
2906 : */
2907 15028 : return negate_clause(arg);
2908 : }
2909 0 : default:
2910 0 : elog(ERROR, "unrecognized boolop: %d",
2911 : (int) expr->boolop);
2912 : break;
2913 : }
2914 : break;
2915 : }
2916 :
2917 750 : case T_JsonValueExpr:
2918 : {
2919 750 : JsonValueExpr *jve = (JsonValueExpr *) node;
2920 750 : Node *raw_expr = (Node *) jve->raw_expr;
2921 750 : Node *formatted_expr = (Node *) jve->formatted_expr;
2922 :
2923 : /*
2924 : * If we can fold formatted_expr to a constant, we can elide
2925 : * the JsonValueExpr altogether. Otherwise we must process
2926 : * raw_expr too. But JsonFormat is a flat node and requires
2927 : * no simplification, only copying.
2928 : */
2929 750 : formatted_expr = eval_const_expressions_mutator(formatted_expr,
2930 : context);
2931 750 : if (formatted_expr && IsA(formatted_expr, Const))
2932 522 : return formatted_expr;
2933 :
2934 228 : raw_expr = eval_const_expressions_mutator(raw_expr, context);
2935 :
2936 228 : return (Node *) makeJsonValueExpr((Expr *) raw_expr,
2937 : (Expr *) formatted_expr,
2938 228 : copyObject(jve->format));
2939 : }
2940 :
2941 582 : case T_SubPlan:
2942 : case T_AlternativeSubPlan:
2943 :
2944 : /*
2945 : * Return a SubPlan unchanged --- too late to do anything with it.
2946 : *
2947 : * XXX should we ereport() here instead? Probably this routine
2948 : * should never be invoked after SubPlan creation.
2949 : */
2950 582 : return node;
2951 177692 : case T_RelabelType:
2952 : {
2953 177692 : RelabelType *relabel = (RelabelType *) node;
2954 : Node *arg;
2955 :
2956 : /* Simplify the input ... */
2957 177692 : arg = eval_const_expressions_mutator((Node *) relabel->arg,
2958 : context);
2959 : /* ... and attach a new RelabelType node, if needed */
2960 177686 : return applyRelabelType(arg,
2961 : relabel->resulttype,
2962 : relabel->resulttypmod,
2963 : relabel->resultcollid,
2964 : relabel->relabelformat,
2965 : relabel->location,
2966 : true);
2967 : }
2968 25620 : case T_CoerceViaIO:
2969 : {
2970 25620 : CoerceViaIO *expr = (CoerceViaIO *) node;
2971 : List *args;
2972 : Oid outfunc;
2973 : bool outtypisvarlena;
2974 : Oid infunc;
2975 : Oid intypioparam;
2976 : Expr *simple;
2977 : CoerceViaIO *newexpr;
2978 :
2979 : /* Make a List so we can use simplify_function */
2980 25620 : args = list_make1(expr->arg);
2981 :
2982 : /*
2983 : * CoerceViaIO represents calling the source type's output
2984 : * function then the result type's input function. So, try to
2985 : * simplify it as though it were a stack of two such function
2986 : * calls. First we need to know what the functions are.
2987 : *
2988 : * Note that the coercion functions are assumed not to care
2989 : * about input collation, so we just pass InvalidOid for that.
2990 : */
2991 25620 : getTypeOutputInfo(exprType((Node *) expr->arg),
2992 : &outfunc, &outtypisvarlena);
2993 25620 : getTypeInputInfo(expr->resulttype,
2994 : &infunc, &intypioparam);
2995 :
2996 25620 : simple = simplify_function(outfunc,
2997 : CSTRINGOID, -1,
2998 : InvalidOid,
2999 : InvalidOid,
3000 : &args,
3001 : false,
3002 : true,
3003 : true,
3004 : context);
3005 25620 : if (simple) /* successfully simplified output fn */
3006 : {
3007 : /*
3008 : * Input functions may want 1 to 3 arguments. We always
3009 : * supply all three, trusting that nothing downstream will
3010 : * complain.
3011 : */
3012 2326 : args = list_make3(simple,
3013 : makeConst(OIDOID,
3014 : -1,
3015 : InvalidOid,
3016 : sizeof(Oid),
3017 : ObjectIdGetDatum(intypioparam),
3018 : false,
3019 : true),
3020 : makeConst(INT4OID,
3021 : -1,
3022 : InvalidOid,
3023 : sizeof(int32),
3024 : Int32GetDatum(-1),
3025 : false,
3026 : true));
3027 :
3028 2326 : simple = simplify_function(infunc,
3029 : expr->resulttype, -1,
3030 : expr->resultcollid,
3031 : InvalidOid,
3032 : &args,
3033 : false,
3034 : false,
3035 : true,
3036 : context);
3037 2274 : if (simple) /* successfully simplified input fn */
3038 2194 : return (Node *) simple;
3039 : }
3040 :
3041 : /*
3042 : * The expression cannot be simplified any further, so build
3043 : * and return a replacement CoerceViaIO node using the
3044 : * possibly-simplified argument.
3045 : */
3046 23374 : newexpr = makeNode(CoerceViaIO);
3047 23374 : newexpr->arg = (Expr *) linitial(args);
3048 23374 : newexpr->resulttype = expr->resulttype;
3049 23374 : newexpr->resultcollid = expr->resultcollid;
3050 23374 : newexpr->coerceformat = expr->coerceformat;
3051 23374 : newexpr->location = expr->location;
3052 23374 : return (Node *) newexpr;
3053 : }
3054 10394 : case T_ArrayCoerceExpr:
3055 : {
3056 10394 : ArrayCoerceExpr *ac = makeNode(ArrayCoerceExpr);
3057 : Node *save_case_val;
3058 :
3059 : /*
3060 : * Copy the node and const-simplify its arguments. We can't
3061 : * use ece_generic_processing() here because we need to mess
3062 : * with case_val only while processing the elemexpr.
3063 : */
3064 10394 : memcpy(ac, node, sizeof(ArrayCoerceExpr));
3065 10394 : ac->arg = (Expr *)
3066 10394 : eval_const_expressions_mutator((Node *) ac->arg,
3067 : context);
3068 :
3069 : /*
3070 : * Set up for the CaseTestExpr node contained in the elemexpr.
3071 : * We must prevent it from absorbing any outer CASE value.
3072 : */
3073 10394 : save_case_val = context->case_val;
3074 10394 : context->case_val = NULL;
3075 :
3076 10394 : ac->elemexpr = (Expr *)
3077 10394 : eval_const_expressions_mutator((Node *) ac->elemexpr,
3078 : context);
3079 :
3080 10394 : context->case_val = save_case_val;
3081 :
3082 : /*
3083 : * If constant argument and the per-element expression is
3084 : * immutable, we can simplify the whole thing to a constant.
3085 : * Exception: although contain_mutable_functions considers
3086 : * CoerceToDomain immutable for historical reasons, let's not
3087 : * do so here; this ensures coercion to an array-over-domain
3088 : * does not apply the domain's constraints until runtime.
3089 : */
3090 10394 : if (ac->arg && IsA(ac->arg, Const) &&
3091 1126 : ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3092 1102 : !contain_mutable_functions((Node *) ac->elemexpr))
3093 1102 : return ece_evaluate_expr(ac);
3094 :
3095 9292 : return (Node *) ac;
3096 : }
3097 8966 : case T_CollateExpr:
3098 : {
3099 : /*
3100 : * We replace CollateExpr with RelabelType, so as to improve
3101 : * uniformity of expression representation and thus simplify
3102 : * comparison of expressions. Hence this looks very nearly
3103 : * the same as the RelabelType case, and we can apply the same
3104 : * optimizations to avoid unnecessary RelabelTypes.
3105 : */
3106 8966 : CollateExpr *collate = (CollateExpr *) node;
3107 : Node *arg;
3108 :
3109 : /* Simplify the input ... */
3110 8966 : arg = eval_const_expressions_mutator((Node *) collate->arg,
3111 : context);
3112 : /* ... and attach a new RelabelType node, if needed */
3113 8966 : return applyRelabelType(arg,
3114 : exprType(arg),
3115 : exprTypmod(arg),
3116 : collate->collOid,
3117 : COERCE_IMPLICIT_CAST,
3118 : collate->location,
3119 : true);
3120 : }
3121 34298 : case T_CaseExpr:
3122 : {
3123 : /*----------
3124 : * CASE expressions can be simplified if there are constant
3125 : * condition clauses:
3126 : * FALSE (or NULL): drop the alternative
3127 : * TRUE: drop all remaining alternatives
3128 : * If the first non-FALSE alternative is a constant TRUE,
3129 : * we can simplify the entire CASE to that alternative's
3130 : * expression. If there are no non-FALSE alternatives,
3131 : * we simplify the entire CASE to the default result (ELSE).
3132 : *
3133 : * If we have a simple-form CASE with constant test
3134 : * expression, we substitute the constant value for contained
3135 : * CaseTestExpr placeholder nodes, so that we have the
3136 : * opportunity to reduce constant test conditions. For
3137 : * example this allows
3138 : * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3139 : * to reduce to 1 rather than drawing a divide-by-0 error.
3140 : * Note that when the test expression is constant, we don't
3141 : * have to include it in the resulting CASE; for example
3142 : * CASE 0 WHEN x THEN y ELSE z END
3143 : * is transformed by the parser to
3144 : * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3145 : * which we can simplify to
3146 : * CASE WHEN 0 = x THEN y ELSE z END
3147 : * It is not necessary for the executor to evaluate the "arg"
3148 : * expression when executing the CASE, since any contained
3149 : * CaseTestExprs that might have referred to it will have been
3150 : * replaced by the constant.
3151 : *----------
3152 : */
3153 34298 : CaseExpr *caseexpr = (CaseExpr *) node;
3154 : CaseExpr *newcase;
3155 : Node *save_case_val;
3156 : Node *newarg;
3157 : List *newargs;
3158 : bool const_true_cond;
3159 34298 : Node *defresult = NULL;
3160 : ListCell *arg;
3161 :
3162 : /* Simplify the test expression, if any */
3163 34298 : newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
3164 : context);
3165 :
3166 : /* Set up for contained CaseTestExpr nodes */
3167 34298 : save_case_val = context->case_val;
3168 34298 : if (newarg && IsA(newarg, Const))
3169 : {
3170 78 : context->case_val = newarg;
3171 78 : newarg = NULL; /* not needed anymore, see above */
3172 : }
3173 : else
3174 34220 : context->case_val = NULL;
3175 :
3176 : /* Simplify the WHEN clauses */
3177 34298 : newargs = NIL;
3178 34298 : const_true_cond = false;
3179 96318 : foreach(arg, caseexpr->args)
3180 : {
3181 62742 : CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
3182 : Node *casecond;
3183 : Node *caseresult;
3184 :
3185 : /* Simplify this alternative's test condition */
3186 62742 : casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
3187 : context);
3188 :
3189 : /*
3190 : * If the test condition is constant FALSE (or NULL), then
3191 : * drop this WHEN clause completely, without processing
3192 : * the result.
3193 : */
3194 62742 : if (casecond && IsA(casecond, Const))
3195 : {
3196 1922 : Const *const_input = (Const *) casecond;
3197 :
3198 1922 : if (const_input->constisnull ||
3199 1922 : !DatumGetBool(const_input->constvalue))
3200 1206 : continue; /* drop alternative with FALSE cond */
3201 : /* Else it's constant TRUE */
3202 716 : const_true_cond = true;
3203 : }
3204 :
3205 : /* Simplify this alternative's result value */
3206 61536 : caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
3207 : context);
3208 :
3209 : /* If non-constant test condition, emit a new WHEN node */
3210 61530 : if (!const_true_cond)
3211 60814 : {
3212 60814 : CaseWhen *newcasewhen = makeNode(CaseWhen);
3213 :
3214 60814 : newcasewhen->expr = (Expr *) casecond;
3215 60814 : newcasewhen->result = (Expr *) caseresult;
3216 60814 : newcasewhen->location = oldcasewhen->location;
3217 60814 : newargs = lappend(newargs, newcasewhen);
3218 60814 : continue;
3219 : }
3220 :
3221 : /*
3222 : * Found a TRUE condition, so none of the remaining
3223 : * alternatives can be reached. We treat the result as
3224 : * the default result.
3225 : */
3226 716 : defresult = caseresult;
3227 716 : break;
3228 : }
3229 :
3230 : /* Simplify the default result, unless we replaced it above */
3231 34292 : if (!const_true_cond)
3232 33576 : defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3233 : context);
3234 :
3235 34292 : context->case_val = save_case_val;
3236 :
3237 : /*
3238 : * If no non-FALSE alternatives, CASE reduces to the default
3239 : * result
3240 : */
3241 34292 : if (newargs == NIL)
3242 1148 : return defresult;
3243 : /* Otherwise we need a new CASE node */
3244 33144 : newcase = makeNode(CaseExpr);
3245 33144 : newcase->casetype = caseexpr->casetype;
3246 33144 : newcase->casecollid = caseexpr->casecollid;
3247 33144 : newcase->arg = (Expr *) newarg;
3248 33144 : newcase->args = newargs;
3249 33144 : newcase->defresult = (Expr *) defresult;
3250 33144 : newcase->location = caseexpr->location;
3251 33144 : return (Node *) newcase;
3252 : }
3253 33000 : case T_CaseTestExpr:
3254 : {
3255 : /*
3256 : * If we know a constant test value for the current CASE
3257 : * construct, substitute it for the placeholder. Else just
3258 : * return the placeholder as-is.
3259 : */
3260 33000 : if (context->case_val)
3261 144 : return copyObject(context->case_val);
3262 : else
3263 32856 : return copyObject(node);
3264 : }
3265 60112 : case T_SubscriptingRef:
3266 : case T_ArrayExpr:
3267 : case T_RowExpr:
3268 : case T_MinMaxExpr:
3269 : {
3270 : /*
3271 : * Generic handling for node types whose own processing is
3272 : * known to be immutable, and for which we need no smarts
3273 : * beyond "simplify if all inputs are constants".
3274 : *
3275 : * Treating SubscriptingRef this way assumes that subscripting
3276 : * fetch and assignment are both immutable. This constrains
3277 : * type-specific subscripting implementations; maybe we should
3278 : * relax it someday.
3279 : *
3280 : * Treating MinMaxExpr this way amounts to assuming that the
3281 : * btree comparison function it calls is immutable; see the
3282 : * reasoning in contain_mutable_functions_walker.
3283 : */
3284 :
3285 : /* Copy the node and const-simplify its arguments */
3286 60112 : node = ece_generic_processing(node);
3287 : /* If all arguments are Consts, we can fold to a constant */
3288 60112 : if (ece_all_arguments_const(node))
3289 29898 : return ece_evaluate_expr(node);
3290 30214 : return node;
3291 : }
3292 2610 : case T_CoalesceExpr:
3293 : {
3294 2610 : CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3295 : CoalesceExpr *newcoalesce;
3296 : List *newargs;
3297 : ListCell *arg;
3298 :
3299 2610 : newargs = NIL;
3300 6294 : foreach(arg, coalesceexpr->args)
3301 : {
3302 : Node *e;
3303 :
3304 5160 : e = eval_const_expressions_mutator((Node *) lfirst(arg),
3305 : context);
3306 :
3307 : /*
3308 : * We can remove null constants from the list. For a
3309 : * non-null constant, if it has not been preceded by any
3310 : * other non-null-constant expressions then it is the
3311 : * result. Otherwise, it's the next argument, but we can
3312 : * drop following arguments since they will never be
3313 : * reached.
3314 : */
3315 5160 : if (IsA(e, Const))
3316 : {
3317 1520 : if (((Const *) e)->constisnull)
3318 44 : continue; /* drop null constant */
3319 1476 : if (newargs == NIL)
3320 98 : return e; /* first expr */
3321 1378 : newargs = lappend(newargs, e);
3322 1378 : break;
3323 : }
3324 3640 : newargs = lappend(newargs, e);
3325 : }
3326 :
3327 : /*
3328 : * If all the arguments were constant null, the result is just
3329 : * null
3330 : */
3331 2512 : if (newargs == NIL)
3332 0 : return (Node *) makeNullConst(coalesceexpr->coalescetype,
3333 : -1,
3334 : coalesceexpr->coalescecollid);
3335 :
3336 : /*
3337 : * If there's exactly one surviving argument, we no longer
3338 : * need COALESCE at all: the result is that argument
3339 : */
3340 2512 : if (list_length(newargs) == 1)
3341 18 : return (Node *) linitial(newargs);
3342 :
3343 2494 : newcoalesce = makeNode(CoalesceExpr);
3344 2494 : newcoalesce->coalescetype = coalesceexpr->coalescetype;
3345 2494 : newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3346 2494 : newcoalesce->args = newargs;
3347 2494 : newcoalesce->location = coalesceexpr->location;
3348 2494 : return (Node *) newcoalesce;
3349 : }
3350 4980 : case T_SQLValueFunction:
3351 : {
3352 : /*
3353 : * All variants of SQLValueFunction are stable, so if we are
3354 : * estimating the expression's value, we should evaluate the
3355 : * current function value. Otherwise just copy.
3356 : */
3357 4980 : SQLValueFunction *svf = (SQLValueFunction *) node;
3358 :
3359 4980 : if (context->estimate)
3360 844 : return (Node *) evaluate_expr((Expr *) svf,
3361 : svf->type,
3362 : svf->typmod,
3363 : InvalidOid);
3364 : else
3365 4136 : return copyObject((Node *) svf);
3366 : }
3367 5482 : case T_FieldSelect:
3368 : {
3369 : /*
3370 : * We can optimize field selection from a whole-row Var into a
3371 : * simple Var. (This case won't be generated directly by the
3372 : * parser, because ParseComplexProjection short-circuits it.
3373 : * But it can arise while simplifying functions.) Also, we
3374 : * can optimize field selection from a RowExpr construct, or
3375 : * of course from a constant.
3376 : *
3377 : * However, replacing a whole-row Var in this way has a
3378 : * pitfall: if we've already built the rel targetlist for the
3379 : * source relation, then the whole-row Var is scheduled to be
3380 : * produced by the relation scan, but the simple Var probably
3381 : * isn't, which will lead to a failure in setrefs.c. This is
3382 : * not a problem when handling simple single-level queries, in
3383 : * which expression simplification always happens first. It
3384 : * is a risk for lateral references from subqueries, though.
3385 : * To avoid such failures, don't optimize uplevel references.
3386 : *
3387 : * We must also check that the declared type of the field is
3388 : * still the same as when the FieldSelect was created --- this
3389 : * can change if someone did ALTER COLUMN TYPE on the rowtype.
3390 : * If it isn't, we skip the optimization; the case will
3391 : * probably fail at runtime, but that's not our problem here.
3392 : */
3393 5482 : FieldSelect *fselect = (FieldSelect *) node;
3394 : FieldSelect *newfselect;
3395 : Node *arg;
3396 :
3397 5482 : arg = eval_const_expressions_mutator((Node *) fselect->arg,
3398 : context);
3399 5482 : if (arg && IsA(arg, Var) &&
3400 1560 : ((Var *) arg)->varattno == InvalidAttrNumber &&
3401 90 : ((Var *) arg)->varlevelsup == 0)
3402 : {
3403 78 : if (rowtype_field_matches(((Var *) arg)->vartype,
3404 78 : fselect->fieldnum,
3405 : fselect->resulttype,
3406 : fselect->resulttypmod,
3407 : fselect->resultcollid))
3408 : {
3409 : Var *newvar;
3410 :
3411 78 : newvar = makeVar(((Var *) arg)->varno,
3412 78 : fselect->fieldnum,
3413 : fselect->resulttype,
3414 : fselect->resulttypmod,
3415 : fselect->resultcollid,
3416 : ((Var *) arg)->varlevelsup);
3417 : /* New Var has same OLD/NEW returning as old one */
3418 78 : newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3419 : /* New Var is nullable by same rels as the old one */
3420 78 : newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3421 78 : return (Node *) newvar;
3422 : }
3423 : }
3424 5404 : if (arg && IsA(arg, RowExpr))
3425 : {
3426 24 : RowExpr *rowexpr = (RowExpr *) arg;
3427 :
3428 48 : if (fselect->fieldnum > 0 &&
3429 24 : fselect->fieldnum <= list_length(rowexpr->args))
3430 : {
3431 24 : Node *fld = (Node *) list_nth(rowexpr->args,
3432 24 : fselect->fieldnum - 1);
3433 :
3434 24 : if (rowtype_field_matches(rowexpr->row_typeid,
3435 24 : fselect->fieldnum,
3436 : fselect->resulttype,
3437 : fselect->resulttypmod,
3438 24 : fselect->resultcollid) &&
3439 48 : fselect->resulttype == exprType(fld) &&
3440 48 : fselect->resulttypmod == exprTypmod(fld) &&
3441 24 : fselect->resultcollid == exprCollation(fld))
3442 24 : return fld;
3443 : }
3444 : }
3445 5380 : newfselect = makeNode(FieldSelect);
3446 5380 : newfselect->arg = (Expr *) arg;
3447 5380 : newfselect->fieldnum = fselect->fieldnum;
3448 5380 : newfselect->resulttype = fselect->resulttype;
3449 5380 : newfselect->resulttypmod = fselect->resulttypmod;
3450 5380 : newfselect->resultcollid = fselect->resultcollid;
3451 5380 : if (arg && IsA(arg, Const))
3452 : {
3453 604 : Const *con = (Const *) arg;
3454 :
3455 604 : if (rowtype_field_matches(con->consttype,
3456 604 : newfselect->fieldnum,
3457 : newfselect->resulttype,
3458 : newfselect->resulttypmod,
3459 : newfselect->resultcollid))
3460 604 : return ece_evaluate_expr(newfselect);
3461 : }
3462 4776 : return (Node *) newfselect;
3463 : }
3464 37066 : case T_NullTest:
3465 : {
3466 37066 : NullTest *ntest = (NullTest *) node;
3467 : NullTest *newntest;
3468 : Node *arg;
3469 :
3470 37066 : arg = eval_const_expressions_mutator((Node *) ntest->arg,
3471 : context);
3472 37064 : if (ntest->argisrow && arg && IsA(arg, RowExpr))
3473 : {
3474 : /*
3475 : * We break ROW(...) IS [NOT] NULL into separate tests on
3476 : * its component fields. This form is usually more
3477 : * efficient to evaluate, as well as being more amenable
3478 : * to optimization.
3479 : */
3480 50 : RowExpr *rarg = (RowExpr *) arg;
3481 50 : List *newargs = NIL;
3482 : ListCell *l;
3483 :
3484 180 : foreach(l, rarg->args)
3485 : {
3486 130 : Node *relem = (Node *) lfirst(l);
3487 :
3488 : /*
3489 : * A constant field refutes the whole NullTest if it's
3490 : * of the wrong nullness; else we can discard it.
3491 : */
3492 130 : if (relem && IsA(relem, Const))
3493 0 : {
3494 0 : Const *carg = (Const *) relem;
3495 :
3496 0 : if (carg->constisnull ?
3497 0 : (ntest->nulltesttype == IS_NOT_NULL) :
3498 0 : (ntest->nulltesttype == IS_NULL))
3499 0 : return makeBoolConst(false, false);
3500 0 : continue;
3501 : }
3502 :
3503 : /*
3504 : * Else, make a scalar (argisrow == false) NullTest
3505 : * for this field. Scalar semantics are required
3506 : * because IS [NOT] NULL doesn't recurse; see comments
3507 : * in ExecEvalRowNullInt().
3508 : */
3509 130 : newntest = makeNode(NullTest);
3510 130 : newntest->arg = (Expr *) relem;
3511 130 : newntest->nulltesttype = ntest->nulltesttype;
3512 130 : newntest->argisrow = false;
3513 130 : newntest->location = ntest->location;
3514 130 : newargs = lappend(newargs, newntest);
3515 : }
3516 : /* If all the inputs were constants, result is TRUE */
3517 50 : if (newargs == NIL)
3518 0 : return makeBoolConst(true, false);
3519 : /* If only one nonconst input, it's the result */
3520 50 : if (list_length(newargs) == 1)
3521 0 : return (Node *) linitial(newargs);
3522 : /* Else we need an AND node */
3523 50 : return (Node *) make_andclause(newargs);
3524 : }
3525 37014 : if (!ntest->argisrow && arg && IsA(arg, Const))
3526 : {
3527 394 : Const *carg = (Const *) arg;
3528 : bool result;
3529 :
3530 394 : switch (ntest->nulltesttype)
3531 : {
3532 328 : case IS_NULL:
3533 328 : result = carg->constisnull;
3534 328 : break;
3535 66 : case IS_NOT_NULL:
3536 66 : result = !carg->constisnull;
3537 66 : break;
3538 0 : default:
3539 0 : elog(ERROR, "unrecognized nulltesttype: %d",
3540 : (int) ntest->nulltesttype);
3541 : result = false; /* keep compiler quiet */
3542 : break;
3543 : }
3544 :
3545 394 : return makeBoolConst(result, false);
3546 : }
3547 :
3548 36620 : newntest = makeNode(NullTest);
3549 36620 : newntest->arg = (Expr *) arg;
3550 36620 : newntest->nulltesttype = ntest->nulltesttype;
3551 36620 : newntest->argisrow = ntest->argisrow;
3552 36620 : newntest->location = ntest->location;
3553 36620 : return (Node *) newntest;
3554 : }
3555 2012 : case T_BooleanTest:
3556 : {
3557 : /*
3558 : * This case could be folded into the generic handling used
3559 : * for ArrayExpr etc. But because the simplification logic is
3560 : * so trivial, applying evaluate_expr() to perform it would be
3561 : * a heavy overhead. BooleanTest is probably common enough to
3562 : * justify keeping this bespoke implementation.
3563 : */
3564 2012 : BooleanTest *btest = (BooleanTest *) node;
3565 : BooleanTest *newbtest;
3566 : Node *arg;
3567 :
3568 2012 : arg = eval_const_expressions_mutator((Node *) btest->arg,
3569 : context);
3570 2012 : if (arg && IsA(arg, Const))
3571 : {
3572 222 : Const *carg = (Const *) arg;
3573 : bool result;
3574 :
3575 222 : switch (btest->booltesttype)
3576 : {
3577 0 : case IS_TRUE:
3578 0 : result = (!carg->constisnull &&
3579 0 : DatumGetBool(carg->constvalue));
3580 0 : break;
3581 222 : case IS_NOT_TRUE:
3582 444 : result = (carg->constisnull ||
3583 222 : !DatumGetBool(carg->constvalue));
3584 222 : break;
3585 0 : case IS_FALSE:
3586 0 : result = (!carg->constisnull &&
3587 0 : !DatumGetBool(carg->constvalue));
3588 0 : break;
3589 0 : case IS_NOT_FALSE:
3590 0 : result = (carg->constisnull ||
3591 0 : DatumGetBool(carg->constvalue));
3592 0 : break;
3593 0 : case IS_UNKNOWN:
3594 0 : result = carg->constisnull;
3595 0 : break;
3596 0 : case IS_NOT_UNKNOWN:
3597 0 : result = !carg->constisnull;
3598 0 : break;
3599 0 : default:
3600 0 : elog(ERROR, "unrecognized booltesttype: %d",
3601 : (int) btest->booltesttype);
3602 : result = false; /* keep compiler quiet */
3603 : break;
3604 : }
3605 :
3606 222 : return makeBoolConst(result, false);
3607 : }
3608 :
3609 1790 : newbtest = makeNode(BooleanTest);
3610 1790 : newbtest->arg = (Expr *) arg;
3611 1790 : newbtest->booltesttype = btest->booltesttype;
3612 1790 : newbtest->location = btest->location;
3613 1790 : return (Node *) newbtest;
3614 : }
3615 27606 : case T_CoerceToDomain:
3616 : {
3617 : /*
3618 : * If the domain currently has no constraints, we replace the
3619 : * CoerceToDomain node with a simple RelabelType, which is
3620 : * both far faster to execute and more amenable to later
3621 : * optimization. We must then mark the plan as needing to be
3622 : * rebuilt if the domain's constraints change.
3623 : *
3624 : * Also, in estimation mode, always replace CoerceToDomain
3625 : * nodes, effectively assuming that the coercion will succeed.
3626 : */
3627 27606 : CoerceToDomain *cdomain = (CoerceToDomain *) node;
3628 : CoerceToDomain *newcdomain;
3629 : Node *arg;
3630 :
3631 27606 : arg = eval_const_expressions_mutator((Node *) cdomain->arg,
3632 : context);
3633 27576 : if (context->estimate ||
3634 27528 : !DomainHasConstraints(cdomain->resulttype))
3635 : {
3636 : /* Record dependency, if this isn't estimation mode */
3637 18346 : if (context->root && !context->estimate)
3638 18232 : record_plan_type_dependency(context->root,
3639 : cdomain->resulttype);
3640 :
3641 : /* Generate RelabelType to substitute for CoerceToDomain */
3642 18346 : return applyRelabelType(arg,
3643 : cdomain->resulttype,
3644 : cdomain->resulttypmod,
3645 : cdomain->resultcollid,
3646 : cdomain->coercionformat,
3647 : cdomain->location,
3648 : true);
3649 : }
3650 :
3651 9230 : newcdomain = makeNode(CoerceToDomain);
3652 9230 : newcdomain->arg = (Expr *) arg;
3653 9230 : newcdomain->resulttype = cdomain->resulttype;
3654 9230 : newcdomain->resulttypmod = cdomain->resulttypmod;
3655 9230 : newcdomain->resultcollid = cdomain->resultcollid;
3656 9230 : newcdomain->coercionformat = cdomain->coercionformat;
3657 9230 : newcdomain->location = cdomain->location;
3658 9230 : return (Node *) newcdomain;
3659 : }
3660 3692 : case T_PlaceHolderVar:
3661 :
3662 : /*
3663 : * In estimation mode, just strip the PlaceHolderVar node
3664 : * altogether; this amounts to estimating that the contained value
3665 : * won't be forced to null by an outer join. In regular mode we
3666 : * just use the default behavior (ie, simplify the expression but
3667 : * leave the PlaceHolderVar node intact).
3668 : */
3669 3692 : if (context->estimate)
3670 : {
3671 354 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
3672 :
3673 354 : return eval_const_expressions_mutator((Node *) phv->phexpr,
3674 : context);
3675 : }
3676 3338 : break;
3677 78 : case T_ConvertRowtypeExpr:
3678 : {
3679 78 : ConvertRowtypeExpr *cre = castNode(ConvertRowtypeExpr, node);
3680 : Node *arg;
3681 : ConvertRowtypeExpr *newcre;
3682 :
3683 78 : arg = eval_const_expressions_mutator((Node *) cre->arg,
3684 : context);
3685 :
3686 78 : newcre = makeNode(ConvertRowtypeExpr);
3687 78 : newcre->resulttype = cre->resulttype;
3688 78 : newcre->convertformat = cre->convertformat;
3689 78 : newcre->location = cre->location;
3690 :
3691 : /*
3692 : * In case of a nested ConvertRowtypeExpr, we can convert the
3693 : * leaf row directly to the topmost row format without any
3694 : * intermediate conversions. (This works because
3695 : * ConvertRowtypeExpr is used only for child->parent
3696 : * conversion in inheritance trees, which works by exact match
3697 : * of column name, and a column absent in an intermediate
3698 : * result can't be present in the final result.)
3699 : *
3700 : * No need to check more than one level deep, because the
3701 : * above recursion will have flattened anything else.
3702 : */
3703 78 : if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3704 : {
3705 12 : ConvertRowtypeExpr *argcre = (ConvertRowtypeExpr *) arg;
3706 :
3707 12 : arg = (Node *) argcre->arg;
3708 :
3709 : /*
3710 : * Make sure an outer implicit conversion can't hide an
3711 : * inner explicit one.
3712 : */
3713 12 : if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3714 0 : newcre->convertformat = argcre->convertformat;
3715 : }
3716 :
3717 78 : newcre->arg = (Expr *) arg;
3718 :
3719 78 : if (arg != NULL && IsA(arg, Const))
3720 18 : return ece_evaluate_expr((Node *) newcre);
3721 60 : return (Node *) newcre;
3722 : }
3723 6584902 : default:
3724 6584902 : break;
3725 : }
3726 :
3727 : /*
3728 : * For any node type not handled above, copy the node unchanged but
3729 : * const-simplify its subexpressions. This is the correct thing for node
3730 : * types whose behavior might change between planning and execution, such
3731 : * as CurrentOfExpr. It's also a safe default for new node types not
3732 : * known to this routine.
3733 : */
3734 6588240 : return ece_generic_processing(node);
3735 : }
3736 :
3737 : /*
3738 : * Subroutine for eval_const_expressions: check for non-Const nodes.
3739 : *
3740 : * We can abort recursion immediately on finding a non-Const node. This is
3741 : * critical for performance, else eval_const_expressions_mutator would take
3742 : * O(N^2) time on non-simplifiable trees. However, we do need to descend
3743 : * into List nodes since expression_tree_walker sometimes invokes the walker
3744 : * function directly on List subtrees.
3745 : */
3746 : static bool
3747 212228 : contain_non_const_walker(Node *node, void *context)
3748 : {
3749 212228 : if (node == NULL)
3750 702 : return false;
3751 211526 : if (IsA(node, Const))
3752 107938 : return false;
3753 103588 : if (IsA(node, List))
3754 35568 : return expression_tree_walker(node, contain_non_const_walker, context);
3755 : /* Otherwise, abort the tree traversal and return true */
3756 68020 : return true;
3757 : }
3758 :
3759 : /*
3760 : * Subroutine for eval_const_expressions: check if a function is OK to evaluate
3761 : */
3762 : static bool
3763 376 : ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
3764 : {
3765 376 : char provolatile = func_volatile(funcid);
3766 :
3767 : /*
3768 : * Ordinarily we are only allowed to simplify immutable functions. But for
3769 : * purposes of estimation, we consider it okay to simplify functions that
3770 : * are merely stable; the risk that the result might change from planning
3771 : * time to execution time is worth taking in preference to not being able
3772 : * to estimate the value at all.
3773 : */
3774 376 : if (provolatile == PROVOLATILE_IMMUTABLE)
3775 376 : return true;
3776 0 : if (context->estimate && provolatile == PROVOLATILE_STABLE)
3777 0 : return true;
3778 0 : return false;
3779 : }
3780 :
3781 : /*
3782 : * Subroutine for eval_const_expressions: process arguments of an OR clause
3783 : *
3784 : * This includes flattening of nested ORs as well as recursion to
3785 : * eval_const_expressions to simplify the OR arguments.
3786 : *
3787 : * After simplification, OR arguments are handled as follows:
3788 : * non constant: keep
3789 : * FALSE: drop (does not affect result)
3790 : * TRUE: force result to TRUE
3791 : * NULL: keep only one
3792 : * We must keep one NULL input because OR expressions evaluate to NULL when no
3793 : * input is TRUE and at least one is NULL. We don't actually include the NULL
3794 : * here, that's supposed to be done by the caller.
3795 : *
3796 : * The output arguments *haveNull and *forceTrue must be initialized false
3797 : * by the caller. They will be set true if a NULL constant or TRUE constant,
3798 : * respectively, is detected anywhere in the argument list.
3799 : */
3800 : static List *
3801 13250 : simplify_or_arguments(List *args,
3802 : eval_const_expressions_context *context,
3803 : bool *haveNull, bool *forceTrue)
3804 : {
3805 13250 : List *newargs = NIL;
3806 : List *unprocessed_args;
3807 :
3808 : /*
3809 : * We want to ensure that any OR immediately beneath another OR gets
3810 : * flattened into a single OR-list, so as to simplify later reasoning.
3811 : *
3812 : * To avoid stack overflow from recursion of eval_const_expressions, we
3813 : * resort to some tenseness here: we keep a list of not-yet-processed
3814 : * inputs, and handle flattening of nested ORs by prepending to the to-do
3815 : * list instead of recursing. Now that the parser generates N-argument
3816 : * ORs from simple lists, this complexity is probably less necessary than
3817 : * it once was, but we might as well keep the logic.
3818 : */
3819 13250 : unprocessed_args = list_copy(args);
3820 44584 : while (unprocessed_args)
3821 : {
3822 31494 : Node *arg = (Node *) linitial(unprocessed_args);
3823 :
3824 31494 : unprocessed_args = list_delete_first(unprocessed_args);
3825 :
3826 : /* flatten nested ORs as per above comment */
3827 31494 : if (is_orclause(arg))
3828 6 : {
3829 6 : List *subargs = ((BoolExpr *) arg)->args;
3830 6 : List *oldlist = unprocessed_args;
3831 :
3832 6 : unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3833 : /* perhaps-overly-tense code to avoid leaking old lists */
3834 6 : list_free(oldlist);
3835 6 : continue;
3836 : }
3837 :
3838 : /* If it's not an OR, simplify it */
3839 31488 : arg = eval_const_expressions_mutator(arg, context);
3840 :
3841 : /*
3842 : * It is unlikely but not impossible for simplification of a non-OR
3843 : * clause to produce an OR. Recheck, but don't be too tense about it
3844 : * since it's not a mainstream case. In particular we don't worry
3845 : * about const-simplifying the input twice, nor about list leakage.
3846 : */
3847 31488 : if (is_orclause(arg))
3848 0 : {
3849 0 : List *subargs = ((BoolExpr *) arg)->args;
3850 :
3851 0 : unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3852 0 : continue;
3853 : }
3854 :
3855 : /*
3856 : * OK, we have a const-simplified non-OR argument. Process it per
3857 : * comments above.
3858 : */
3859 31488 : if (IsA(arg, Const))
3860 176 : {
3861 336 : Const *const_input = (Const *) arg;
3862 :
3863 336 : if (const_input->constisnull)
3864 48 : *haveNull = true;
3865 288 : else if (DatumGetBool(const_input->constvalue))
3866 : {
3867 160 : *forceTrue = true;
3868 :
3869 : /*
3870 : * Once we detect a TRUE result we can just exit the loop
3871 : * immediately. However, if we ever add a notion of
3872 : * non-removable functions, we'd need to keep scanning.
3873 : */
3874 160 : return NIL;
3875 : }
3876 : /* otherwise, we can drop the constant-false input */
3877 176 : continue;
3878 : }
3879 :
3880 : /* else emit the simplified arg into the result list */
3881 31152 : newargs = lappend(newargs, arg);
3882 : }
3883 :
3884 13090 : return newargs;
3885 : }
3886 :
3887 : /*
3888 : * Subroutine for eval_const_expressions: process arguments of an AND clause
3889 : *
3890 : * This includes flattening of nested ANDs as well as recursion to
3891 : * eval_const_expressions to simplify the AND arguments.
3892 : *
3893 : * After simplification, AND arguments are handled as follows:
3894 : * non constant: keep
3895 : * TRUE: drop (does not affect result)
3896 : * FALSE: force result to FALSE
3897 : * NULL: keep only one
3898 : * We must keep one NULL input because AND expressions evaluate to NULL when
3899 : * no input is FALSE and at least one is NULL. We don't actually include the
3900 : * NULL here, that's supposed to be done by the caller.
3901 : *
3902 : * The output arguments *haveNull and *forceFalse must be initialized false
3903 : * by the caller. They will be set true if a null constant or false constant,
3904 : * respectively, is detected anywhere in the argument list.
3905 : */
3906 : static List *
3907 141726 : simplify_and_arguments(List *args,
3908 : eval_const_expressions_context *context,
3909 : bool *haveNull, bool *forceFalse)
3910 : {
3911 141726 : List *newargs = NIL;
3912 : List *unprocessed_args;
3913 :
3914 : /* See comments in simplify_or_arguments */
3915 141726 : unprocessed_args = list_copy(args);
3916 523878 : while (unprocessed_args)
3917 : {
3918 383700 : Node *arg = (Node *) linitial(unprocessed_args);
3919 :
3920 383700 : unprocessed_args = list_delete_first(unprocessed_args);
3921 :
3922 : /* flatten nested ANDs as per above comment */
3923 383700 : if (is_andclause(arg))
3924 2124 : {
3925 2124 : List *subargs = ((BoolExpr *) arg)->args;
3926 2124 : List *oldlist = unprocessed_args;
3927 :
3928 2124 : unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3929 : /* perhaps-overly-tense code to avoid leaking old lists */
3930 2124 : list_free(oldlist);
3931 2124 : continue;
3932 : }
3933 :
3934 : /* If it's not an AND, simplify it */
3935 381576 : arg = eval_const_expressions_mutator(arg, context);
3936 :
3937 : /*
3938 : * It is unlikely but not impossible for simplification of a non-AND
3939 : * clause to produce an AND. Recheck, but don't be too tense about it
3940 : * since it's not a mainstream case. In particular we don't worry
3941 : * about const-simplifying the input twice, nor about list leakage.
3942 : */
3943 381576 : if (is_andclause(arg))
3944 30 : {
3945 30 : List *subargs = ((BoolExpr *) arg)->args;
3946 :
3947 30 : unprocessed_args = list_concat_copy(subargs, unprocessed_args);
3948 30 : continue;
3949 : }
3950 :
3951 : /*
3952 : * OK, we have a const-simplified non-AND argument. Process it per
3953 : * comments above.
3954 : */
3955 381546 : if (IsA(arg, Const))
3956 1692 : {
3957 3240 : Const *const_input = (Const *) arg;
3958 :
3959 3240 : if (const_input->constisnull)
3960 18 : *haveNull = true;
3961 3222 : else if (!DatumGetBool(const_input->constvalue))
3962 : {
3963 1548 : *forceFalse = true;
3964 :
3965 : /*
3966 : * Once we detect a FALSE result we can just exit the loop
3967 : * immediately. However, if we ever add a notion of
3968 : * non-removable functions, we'd need to keep scanning.
3969 : */
3970 1548 : return NIL;
3971 : }
3972 : /* otherwise, we can drop the constant-true input */
3973 1692 : continue;
3974 : }
3975 :
3976 : /* else emit the simplified arg into the result list */
3977 378306 : newargs = lappend(newargs, arg);
3978 : }
3979 :
3980 140178 : return newargs;
3981 : }
3982 :
3983 : /*
3984 : * Subroutine for eval_const_expressions: try to simplify boolean equality
3985 : * or inequality condition
3986 : *
3987 : * Inputs are the operator OID and the simplified arguments to the operator.
3988 : * Returns a simplified expression if successful, or NULL if cannot
3989 : * simplify the expression.
3990 : *
3991 : * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
3992 : * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
3993 : * This is only marginally useful in itself, but doing it in constant folding
3994 : * ensures that we will recognize these forms as being equivalent in, for
3995 : * example, partial index matching.
3996 : *
3997 : * We come here only if simplify_function has failed; therefore we cannot
3998 : * see two constant inputs, nor a constant-NULL input.
3999 : */
4000 : static Node *
4001 1278 : simplify_boolean_equality(Oid opno, List *args)
4002 : {
4003 : Node *leftop;
4004 : Node *rightop;
4005 :
4006 : Assert(list_length(args) == 2);
4007 1278 : leftop = linitial(args);
4008 1278 : rightop = lsecond(args);
4009 1278 : if (leftop && IsA(leftop, Const))
4010 : {
4011 : Assert(!((Const *) leftop)->constisnull);
4012 0 : if (opno == BooleanEqualOperator)
4013 : {
4014 0 : if (DatumGetBool(((Const *) leftop)->constvalue))
4015 0 : return rightop; /* true = foo */
4016 : else
4017 0 : return negate_clause(rightop); /* false = foo */
4018 : }
4019 : else
4020 : {
4021 0 : if (DatumGetBool(((Const *) leftop)->constvalue))
4022 0 : return negate_clause(rightop); /* true <> foo */
4023 : else
4024 0 : return rightop; /* false <> foo */
4025 : }
4026 : }
4027 1278 : if (rightop && IsA(rightop, Const))
4028 : {
4029 : Assert(!((Const *) rightop)->constisnull);
4030 1046 : if (opno == BooleanEqualOperator)
4031 : {
4032 980 : if (DatumGetBool(((Const *) rightop)->constvalue))
4033 238 : return leftop; /* foo = true */
4034 : else
4035 742 : return negate_clause(leftop); /* foo = false */
4036 : }
4037 : else
4038 : {
4039 66 : if (DatumGetBool(((Const *) rightop)->constvalue))
4040 60 : return negate_clause(leftop); /* foo <> true */
4041 : else
4042 6 : return leftop; /* foo <> false */
4043 : }
4044 : }
4045 232 : return NULL;
4046 : }
4047 :
4048 : /*
4049 : * Subroutine for eval_const_expressions: try to simplify a function call
4050 : * (which might originally have been an operator; we don't care)
4051 : *
4052 : * Inputs are the function OID, actual result type OID (which is needed for
4053 : * polymorphic functions), result typmod, result collation, the input
4054 : * collation to use for the function, the original argument list (not
4055 : * const-simplified yet, unless process_args is false), and some flags;
4056 : * also the context data for eval_const_expressions.
4057 : *
4058 : * Returns a simplified expression if successful, or NULL if cannot
4059 : * simplify the function call.
4060 : *
4061 : * This function is also responsible for converting named-notation argument
4062 : * lists into positional notation and/or adding any needed default argument
4063 : * expressions; which is a bit grotty, but it avoids extra fetches of the
4064 : * function's pg_proc tuple. For this reason, the args list is
4065 : * pass-by-reference. Conversion and const-simplification of the args list
4066 : * will be done even if simplification of the function call itself is not
4067 : * possible.
4068 : */
4069 : static Expr *
4070 1254740 : simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
4071 : Oid result_collid, Oid input_collid, List **args_p,
4072 : bool funcvariadic, bool process_args, bool allow_non_const,
4073 : eval_const_expressions_context *context)
4074 : {
4075 1254740 : List *args = *args_p;
4076 : HeapTuple func_tuple;
4077 : Form_pg_proc func_form;
4078 : Expr *newexpr;
4079 :
4080 : /*
4081 : * We have three strategies for simplification: execute the function to
4082 : * deliver a constant result, use a transform function to generate a
4083 : * substitute node tree, or expand in-line the body of the function
4084 : * definition (which only works for simple SQL-language functions, but
4085 : * that is a common case). Each case needs access to the function's
4086 : * pg_proc tuple, so fetch it just once.
4087 : *
4088 : * Note: the allow_non_const flag suppresses both the second and third
4089 : * strategies; so if !allow_non_const, simplify_function can only return a
4090 : * Const or NULL. Argument-list rewriting happens anyway, though.
4091 : */
4092 1254740 : func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4093 1254740 : if (!HeapTupleIsValid(func_tuple))
4094 0 : elog(ERROR, "cache lookup failed for function %u", funcid);
4095 1254740 : func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
4096 :
4097 : /*
4098 : * Process the function arguments, unless the caller did it already.
4099 : *
4100 : * Here we must deal with named or defaulted arguments, and then
4101 : * recursively apply eval_const_expressions to the whole argument list.
4102 : */
4103 1254740 : if (process_args)
4104 : {
4105 1252390 : args = expand_function_arguments(args, false, result_type, func_tuple);
4106 1252390 : args = (List *) expression_tree_mutator((Node *) args,
4107 : eval_const_expressions_mutator,
4108 : context);
4109 : /* Argument processing done, give it back to the caller */
4110 1252264 : *args_p = args;
4111 : }
4112 :
4113 : /* Now attempt simplification of the function call proper. */
4114 :
4115 1254614 : newexpr = evaluate_function(funcid, result_type, result_typmod,
4116 : result_collid, input_collid,
4117 : args, funcvariadic,
4118 : func_tuple, context);
4119 :
4120 1250790 : if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4121 : {
4122 : /*
4123 : * Build a SupportRequestSimplify node to pass to the support
4124 : * function, pointing to a dummy FuncExpr node containing the
4125 : * simplified arg list. We use this approach to present a uniform
4126 : * interface to the support function regardless of how the target
4127 : * function is actually being invoked.
4128 : */
4129 : SupportRequestSimplify req;
4130 : FuncExpr fexpr;
4131 :
4132 34880 : fexpr.xpr.type = T_FuncExpr;
4133 34880 : fexpr.funcid = funcid;
4134 34880 : fexpr.funcresulttype = result_type;
4135 34880 : fexpr.funcretset = func_form->proretset;
4136 34880 : fexpr.funcvariadic = funcvariadic;
4137 34880 : fexpr.funcformat = COERCE_EXPLICIT_CALL;
4138 34880 : fexpr.funccollid = result_collid;
4139 34880 : fexpr.inputcollid = input_collid;
4140 34880 : fexpr.args = args;
4141 34880 : fexpr.location = -1;
4142 :
4143 34880 : req.type = T_SupportRequestSimplify;
4144 34880 : req.root = context->root;
4145 34880 : req.fcall = &fexpr;
4146 :
4147 : newexpr = (Expr *)
4148 34880 : DatumGetPointer(OidFunctionCall1(func_form->prosupport,
4149 : PointerGetDatum(&req)));
4150 :
4151 : /* catch a possible API misunderstanding */
4152 : Assert(newexpr != (Expr *) &fexpr);
4153 : }
4154 :
4155 1250790 : if (!newexpr && allow_non_const)
4156 1072440 : newexpr = inline_function(funcid, result_type, result_collid,
4157 : input_collid, args, funcvariadic,
4158 : func_tuple, context);
4159 :
4160 1250776 : ReleaseSysCache(func_tuple);
4161 :
4162 1250776 : return newexpr;
4163 : }
4164 :
4165 : /*
4166 : * expand_function_arguments: convert named-notation args to positional args
4167 : * and/or insert default args, as needed
4168 : *
4169 : * Returns a possibly-transformed version of the args list.
4170 : *
4171 : * If include_out_arguments is true, then the args list and the result
4172 : * include OUT arguments.
4173 : *
4174 : * The expected result type of the call must be given, for sanity-checking
4175 : * purposes. Also, we ask the caller to provide the function's actual
4176 : * pg_proc tuple, not just its OID.
4177 : *
4178 : * If we need to change anything, the input argument list is copied, not
4179 : * modified.
4180 : *
4181 : * Note: this gets applied to operator argument lists too, even though the
4182 : * cases it handles should never occur there. This should be OK since it
4183 : * will fall through very quickly if there's nothing to do.
4184 : */
4185 : List *
4186 1256140 : expand_function_arguments(List *args, bool include_out_arguments,
4187 : Oid result_type, HeapTuple func_tuple)
4188 : {
4189 1256140 : Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4190 1256140 : Oid *proargtypes = funcform->proargtypes.values;
4191 1256140 : int pronargs = funcform->pronargs;
4192 1256140 : bool has_named_args = false;
4193 : ListCell *lc;
4194 :
4195 : /*
4196 : * If we are asked to match to OUT arguments, then use the proallargtypes
4197 : * array (which includes those); otherwise use proargtypes (which
4198 : * doesn't). Of course, if proallargtypes is null, we always use
4199 : * proargtypes. (Fetching proallargtypes is annoyingly expensive
4200 : * considering that we may have nothing to do here, but fortunately the
4201 : * common case is include_out_arguments == false.)
4202 : */
4203 1256140 : if (include_out_arguments)
4204 : {
4205 : Datum proallargtypes;
4206 : bool isNull;
4207 :
4208 490 : proallargtypes = SysCacheGetAttr(PROCOID, func_tuple,
4209 : Anum_pg_proc_proallargtypes,
4210 : &isNull);
4211 490 : if (!isNull)
4212 : {
4213 202 : ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
4214 :
4215 202 : pronargs = ARR_DIMS(arr)[0];
4216 202 : if (ARR_NDIM(arr) != 1 ||
4217 202 : pronargs < 0 ||
4218 202 : ARR_HASNULL(arr) ||
4219 202 : ARR_ELEMTYPE(arr) != OIDOID)
4220 0 : elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4221 : Assert(pronargs >= funcform->pronargs);
4222 202 : proargtypes = (Oid *) ARR_DATA_PTR(arr);
4223 : }
4224 : }
4225 :
4226 : /* Do we have any named arguments? */
4227 3392840 : foreach(lc, args)
4228 : {
4229 2152834 : Node *arg = (Node *) lfirst(lc);
4230 :
4231 2152834 : if (IsA(arg, NamedArgExpr))
4232 : {
4233 16134 : has_named_args = true;
4234 16134 : break;
4235 : }
4236 : }
4237 :
4238 : /* If so, we must apply reorder_function_arguments */
4239 1256140 : if (has_named_args)
4240 : {
4241 16134 : args = reorder_function_arguments(args, pronargs, func_tuple);
4242 : /* Recheck argument types and add casts if needed */
4243 16134 : recheck_cast_function_args(args, result_type,
4244 : proargtypes, pronargs,
4245 : func_tuple);
4246 : }
4247 1240006 : else if (list_length(args) < pronargs)
4248 : {
4249 : /* No named args, but we seem to be short some defaults */
4250 6312 : args = add_function_defaults(args, pronargs, func_tuple);
4251 : /* Recheck argument types and add casts if needed */
4252 6312 : recheck_cast_function_args(args, result_type,
4253 : proargtypes, pronargs,
4254 : func_tuple);
4255 : }
4256 :
4257 1256140 : return args;
4258 : }
4259 :
4260 : /*
4261 : * reorder_function_arguments: convert named-notation args to positional args
4262 : *
4263 : * This function also inserts default argument values as needed, since it's
4264 : * impossible to form a truly valid positional call without that.
4265 : */
4266 : static List *
4267 16134 : reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
4268 : {
4269 16134 : Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4270 16134 : int nargsprovided = list_length(args);
4271 : Node *argarray[FUNC_MAX_ARGS];
4272 : ListCell *lc;
4273 : int i;
4274 :
4275 : Assert(nargsprovided <= pronargs);
4276 16134 : if (pronargs < 0 || pronargs > FUNC_MAX_ARGS)
4277 0 : elog(ERROR, "too many function arguments");
4278 16134 : memset(argarray, 0, pronargs * sizeof(Node *));
4279 :
4280 : /* Deconstruct the argument list into an array indexed by argnumber */
4281 16134 : i = 0;
4282 65614 : foreach(lc, args)
4283 : {
4284 49480 : Node *arg = (Node *) lfirst(lc);
4285 :
4286 49480 : if (!IsA(arg, NamedArgExpr))
4287 : {
4288 : /* positional argument, assumed to precede all named args */
4289 : Assert(argarray[i] == NULL);
4290 2460 : argarray[i++] = arg;
4291 : }
4292 : else
4293 : {
4294 47020 : NamedArgExpr *na = (NamedArgExpr *) arg;
4295 :
4296 : Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4297 : Assert(argarray[na->argnumber] == NULL);
4298 47020 : argarray[na->argnumber] = (Node *) na->arg;
4299 : }
4300 : }
4301 :
4302 : /*
4303 : * Fetch default expressions, if needed, and insert into array at proper
4304 : * locations (they aren't necessarily consecutive or all used)
4305 : */
4306 16134 : if (nargsprovided < pronargs)
4307 : {
4308 7524 : List *defaults = fetch_function_defaults(func_tuple);
4309 :
4310 7524 : i = pronargs - funcform->pronargdefaults;
4311 43032 : foreach(lc, defaults)
4312 : {
4313 35508 : if (argarray[i] == NULL)
4314 15238 : argarray[i] = (Node *) lfirst(lc);
4315 35508 : i++;
4316 : }
4317 : }
4318 :
4319 : /* Now reconstruct the args list in proper order */
4320 16134 : args = NIL;
4321 80852 : for (i = 0; i < pronargs; i++)
4322 : {
4323 : Assert(argarray[i] != NULL);
4324 64718 : args = lappend(args, argarray[i]);
4325 : }
4326 :
4327 16134 : return args;
4328 : }
4329 :
4330 : /*
4331 : * add_function_defaults: add missing function arguments from its defaults
4332 : *
4333 : * This is used only when the argument list was positional to begin with,
4334 : * and so we know we just need to add defaults at the end.
4335 : */
4336 : static List *
4337 6312 : add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
4338 : {
4339 6312 : int nargsprovided = list_length(args);
4340 : List *defaults;
4341 : int ndelete;
4342 :
4343 : /* Get all the default expressions from the pg_proc tuple */
4344 6312 : defaults = fetch_function_defaults(func_tuple);
4345 :
4346 : /* Delete any unused defaults from the list */
4347 6312 : ndelete = nargsprovided + list_length(defaults) - pronargs;
4348 6312 : if (ndelete < 0)
4349 0 : elog(ERROR, "not enough default arguments");
4350 6312 : if (ndelete > 0)
4351 234 : defaults = list_delete_first_n(defaults, ndelete);
4352 :
4353 : /* And form the combined argument list, not modifying the input list */
4354 6312 : return list_concat_copy(args, defaults);
4355 : }
4356 :
4357 : /*
4358 : * fetch_function_defaults: get function's default arguments as expression list
4359 : */
4360 : static List *
4361 13836 : fetch_function_defaults(HeapTuple func_tuple)
4362 : {
4363 : List *defaults;
4364 : Datum proargdefaults;
4365 : char *str;
4366 :
4367 13836 : proargdefaults = SysCacheGetAttrNotNull(PROCOID, func_tuple,
4368 : Anum_pg_proc_proargdefaults);
4369 13836 : str = TextDatumGetCString(proargdefaults);
4370 13836 : defaults = castNode(List, stringToNode(str));
4371 13836 : pfree(str);
4372 13836 : return defaults;
4373 : }
4374 :
4375 : /*
4376 : * recheck_cast_function_args: recheck function args and typecast as needed
4377 : * after adding defaults.
4378 : *
4379 : * It is possible for some of the defaulted arguments to be polymorphic;
4380 : * therefore we can't assume that the default expressions have the correct
4381 : * data types already. We have to re-resolve polymorphics and do coercion
4382 : * just like the parser did.
4383 : *
4384 : * This should be a no-op if there are no polymorphic arguments,
4385 : * but we do it anyway to be sure.
4386 : *
4387 : * Note: if any casts are needed, the args list is modified in-place;
4388 : * caller should have already copied the list structure.
4389 : */
4390 : static void
4391 22446 : recheck_cast_function_args(List *args, Oid result_type,
4392 : Oid *proargtypes, int pronargs,
4393 : HeapTuple func_tuple)
4394 : {
4395 22446 : Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4396 : int nargs;
4397 : Oid actual_arg_types[FUNC_MAX_ARGS];
4398 : Oid declared_arg_types[FUNC_MAX_ARGS];
4399 : Oid rettype;
4400 : ListCell *lc;
4401 :
4402 22446 : if (list_length(args) > FUNC_MAX_ARGS)
4403 0 : elog(ERROR, "too many function arguments");
4404 22446 : nargs = 0;
4405 110728 : foreach(lc, args)
4406 : {
4407 88282 : actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4408 : }
4409 : Assert(nargs == pronargs);
4410 22446 : memcpy(declared_arg_types, proargtypes, pronargs * sizeof(Oid));
4411 22446 : rettype = enforce_generic_type_consistency(actual_arg_types,
4412 : declared_arg_types,
4413 : nargs,
4414 : funcform->prorettype,
4415 : false);
4416 : /* let's just check we got the same answer as the parser did ... */
4417 22446 : if (rettype != result_type)
4418 0 : elog(ERROR, "function's resolved result type changed during planning");
4419 :
4420 : /* perform any necessary typecasting of arguments */
4421 22446 : make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4422 22446 : }
4423 :
4424 : /*
4425 : * evaluate_function: try to pre-evaluate a function call
4426 : *
4427 : * We can do this if the function is strict and has any constant-null inputs
4428 : * (just return a null constant), or if the function is immutable and has all
4429 : * constant inputs (call it and return the result as a Const node). In
4430 : * estimation mode we are willing to pre-evaluate stable functions too.
4431 : *
4432 : * Returns a simplified expression if successful, or NULL if cannot
4433 : * simplify the function.
4434 : */
4435 : static Expr *
4436 1254614 : evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
4437 : Oid result_collid, Oid input_collid, List *args,
4438 : bool funcvariadic,
4439 : HeapTuple func_tuple,
4440 : eval_const_expressions_context *context)
4441 : {
4442 1254614 : Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4443 1254614 : bool has_nonconst_input = false;
4444 1254614 : bool has_null_input = false;
4445 : ListCell *arg;
4446 : FuncExpr *newexpr;
4447 :
4448 : /*
4449 : * Can't simplify if it returns a set.
4450 : */
4451 1254614 : if (funcform->proretset)
4452 65388 : return NULL;
4453 :
4454 : /*
4455 : * Can't simplify if it returns RECORD. The immediate problem is that it
4456 : * will be needing an expected tupdesc which we can't supply here.
4457 : *
4458 : * In the case where it has OUT parameters, we could build an expected
4459 : * tupdesc from those, but there may be other gotchas lurking. In
4460 : * particular, if the function were to return NULL, we would produce a
4461 : * null constant with no remaining indication of which concrete record
4462 : * type it is. For now, seems best to leave the function call unreduced.
4463 : */
4464 1189226 : if (funcform->prorettype == RECORDOID)
4465 5044 : return NULL;
4466 :
4467 : /*
4468 : * Check for constant inputs and especially constant-NULL inputs.
4469 : */
4470 3228006 : foreach(arg, args)
4471 : {
4472 2043824 : if (IsA(lfirst(arg), Const))
4473 938976 : has_null_input |= ((Const *) lfirst(arg))->constisnull;
4474 : else
4475 1104848 : has_nonconst_input = true;
4476 : }
4477 :
4478 : /*
4479 : * If the function is strict and has a constant-NULL input, it will never
4480 : * be called at all, so we can replace the call by a NULL constant, even
4481 : * if there are other inputs that aren't constant, and even if the
4482 : * function is not otherwise immutable.
4483 : */
4484 1184182 : if (funcform->proisstrict && has_null_input)
4485 726 : return (Expr *) makeNullConst(result_type, result_typmod,
4486 : result_collid);
4487 :
4488 : /*
4489 : * Otherwise, can simplify only if all inputs are constants. (For a
4490 : * non-strict function, constant NULL inputs are treated the same as
4491 : * constant non-NULL inputs.)
4492 : */
4493 1183456 : if (has_nonconst_input)
4494 853648 : return NULL;
4495 :
4496 : /*
4497 : * Ordinarily we are only allowed to simplify immutable functions. But for
4498 : * purposes of estimation, we consider it okay to simplify functions that
4499 : * are merely stable; the risk that the result might change from planning
4500 : * time to execution time is worth taking in preference to not being able
4501 : * to estimate the value at all.
4502 : */
4503 329808 : if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4504 : /* okay */ ;
4505 151142 : else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4506 : /* okay */ ;
4507 : else
4508 148486 : return NULL;
4509 :
4510 : /*
4511 : * OK, looks like we can simplify this operator/function.
4512 : *
4513 : * Build a new FuncExpr node containing the already-simplified arguments.
4514 : */
4515 181322 : newexpr = makeNode(FuncExpr);
4516 181322 : newexpr->funcid = funcid;
4517 181322 : newexpr->funcresulttype = result_type;
4518 181322 : newexpr->funcretset = false;
4519 181322 : newexpr->funcvariadic = funcvariadic;
4520 181322 : newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4521 181322 : newexpr->funccollid = result_collid; /* doesn't matter */
4522 181322 : newexpr->inputcollid = input_collid;
4523 181322 : newexpr->args = args;
4524 181322 : newexpr->location = -1;
4525 :
4526 181322 : return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4527 : result_collid);
4528 : }
4529 :
4530 : /*
4531 : * inline_function: try to expand a function call inline
4532 : *
4533 : * If the function is a sufficiently simple SQL-language function
4534 : * (just "SELECT expression"), then we can inline it and avoid the rather
4535 : * high per-call overhead of SQL functions. Furthermore, this can expose
4536 : * opportunities for constant-folding within the function expression.
4537 : *
4538 : * We have to beware of some special cases however. A directly or
4539 : * indirectly recursive function would cause us to recurse forever,
4540 : * so we keep track of which functions we are already expanding and
4541 : * do not re-expand them. Also, if a parameter is used more than once
4542 : * in the SQL-function body, we require it not to contain any volatile
4543 : * functions (volatiles might deliver inconsistent answers) nor to be
4544 : * unreasonably expensive to evaluate. The expensiveness check not only
4545 : * prevents us from doing multiple evaluations of an expensive parameter
4546 : * at runtime, but is a safety value to limit growth of an expression due
4547 : * to repeated inlining.
4548 : *
4549 : * We must also beware of changing the volatility or strictness status of
4550 : * functions by inlining them.
4551 : *
4552 : * Also, at the moment we can't inline functions returning RECORD. This
4553 : * doesn't work in the general case because it discards information such
4554 : * as OUT-parameter declarations.
4555 : *
4556 : * Also, context-dependent expression nodes in the argument list are trouble.
4557 : *
4558 : * Returns a simplified expression if successful, or NULL if cannot
4559 : * simplify the function.
4560 : */
4561 : static Expr *
4562 1072440 : inline_function(Oid funcid, Oid result_type, Oid result_collid,
4563 : Oid input_collid, List *args,
4564 : bool funcvariadic,
4565 : HeapTuple func_tuple,
4566 : eval_const_expressions_context *context)
4567 : {
4568 1072440 : Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4569 : char *src;
4570 : Datum tmp;
4571 : bool isNull;
4572 : MemoryContext oldcxt;
4573 : MemoryContext mycxt;
4574 : inline_error_callback_arg callback_arg;
4575 : ErrorContextCallback sqlerrcontext;
4576 : FuncExpr *fexpr;
4577 : SQLFunctionParseInfoPtr pinfo;
4578 : TupleDesc rettupdesc;
4579 : ParseState *pstate;
4580 : List *raw_parsetree_list;
4581 : List *querytree_list;
4582 : Query *querytree;
4583 : Node *newexpr;
4584 : int *usecounts;
4585 : ListCell *arg;
4586 : int i;
4587 :
4588 : /*
4589 : * Forget it if the function is not SQL-language or has other showstopper
4590 : * properties. (The prokind and nargs checks are just paranoia.)
4591 : */
4592 1072440 : if (funcform->prolang != SQLlanguageId ||
4593 8270 : funcform->prokind != PROKIND_FUNCTION ||
4594 8270 : funcform->prosecdef ||
4595 8258 : funcform->proretset ||
4596 6832 : funcform->prorettype == RECORDOID ||
4597 13010 : !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4598 6484 : funcform->pronargs != list_length(args))
4599 1065956 : return NULL;
4600 :
4601 : /* Check for recursive function, and give up trying to expand if so */
4602 6484 : if (list_member_oid(context->active_fns, funcid))
4603 12 : return NULL;
4604 :
4605 : /* Check permission to call function (fail later, if not) */
4606 6472 : if (object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4607 20 : return NULL;
4608 :
4609 : /* Check whether a plugin wants to hook function entry/exit */
4610 6452 : if (FmgrHookIsNeeded(funcid))
4611 0 : return NULL;
4612 :
4613 : /*
4614 : * Make a temporary memory context, so that we don't leak all the stuff
4615 : * that parsing might create.
4616 : */
4617 6452 : mycxt = AllocSetContextCreate(CurrentMemoryContext,
4618 : "inline_function",
4619 : ALLOCSET_DEFAULT_SIZES);
4620 6452 : oldcxt = MemoryContextSwitchTo(mycxt);
4621 :
4622 : /*
4623 : * We need a dummy FuncExpr node containing the already-simplified
4624 : * arguments. (In some cases we don't really need it, but building it is
4625 : * cheap enough that it's not worth contortions to avoid.)
4626 : */
4627 6452 : fexpr = makeNode(FuncExpr);
4628 6452 : fexpr->funcid = funcid;
4629 6452 : fexpr->funcresulttype = result_type;
4630 6452 : fexpr->funcretset = false;
4631 6452 : fexpr->funcvariadic = funcvariadic;
4632 6452 : fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4633 6452 : fexpr->funccollid = result_collid; /* doesn't matter */
4634 6452 : fexpr->inputcollid = input_collid;
4635 6452 : fexpr->args = args;
4636 6452 : fexpr->location = -1;
4637 :
4638 : /* Fetch the function body */
4639 6452 : tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
4640 6452 : src = TextDatumGetCString(tmp);
4641 :
4642 : /*
4643 : * Setup error traceback support for ereport(). This is so that we can
4644 : * finger the function that bad information came from.
4645 : */
4646 6452 : callback_arg.proname = NameStr(funcform->proname);
4647 6452 : callback_arg.prosrc = src;
4648 :
4649 6452 : sqlerrcontext.callback = sql_inline_error_callback;
4650 6452 : sqlerrcontext.arg = &callback_arg;
4651 6452 : sqlerrcontext.previous = error_context_stack;
4652 6452 : error_context_stack = &sqlerrcontext;
4653 :
4654 : /* If we have prosqlbody, pay attention to that not prosrc */
4655 6452 : tmp = SysCacheGetAttr(PROCOID,
4656 : func_tuple,
4657 : Anum_pg_proc_prosqlbody,
4658 : &isNull);
4659 6452 : if (!isNull)
4660 : {
4661 : Node *n;
4662 : List *query_list;
4663 :
4664 3424 : n = stringToNode(TextDatumGetCString(tmp));
4665 3424 : if (IsA(n, List))
4666 2606 : query_list = linitial_node(List, castNode(List, n));
4667 : else
4668 818 : query_list = list_make1(n);
4669 3424 : if (list_length(query_list) != 1)
4670 6 : goto fail;
4671 3418 : querytree = linitial(query_list);
4672 :
4673 : /*
4674 : * Because we'll insist below that the querytree have an empty rtable
4675 : * and no sublinks, it cannot have any relation references that need
4676 : * to be locked or rewritten. So we can omit those steps.
4677 : */
4678 : }
4679 : else
4680 : {
4681 : /* Set up to handle parameters while parsing the function body. */
4682 3028 : pinfo = prepare_sql_fn_parse_info(func_tuple,
4683 : (Node *) fexpr,
4684 : input_collid);
4685 :
4686 : /*
4687 : * We just do parsing and parse analysis, not rewriting, because
4688 : * rewriting will not affect table-free-SELECT-only queries, which is
4689 : * all that we care about. Also, we can punt as soon as we detect
4690 : * more than one command in the function body.
4691 : */
4692 3028 : raw_parsetree_list = pg_parse_query(src);
4693 3028 : if (list_length(raw_parsetree_list) != 1)
4694 58 : goto fail;
4695 :
4696 2970 : pstate = make_parsestate(NULL);
4697 2970 : pstate->p_sourcetext = src;
4698 2970 : sql_fn_parser_setup(pstate, pinfo);
4699 :
4700 2970 : querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4701 :
4702 2964 : free_parsestate(pstate);
4703 : }
4704 :
4705 : /*
4706 : * The single command must be a simple "SELECT expression".
4707 : *
4708 : * Note: if you change the tests involved in this, see also plpgsql's
4709 : * exec_simple_check_plan(). That generally needs to have the same idea
4710 : * of what's a "simple expression", so that inlining a function that
4711 : * previously wasn't inlined won't change plpgsql's conclusion.
4712 : */
4713 6382 : if (!IsA(querytree, Query) ||
4714 6382 : querytree->commandType != CMD_SELECT ||
4715 6262 : querytree->hasAggs ||
4716 6124 : querytree->hasWindowFuncs ||
4717 6124 : querytree->hasTargetSRFs ||
4718 6124 : querytree->hasSubLinks ||
4719 5286 : querytree->cteList ||
4720 5286 : querytree->rtable ||
4721 3456 : querytree->jointree->fromlist ||
4722 3456 : querytree->jointree->quals ||
4723 3456 : querytree->groupClause ||
4724 3456 : querytree->groupingSets ||
4725 3456 : querytree->havingQual ||
4726 3456 : querytree->windowClause ||
4727 3456 : querytree->distinctClause ||
4728 3456 : querytree->sortClause ||
4729 3456 : querytree->limitOffset ||
4730 3456 : querytree->limitCount ||
4731 6772 : querytree->setOperations ||
4732 3386 : list_length(querytree->targetList) != 1)
4733 3056 : goto fail;
4734 :
4735 : /* If the function result is composite, resolve it */
4736 3326 : (void) get_expr_result_type((Node *) fexpr,
4737 : NULL,
4738 : &rettupdesc);
4739 :
4740 : /*
4741 : * Make sure the function (still) returns what it's declared to. This
4742 : * will raise an error if wrong, but that's okay since the function would
4743 : * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4744 : * a coercion if needed to make the tlist expression match the declared
4745 : * type of the function.
4746 : *
4747 : * Note: we do not try this until we have verified that no rewriting was
4748 : * needed; that's probably not important, but let's be careful.
4749 : */
4750 3326 : querytree_list = list_make1(querytree);
4751 3326 : if (check_sql_fn_retval(list_make1(querytree_list),
4752 : result_type, rettupdesc,
4753 3326 : funcform->prokind,
4754 : false))
4755 12 : goto fail; /* reject whole-tuple-result cases */
4756 :
4757 : /*
4758 : * Given the tests above, check_sql_fn_retval shouldn't have decided to
4759 : * inject a projection step, but let's just make sure.
4760 : */
4761 3308 : if (querytree != linitial(querytree_list))
4762 0 : goto fail;
4763 :
4764 : /* Now we can grab the tlist expression */
4765 3308 : newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4766 :
4767 : /*
4768 : * If the SQL function returns VOID, we can only inline it if it is a
4769 : * SELECT of an expression returning VOID (ie, it's just a redirection to
4770 : * another VOID-returning function). In all non-VOID-returning cases,
4771 : * check_sql_fn_retval should ensure that newexpr returns the function's
4772 : * declared result type, so this test shouldn't fail otherwise; but we may
4773 : * as well cope gracefully if it does.
4774 : */
4775 3308 : if (exprType(newexpr) != result_type)
4776 18 : goto fail;
4777 :
4778 : /*
4779 : * Additional validity checks on the expression. It mustn't be more
4780 : * volatile than the surrounding function (this is to avoid breaking hacks
4781 : * that involve pretending a function is immutable when it really ain't).
4782 : * If the surrounding function is declared strict, then the expression
4783 : * must contain only strict constructs and must use all of the function
4784 : * parameters (this is overkill, but an exact analysis is hard).
4785 : */
4786 3996 : if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4787 706 : contain_mutable_functions(newexpr))
4788 12 : goto fail;
4789 4226 : else if (funcform->provolatile == PROVOLATILE_STABLE &&
4790 948 : contain_volatile_functions(newexpr))
4791 0 : goto fail;
4792 :
4793 4940 : if (funcform->proisstrict &&
4794 1662 : contain_nonstrict_functions(newexpr))
4795 46 : goto fail;
4796 :
4797 : /*
4798 : * If any parameter expression contains a context-dependent node, we can't
4799 : * inline, for fear of putting such a node into the wrong context.
4800 : */
4801 3232 : if (contain_context_dependent_node((Node *) args))
4802 6 : goto fail;
4803 :
4804 : /*
4805 : * We may be able to do it; there are still checks on parameter usage to
4806 : * make, but those are most easily done in combination with the actual
4807 : * substitution of the inputs. So start building expression with inputs
4808 : * substituted.
4809 : */
4810 3226 : usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4811 3226 : newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4812 : args, usecounts);
4813 :
4814 : /* Now check for parameter usage */
4815 3226 : i = 0;
4816 8562 : foreach(arg, args)
4817 : {
4818 5336 : Node *param = lfirst(arg);
4819 :
4820 5336 : if (usecounts[i] == 0)
4821 : {
4822 : /* Param not used at all: uncool if func is strict */
4823 288 : if (funcform->proisstrict)
4824 0 : goto fail;
4825 : }
4826 5048 : else if (usecounts[i] != 1)
4827 : {
4828 : /* Param used multiple times: uncool if expensive or volatile */
4829 : QualCost eval_cost;
4830 :
4831 : /*
4832 : * We define "expensive" as "contains any subplan or more than 10
4833 : * operators". Note that the subplan search has to be done
4834 : * explicitly, since cost_qual_eval() will barf on unplanned
4835 : * subselects.
4836 : */
4837 462 : if (contain_subplans(param))
4838 0 : goto fail;
4839 462 : cost_qual_eval(&eval_cost, list_make1(param), NULL);
4840 462 : if (eval_cost.startup + eval_cost.per_tuple >
4841 462 : 10 * cpu_operator_cost)
4842 0 : goto fail;
4843 :
4844 : /*
4845 : * Check volatility last since this is more expensive than the
4846 : * above tests
4847 : */
4848 462 : if (contain_volatile_functions(param))
4849 0 : goto fail;
4850 : }
4851 5336 : i++;
4852 : }
4853 :
4854 : /*
4855 : * Whew --- we can make the substitution. Copy the modified expression
4856 : * out of the temporary memory context, and clean up.
4857 : */
4858 3226 : MemoryContextSwitchTo(oldcxt);
4859 :
4860 3226 : newexpr = copyObject(newexpr);
4861 :
4862 3226 : MemoryContextDelete(mycxt);
4863 :
4864 : /*
4865 : * If the result is of a collatable type, force the result to expose the
4866 : * correct collation. In most cases this does not matter, but it's
4867 : * possible that the function result is used directly as a sort key or in
4868 : * other places where we expect exprCollation() to tell the truth.
4869 : */
4870 3226 : if (OidIsValid(result_collid))
4871 : {
4872 1448 : Oid exprcoll = exprCollation(newexpr);
4873 :
4874 1448 : if (OidIsValid(exprcoll) && exprcoll != result_collid)
4875 : {
4876 36 : CollateExpr *newnode = makeNode(CollateExpr);
4877 :
4878 36 : newnode->arg = (Expr *) newexpr;
4879 36 : newnode->collOid = result_collid;
4880 36 : newnode->location = -1;
4881 :
4882 36 : newexpr = (Node *) newnode;
4883 : }
4884 : }
4885 :
4886 : /*
4887 : * Since there is now no trace of the function in the plan tree, we must
4888 : * explicitly record the plan's dependency on the function.
4889 : */
4890 3226 : if (context->root)
4891 3002 : record_plan_function_dependency(context->root, funcid);
4892 :
4893 : /*
4894 : * Recursively try to simplify the modified expression. Here we must add
4895 : * the current function to the context list of active functions.
4896 : */
4897 3226 : context->active_fns = lappend_oid(context->active_fns, funcid);
4898 3226 : newexpr = eval_const_expressions_mutator(newexpr, context);
4899 3224 : context->active_fns = list_delete_last(context->active_fns);
4900 :
4901 3224 : error_context_stack = sqlerrcontext.previous;
4902 :
4903 3224 : return (Expr *) newexpr;
4904 :
4905 : /* Here if func is not inlinable: release temp memory and return NULL */
4906 3214 : fail:
4907 3214 : MemoryContextSwitchTo(oldcxt);
4908 3214 : MemoryContextDelete(mycxt);
4909 3214 : error_context_stack = sqlerrcontext.previous;
4910 :
4911 3214 : return NULL;
4912 : }
4913 :
4914 : /*
4915 : * Replace Param nodes by appropriate actual parameters
4916 : */
4917 : static Node *
4918 3226 : substitute_actual_parameters(Node *expr, int nargs, List *args,
4919 : int *usecounts)
4920 : {
4921 : substitute_actual_parameters_context context;
4922 :
4923 3226 : context.nargs = nargs;
4924 3226 : context.args = args;
4925 3226 : context.usecounts = usecounts;
4926 :
4927 3226 : return substitute_actual_parameters_mutator(expr, &context);
4928 : }
4929 :
4930 : static Node *
4931 18792 : substitute_actual_parameters_mutator(Node *node,
4932 : substitute_actual_parameters_context *context)
4933 : {
4934 18792 : if (node == NULL)
4935 560 : return NULL;
4936 18232 : if (IsA(node, Param))
4937 : {
4938 5546 : Param *param = (Param *) node;
4939 :
4940 5546 : if (param->paramkind != PARAM_EXTERN)
4941 0 : elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
4942 5546 : if (param->paramid <= 0 || param->paramid > context->nargs)
4943 0 : elog(ERROR, "invalid paramid: %d", param->paramid);
4944 :
4945 : /* Count usage of parameter */
4946 5546 : context->usecounts[param->paramid - 1]++;
4947 :
4948 : /* Select the appropriate actual arg and replace the Param with it */
4949 : /* We don't need to copy at this time (it'll get done later) */
4950 5546 : return list_nth(context->args, param->paramid - 1);
4951 : }
4952 12686 : return expression_tree_mutator(node, substitute_actual_parameters_mutator, context);
4953 : }
4954 :
4955 : /*
4956 : * error context callback to let us supply a call-stack traceback
4957 : */
4958 : static void
4959 20 : sql_inline_error_callback(void *arg)
4960 : {
4961 20 : inline_error_callback_arg *callback_arg = (inline_error_callback_arg *) arg;
4962 : int syntaxerrposition;
4963 :
4964 : /* If it's a syntax error, convert to internal syntax error report */
4965 20 : syntaxerrposition = geterrposition();
4966 20 : if (syntaxerrposition > 0)
4967 : {
4968 6 : errposition(0);
4969 6 : internalerrposition(syntaxerrposition);
4970 6 : internalerrquery(callback_arg->prosrc);
4971 : }
4972 :
4973 20 : errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4974 20 : }
4975 :
4976 : /*
4977 : * evaluate_expr: pre-evaluate a constant expression
4978 : *
4979 : * We use the executor's routine ExecEvalExpr() to avoid duplication of
4980 : * code and ensure we get the same result as the executor would get.
4981 : */
4982 : Expr *
4983 214714 : evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
4984 : Oid result_collation)
4985 : {
4986 : EState *estate;
4987 : ExprState *exprstate;
4988 : MemoryContext oldcontext;
4989 : Datum const_val;
4990 : bool const_is_null;
4991 : int16 resultTypLen;
4992 : bool resultTypByVal;
4993 :
4994 : /*
4995 : * To use the executor, we need an EState.
4996 : */
4997 214714 : estate = CreateExecutorState();
4998 :
4999 : /* We can use the estate's working context to avoid memory leaks. */
5000 214714 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5001 :
5002 : /* Make sure any opfuncids are filled in. */
5003 214714 : fix_opfuncids((Node *) expr);
5004 :
5005 : /*
5006 : * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5007 : * because it'd result in recursively invoking eval_const_expressions.)
5008 : */
5009 214714 : exprstate = ExecInitExpr(expr, NULL);
5010 :
5011 : /*
5012 : * And evaluate it.
5013 : *
5014 : * It is OK to use a default econtext because none of the ExecEvalExpr()
5015 : * code used in this situation will use econtext. That might seem
5016 : * fortuitous, but it's not so unreasonable --- a constant expression does
5017 : * not depend on context, by definition, n'est ce pas?
5018 : */
5019 214690 : const_val = ExecEvalExprSwitchContext(exprstate,
5020 214690 : GetPerTupleExprContext(estate),
5021 : &const_is_null);
5022 :
5023 : /* Get info needed about result datatype */
5024 210848 : get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
5025 :
5026 : /* Get back to outer memory context */
5027 210848 : MemoryContextSwitchTo(oldcontext);
5028 :
5029 : /*
5030 : * Must copy result out of sub-context used by expression eval.
5031 : *
5032 : * Also, if it's varlena, forcibly detoast it. This protects us against
5033 : * storing TOAST pointers into plans that might outlive the referenced
5034 : * data. (makeConst would handle detoasting anyway, but it's worth a few
5035 : * extra lines here so that we can do the copy and detoast in one step.)
5036 : */
5037 210848 : if (!const_is_null)
5038 : {
5039 209354 : if (resultTypLen == -1)
5040 80856 : const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
5041 : else
5042 128498 : const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
5043 : }
5044 :
5045 : /* Release all the junk we just created */
5046 210848 : FreeExecutorState(estate);
5047 :
5048 : /*
5049 : * Make the constant result node.
5050 : */
5051 210848 : return (Expr *) makeConst(result_type, result_typmod, result_collation,
5052 : resultTypLen,
5053 : const_val, const_is_null,
5054 : resultTypByVal);
5055 : }
5056 :
5057 :
5058 : /*
5059 : * inline_set_returning_function
5060 : * Attempt to "inline" a set-returning function in the FROM clause.
5061 : *
5062 : * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
5063 : * set-returning SQL function that can safely be inlined, expand the function
5064 : * and return the substitute Query structure. Otherwise, return NULL.
5065 : *
5066 : * We assume that the RTE's expression has already been put through
5067 : * eval_const_expressions(), which among other things will take care of
5068 : * default arguments and named-argument notation.
5069 : *
5070 : * This has a good deal of similarity to inline_function(), but that's
5071 : * for the non-set-returning case, and there are enough differences to
5072 : * justify separate functions.
5073 : */
5074 : Query *
5075 52328 : inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
5076 : {
5077 : RangeTblFunction *rtfunc;
5078 : FuncExpr *fexpr;
5079 : Oid func_oid;
5080 : HeapTuple func_tuple;
5081 : Form_pg_proc funcform;
5082 : char *src;
5083 : Datum tmp;
5084 : bool isNull;
5085 : MemoryContext oldcxt;
5086 : MemoryContext mycxt;
5087 : inline_error_callback_arg callback_arg;
5088 : ErrorContextCallback sqlerrcontext;
5089 : SQLFunctionParseInfoPtr pinfo;
5090 : TypeFuncClass functypclass;
5091 : TupleDesc rettupdesc;
5092 : List *raw_parsetree_list;
5093 : List *querytree_list;
5094 : Query *querytree;
5095 :
5096 : Assert(rte->rtekind == RTE_FUNCTION);
5097 :
5098 : /*
5099 : * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
5100 : * own FROM clause, since that must cause infinite recursion at runtime.
5101 : * It will cause this code to recurse too, so check for stack overflow.
5102 : * (There's no need to do more.)
5103 : */
5104 52328 : check_stack_depth();
5105 :
5106 : /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5107 52328 : if (rte->funcordinality)
5108 914 : return NULL;
5109 :
5110 : /* Fail if RTE isn't a single, simple FuncExpr */
5111 51414 : if (list_length(rte->functions) != 1)
5112 72 : return NULL;
5113 51342 : rtfunc = (RangeTblFunction *) linitial(rte->functions);
5114 :
5115 51342 : if (!IsA(rtfunc->funcexpr, FuncExpr))
5116 414 : return NULL;
5117 50928 : fexpr = (FuncExpr *) rtfunc->funcexpr;
5118 :
5119 50928 : func_oid = fexpr->funcid;
5120 :
5121 : /*
5122 : * The function must be declared to return a set, else inlining would
5123 : * change the results if the contained SELECT didn't return exactly one
5124 : * row.
5125 : */
5126 50928 : if (!fexpr->funcretset)
5127 8124 : return NULL;
5128 :
5129 : /*
5130 : * Refuse to inline if the arguments contain any volatile functions or
5131 : * sub-selects. Volatile functions are rejected because inlining may
5132 : * result in the arguments being evaluated multiple times, risking a
5133 : * change in behavior. Sub-selects are rejected partly for implementation
5134 : * reasons (pushing them down another level might change their behavior)
5135 : * and partly because they're likely to be expensive and so multiple
5136 : * evaluation would be bad.
5137 : */
5138 85452 : if (contain_volatile_functions((Node *) fexpr->args) ||
5139 42648 : contain_subplans((Node *) fexpr->args))
5140 406 : return NULL;
5141 :
5142 : /* Check permission to call function (fail later, if not) */
5143 42398 : if (object_aclcheck(ProcedureRelationId, func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5144 8 : return NULL;
5145 :
5146 : /* Check whether a plugin wants to hook function entry/exit */
5147 42390 : if (FmgrHookIsNeeded(func_oid))
5148 0 : return NULL;
5149 :
5150 : /*
5151 : * OK, let's take a look at the function's pg_proc entry.
5152 : */
5153 42390 : func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5154 42390 : if (!HeapTupleIsValid(func_tuple))
5155 0 : elog(ERROR, "cache lookup failed for function %u", func_oid);
5156 42390 : funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5157 :
5158 : /*
5159 : * Forget it if the function is not SQL-language or has other showstopper
5160 : * properties. In particular it mustn't be declared STRICT, since we
5161 : * couldn't enforce that. It also mustn't be VOLATILE, because that is
5162 : * supposed to cause it to be executed with its own snapshot, rather than
5163 : * sharing the snapshot of the calling query. We also disallow returning
5164 : * SETOF VOID, because inlining would result in exposing the actual result
5165 : * of the function's last SELECT, which should not happen in that case.
5166 : * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5167 : */
5168 42390 : if (funcform->prolang != SQLlanguageId ||
5169 648 : funcform->prokind != PROKIND_FUNCTION ||
5170 648 : funcform->proisstrict ||
5171 588 : funcform->provolatile == PROVOLATILE_VOLATILE ||
5172 234 : funcform->prorettype == VOIDOID ||
5173 228 : funcform->prosecdef ||
5174 228 : !funcform->proretset ||
5175 228 : list_length(fexpr->args) != funcform->pronargs ||
5176 228 : !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5177 : {
5178 42162 : ReleaseSysCache(func_tuple);
5179 42162 : return NULL;
5180 : }
5181 :
5182 : /*
5183 : * Make a temporary memory context, so that we don't leak all the stuff
5184 : * that parsing might create.
5185 : */
5186 228 : mycxt = AllocSetContextCreate(CurrentMemoryContext,
5187 : "inline_set_returning_function",
5188 : ALLOCSET_DEFAULT_SIZES);
5189 228 : oldcxt = MemoryContextSwitchTo(mycxt);
5190 :
5191 : /* Fetch the function body */
5192 228 : tmp = SysCacheGetAttrNotNull(PROCOID, func_tuple, Anum_pg_proc_prosrc);
5193 228 : src = TextDatumGetCString(tmp);
5194 :
5195 : /*
5196 : * Setup error traceback support for ereport(). This is so that we can
5197 : * finger the function that bad information came from.
5198 : */
5199 228 : callback_arg.proname = NameStr(funcform->proname);
5200 228 : callback_arg.prosrc = src;
5201 :
5202 228 : sqlerrcontext.callback = sql_inline_error_callback;
5203 228 : sqlerrcontext.arg = &callback_arg;
5204 228 : sqlerrcontext.previous = error_context_stack;
5205 228 : error_context_stack = &sqlerrcontext;
5206 :
5207 : /* If we have prosqlbody, pay attention to that not prosrc */
5208 228 : tmp = SysCacheGetAttr(PROCOID,
5209 : func_tuple,
5210 : Anum_pg_proc_prosqlbody,
5211 : &isNull);
5212 228 : if (!isNull)
5213 : {
5214 : Node *n;
5215 :
5216 12 : n = stringToNode(TextDatumGetCString(tmp));
5217 12 : if (IsA(n, List))
5218 12 : querytree_list = linitial_node(List, castNode(List, n));
5219 : else
5220 0 : querytree_list = list_make1(n);
5221 12 : if (list_length(querytree_list) != 1)
5222 0 : goto fail;
5223 12 : querytree = linitial(querytree_list);
5224 :
5225 : /* Acquire necessary locks, then apply rewriter. */
5226 12 : AcquireRewriteLocks(querytree, true, false);
5227 12 : querytree_list = pg_rewrite_query(querytree);
5228 12 : if (list_length(querytree_list) != 1)
5229 0 : goto fail;
5230 12 : querytree = linitial(querytree_list);
5231 : }
5232 : else
5233 : {
5234 : /*
5235 : * Set up to handle parameters while parsing the function body. We
5236 : * can use the FuncExpr just created as the input for
5237 : * prepare_sql_fn_parse_info.
5238 : */
5239 216 : pinfo = prepare_sql_fn_parse_info(func_tuple,
5240 : (Node *) fexpr,
5241 : fexpr->inputcollid);
5242 :
5243 : /*
5244 : * Parse, analyze, and rewrite (unlike inline_function(), we can't
5245 : * skip rewriting here). We can fail as soon as we find more than one
5246 : * query, though.
5247 : */
5248 216 : raw_parsetree_list = pg_parse_query(src);
5249 216 : if (list_length(raw_parsetree_list) != 1)
5250 0 : goto fail;
5251 :
5252 216 : querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
5253 : src,
5254 : (ParserSetupHook) sql_fn_parser_setup,
5255 : pinfo, NULL);
5256 216 : if (list_length(querytree_list) != 1)
5257 0 : goto fail;
5258 216 : querytree = linitial(querytree_list);
5259 : }
5260 :
5261 : /*
5262 : * Also resolve the actual function result tupdesc, if composite. If we
5263 : * have a coldeflist, believe that; otherwise use get_expr_result_type.
5264 : * (This logic should match ExecInitFunctionScan.)
5265 : */
5266 228 : if (rtfunc->funccolnames != NIL)
5267 : {
5268 24 : functypclass = TYPEFUNC_RECORD;
5269 24 : rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5270 24 : rtfunc->funccoltypes,
5271 24 : rtfunc->funccoltypmods,
5272 24 : rtfunc->funccolcollations);
5273 : }
5274 : else
5275 204 : functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5276 :
5277 : /*
5278 : * The single command must be a plain SELECT.
5279 : */
5280 228 : if (!IsA(querytree, Query) ||
5281 228 : querytree->commandType != CMD_SELECT)
5282 0 : goto fail;
5283 :
5284 : /*
5285 : * Make sure the function (still) returns what it's declared to. This
5286 : * will raise an error if wrong, but that's okay since the function would
5287 : * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5288 : * coercions if needed to make the tlist expression(s) match the declared
5289 : * type of the function. We also ask it to insert dummy NULL columns for
5290 : * any dropped columns in rettupdesc, so that the elements of the modified
5291 : * tlist match up to the attribute numbers.
5292 : *
5293 : * If the function returns a composite type, don't inline unless the check
5294 : * shows it's returning a whole tuple result; otherwise what it's
5295 : * returning is a single composite column which is not what we need.
5296 : */
5297 228 : if (!check_sql_fn_retval(list_make1(querytree_list),
5298 : fexpr->funcresulttype, rettupdesc,
5299 228 : funcform->prokind,
5300 90 : true) &&
5301 90 : (functypclass == TYPEFUNC_COMPOSITE ||
5302 90 : functypclass == TYPEFUNC_COMPOSITE_DOMAIN ||
5303 : functypclass == TYPEFUNC_RECORD))
5304 0 : goto fail; /* reject not-whole-tuple-result cases */
5305 :
5306 : /*
5307 : * check_sql_fn_retval might've inserted a projection step, but that's
5308 : * fine; just make sure we use the upper Query.
5309 : */
5310 222 : querytree = linitial_node(Query, querytree_list);
5311 :
5312 : /*
5313 : * Looks good --- substitute parameters into the query.
5314 : */
5315 222 : querytree = substitute_actual_srf_parameters(querytree,
5316 222 : funcform->pronargs,
5317 : fexpr->args);
5318 :
5319 : /*
5320 : * Copy the modified query out of the temporary memory context, and clean
5321 : * up.
5322 : */
5323 222 : MemoryContextSwitchTo(oldcxt);
5324 :
5325 222 : querytree = copyObject(querytree);
5326 :
5327 222 : MemoryContextDelete(mycxt);
5328 222 : error_context_stack = sqlerrcontext.previous;
5329 222 : ReleaseSysCache(func_tuple);
5330 :
5331 : /*
5332 : * We don't have to fix collations here because the upper query is already
5333 : * parsed, ie, the collations in the RTE are what count.
5334 : */
5335 :
5336 : /*
5337 : * Since there is now no trace of the function in the plan tree, we must
5338 : * explicitly record the plan's dependency on the function.
5339 : */
5340 222 : record_plan_function_dependency(root, func_oid);
5341 :
5342 : /*
5343 : * We must also notice if the inserted query adds a dependency on the
5344 : * calling role due to RLS quals.
5345 : */
5346 222 : if (querytree->hasRowSecurity)
5347 72 : root->glob->dependsOnRole = true;
5348 :
5349 222 : return querytree;
5350 :
5351 : /* Here if func is not inlinable: release temp memory and return NULL */
5352 0 : fail:
5353 0 : MemoryContextSwitchTo(oldcxt);
5354 0 : MemoryContextDelete(mycxt);
5355 0 : error_context_stack = sqlerrcontext.previous;
5356 0 : ReleaseSysCache(func_tuple);
5357 :
5358 0 : return NULL;
5359 : }
5360 :
5361 : /*
5362 : * Replace Param nodes by appropriate actual parameters
5363 : *
5364 : * This is just enough different from substitute_actual_parameters()
5365 : * that it needs its own code.
5366 : */
5367 : static Query *
5368 222 : substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
5369 : {
5370 : substitute_actual_srf_parameters_context context;
5371 :
5372 222 : context.nargs = nargs;
5373 222 : context.args = args;
5374 222 : context.sublevels_up = 1;
5375 :
5376 222 : return query_tree_mutator(expr,
5377 : substitute_actual_srf_parameters_mutator,
5378 : &context,
5379 : 0);
5380 : }
5381 :
5382 : static Node *
5383 8346 : substitute_actual_srf_parameters_mutator(Node *node,
5384 : substitute_actual_srf_parameters_context *context)
5385 : {
5386 : Node *result;
5387 :
5388 8346 : if (node == NULL)
5389 4680 : return NULL;
5390 3666 : if (IsA(node, Query))
5391 : {
5392 150 : context->sublevels_up++;
5393 150 : result = (Node *) query_tree_mutator((Query *) node,
5394 : substitute_actual_srf_parameters_mutator,
5395 : context,
5396 : 0);
5397 150 : context->sublevels_up--;
5398 150 : return result;
5399 : }
5400 3516 : if (IsA(node, Param))
5401 : {
5402 102 : Param *param = (Param *) node;
5403 :
5404 102 : if (param->paramkind == PARAM_EXTERN)
5405 : {
5406 102 : if (param->paramid <= 0 || param->paramid > context->nargs)
5407 0 : elog(ERROR, "invalid paramid: %d", param->paramid);
5408 :
5409 : /*
5410 : * Since the parameter is being inserted into a subquery, we must
5411 : * adjust levels.
5412 : */
5413 102 : result = copyObject(list_nth(context->args, param->paramid - 1));
5414 102 : IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5415 102 : return result;
5416 : }
5417 : }
5418 3414 : return expression_tree_mutator(node,
5419 : substitute_actual_srf_parameters_mutator,
5420 : context);
5421 : }
5422 :
5423 : /*
5424 : * pull_paramids
5425 : * Returns a Bitmapset containing the paramids of all Params in 'expr'.
5426 : */
5427 : Bitmapset *
5428 1914 : pull_paramids(Expr *expr)
5429 : {
5430 1914 : Bitmapset *result = NULL;
5431 :
5432 1914 : (void) pull_paramids_walker((Node *) expr, &result);
5433 :
5434 1914 : return result;
5435 : }
5436 :
5437 : static bool
5438 4280 : pull_paramids_walker(Node *node, Bitmapset **context)
5439 : {
5440 4280 : if (node == NULL)
5441 22 : return false;
5442 4258 : if (IsA(node, Param))
5443 : {
5444 1976 : Param *param = (Param *) node;
5445 :
5446 1976 : *context = bms_add_member(*context, param->paramid);
5447 1976 : return false;
5448 : }
5449 2282 : return expression_tree_walker(node, pull_paramids_walker, context);
5450 : }
5451 :
5452 : /*
5453 : * Build ScalarArrayOpExpr on top of 'exprs.' 'haveNonConst' indicates
5454 : * whether at least one of the expressions is not Const. When it's false,
5455 : * the array constant is built directly; otherwise, we have to build a child
5456 : * ArrayExpr. The 'exprs' list gets freed if not directly used in the output
5457 : * expression tree.
5458 : */
5459 : ScalarArrayOpExpr *
5460 1134 : make_SAOP_expr(Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid,
5461 : Oid inputcollid, List *exprs, bool haveNonConst)
5462 : {
5463 1134 : Node *arrayNode = NULL;
5464 1134 : ScalarArrayOpExpr *saopexpr = NULL;
5465 1134 : Oid arraytype = get_array_type(coltype);
5466 :
5467 1134 : if (!OidIsValid(arraytype))
5468 0 : return NULL;
5469 :
5470 : /*
5471 : * Assemble an array from the list of constants. It seems more profitable
5472 : * to build a const array. But in the presence of other nodes, we don't
5473 : * have a specific value here and must employ an ArrayExpr instead.
5474 : */
5475 1134 : if (haveNonConst)
5476 : {
5477 96 : ArrayExpr *arrayExpr = makeNode(ArrayExpr);
5478 :
5479 : /* array_collid will be set by parse_collate.c */
5480 96 : arrayExpr->element_typeid = coltype;
5481 96 : arrayExpr->array_typeid = arraytype;
5482 96 : arrayExpr->multidims = false;
5483 96 : arrayExpr->elements = exprs;
5484 96 : arrayExpr->location = -1;
5485 :
5486 96 : arrayNode = (Node *) arrayExpr;
5487 : }
5488 : else
5489 : {
5490 : int16 typlen;
5491 : bool typbyval;
5492 : char typalign;
5493 : Datum *elems;
5494 : bool *nulls;
5495 1038 : int i = 0;
5496 : ArrayType *arrayConst;
5497 1038 : int dims[1] = {list_length(exprs)};
5498 1038 : int lbs[1] = {1};
5499 :
5500 1038 : get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5501 :
5502 1038 : elems = (Datum *) palloc(sizeof(Datum) * list_length(exprs));
5503 1038 : nulls = (bool *) palloc(sizeof(bool) * list_length(exprs));
5504 4638 : foreach_node(Const, value, exprs)
5505 : {
5506 2562 : elems[i] = value->constvalue;
5507 2562 : nulls[i++] = value->constisnull;
5508 : }
5509 :
5510 1038 : arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5511 : coltype, typlen, typbyval, typalign);
5512 1038 : arrayNode = (Node *) makeConst(arraytype, -1, arraycollid,
5513 : -1, PointerGetDatum(arrayConst),
5514 : false, false);
5515 :
5516 1038 : pfree(elems);
5517 1038 : pfree(nulls);
5518 1038 : list_free(exprs);
5519 : }
5520 :
5521 : /* Build the SAOP expression node */
5522 1134 : saopexpr = makeNode(ScalarArrayOpExpr);
5523 1134 : saopexpr->opno = oper;
5524 1134 : saopexpr->opfuncid = get_opcode(oper);
5525 1134 : saopexpr->hashfuncid = InvalidOid;
5526 1134 : saopexpr->negfuncid = InvalidOid;
5527 1134 : saopexpr->useOr = true;
5528 1134 : saopexpr->inputcollid = inputcollid;
5529 1134 : saopexpr->args = list_make2(leftexpr, arrayNode);
5530 1134 : saopexpr->location = -1;
5531 :
5532 1134 : return saopexpr;
5533 : }
|