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