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