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