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