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