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