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