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