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