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