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