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