Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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