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