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