Debian Codegraph @

src/backend/optimizer/util/clauses.c

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