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