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