| 1 |
/*------------------------------------------------------------------------- |
| 2 |
* |
| 3 |
* prepjointree.c |
| 4 |
* Planner preprocessing for subqueries and join tree manipulation. |
| 5 |
* |
| 6 |
* NOTE: the intended sequence for invoking these operations is |
| 7 |
* replace_empty_jointree |
| 8 |
* pull_up_sublinks |
| 9 |
* preprocess_function_rtes |
| 10 |
* expand_virtual_generated_columns |
| 11 |
* pull_up_subqueries |
| 12 |
* flatten_simple_union_all |
| 13 |
* do expression preprocessing (including flattening JOIN alias vars) |
| 14 |
* reduce_outer_joins |
| 15 |
* remove_useless_result_rtes |
| 16 |
* |
| 17 |
* |
| 18 |
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
| 19 |
* Portions Copyright (c) 1994, Regents of the University of California |
| 20 |
* |
| 21 |
* |
| 22 |
* IDENTIFICATION |
| 23 |
* src/backend/optimizer/prep/prepjointree.c |
| 24 |
* |
| 25 |
*------------------------------------------------------------------------- |
| 26 |
*/ |
| 27 |
#include "postgres.h" |
| 28 |
|
| 29 |
#include "access/table.h" |
| 30 |
#include "catalog/pg_type.h" |
| 31 |
#include "funcapi.h" |
| 32 |
#include "miscadmin.h" |
| 33 |
#include "nodes/makefuncs.h" |
| 34 |
#include "nodes/multibitmapset.h" |
| 35 |
#include "nodes/nodeFuncs.h" |
| 36 |
#include "optimizer/clauses.h" |
| 37 |
#include "optimizer/optimizer.h" |
| 38 |
#include "optimizer/placeholder.h" |
| 39 |
#include "optimizer/prep.h" |
| 40 |
#include "optimizer/subselect.h" |
| 41 |
#include "optimizer/tlist.h" |
| 42 |
#include "parser/parse_relation.h" |
| 43 |
#include "parser/parsetree.h" |
| 44 |
#include "rewrite/rewriteHandler.h" |
| 45 |
#include "rewrite/rewriteManip.h" |
| 46 |
#include "utils/rel.h" |
| 47 |
|
| 48 |
|
| 49 |
typedef struct nullingrel_info |
| 50 |
{ |
| 51 |
/* |
| 52 |
* For each leaf RTE, nullingrels[rti] is the set of relids of outer joins |
| 53 |
* that potentially null that RTE. |
| 54 |
*/ |
| 55 |
Relids *nullingrels; |
| 56 |
/* Length of range table (maximum index in nullingrels[]) */ |
| 57 |
int rtlength; /* used only for assertion checks */ |
| 58 |
} nullingrel_info; |
| 59 |
|
| 60 |
/* Options for wrapping an expression for identification purposes */ |
| 61 |
typedef enum ReplaceWrapOption |
| 62 |
{ |
| 63 |
REPLACE_WRAP_NONE, /* no expressions need to be wrapped */ |
| 64 |
REPLACE_WRAP_ALL, /* all expressions need to be wrapped */ |
| 65 |
REPLACE_WRAP_VARFREE, /* variable-free expressions need to be |
| 66 |
* wrapped */ |
| 67 |
} ReplaceWrapOption; |
| 68 |
|
| 69 |
typedef struct pullup_replace_vars_context |
| 70 |
{ |
| 71 |
PlannerInfo *root; |
| 72 |
List *targetlist; /* tlist of subquery being pulled up */ |
| 73 |
RangeTblEntry *target_rte; /* RTE of subquery */ |
| 74 |
int result_relation; /* the index of the result relation in the |
| 75 |
* rewritten query */ |
| 76 |
Relids relids; /* relids within subquery, as numbered after |
| 77 |
* pullup (set only if target_rte->lateral) */ |
| 78 |
nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if |
| 79 |
* target_rte->lateral) */ |
| 80 |
bool *outer_hasSubLinks; /* -> outer query's hasSubLinks */ |
| 81 |
int varno; /* varno of subquery */ |
| 82 |
ReplaceWrapOption wrap_option; /* do we need certain outputs to be PHVs? */ |
| 83 |
Node **rv_cache; /* cache for results with PHVs */ |
| 84 |
} pullup_replace_vars_context; |
| 85 |
|
| 86 |
typedef struct reduce_outer_joins_pass1_state |
| 87 |
{ |
| 88 |
Relids relids; /* base relids within this subtree */ |
| 89 |
bool contains_outer; /* does subtree contain outer join(s)? */ |
| 90 |
List *sub_states; /* List of states for subtree components */ |
| 91 |
} reduce_outer_joins_pass1_state; |
| 92 |
|
| 93 |
typedef struct reduce_outer_joins_pass2_state |
| 94 |
{ |
| 95 |
Relids inner_reduced; /* OJ relids reduced to plain inner joins */ |
| 96 |
List *partial_reduced; /* List of partially reduced FULL joins */ |
| 97 |
} reduce_outer_joins_pass2_state; |
| 98 |
|
| 99 |
typedef struct reduce_outer_joins_partial_state |
| 100 |
{ |
| 101 |
int full_join_rti; /* RT index of a formerly-FULL join */ |
| 102 |
Relids unreduced_side; /* relids in its still-nullable side */ |
| 103 |
} reduce_outer_joins_partial_state; |
| 104 |
|
| 105 |
static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode, |
| 106 |
Relids *relids); |
| 107 |
static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node, |
| 108 |
Node **jtlink1, Relids available_rels1, |
| 109 |
Node **jtlink2, Relids available_rels2); |
| 110 |
static Node *pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode, |
| 111 |
JoinExpr *lowest_outer_join, |
| 112 |
AppendRelInfo *containing_appendrel); |
| 113 |
static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, |
| 114 |
RangeTblEntry *rte, |
| 115 |
JoinExpr *lowest_outer_join, |
| 116 |
AppendRelInfo *containing_appendrel); |
| 117 |
static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, |
| 118 |
RangeTblEntry *rte); |
| 119 |
static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, |
| 120 |
int parentRTindex, Query *setOpQuery, |
| 121 |
int childRToffset); |
| 122 |
static void make_setop_translation_list(Query *query, int newvarno, |
| 123 |
AppendRelInfo *appinfo); |
| 124 |
static bool is_simple_subquery(PlannerInfo *root, Query *subquery, |
| 125 |
RangeTblEntry *rte, |
| 126 |
JoinExpr *lowest_outer_join); |
| 127 |
static Node *pull_up_simple_values(PlannerInfo *root, Node *jtnode, |
| 128 |
RangeTblEntry *rte); |
| 129 |
static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte); |
| 130 |
static Node *pull_up_constant_function(PlannerInfo *root, Node *jtnode, |
| 131 |
RangeTblEntry *rte, |
| 132 |
AppendRelInfo *containing_appendrel); |
| 133 |
static bool is_simple_union_all(Query *subquery); |
| 134 |
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, |
| 135 |
List *colTypes); |
| 136 |
static bool is_safe_append_member(Query *subquery); |
| 137 |
static bool jointree_contains_lateral_outer_refs(PlannerInfo *root, |
| 138 |
Node *jtnode, bool restricted, |
| 139 |
Relids safe_upper_varnos); |
| 140 |
static void perform_pullup_replace_vars(PlannerInfo *root, |
| 141 |
pullup_replace_vars_context *rvcontext, |
| 142 |
AppendRelInfo *containing_appendrel); |
| 143 |
static void replace_vars_in_jointree(Node *jtnode, |
| 144 |
pullup_replace_vars_context *context); |
| 145 |
static Node *pullup_replace_vars(Node *expr, |
| 146 |
pullup_replace_vars_context *context); |
| 147 |
static Node *pullup_replace_vars_callback(Var *var, |
| 148 |
replace_rte_variables_context *context); |
| 149 |
static Query *pullup_replace_vars_subquery(Query *query, |
| 150 |
pullup_replace_vars_context *context); |
| 151 |
static reduce_outer_joins_pass1_state *reduce_outer_joins_pass1(Node *jtnode); |
| 152 |
static void reduce_outer_joins_pass2(Node *jtnode, |
| 153 |
reduce_outer_joins_pass1_state *state1, |
| 154 |
reduce_outer_joins_pass2_state *state2, |
| 155 |
PlannerInfo *root, |
| 156 |
Relids nonnullable_rels, |
| 157 |
List *forced_null_vars); |
| 158 |
static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2, |
| 159 |
int rtindex, Relids relids); |
| 160 |
static Node *remove_useless_results_recurse(PlannerInfo *root, Node *jtnode, |
| 161 |
Relids baserels, |
| 162 |
Node **parent_quals, |
| 163 |
Relids *dropped_outer_joins); |
| 164 |
static int get_result_relid(PlannerInfo *root, Node *jtnode); |
| 165 |
static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc); |
| 166 |
static bool find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels); |
| 167 |
static bool find_dependent_phvs_in_jointree(PlannerInfo *root, |
| 168 |
Node *node, int varno, |
| 169 |
Relids baserels); |
| 170 |
static void substitute_phv_relids(Node *node, |
| 171 |
int varno, Relids subrelids); |
| 172 |
static void fix_append_rel_relids(PlannerInfo *root, int varno, |
| 173 |
Relids subrelids); |
| 174 |
static Node *find_jointree_node_for_rel(Node *jtnode, int relid); |
| 175 |
static nullingrel_info *get_nullingrels(Query *parse); |
| 176 |
static void get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels, |
| 177 |
nullingrel_info *info); |
| 178 |
|
| 179 |
|
| 180 |
/* |
| 181 |
* transform_MERGE_to_join |
| 182 |
* Replace a MERGE's jointree to also include the target relation. |
| 183 |
*/ |
| 184 |
void |
| 185 |
transform_MERGE_to_join(Query *parse) |
| 186 |
{ |
| 187 |
RangeTblEntry *joinrte; |
| 188 |
JoinExpr *joinexpr; |
| 189 |
bool have_action[NUM_MERGE_MATCH_KINDS]; |
| 190 |
JoinType jointype; |
| 191 |
int joinrti; |
| 192 |
List *vars; |
| 193 |
RangeTblRef *rtr; |
| 194 |
FromExpr *target; |
| 195 |
Node *source; |
| 196 |
int sourcerti; |
| 197 |
|
| 198 |
if (parse->commandType != CMD_MERGE) |
| 199 |
return; |
| 200 |
|
| 201 |
/* XXX probably bogus */ |
| 202 |
vars = NIL; |
| 203 |
|
| 204 |
/* |
| 205 |
* Work out what kind of join is required. If there any WHEN NOT MATCHED |
| 206 |
* BY SOURCE/TARGET actions, an outer join is required so that we process |
| 207 |
* all unmatched tuples from the source and/or target relations. |
| 208 |
* Otherwise, we can use an inner join. |
| 209 |
*/ |
| 210 |
have_action[MERGE_WHEN_MATCHED] = false; |
| 211 |
have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = false; |
| 212 |
have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = false; |
| 213 |
|
| 214 |
foreach_node(MergeAction, action, parse->mergeActionList) |
| 215 |
{ |
| 216 |
if (action->commandType != CMD_NOTHING) |
| 217 |
have_action[action->matchKind] = true; |
| 218 |
} |
| 219 |
|
| 220 |
if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] && |
| 221 |
have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET]) |
| 222 |
jointype = JOIN_FULL; |
| 223 |
else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE]) |
| 224 |
jointype = JOIN_LEFT; |
| 225 |
else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET]) |
| 226 |
jointype = JOIN_RIGHT; |
| 227 |
else |
| 228 |
jointype = JOIN_INNER; |
| 229 |
|
| 230 |
/* Manufacture a join RTE to use. */ |
| 231 |
joinrte = makeNode(RangeTblEntry); |
| 232 |
joinrte->rtekind = RTE_JOIN; |
| 233 |
joinrte->jointype = jointype; |
| 234 |
joinrte->joinmergedcols = 0; |
| 235 |
joinrte->joinaliasvars = vars; |
| 236 |
joinrte->joinleftcols = NIL; /* MERGE does not allow JOIN USING */ |
| 237 |
joinrte->joinrightcols = NIL; /* ditto */ |
| 238 |
joinrte->join_using_alias = NULL; |
| 239 |
|
| 240 |
joinrte->alias = NULL; |
| 241 |
joinrte->eref = makeAlias("*MERGE*", NIL); |
| 242 |
joinrte->lateral = false; |
| 243 |
joinrte->inh = false; |
| 244 |
joinrte->inFromCl = true; |
| 245 |
|
| 246 |
/* |
| 247 |
* Add completed RTE to pstate's range table list, so that we know its |
| 248 |
* index. |
| 249 |
*/ |
| 250 |
parse->rtable = lappend(parse->rtable, joinrte); |
| 251 |
joinrti = list_length(parse->rtable); |
| 252 |
|
| 253 |
/* |
| 254 |
* Create a JOIN between the target and the source relation. |
| 255 |
* |
| 256 |
* Here the target is identified by parse->mergeTargetRelation. For a |
| 257 |
* regular table, this will equal parse->resultRelation, but for a |
| 258 |
* trigger-updatable view, it will be the expanded view subquery that we |
| 259 |
* need to pull data from. |
| 260 |
* |
| 261 |
* The source relation is in parse->jointree->fromlist, but any quals in |
| 262 |
* parse->jointree->quals are restrictions on the target relation (if the |
| 263 |
* target relation is an auto-updatable view). |
| 264 |
*/ |
| 265 |
/* target rel, with any quals */ |
| 266 |
rtr = makeNode(RangeTblRef); |
| 267 |
rtr->rtindex = parse->mergeTargetRelation; |
| 268 |
target = makeFromExpr(list_make1(rtr), parse->jointree->quals); |
| 269 |
|
| 270 |
/* source rel (expect exactly one -- see transformMergeStmt()) */ |
| 271 |
Assert(list_length(parse->jointree->fromlist) == 1); |
| 272 |
source = linitial(parse->jointree->fromlist); |
| 273 |
|
| 274 |
/* |
| 275 |
* index of source rel (expect either a RangeTblRef or a JoinExpr -- see |
| 276 |
* transformFromClauseItem()). |
| 277 |
*/ |
| 278 |
if (IsA(source, RangeTblRef)) |
| 279 |
sourcerti = ((RangeTblRef *) source)->rtindex; |
| 280 |
else if (IsA(source, JoinExpr)) |
| 281 |
sourcerti = ((JoinExpr *) source)->rtindex; |
| 282 |
else |
| 283 |
{ |
| 284 |
elog(ERROR, "unrecognized source node type: %d", |
| 285 |
(int) nodeTag(source)); |
| 286 |
sourcerti = 0; /* keep compiler quiet */ |
| 287 |
} |
| 288 |
|
| 289 |
/* Join the source and target */ |
| 290 |
joinexpr = makeNode(JoinExpr); |
| 291 |
joinexpr->jointype = jointype; |
| 292 |
joinexpr->isNatural = false; |
| 293 |
joinexpr->larg = (Node *) target; |
| 294 |
joinexpr->rarg = source; |
| 295 |
joinexpr->usingClause = NIL; |
| 296 |
joinexpr->join_using_alias = NULL; |
| 297 |
joinexpr->quals = parse->mergeJoinCondition; |
| 298 |
joinexpr->alias = NULL; |
| 299 |
joinexpr->rtindex = joinrti; |
| 300 |
|
| 301 |
/* Make the new join be the sole entry in the query's jointree */ |
| 302 |
parse->jointree->fromlist = list_make1(joinexpr); |
| 303 |
parse->jointree->quals = NULL; |
| 304 |
|
| 305 |
/* |
| 306 |
* If necessary, mark parse->targetlist entries that refer to the target |
| 307 |
* as nullable by the join. Normally the targetlist will be empty for a |
| 308 |
* MERGE, but if the target is a trigger-updatable view, it will contain a |
| 309 |
* whole-row Var referring to the expanded view query. |
| 310 |
*/ |
| 311 |
if (parse->targetList != NIL && |
| 312 |
(jointype == JOIN_RIGHT || jointype == JOIN_FULL)) |
| 313 |
parse->targetList = (List *) |
| 314 |
add_nulling_relids((Node *) parse->targetList, |
| 315 |
bms_make_singleton(parse->mergeTargetRelation), |
| 316 |
bms_make_singleton(joinrti)); |
| 317 |
|
| 318 |
/* |
| 319 |
* If the source relation is on the outer side of the join, mark any |
| 320 |
* source relation Vars in the join condition, actions, and RETURNING list |
| 321 |
* as nullable by the join. These Vars will be added to the targetlist by |
| 322 |
* preprocess_targetlist(), so it's important to mark them correctly here. |
| 323 |
* |
| 324 |
* It might seem that this is not necessary for Vars in the join |
| 325 |
* condition, since it is inside the join, but it is also needed above the |
| 326 |
* join (in the ModifyTable node) to distinguish between the MATCHED and |
| 327 |
* NOT MATCHED BY SOURCE cases -- see ExecMergeMatched(). Note that this |
| 328 |
* creates a modified copy of the join condition, for use above the join, |
| 329 |
* without modifying the original join condition, inside the join. |
| 330 |
*/ |
| 331 |
if (jointype == JOIN_LEFT || jointype == JOIN_FULL) |
| 332 |
{ |
| 333 |
parse->mergeJoinCondition = |
| 334 |
add_nulling_relids(parse->mergeJoinCondition, |
| 335 |
bms_make_singleton(sourcerti), |
| 336 |
bms_make_singleton(joinrti)); |
| 337 |
|
| 338 |
foreach_node(MergeAction, action, parse->mergeActionList) |
| 339 |
{ |
| 340 |
action->qual = |
| 341 |
add_nulling_relids(action->qual, |
| 342 |
bms_make_singleton(sourcerti), |
| 343 |
bms_make_singleton(joinrti)); |
| 344 |
|
| 345 |
action->targetList = (List *) |
| 346 |
add_nulling_relids((Node *) action->targetList, |
| 347 |
bms_make_singleton(sourcerti), |
| 348 |
bms_make_singleton(joinrti)); |
| 349 |
} |
| 350 |
|
| 351 |
parse->returningList = (List *) |
| 352 |
add_nulling_relids((Node *) parse->returningList, |
| 353 |
bms_make_singleton(sourcerti), |
| 354 |
bms_make_singleton(joinrti)); |
| 355 |
} |
| 356 |
|
| 357 |
/* |
| 358 |
* If there are any WHEN NOT MATCHED BY SOURCE actions, the executor will |
| 359 |
* use the join condition to distinguish between MATCHED and NOT MATCHED |
| 360 |
* BY SOURCE cases. Otherwise, it's no longer needed, and we set it to |
| 361 |
* NULL, saving cycles during planning and execution. |
| 362 |
* |
| 363 |
* We need to be careful though: the executor evaluates this condition |
| 364 |
* using the output of the join subplan node, which nulls the output from |
| 365 |
* the source relation when the join condition doesn't match. That risks |
| 366 |
* producing incorrect results when rechecking using a "non-strict" join |
| 367 |
* condition, such as "src.col IS NOT DISTINCT FROM tgt.col". To guard |
| 368 |
* against that, we add an additional "src IS NOT NULL" check to the join |
| 369 |
* condition, so that it does the right thing when performing a recheck |
| 370 |
* based on the output of the join subplan. |
| 371 |
*/ |
| 372 |
if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE]) |
| 373 |
{ |
| 374 |
Var *var; |
| 375 |
NullTest *ntest; |
| 376 |
|
| 377 |
/* source wholerow Var (nullable by the new join) */ |
| 378 |
var = makeWholeRowVar(rt_fetch(sourcerti, parse->rtable), |
| 379 |
sourcerti, 0, false); |
| 380 |
var->varnullingrels = bms_make_singleton(joinrti); |
| 381 |
|
| 382 |
/* "src IS NOT NULL" check */ |
| 383 |
ntest = makeNode(NullTest); |
| 384 |
ntest->arg = (Expr *) var; |
| 385 |
ntest->nulltesttype = IS_NOT_NULL; |
| 386 |
ntest->argisrow = false; |
| 387 |
ntest->location = -1; |
| 388 |
|
| 389 |
/* combine it with the original join condition */ |
| 390 |
parse->mergeJoinCondition = |
| 391 |
(Node *) make_and_qual((Node *) ntest, parse->mergeJoinCondition); |
| 392 |
} |
| 393 |
else |
| 394 |
parse->mergeJoinCondition = NULL; /* join condition not needed */ |
| 395 |
} |
| 396 |
|
| 397 |
/* |
| 398 |
* replace_empty_jointree |
| 399 |
* If the Query's jointree is empty, replace it with a dummy RTE_RESULT |
| 400 |
* relation. |
| 401 |
* |
| 402 |
* By doing this, we can avoid a bunch of corner cases that formerly existed |
| 403 |
* for SELECTs with omitted FROM clauses. An example is that a subquery |
| 404 |
* with empty jointree previously could not be pulled up, because that would |
| 405 |
* have resulted in an empty relid set, making the subquery not uniquely |
| 406 |
* identifiable for join or PlaceHolderVar processing. |
| 407 |
* |
| 408 |
* Unlike most other functions in this file, this function doesn't recurse; |
| 409 |
* we rely on other processing to invoke it on sub-queries at suitable times. |
| 410 |
*/ |
| 411 |
void |
| 412 |
replace_empty_jointree(Query *parse) |
| 413 |
{ |
| 414 |
RangeTblEntry *rte; |
| 415 |
Index rti; |
| 416 |
RangeTblRef *rtr; |
| 417 |
|
| 418 |
/* Nothing to do if jointree is already nonempty */ |
| 419 |
if (parse->jointree->fromlist != NIL) |
| 420 |
return; |
| 421 |
|
| 422 |
/* We mustn't change it in the top level of a setop tree, either */ |
| 423 |
if (parse->setOperations) |
| 424 |
return; |
| 425 |
|
| 426 |
/* Create suitable RTE */ |
| 427 |
rte = makeNode(RangeTblEntry); |
| 428 |
rte->rtekind = RTE_RESULT; |
| 429 |
rte->eref = makeAlias("*RESULT*", NIL); |
| 430 |
|
| 431 |
/* Add it to rangetable */ |
| 432 |
parse->rtable = lappend(parse->rtable, rte); |
| 433 |
rti = list_length(parse->rtable); |
| 434 |
|
| 435 |
/* And jam a reference into the jointree */ |
| 436 |
rtr = makeNode(RangeTblRef); |
| 437 |
rtr->rtindex = rti; |
| 438 |
parse->jointree->fromlist = list_make1(rtr); |
| 439 |
} |
| 440 |
|
| 441 |
/* |
| 442 |
* pull_up_sublinks |
| 443 |
* Attempt to pull up ANY and EXISTS SubLinks to be treated as |
| 444 |
* semijoins or anti-semijoins. |
| 445 |
* |
| 446 |
* A clause "foo op ANY (sub-SELECT)" can be processed by pulling the |
| 447 |
* sub-SELECT up to become a rangetable entry and treating the implied |
| 448 |
* comparisons as quals of a semijoin. However, this optimization *only* |
| 449 |
* works at the top level of WHERE or a JOIN/ON clause, because we cannot |
| 450 |
* distinguish whether the ANY ought to return FALSE or NULL in cases |
| 451 |
* involving NULL inputs. Also, in an outer join's ON clause we can only |
| 452 |
* do this if the sublink is degenerate (ie, references only the nullable |
| 453 |
* side of the join). In that case it is legal to push the semijoin |
| 454 |
* down into the nullable side of the join. If the sublink references any |
| 455 |
* nonnullable-side variables then it would have to be evaluated as part |
| 456 |
* of the outer join, which makes things way too complicated. |
| 457 |
* |
| 458 |
* Under similar conditions, EXISTS and NOT EXISTS clauses can be handled |
| 459 |
* by pulling up the sub-SELECT and creating a semijoin or anti-semijoin. |
| 460 |
* |
| 461 |
* This routine searches for such clauses and does the necessary parsetree |
| 462 |
* transformations if any are found. |
| 463 |
* |
| 464 |
* This routine has to run before preprocess_expression(), so the quals |
| 465 |
* clauses are not yet reduced to implicit-AND format, and are not guaranteed |
| 466 |
* to be AND/OR-flat either. That means we need to recursively search through |
| 467 |
* explicit AND clauses. We stop as soon as we hit a non-AND item. |
| 468 |
*/ |
| 469 |
void |
| 470 |
pull_up_sublinks(PlannerInfo *root) |
| 471 |
{ |
| 472 |
Node *jtnode; |
| 473 |
Relids relids; |
| 474 |
|
| 475 |
/* Begin recursion through the jointree */ |
| 476 |
jtnode = pull_up_sublinks_jointree_recurse(root, |
| 477 |
(Node *) root->parse->jointree, |
| 478 |
&relids); |
| 479 |
|
| 480 |
/* |
| 481 |
* root->parse->jointree must always be a FromExpr, so insert a dummy one |
| 482 |
* if we got a bare RangeTblRef or JoinExpr out of the recursion. |
| 483 |
*/ |
| 484 |
if (IsA(jtnode, FromExpr)) |
| 485 |
root->parse->jointree = (FromExpr *) jtnode; |
| 486 |
else |
| 487 |
root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL); |
| 488 |
} |
| 489 |
|
| 490 |
/* |
| 491 |
* Recurse through jointree nodes for pull_up_sublinks() |
| 492 |
* |
| 493 |
* In addition to returning the possibly-modified jointree node, we return |
| 494 |
* a relids set of the contained rels into *relids. |
| 495 |
*/ |
| 496 |
static Node * |
| 497 |
pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode, |
| 498 |
Relids *relids) |
| 499 |
{ |
| 500 |
/* Since this function recurses, it could be driven to stack overflow. */ |
| 501 |
check_stack_depth(); |
| 502 |
|
| 503 |
if (jtnode == NULL) |
| 504 |
{ |
| 505 |
*relids = NULL; |
| 506 |
} |
| 507 |
else if (IsA(jtnode, RangeTblRef)) |
| 508 |
{ |
| 509 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 510 |
|
| 511 |
*relids = bms_make_singleton(varno); |
| 512 |
/* jtnode is returned unmodified */ |
| 513 |
} |
| 514 |
else if (IsA(jtnode, FromExpr)) |
| 515 |
{ |
| 516 |
FromExpr *f = (FromExpr *) jtnode; |
| 517 |
List *newfromlist = NIL; |
| 518 |
Relids frelids = NULL; |
| 519 |
FromExpr *newf; |
| 520 |
Node *jtlink; |
| 521 |
ListCell *l; |
| 522 |
|
| 523 |
/* First, recurse to process children and collect their relids */ |
| 524 |
foreach(l, f->fromlist) |
| 525 |
{ |
| 526 |
Node *newchild; |
| 527 |
Relids childrelids; |
| 528 |
|
| 529 |
newchild = pull_up_sublinks_jointree_recurse(root, |
| 530 |
lfirst(l), |
| 531 |
&childrelids); |
| 532 |
newfromlist = lappend(newfromlist, newchild); |
| 533 |
frelids = bms_join(frelids, childrelids); |
| 534 |
} |
| 535 |
/* Build the replacement FromExpr; no quals yet */ |
| 536 |
newf = makeFromExpr(newfromlist, NULL); |
| 537 |
/* Set up a link representing the rebuilt jointree */ |
| 538 |
jtlink = (Node *) newf; |
| 539 |
/* Now process qual --- all children are available for use */ |
| 540 |
newf->quals = pull_up_sublinks_qual_recurse(root, f->quals, |
| 541 |
&jtlink, frelids, |
| 542 |
NULL, NULL); |
| 543 |
|
| 544 |
/* |
| 545 |
* Note that the result will be either newf, or a stack of JoinExprs |
| 546 |
* with newf at the base. We rely on subsequent optimization steps to |
| 547 |
* flatten this and rearrange the joins as needed. |
| 548 |
* |
| 549 |
* Although we could include the pulled-up subqueries in the returned |
| 550 |
* relids, there's no need since upper quals couldn't refer to their |
| 551 |
* outputs anyway. |
| 552 |
*/ |
| 553 |
*relids = frelids; |
| 554 |
jtnode = jtlink; |
| 555 |
} |
| 556 |
else if (IsA(jtnode, JoinExpr)) |
| 557 |
{ |
| 558 |
JoinExpr *j; |
| 559 |
Relids leftrelids; |
| 560 |
Relids rightrelids; |
| 561 |
Node *jtlink; |
| 562 |
|
| 563 |
/* |
| 564 |
* Make a modifiable copy of join node, but don't bother copying its |
| 565 |
* subnodes (yet). |
| 566 |
*/ |
| 567 |
j = (JoinExpr *) palloc(sizeof(JoinExpr)); |
| 568 |
memcpy(j, jtnode, sizeof(JoinExpr)); |
| 569 |
jtlink = (Node *) j; |
| 570 |
|
| 571 |
/* Recurse to process children and collect their relids */ |
| 572 |
j->larg = pull_up_sublinks_jointree_recurse(root, j->larg, |
| 573 |
&leftrelids); |
| 574 |
j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg, |
| 575 |
&rightrelids); |
| 576 |
|
| 577 |
/* |
| 578 |
* Now process qual, showing appropriate child relids as available, |
| 579 |
* and attach any pulled-up jointree items at the right place. In the |
| 580 |
* inner-join case we put new JoinExprs above the existing one (much |
| 581 |
* as for a FromExpr-style join). In outer-join cases the new |
| 582 |
* JoinExprs must go into the nullable side of the outer join. The |
| 583 |
* point of the available_rels machinations is to ensure that we only |
| 584 |
* pull up quals for which that's okay. |
| 585 |
* |
| 586 |
* We don't expect to see any pre-existing JOIN_SEMI, JOIN_ANTI, |
| 587 |
* JOIN_RIGHT_SEMI, or JOIN_RIGHT_ANTI jointypes here. |
| 588 |
*/ |
| 589 |
switch (j->jointype) |
| 590 |
{ |
| 591 |
case JOIN_INNER: |
| 592 |
j->quals = pull_up_sublinks_qual_recurse(root, j->quals, |
| 593 |
&jtlink, |
| 594 |
bms_union(leftrelids, |
| 595 |
rightrelids), |
| 596 |
NULL, NULL); |
| 597 |
break; |
| 598 |
case JOIN_LEFT: |
| 599 |
j->quals = pull_up_sublinks_qual_recurse(root, j->quals, |
| 600 |
&j->rarg, |
| 601 |
rightrelids, |
| 602 |
NULL, NULL); |
| 603 |
break; |
| 604 |
case JOIN_FULL: |
| 605 |
/* can't do anything with full-join quals */ |
| 606 |
break; |
| 607 |
case JOIN_RIGHT: |
| 608 |
j->quals = pull_up_sublinks_qual_recurse(root, j->quals, |
| 609 |
&j->larg, |
| 610 |
leftrelids, |
| 611 |
NULL, NULL); |
| 612 |
break; |
| 613 |
default: |
| 614 |
elog(ERROR, "unrecognized join type: %d", |
| 615 |
(int) j->jointype); |
| 616 |
break; |
| 617 |
} |
| 618 |
|
| 619 |
/* |
| 620 |
* Although we could include the pulled-up subqueries in the returned |
| 621 |
* relids, there's no need since upper quals couldn't refer to their |
| 622 |
* outputs anyway. But we *do* need to include the join's own rtindex |
| 623 |
* because we haven't yet collapsed join alias variables, so upper |
| 624 |
* levels would mistakenly think they couldn't use references to this |
| 625 |
* join. |
| 626 |
*/ |
| 627 |
*relids = bms_join(leftrelids, rightrelids); |
| 628 |
if (j->rtindex) |
| 629 |
*relids = bms_add_member(*relids, j->rtindex); |
| 630 |
jtnode = jtlink; |
| 631 |
} |
| 632 |
else |
| 633 |
elog(ERROR, "unrecognized node type: %d", |
| 634 |
(int) nodeTag(jtnode)); |
| 635 |
return jtnode; |
| 636 |
} |
| 637 |
|
| 638 |
/* |
| 639 |
* Recurse through top-level qual nodes for pull_up_sublinks() |
| 640 |
* |
| 641 |
* jtlink1 points to the link in the jointree where any new JoinExprs should |
| 642 |
* be inserted if they reference available_rels1 (i.e., available_rels1 |
| 643 |
* denotes the relations present underneath jtlink1). Optionally, jtlink2 can |
| 644 |
* point to a second link where new JoinExprs should be inserted if they |
| 645 |
* reference available_rels2 (pass NULL for both those arguments if not used). |
| 646 |
* Note that SubLinks referencing both sets of variables cannot be optimized. |
| 647 |
* If we find multiple pull-up-able SubLinks, they'll get stacked onto jtlink1 |
| 648 |
* and/or jtlink2 in the order we encounter them. We rely on subsequent |
| 649 |
* optimization to rearrange the stack if appropriate. |
| 650 |
* |
| 651 |
* Returns the replacement qual node, or NULL if the qual should be removed. |
| 652 |
*/ |
| 653 |
static Node * |
| 654 |
pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node, |
| 655 |
Node **jtlink1, Relids available_rels1, |
| 656 |
Node **jtlink2, Relids available_rels2) |
| 657 |
{ |
| 658 |
if (node == NULL) |
| 659 |
return NULL; |
| 660 |
if (IsA(node, SubLink)) |
| 661 |
{ |
| 662 |
SubLink *sublink = (SubLink *) node; |
| 663 |
JoinExpr *j; |
| 664 |
Relids child_rels; |
| 665 |
|
| 666 |
/* Is it a convertible ANY or EXISTS clause? */ |
| 667 |
if (sublink->subLinkType == ANY_SUBLINK) |
| 668 |
{ |
| 669 |
ScalarArrayOpExpr *saop; |
| 670 |
|
| 671 |
if ((saop = convert_VALUES_to_ANY(root, |
| 672 |
sublink->testexpr, |
| 673 |
(Query *) sublink->subselect)) != NULL) |
| 674 |
|
| 675 |
/* |
| 676 |
* The VALUES sequence was simplified. Nothing more to do |
| 677 |
* here. |
| 678 |
*/ |
| 679 |
return (Node *) saop; |
| 680 |
|
| 681 |
if ((j = convert_ANY_sublink_to_join(root, sublink, |
| 682 |
available_rels1)) != NULL) |
| 683 |
{ |
| 684 |
/* Yes; insert the new join node into the join tree */ |
| 685 |
j->larg = *jtlink1; |
| 686 |
*jtlink1 = (Node *) j; |
| 687 |
/* Recursively process pulled-up jointree nodes */ |
| 688 |
j->rarg = pull_up_sublinks_jointree_recurse(root, |
| 689 |
j->rarg, |
| 690 |
&child_rels); |
| 691 |
|
| 692 |
/* |
| 693 |
* Now recursively process the pulled-up quals. Any inserted |
| 694 |
* joins can get stacked onto either j->larg or j->rarg, |
| 695 |
* depending on which rels they reference. |
| 696 |
*/ |
| 697 |
j->quals = pull_up_sublinks_qual_recurse(root, |
| 698 |
j->quals, |
| 699 |
&j->larg, |
| 700 |
available_rels1, |
| 701 |
&j->rarg, |
| 702 |
child_rels); |
| 703 |
/* Return NULL representing constant TRUE */ |
| 704 |
return NULL; |
| 705 |
} |
| 706 |
if (available_rels2 != NULL && |
| 707 |
(j = convert_ANY_sublink_to_join(root, sublink, |
| 708 |
available_rels2)) != NULL) |
| 709 |
{ |
| 710 |
/* Yes; insert the new join node into the join tree */ |
| 711 |
j->larg = *jtlink2; |
| 712 |
*jtlink2 = (Node *) j; |
| 713 |
/* Recursively process pulled-up jointree nodes */ |
| 714 |
j->rarg = pull_up_sublinks_jointree_recurse(root, |
| 715 |
j->rarg, |
| 716 |
&child_rels); |
| 717 |
|
| 718 |
/* |
| 719 |
* Now recursively process the pulled-up quals. Any inserted |
| 720 |
* joins can get stacked onto either j->larg or j->rarg, |
| 721 |
* depending on which rels they reference. |
| 722 |
*/ |
| 723 |
j->quals = pull_up_sublinks_qual_recurse(root, |
| 724 |
j->quals, |
| 725 |
&j->larg, |
| 726 |
available_rels2, |
| 727 |
&j->rarg, |
| 728 |
child_rels); |
| 729 |
/* Return NULL representing constant TRUE */ |
| 730 |
return NULL; |
| 731 |
} |
| 732 |
} |
| 733 |
else if (sublink->subLinkType == EXISTS_SUBLINK) |
| 734 |
{ |
| 735 |
if ((j = convert_EXISTS_sublink_to_join(root, sublink, false, |
| 736 |
available_rels1)) != NULL) |
| 737 |
{ |
| 738 |
/* Yes; insert the new join node into the join tree */ |
| 739 |
j->larg = *jtlink1; |
| 740 |
*jtlink1 = (Node *) j; |
| 741 |
/* Recursively process pulled-up jointree nodes */ |
| 742 |
j->rarg = pull_up_sublinks_jointree_recurse(root, |
| 743 |
j->rarg, |
| 744 |
&child_rels); |
| 745 |
|
| 746 |
/* |
| 747 |
* Now recursively process the pulled-up quals. Any inserted |
| 748 |
* joins can get stacked onto either j->larg or j->rarg, |
| 749 |
* depending on which rels they reference. |
| 750 |
*/ |
| 751 |
j->quals = pull_up_sublinks_qual_recurse(root, |
| 752 |
j->quals, |
| 753 |
&j->larg, |
| 754 |
available_rels1, |
| 755 |
&j->rarg, |
| 756 |
child_rels); |
| 757 |
/* Return NULL representing constant TRUE */ |
| 758 |
return NULL; |
| 759 |
} |
| 760 |
if (available_rels2 != NULL && |
| 761 |
(j = convert_EXISTS_sublink_to_join(root, sublink, false, |
| 762 |
available_rels2)) != NULL) |
| 763 |
{ |
| 764 |
/* Yes; insert the new join node into the join tree */ |
| 765 |
j->larg = *jtlink2; |
| 766 |
*jtlink2 = (Node *) j; |
| 767 |
/* Recursively process pulled-up jointree nodes */ |
| 768 |
j->rarg = pull_up_sublinks_jointree_recurse(root, |
| 769 |
j->rarg, |
| 770 |
&child_rels); |
| 771 |
|
| 772 |
/* |
| 773 |
* Now recursively process the pulled-up quals. Any inserted |
| 774 |
* joins can get stacked onto either j->larg or j->rarg, |
| 775 |
* depending on which rels they reference. |
| 776 |
*/ |
| 777 |
j->quals = pull_up_sublinks_qual_recurse(root, |
| 778 |
j->quals, |
| 779 |
&j->larg, |
| 780 |
available_rels2, |
| 781 |
&j->rarg, |
| 782 |
child_rels); |
| 783 |
/* Return NULL representing constant TRUE */ |
| 784 |
return NULL; |
| 785 |
} |
| 786 |
} |
| 787 |
/* Else return it unmodified */ |
| 788 |
return node; |
| 789 |
} |
| 790 |
if (is_notclause(node)) |
| 791 |
{ |
| 792 |
/* If the immediate argument of NOT is EXISTS, try to convert */ |
| 793 |
SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node); |
| 794 |
JoinExpr *j; |
| 795 |
Relids child_rels; |
| 796 |
|
| 797 |
if (sublink && IsA(sublink, SubLink)) |
| 798 |
{ |
| 799 |
if (sublink->subLinkType == EXISTS_SUBLINK) |
| 800 |
{ |
| 801 |
if ((j = convert_EXISTS_sublink_to_join(root, sublink, true, |
| 802 |
available_rels1)) != NULL) |
| 803 |
{ |
| 804 |
/* Yes; insert the new join node into the join tree */ |
| 805 |
j->larg = *jtlink1; |
| 806 |
*jtlink1 = (Node *) j; |
| 807 |
/* Recursively process pulled-up jointree nodes */ |
| 808 |
j->rarg = pull_up_sublinks_jointree_recurse(root, |
| 809 |
j->rarg, |
| 810 |
&child_rels); |
| 811 |
|
| 812 |
/* |
| 813 |
* Now recursively process the pulled-up quals. Because |
| 814 |
* we are underneath a NOT, we can't pull up sublinks that |
| 815 |
* reference the left-hand stuff, but it's still okay to |
| 816 |
* pull up sublinks referencing j->rarg. |
| 817 |
*/ |
| 818 |
j->quals = pull_up_sublinks_qual_recurse(root, |
| 819 |
j->quals, |
| 820 |
&j->rarg, |
| 821 |
child_rels, |
| 822 |
NULL, NULL); |
| 823 |
/* Return NULL representing constant TRUE */ |
| 824 |
return NULL; |
| 825 |
} |
| 826 |
if (available_rels2 != NULL && |
| 827 |
(j = convert_EXISTS_sublink_to_join(root, sublink, true, |
| 828 |
available_rels2)) != NULL) |
| 829 |
{ |
| 830 |
/* Yes; insert the new join node into the join tree */ |
| 831 |
j->larg = *jtlink2; |
| 832 |
*jtlink2 = (Node *) j; |
| 833 |
/* Recursively process pulled-up jointree nodes */ |
| 834 |
j->rarg = pull_up_sublinks_jointree_recurse(root, |
| 835 |
j->rarg, |
| 836 |
&child_rels); |
| 837 |
|
| 838 |
/* |
| 839 |
* Now recursively process the pulled-up quals. Because |
| 840 |
* we are underneath a NOT, we can't pull up sublinks that |
| 841 |
* reference the left-hand stuff, but it's still okay to |
| 842 |
* pull up sublinks referencing j->rarg. |
| 843 |
*/ |
| 844 |
j->quals = pull_up_sublinks_qual_recurse(root, |
| 845 |
j->quals, |
| 846 |
&j->rarg, |
| 847 |
child_rels, |
| 848 |
NULL, NULL); |
| 849 |
/* Return NULL representing constant TRUE */ |
| 850 |
return NULL; |
| 851 |
} |
| 852 |
} |
| 853 |
} |
| 854 |
/* Else return it unmodified */ |
| 855 |
return node; |
| 856 |
} |
| 857 |
if (is_andclause(node)) |
| 858 |
{ |
| 859 |
/* Recurse into AND clause */ |
| 860 |
List *newclauses = NIL; |
| 861 |
ListCell *l; |
| 862 |
|
| 863 |
foreach(l, ((BoolExpr *) node)->args) |
| 864 |
{ |
| 865 |
Node *oldclause = (Node *) lfirst(l); |
| 866 |
Node *newclause; |
| 867 |
|
| 868 |
newclause = pull_up_sublinks_qual_recurse(root, |
| 869 |
oldclause, |
| 870 |
jtlink1, |
| 871 |
available_rels1, |
| 872 |
jtlink2, |
| 873 |
available_rels2); |
| 874 |
if (newclause) |
| 875 |
newclauses = lappend(newclauses, newclause); |
| 876 |
} |
| 877 |
/* We might have got back fewer clauses than we started with */ |
| 878 |
if (newclauses == NIL) |
| 879 |
return NULL; |
| 880 |
else if (list_length(newclauses) == 1) |
| 881 |
return (Node *) linitial(newclauses); |
| 882 |
else |
| 883 |
return (Node *) make_andclause(newclauses); |
| 884 |
} |
| 885 |
/* Stop if not an AND */ |
| 886 |
return node; |
| 887 |
} |
| 888 |
|
| 889 |
/* |
| 890 |
* preprocess_function_rtes |
| 891 |
* Constant-simplify any FUNCTION RTEs in the FROM clause, and then |
| 892 |
* attempt to "inline" any that are set-returning functions. |
| 893 |
* |
| 894 |
* If an RTE_FUNCTION rtable entry invokes a set-returning function that |
| 895 |
* contains just a simple SELECT, we can convert the rtable entry to an |
| 896 |
* RTE_SUBQUERY entry exposing the SELECT directly. This is especially |
| 897 |
* useful if the subquery can then be "pulled up" for further optimization, |
| 898 |
* but we do it even if not, to reduce executor overhead. |
| 899 |
* |
| 900 |
* This has to be done before we have started to do any optimization of |
| 901 |
* subqueries, else any such steps wouldn't get applied to subqueries |
| 902 |
* obtained via inlining. However, we do it after pull_up_sublinks |
| 903 |
* so that we can inline any functions used in SubLink subselects. |
| 904 |
* |
| 905 |
* The reason for applying const-simplification at this stage is that |
| 906 |
* (a) we'd need to do it anyway to inline a SRF, and (b) by doing it now, |
| 907 |
* we can be sure that pull_up_constant_function() will see constants |
| 908 |
* if there are constants to be seen. This approach also guarantees |
| 909 |
* that every FUNCTION RTE has been const-simplified, allowing planner.c's |
| 910 |
* preprocess_expression() to skip doing it again. |
| 911 |
* |
| 912 |
* Like most of the planner, this feels free to scribble on its input data |
| 913 |
* structure. |
| 914 |
*/ |
| 915 |
void |
| 916 |
preprocess_function_rtes(PlannerInfo *root) |
| 917 |
{ |
| 918 |
ListCell *rt; |
| 919 |
|
| 920 |
foreach(rt, root->parse->rtable) |
| 921 |
{ |
| 922 |
RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt); |
| 923 |
|
| 924 |
if (rte->rtekind == RTE_FUNCTION) |
| 925 |
{ |
| 926 |
Query *funcquery; |
| 927 |
|
| 928 |
/* Apply const-simplification */ |
| 929 |
rte->functions = (List *) |
| 930 |
eval_const_expressions(root, (Node *) rte->functions); |
| 931 |
|
| 932 |
/* Check safety of expansion, and expand if possible */ |
| 933 |
funcquery = inline_set_returning_function(root, rte); |
| 934 |
if (funcquery) |
| 935 |
{ |
| 936 |
/* Successful expansion, convert the RTE to a subquery */ |
| 937 |
rte->rtekind = RTE_SUBQUERY; |
| 938 |
rte->subquery = funcquery; |
| 939 |
rte->security_barrier = false; |
| 940 |
|
| 941 |
/* |
| 942 |
* Clear fields that should not be set in a subquery RTE. |
| 943 |
* However, we leave rte->functions filled in for the moment, |
| 944 |
* in case makeWholeRowVar needs to consult it. We'll clear |
| 945 |
* it in setrefs.c (see add_rte_to_flat_rtable) so that this |
| 946 |
* abuse of the data structure doesn't escape the planner. |
| 947 |
*/ |
| 948 |
rte->funcordinality = false; |
| 949 |
} |
| 950 |
} |
| 951 |
} |
| 952 |
} |
| 953 |
|
| 954 |
/* |
| 955 |
* expand_virtual_generated_columns |
| 956 |
* Expand all virtual generated column references in a query. |
| 957 |
* |
| 958 |
* This scans the rangetable for relations with virtual generated columns, and |
| 959 |
* replaces all Var nodes in the query that reference these columns with the |
| 960 |
* generation expressions. Note that we do not descend into subqueries; that |
| 961 |
* is taken care of when the subqueries are planned. |
| 962 |
* |
| 963 |
* This has to be done after we have pulled up any SubLinks within the query's |
| 964 |
* quals; otherwise any virtual generated column references within the SubLinks |
| 965 |
* that should be transformed into joins wouldn't get expanded. |
| 966 |
* |
| 967 |
* Returns a modified copy of the query tree, if any relations with virtual |
| 968 |
* generated columns are present. |
| 969 |
*/ |
| 970 |
Query * |
| 971 |
expand_virtual_generated_columns(PlannerInfo *root) |
| 972 |
{ |
| 973 |
Query *parse = root->parse; |
| 974 |
int rt_index; |
| 975 |
ListCell *lc; |
| 976 |
|
| 977 |
rt_index = 0; |
| 978 |
foreach(lc, parse->rtable) |
| 979 |
{ |
| 980 |
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc); |
| 981 |
Relation rel; |
| 982 |
TupleDesc tupdesc; |
| 983 |
|
| 984 |
++rt_index; |
| 985 |
|
| 986 |
/* |
| 987 |
* Only normal relations can have virtual generated columns. |
| 988 |
*/ |
| 989 |
if (rte->rtekind != RTE_RELATION) |
| 990 |
continue; |
| 991 |
|
| 992 |
rel = table_open(rte->relid, NoLock); |
| 993 |
|
| 994 |
tupdesc = RelationGetDescr(rel); |
| 995 |
if (tupdesc->constr && tupdesc->constr->has_generated_virtual) |
| 996 |
{ |
| 997 |
List *tlist = NIL; |
| 998 |
pullup_replace_vars_context rvcontext; |
| 999 |
List *save_exclRelTlist = NIL; |
| 1000 |
|
| 1001 |
for (int i = 0; i < tupdesc->natts; i++) |
| 1002 |
{ |
| 1003 |
Form_pg_attribute attr = TupleDescAttr(tupdesc, i); |
| 1004 |
TargetEntry *tle; |
| 1005 |
|
| 1006 |
if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL) |
| 1007 |
{ |
| 1008 |
Node *defexpr; |
| 1009 |
|
| 1010 |
defexpr = build_generation_expression(rel, i + 1); |
| 1011 |
ChangeVarNodes(defexpr, 1, rt_index, 0); |
| 1012 |
|
| 1013 |
tle = makeTargetEntry((Expr *) defexpr, i + 1, 0, false); |
| 1014 |
tlist = lappend(tlist, tle); |
| 1015 |
} |
| 1016 |
else |
| 1017 |
{ |
| 1018 |
Var *var; |
| 1019 |
|
| 1020 |
var = makeVar(rt_index, |
| 1021 |
i + 1, |
| 1022 |
attr->atttypid, |
| 1023 |
attr->atttypmod, |
| 1024 |
attr->attcollation, |
| 1025 |
0); |
| 1026 |
|
| 1027 |
tle = makeTargetEntry((Expr *) var, i + 1, 0, false); |
| 1028 |
tlist = lappend(tlist, tle); |
| 1029 |
} |
| 1030 |
} |
| 1031 |
|
| 1032 |
Assert(list_length(tlist) > 0); |
| 1033 |
Assert(!rte->lateral); |
| 1034 |
|
| 1035 |
/* |
| 1036 |
* The relation's targetlist items are now in the appropriate form |
| 1037 |
* to insert into the query, except that we may need to wrap them |
| 1038 |
* in PlaceHolderVars. Set up required context data for |
| 1039 |
* pullup_replace_vars. |
| 1040 |
*/ |
| 1041 |
rvcontext.root = root; |
| 1042 |
rvcontext.targetlist = tlist; |
| 1043 |
rvcontext.target_rte = rte; |
| 1044 |
rvcontext.result_relation = parse->resultRelation; |
| 1045 |
/* won't need these values */ |
| 1046 |
rvcontext.relids = NULL; |
| 1047 |
rvcontext.nullinfo = NULL; |
| 1048 |
/* pass NULL for outer_hasSubLinks */ |
| 1049 |
rvcontext.outer_hasSubLinks = NULL; |
| 1050 |
rvcontext.varno = rt_index; |
| 1051 |
/* this flag will be set below, if needed */ |
| 1052 |
rvcontext.wrap_option = REPLACE_WRAP_NONE; |
| 1053 |
/* initialize cache array with indexes 0 .. length(tlist) */ |
| 1054 |
rvcontext.rv_cache = palloc0((list_length(tlist) + 1) * |
| 1055 |
sizeof(Node *)); |
| 1056 |
|
| 1057 |
/* |
| 1058 |
* If the query uses grouping sets, we need a PlaceHolderVar for |
| 1059 |
* each expression of the relation's targetlist items. (See |
| 1060 |
* comments in pull_up_simple_subquery().) |
| 1061 |
*/ |
| 1062 |
if (parse->groupingSets) |
| 1063 |
rvcontext.wrap_option = REPLACE_WRAP_ALL; |
| 1064 |
|
| 1065 |
/* |
| 1066 |
* Apply pullup variable replacement throughout the query tree. |
| 1067 |
* |
| 1068 |
* We intentionally do not touch the EXCLUDED pseudo-relation's |
| 1069 |
* targetlist here. Various places in the planner assume that it |
| 1070 |
* contains only Vars, and we want that to remain the case. More |
| 1071 |
* importantly, we don't want setrefs.c to turn any expanded |
| 1072 |
* EXCLUDED.virtual_column expressions in other parts of the query |
| 1073 |
* back into Vars referencing the original virtual column, which |
| 1074 |
* set_plan_refs() would do if exclRelTlist contained matching |
| 1075 |
* expressions. |
| 1076 |
*/ |
| 1077 |
if (parse->onConflict) |
| 1078 |
{ |
| 1079 |
save_exclRelTlist = parse->onConflict->exclRelTlist; |
| 1080 |
parse->onConflict->exclRelTlist = NIL; |
| 1081 |
} |
| 1082 |
|
| 1083 |
parse = (Query *) pullup_replace_vars((Node *) parse, &rvcontext); |
| 1084 |
|
| 1085 |
if (parse->onConflict) |
| 1086 |
parse->onConflict->exclRelTlist = save_exclRelTlist; |
| 1087 |
} |
| 1088 |
|
| 1089 |
table_close(rel, NoLock); |
| 1090 |
} |
| 1091 |
|
| 1092 |
return parse; |
| 1093 |
} |
| 1094 |
|
| 1095 |
/* |
| 1096 |
* pull_up_subqueries |
| 1097 |
* Look for subqueries in the rangetable that can be pulled up into |
| 1098 |
* the parent query. If the subquery has no special features like |
| 1099 |
* grouping/aggregation then we can merge it into the parent's jointree. |
| 1100 |
* Also, subqueries that are simple UNION ALL structures can be |
| 1101 |
* converted into "append relations". |
| 1102 |
*/ |
| 1103 |
void |
| 1104 |
pull_up_subqueries(PlannerInfo *root) |
| 1105 |
{ |
| 1106 |
/* Top level of jointree must always be a FromExpr */ |
| 1107 |
Assert(IsA(root->parse->jointree, FromExpr)); |
| 1108 |
/* Recursion starts with no containing join nor appendrel */ |
| 1109 |
root->parse->jointree = (FromExpr *) |
| 1110 |
pull_up_subqueries_recurse(root, (Node *) root->parse->jointree, |
| 1111 |
NULL, NULL); |
| 1112 |
/* We should still have a FromExpr */ |
| 1113 |
Assert(IsA(root->parse->jointree, FromExpr)); |
| 1114 |
} |
| 1115 |
|
| 1116 |
/* |
| 1117 |
* pull_up_subqueries_recurse |
| 1118 |
* Recursive guts of pull_up_subqueries. |
| 1119 |
* |
| 1120 |
* This recursively processes the jointree and returns a modified jointree. |
| 1121 |
* |
| 1122 |
* If this jointree node is within either side of an outer join, then |
| 1123 |
* lowest_outer_join references the lowest such JoinExpr node; otherwise |
| 1124 |
* it is NULL. We use this to constrain the effects of LATERAL subqueries. |
| 1125 |
* |
| 1126 |
* If we are looking at a member subquery of an append relation, |
| 1127 |
* containing_appendrel describes that relation; else it is NULL. |
| 1128 |
* This forces use of the PlaceHolderVar mechanism for all non-Var targetlist |
| 1129 |
* items, and puts some additional restrictions on what can be pulled up. |
| 1130 |
* |
| 1131 |
* A tricky aspect of this code is that if we pull up a subquery we have |
| 1132 |
* to replace Vars that reference the subquery's outputs throughout the |
| 1133 |
* parent query, including quals attached to jointree nodes above the one |
| 1134 |
* we are currently processing! We handle this by being careful to maintain |
| 1135 |
* validity of the jointree structure while recursing, in the following sense: |
| 1136 |
* whenever we recurse, all qual expressions in the tree must be reachable |
| 1137 |
* from the top level, in case the recursive call needs to modify them. |
| 1138 |
* |
| 1139 |
* Notice also that we can't turn pullup_replace_vars loose on the whole |
| 1140 |
* jointree, because it'd return a mutated copy of the tree; we have to |
| 1141 |
* invoke it just on the quals, instead. This behavior is what makes it |
| 1142 |
* reasonable to pass lowest_outer_join as a pointer rather than some |
| 1143 |
* more-indirect way of identifying the lowest OJ. Likewise, we don't |
| 1144 |
* replace append_rel_list members but only their substructure, so the |
| 1145 |
* containing_appendrel reference is safe to use. |
| 1146 |
*/ |
| 1147 |
static Node * |
| 1148 |
pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode, |
| 1149 |
JoinExpr *lowest_outer_join, |
| 1150 |
AppendRelInfo *containing_appendrel) |
| 1151 |
{ |
| 1152 |
/* Since this function recurses, it could be driven to stack overflow. */ |
| 1153 |
check_stack_depth(); |
| 1154 |
/* Also, since it's a bit expensive, let's check for query cancel. */ |
| 1155 |
CHECK_FOR_INTERRUPTS(); |
| 1156 |
|
| 1157 |
Assert(jtnode != NULL); |
| 1158 |
if (IsA(jtnode, RangeTblRef)) |
| 1159 |
{ |
| 1160 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 1161 |
RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable); |
| 1162 |
|
| 1163 |
/* |
| 1164 |
* Is this a subquery RTE, and if so, is the subquery simple enough to |
| 1165 |
* pull up? |
| 1166 |
* |
| 1167 |
* If we are looking at an append-relation member, we can't pull it up |
| 1168 |
* unless is_safe_append_member says so. |
| 1169 |
*/ |
| 1170 |
if (rte->rtekind == RTE_SUBQUERY && |
| 1171 |
is_simple_subquery(root, rte->subquery, rte, lowest_outer_join) && |
| 1172 |
(containing_appendrel == NULL || |
| 1173 |
is_safe_append_member(rte->subquery))) |
| 1174 |
return pull_up_simple_subquery(root, jtnode, rte, |
| 1175 |
lowest_outer_join, |
| 1176 |
containing_appendrel); |
| 1177 |
|
| 1178 |
/* |
| 1179 |
* Alternatively, is it a simple UNION ALL subquery? If so, flatten |
| 1180 |
* into an "append relation". |
| 1181 |
* |
| 1182 |
* It's safe to do this regardless of whether this query is itself an |
| 1183 |
* appendrel member. (If you're thinking we should try to flatten the |
| 1184 |
* two levels of appendrel together, you're right; but we handle that |
| 1185 |
* in set_append_rel_pathlist, not here.) |
| 1186 |
*/ |
| 1187 |
if (rte->rtekind == RTE_SUBQUERY && |
| 1188 |
is_simple_union_all(rte->subquery)) |
| 1189 |
return pull_up_simple_union_all(root, jtnode, rte); |
| 1190 |
|
| 1191 |
/* |
| 1192 |
* Or perhaps it's a simple VALUES RTE? |
| 1193 |
* |
| 1194 |
* We don't allow VALUES pullup below an outer join nor into an |
| 1195 |
* appendrel (such cases are impossible anyway at the moment). |
| 1196 |
*/ |
| 1197 |
if (rte->rtekind == RTE_VALUES && |
| 1198 |
lowest_outer_join == NULL && |
| 1199 |
containing_appendrel == NULL && |
| 1200 |
is_simple_values(root, rte)) |
| 1201 |
return pull_up_simple_values(root, jtnode, rte); |
| 1202 |
|
| 1203 |
/* |
| 1204 |
* Or perhaps it's a FUNCTION RTE that we could inline? |
| 1205 |
*/ |
| 1206 |
if (rte->rtekind == RTE_FUNCTION) |
| 1207 |
return pull_up_constant_function(root, jtnode, rte, |
| 1208 |
containing_appendrel); |
| 1209 |
|
| 1210 |
/* Otherwise, do nothing at this node. */ |
| 1211 |
} |
| 1212 |
else if (IsA(jtnode, FromExpr)) |
| 1213 |
{ |
| 1214 |
FromExpr *f = (FromExpr *) jtnode; |
| 1215 |
ListCell *l; |
| 1216 |
|
| 1217 |
Assert(containing_appendrel == NULL); |
| 1218 |
/* Recursively transform all the child nodes */ |
| 1219 |
foreach(l, f->fromlist) |
| 1220 |
{ |
| 1221 |
lfirst(l) = pull_up_subqueries_recurse(root, lfirst(l), |
| 1222 |
lowest_outer_join, |
| 1223 |
NULL); |
| 1224 |
} |
| 1225 |
} |
| 1226 |
else if (IsA(jtnode, JoinExpr)) |
| 1227 |
{ |
| 1228 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 1229 |
|
| 1230 |
Assert(containing_appendrel == NULL); |
| 1231 |
/* Recurse, being careful to tell myself when inside outer join */ |
| 1232 |
switch (j->jointype) |
| 1233 |
{ |
| 1234 |
case JOIN_INNER: |
| 1235 |
j->larg = pull_up_subqueries_recurse(root, j->larg, |
| 1236 |
lowest_outer_join, |
| 1237 |
NULL); |
| 1238 |
j->rarg = pull_up_subqueries_recurse(root, j->rarg, |
| 1239 |
lowest_outer_join, |
| 1240 |
NULL); |
| 1241 |
break; |
| 1242 |
case JOIN_LEFT: |
| 1243 |
case JOIN_SEMI: |
| 1244 |
case JOIN_ANTI: |
| 1245 |
j->larg = pull_up_subqueries_recurse(root, j->larg, |
| 1246 |
j, |
| 1247 |
NULL); |
| 1248 |
j->rarg = pull_up_subqueries_recurse(root, j->rarg, |
| 1249 |
j, |
| 1250 |
NULL); |
| 1251 |
break; |
| 1252 |
case JOIN_FULL: |
| 1253 |
j->larg = pull_up_subqueries_recurse(root, j->larg, |
| 1254 |
j, |
| 1255 |
NULL); |
| 1256 |
j->rarg = pull_up_subqueries_recurse(root, j->rarg, |
| 1257 |
j, |
| 1258 |
NULL); |
| 1259 |
break; |
| 1260 |
case JOIN_RIGHT: |
| 1261 |
j->larg = pull_up_subqueries_recurse(root, j->larg, |
| 1262 |
j, |
| 1263 |
NULL); |
| 1264 |
j->rarg = pull_up_subqueries_recurse(root, j->rarg, |
| 1265 |
j, |
| 1266 |
NULL); |
| 1267 |
break; |
| 1268 |
default: |
| 1269 |
elog(ERROR, "unrecognized join type: %d", |
| 1270 |
(int) j->jointype); |
| 1271 |
break; |
| 1272 |
} |
| 1273 |
} |
| 1274 |
else |
| 1275 |
elog(ERROR, "unrecognized node type: %d", |
| 1276 |
(int) nodeTag(jtnode)); |
| 1277 |
return jtnode; |
| 1278 |
} |
| 1279 |
|
| 1280 |
/* |
| 1281 |
* pull_up_simple_subquery |
| 1282 |
* Attempt to pull up a single simple subquery. |
| 1283 |
* |
| 1284 |
* jtnode is a RangeTblRef that has been tentatively identified as a simple |
| 1285 |
* subquery by pull_up_subqueries. We return the replacement jointree node, |
| 1286 |
* or jtnode itself if we determine that the subquery can't be pulled up |
| 1287 |
* after all. |
| 1288 |
* |
| 1289 |
* rte is the RangeTblEntry referenced by jtnode. Remaining parameters are |
| 1290 |
* as for pull_up_subqueries_recurse. |
| 1291 |
*/ |
| 1292 |
static Node * |
| 1293 |
pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, |
| 1294 |
JoinExpr *lowest_outer_join, |
| 1295 |
AppendRelInfo *containing_appendrel) |
| 1296 |
{ |
| 1297 |
Query *parse = root->parse; |
| 1298 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 1299 |
Query *subquery; |
| 1300 |
PlannerInfo *subroot; |
| 1301 |
int rtoffset; |
| 1302 |
pullup_replace_vars_context rvcontext; |
| 1303 |
ListCell *lc; |
| 1304 |
|
| 1305 |
/* |
| 1306 |
* Make a modifiable copy of the subquery to hack on, so that the RTE will |
| 1307 |
* be left unchanged in case we decide below that we can't pull it up |
| 1308 |
* after all. |
| 1309 |
*/ |
| 1310 |
subquery = copyObject(rte->subquery); |
| 1311 |
|
| 1312 |
/* |
| 1313 |
* Create a PlannerInfo data structure for this subquery. |
| 1314 |
* |
| 1315 |
* NOTE: the next few steps should match the first processing in |
| 1316 |
* subquery_planner(). Can we refactor to avoid code duplication, or |
| 1317 |
* would that just make things uglier? |
| 1318 |
*/ |
| 1319 |
subroot = makeNode(PlannerInfo); |
| 1320 |
subroot->parse = subquery; |
| 1321 |
subroot->glob = root->glob; |
| 1322 |
subroot->query_level = root->query_level; |
| 1323 |
subroot->parent_root = root->parent_root; |
| 1324 |
subroot->plan_params = NIL; |
| 1325 |
subroot->outer_params = NULL; |
| 1326 |
subroot->planner_cxt = CurrentMemoryContext; |
| 1327 |
subroot->init_plans = NIL; |
| 1328 |
subroot->cte_plan_ids = NIL; |
| 1329 |
subroot->multiexpr_params = NIL; |
| 1330 |
subroot->join_domains = NIL; |
| 1331 |
subroot->eq_classes = NIL; |
| 1332 |
subroot->ec_merging_done = false; |
| 1333 |
subroot->last_rinfo_serial = 0; |
| 1334 |
subroot->all_result_relids = NULL; |
| 1335 |
subroot->leaf_result_relids = NULL; |
| 1336 |
subroot->append_rel_list = NIL; |
| 1337 |
subroot->row_identity_vars = NIL; |
| 1338 |
subroot->rowMarks = NIL; |
| 1339 |
memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels)); |
| 1340 |
memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets)); |
| 1341 |
subroot->processed_groupClause = NIL; |
| 1342 |
subroot->processed_distinctClause = NIL; |
| 1343 |
subroot->processed_tlist = NIL; |
| 1344 |
subroot->update_colnos = NIL; |
| 1345 |
subroot->grouping_map = NULL; |
| 1346 |
subroot->minmax_aggs = NIL; |
| 1347 |
subroot->qual_security_level = 0; |
| 1348 |
subroot->placeholdersFrozen = false; |
| 1349 |
subroot->hasRecursion = false; |
| 1350 |
subroot->wt_param_id = -1; |
| 1351 |
subroot->non_recursive_path = NULL; |
| 1352 |
/* We don't currently need a top JoinDomain for the subroot */ |
| 1353 |
|
| 1354 |
/* No CTEs to worry about */ |
| 1355 |
Assert(subquery->cteList == NIL); |
| 1356 |
|
| 1357 |
/* |
| 1358 |
* If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so |
| 1359 |
* that we don't need so many special cases to deal with that situation. |
| 1360 |
*/ |
| 1361 |
replace_empty_jointree(subquery); |
| 1362 |
|
| 1363 |
/* |
| 1364 |
* Pull up any SubLinks within the subquery's quals, so that we don't |
| 1365 |
* leave unoptimized SubLinks behind. |
| 1366 |
*/ |
| 1367 |
if (subquery->hasSubLinks) |
| 1368 |
pull_up_sublinks(subroot); |
| 1369 |
|
| 1370 |
/* |
| 1371 |
* Similarly, preprocess its function RTEs to inline any set-returning |
| 1372 |
* functions in its rangetable. |
| 1373 |
*/ |
| 1374 |
preprocess_function_rtes(subroot); |
| 1375 |
|
| 1376 |
/* |
| 1377 |
* Scan the rangetable for relations with virtual generated columns, and |
| 1378 |
* replace all Var nodes in the query that reference these columns with |
| 1379 |
* the generation expressions. |
| 1380 |
*/ |
| 1381 |
subquery = subroot->parse = expand_virtual_generated_columns(subroot); |
| 1382 |
|
| 1383 |
/* |
| 1384 |
* Recursively pull up the subquery's subqueries, so that |
| 1385 |
* pull_up_subqueries' processing is complete for its jointree and |
| 1386 |
* rangetable. |
| 1387 |
* |
| 1388 |
* Note: it's okay that the subquery's recursion starts with NULL for |
| 1389 |
* containing-join info, even if we are within an outer join in the upper |
| 1390 |
* query; the lower query starts with a clean slate for outer-join |
| 1391 |
* semantics. Likewise, we needn't pass down appendrel state. |
| 1392 |
*/ |
| 1393 |
pull_up_subqueries(subroot); |
| 1394 |
|
| 1395 |
/* |
| 1396 |
* Now we must recheck whether the subquery is still simple enough to pull |
| 1397 |
* up. If not, abandon processing it. |
| 1398 |
* |
| 1399 |
* We don't really need to recheck all the conditions involved, but it's |
| 1400 |
* easier just to keep this "if" looking the same as the one in |
| 1401 |
* pull_up_subqueries_recurse. |
| 1402 |
*/ |
| 1403 |
if (is_simple_subquery(root, subquery, rte, lowest_outer_join) && |
| 1404 |
(containing_appendrel == NULL || is_safe_append_member(subquery))) |
| 1405 |
{ |
| 1406 |
/* good to go */ |
| 1407 |
} |
| 1408 |
else |
| 1409 |
{ |
| 1410 |
/* |
| 1411 |
* Give up, return unmodified RangeTblRef. |
| 1412 |
* |
| 1413 |
* Note: The work we just did will be redone when the subquery gets |
| 1414 |
* planned on its own. Perhaps we could avoid that by storing the |
| 1415 |
* modified subquery back into the rangetable, but I'm not gonna risk |
| 1416 |
* it now. |
| 1417 |
*/ |
| 1418 |
return jtnode; |
| 1419 |
} |
| 1420 |
|
| 1421 |
/* |
| 1422 |
* We must flatten any join alias Vars in the subquery's targetlist, |
| 1423 |
* because pulling up the subquery's subqueries might have changed their |
| 1424 |
* expansions into arbitrary expressions, which could affect |
| 1425 |
* pullup_replace_vars' decisions about whether PlaceHolderVar wrappers |
| 1426 |
* are needed for tlist entries. (Likely it'd be better to do |
| 1427 |
* flatten_join_alias_vars on the whole query tree at some earlier stage, |
| 1428 |
* maybe even in the rewriter; but for now let's just fix this case here.) |
| 1429 |
*/ |
| 1430 |
subquery->targetList = (List *) |
| 1431 |
flatten_join_alias_vars(subroot, subroot->parse, |
| 1432 |
(Node *) subquery->targetList); |
| 1433 |
|
| 1434 |
/* |
| 1435 |
* Adjust level-0 varnos in subquery so that we can append its rangetable |
| 1436 |
* to upper query's. We have to fix the subquery's append_rel_list as |
| 1437 |
* well. |
| 1438 |
*/ |
| 1439 |
rtoffset = list_length(parse->rtable); |
| 1440 |
OffsetVarNodes((Node *) subquery, rtoffset, 0); |
| 1441 |
OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0); |
| 1442 |
|
| 1443 |
/* |
| 1444 |
* Upper-level vars in subquery are now one level closer to their parent |
| 1445 |
* than before. |
| 1446 |
*/ |
| 1447 |
IncrementVarSublevelsUp((Node *) subquery, -1, 1); |
| 1448 |
IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1); |
| 1449 |
|
| 1450 |
/* |
| 1451 |
* The subquery's targetlist items are now in the appropriate form to |
| 1452 |
* insert into the top query, except that we may need to wrap them in |
| 1453 |
* PlaceHolderVars. Set up required context data for pullup_replace_vars. |
| 1454 |
* (Note that we should include the subquery's inner joins in relids, |
| 1455 |
* since it may include join alias vars referencing them.) |
| 1456 |
*/ |
| 1457 |
rvcontext.root = root; |
| 1458 |
rvcontext.targetlist = subquery->targetList; |
| 1459 |
rvcontext.target_rte = rte; |
| 1460 |
rvcontext.result_relation = 0; |
| 1461 |
if (rte->lateral) |
| 1462 |
{ |
| 1463 |
rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, |
| 1464 |
true, true); |
| 1465 |
rvcontext.nullinfo = get_nullingrels(parse); |
| 1466 |
} |
| 1467 |
else /* won't need these values */ |
| 1468 |
{ |
| 1469 |
rvcontext.relids = NULL; |
| 1470 |
rvcontext.nullinfo = NULL; |
| 1471 |
} |
| 1472 |
rvcontext.outer_hasSubLinks = &parse->hasSubLinks; |
| 1473 |
rvcontext.varno = varno; |
| 1474 |
/* this flag will be set below, if needed */ |
| 1475 |
rvcontext.wrap_option = REPLACE_WRAP_NONE; |
| 1476 |
/* initialize cache array with indexes 0 .. length(tlist) */ |
| 1477 |
rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) * |
| 1478 |
sizeof(Node *)); |
| 1479 |
|
| 1480 |
/* |
| 1481 |
* If the parent query uses grouping sets, we need a PlaceHolderVar for |
| 1482 |
* each expression of the subquery's targetlist items. This ensures that |
| 1483 |
* expressions retain their separate identity so that they will match |
| 1484 |
* grouping set columns when appropriate. (It'd be sufficient to wrap |
| 1485 |
* values used in grouping set columns, and do so only in non-aggregated |
| 1486 |
* portions of the tlist and havingQual, but that would require a lot of |
| 1487 |
* infrastructure that pullup_replace_vars hasn't currently got.) |
| 1488 |
*/ |
| 1489 |
if (parse->groupingSets) |
| 1490 |
rvcontext.wrap_option = REPLACE_WRAP_ALL; |
| 1491 |
|
| 1492 |
/* |
| 1493 |
* Replace all of the top query's references to the subquery's outputs |
| 1494 |
* with copies of the adjusted subtlist items, being careful not to |
| 1495 |
* replace any of the jointree structure. |
| 1496 |
*/ |
| 1497 |
perform_pullup_replace_vars(root, &rvcontext, |
| 1498 |
containing_appendrel); |
| 1499 |
|
| 1500 |
/* |
| 1501 |
* If the subquery had a LATERAL marker, propagate that to any of its |
| 1502 |
* child RTEs that could possibly now contain lateral cross-references. |
| 1503 |
* The children might or might not contain any actual lateral |
| 1504 |
* cross-references, but we have to mark the pulled-up child RTEs so that |
| 1505 |
* later planner stages will check for such. |
| 1506 |
*/ |
| 1507 |
if (rte->lateral) |
| 1508 |
{ |
| 1509 |
foreach(lc, subquery->rtable) |
| 1510 |
{ |
| 1511 |
RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc); |
| 1512 |
|
| 1513 |
switch (child_rte->rtekind) |
| 1514 |
{ |
| 1515 |
case RTE_RELATION: |
| 1516 |
if (child_rte->tablesample) |
| 1517 |
child_rte->lateral = true; |
| 1518 |
break; |
| 1519 |
case RTE_SUBQUERY: |
| 1520 |
case RTE_FUNCTION: |
| 1521 |
case RTE_VALUES: |
| 1522 |
case RTE_TABLEFUNC: |
| 1523 |
child_rte->lateral = true; |
| 1524 |
break; |
| 1525 |
case RTE_JOIN: |
| 1526 |
case RTE_CTE: |
| 1527 |
case RTE_NAMEDTUPLESTORE: |
| 1528 |
case RTE_RESULT: |
| 1529 |
case RTE_GROUP: |
| 1530 |
/* these can't contain any lateral references */ |
| 1531 |
break; |
| 1532 |
} |
| 1533 |
} |
| 1534 |
} |
| 1535 |
|
| 1536 |
/* |
| 1537 |
* Now append the adjusted rtable entries and their perminfos to upper |
| 1538 |
* query. (We hold off until after fixing the upper rtable entries; no |
| 1539 |
* point in running that code on the subquery ones too.) |
| 1540 |
*/ |
| 1541 |
CombineRangeTables(&parse->rtable, &parse->rteperminfos, |
| 1542 |
subquery->rtable, subquery->rteperminfos); |
| 1543 |
|
| 1544 |
/* |
| 1545 |
* Pull up any FOR UPDATE/SHARE markers, too. (OffsetVarNodes already |
| 1546 |
* adjusted the marker rtindexes, so just concat the lists.) |
| 1547 |
*/ |
| 1548 |
parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks); |
| 1549 |
|
| 1550 |
/* |
| 1551 |
* We also have to fix the relid sets of any PlaceHolderVar nodes in the |
| 1552 |
* parent query. (This could perhaps be done by pullup_replace_vars(), |
| 1553 |
* but it seems cleaner to use two passes.) Note in particular that any |
| 1554 |
* PlaceHolderVar nodes just created by pullup_replace_vars() will be |
| 1555 |
* adjusted, so having created them with the subquery's varno is correct. |
| 1556 |
* |
| 1557 |
* Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We |
| 1558 |
* already checked that this won't require introducing multiple subrelids |
| 1559 |
* into the single-slot AppendRelInfo structs. |
| 1560 |
*/ |
| 1561 |
if (root->glob->lastPHId != 0 || root->append_rel_list) |
| 1562 |
{ |
| 1563 |
Relids subrelids; |
| 1564 |
|
| 1565 |
subrelids = get_relids_in_jointree((Node *) subquery->jointree, |
| 1566 |
true, false); |
| 1567 |
if (root->glob->lastPHId != 0) |
| 1568 |
substitute_phv_relids((Node *) parse, varno, subrelids); |
| 1569 |
fix_append_rel_relids(root, varno, subrelids); |
| 1570 |
} |
| 1571 |
|
| 1572 |
/* |
| 1573 |
* And now add subquery's AppendRelInfos to our list. |
| 1574 |
*/ |
| 1575 |
root->append_rel_list = list_concat(root->append_rel_list, |
| 1576 |
subroot->append_rel_list); |
| 1577 |
|
| 1578 |
/* |
| 1579 |
* We don't have to do the equivalent bookkeeping for outer-join info, |
| 1580 |
* because that hasn't been set up yet. placeholder_list likewise. |
| 1581 |
*/ |
| 1582 |
Assert(root->join_info_list == NIL); |
| 1583 |
Assert(subroot->join_info_list == NIL); |
| 1584 |
Assert(root->placeholder_list == NIL); |
| 1585 |
Assert(subroot->placeholder_list == NIL); |
| 1586 |
|
| 1587 |
/* |
| 1588 |
* We no longer need the RTE's copy of the subquery's query tree. Getting |
| 1589 |
* rid of it saves nothing in particular so far as this level of query is |
| 1590 |
* concerned; but if this query level is in turn pulled up into a parent, |
| 1591 |
* we'd waste cycles copying the now-unused query tree. |
| 1592 |
*/ |
| 1593 |
rte->subquery = NULL; |
| 1594 |
|
| 1595 |
/* |
| 1596 |
* Miscellaneous housekeeping. |
| 1597 |
* |
| 1598 |
* Although replace_rte_variables() faithfully updated parse->hasSubLinks |
| 1599 |
* if it copied any SubLinks out of the subquery's targetlist, we still |
| 1600 |
* could have SubLinks added to the query in the expressions of FUNCTION |
| 1601 |
* and VALUES RTEs copied up from the subquery. So it's necessary to copy |
| 1602 |
* subquery->hasSubLinks anyway. Perhaps this can be improved someday. |
| 1603 |
*/ |
| 1604 |
parse->hasSubLinks |= subquery->hasSubLinks; |
| 1605 |
|
| 1606 |
/* If subquery had any RLS conditions, now main query does too */ |
| 1607 |
parse->hasRowSecurity |= subquery->hasRowSecurity; |
| 1608 |
|
| 1609 |
/* |
| 1610 |
* subquery won't be pulled up if it hasAggs, hasWindowFuncs, or |
| 1611 |
* hasTargetSRFs, so no work needed on those flags |
| 1612 |
*/ |
| 1613 |
|
| 1614 |
/* |
| 1615 |
* Return the adjusted subquery jointree to replace the RangeTblRef entry |
| 1616 |
* in parent's jointree; or, if the FromExpr is degenerate, just return |
| 1617 |
* its single member. |
| 1618 |
*/ |
| 1619 |
Assert(IsA(subquery->jointree, FromExpr)); |
| 1620 |
Assert(subquery->jointree->fromlist != NIL); |
| 1621 |
if (subquery->jointree->quals == NULL && |
| 1622 |
list_length(subquery->jointree->fromlist) == 1) |
| 1623 |
return (Node *) linitial(subquery->jointree->fromlist); |
| 1624 |
|
| 1625 |
return (Node *) subquery->jointree; |
| 1626 |
} |
| 1627 |
|
| 1628 |
/* |
| 1629 |
* pull_up_simple_union_all |
| 1630 |
* Pull up a single simple UNION ALL subquery. |
| 1631 |
* |
| 1632 |
* jtnode is a RangeTblRef that has been identified as a simple UNION ALL |
| 1633 |
* subquery by pull_up_subqueries. We pull up the leaf subqueries and |
| 1634 |
* build an "append relation" for the union set. The result value is just |
| 1635 |
* jtnode, since we don't actually need to change the query jointree. |
| 1636 |
*/ |
| 1637 |
static Node * |
| 1638 |
pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) |
| 1639 |
{ |
| 1640 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 1641 |
Query *subquery = rte->subquery; |
| 1642 |
int rtoffset = list_length(root->parse->rtable); |
| 1643 |
List *rtable; |
| 1644 |
|
| 1645 |
/* |
| 1646 |
* Make a modifiable copy of the subquery's rtable, so we can adjust |
| 1647 |
* upper-level Vars in it. There are no such Vars in the setOperations |
| 1648 |
* tree proper, so fixing the rtable should be sufficient. |
| 1649 |
*/ |
| 1650 |
rtable = copyObject(subquery->rtable); |
| 1651 |
|
| 1652 |
/* |
| 1653 |
* Upper-level vars in subquery are now one level closer to their parent |
| 1654 |
* than before. We don't have to worry about offsetting varnos, though, |
| 1655 |
* because the UNION leaf queries can't cross-reference each other. |
| 1656 |
*/ |
| 1657 |
IncrementVarSublevelsUp_rtable(rtable, -1, 1); |
| 1658 |
|
| 1659 |
/* |
| 1660 |
* If the UNION ALL subquery had a LATERAL marker, propagate that to all |
| 1661 |
* its children. The individual children might or might not contain any |
| 1662 |
* actual lateral cross-references, but we have to mark the pulled-up |
| 1663 |
* child RTEs so that later planner stages will check for such. |
| 1664 |
*/ |
| 1665 |
if (rte->lateral) |
| 1666 |
{ |
| 1667 |
ListCell *rt; |
| 1668 |
|
| 1669 |
foreach(rt, rtable) |
| 1670 |
{ |
| 1671 |
RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(rt); |
| 1672 |
|
| 1673 |
Assert(child_rte->rtekind == RTE_SUBQUERY); |
| 1674 |
child_rte->lateral = true; |
| 1675 |
} |
| 1676 |
} |
| 1677 |
|
| 1678 |
/* |
| 1679 |
* Append child RTEs (and their perminfos) to parent rtable. |
| 1680 |
*/ |
| 1681 |
CombineRangeTables(&root->parse->rtable, &root->parse->rteperminfos, |
| 1682 |
rtable, subquery->rteperminfos); |
| 1683 |
|
| 1684 |
/* |
| 1685 |
* Recursively scan the subquery's setOperations tree and add |
| 1686 |
* AppendRelInfo nodes for leaf subqueries to the parent's |
| 1687 |
* append_rel_list. Also apply pull_up_subqueries to the leaf subqueries. |
| 1688 |
*/ |
| 1689 |
Assert(subquery->setOperations); |
| 1690 |
pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery, |
| 1691 |
rtoffset); |
| 1692 |
|
| 1693 |
/* |
| 1694 |
* Mark the parent as an append relation. |
| 1695 |
*/ |
| 1696 |
rte->inh = true; |
| 1697 |
|
| 1698 |
return jtnode; |
| 1699 |
} |
| 1700 |
|
| 1701 |
/* |
| 1702 |
* pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all |
| 1703 |
* |
| 1704 |
* Build an AppendRelInfo for each leaf query in the setop tree, and then |
| 1705 |
* apply pull_up_subqueries to the leaf query. |
| 1706 |
* |
| 1707 |
* Note that setOpQuery is the Query containing the setOp node, whose tlist |
| 1708 |
* contains references to all the setop output columns. When called from |
| 1709 |
* pull_up_simple_union_all, this is *not* the same as root->parse, which is |
| 1710 |
* the parent Query we are pulling up into. |
| 1711 |
* |
| 1712 |
* parentRTindex is the appendrel parent's index in root->parse->rtable. |
| 1713 |
* |
| 1714 |
* The child RTEs have already been copied to the parent. childRToffset |
| 1715 |
* tells us where in the parent's range table they were copied. When called |
| 1716 |
* from flatten_simple_union_all, childRToffset is 0 since the child RTEs |
| 1717 |
* were already in root->parse->rtable and no RT index adjustment is needed. |
| 1718 |
*/ |
| 1719 |
static void |
| 1720 |
pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex, |
| 1721 |
Query *setOpQuery, int childRToffset) |
| 1722 |
{ |
| 1723 |
if (IsA(setOp, RangeTblRef)) |
| 1724 |
{ |
| 1725 |
RangeTblRef *rtr = (RangeTblRef *) setOp; |
| 1726 |
int childRTindex; |
| 1727 |
AppendRelInfo *appinfo; |
| 1728 |
|
| 1729 |
/* |
| 1730 |
* Calculate the index in the parent's range table |
| 1731 |
*/ |
| 1732 |
childRTindex = childRToffset + rtr->rtindex; |
| 1733 |
|
| 1734 |
/* |
| 1735 |
* Build a suitable AppendRelInfo, and attach to parent's list. |
| 1736 |
*/ |
| 1737 |
appinfo = makeNode(AppendRelInfo); |
| 1738 |
appinfo->parent_relid = parentRTindex; |
| 1739 |
appinfo->child_relid = childRTindex; |
| 1740 |
appinfo->parent_reltype = InvalidOid; |
| 1741 |
appinfo->child_reltype = InvalidOid; |
| 1742 |
make_setop_translation_list(setOpQuery, childRTindex, appinfo); |
| 1743 |
appinfo->parent_reloid = InvalidOid; |
| 1744 |
root->append_rel_list = lappend(root->append_rel_list, appinfo); |
| 1745 |
|
| 1746 |
/* |
| 1747 |
* Recursively apply pull_up_subqueries to the new child RTE. (We |
| 1748 |
* must build the AppendRelInfo first, because this will modify it; |
| 1749 |
* indeed, that's the only part of the upper query where Vars |
| 1750 |
* referencing childRTindex can exist at this point.) |
| 1751 |
* |
| 1752 |
* Note that we can pass NULL for containing-join info even if we're |
| 1753 |
* actually under an outer join, because the child's expressions |
| 1754 |
* aren't going to propagate up to the join. Also, we ignore the |
| 1755 |
* possibility that pull_up_subqueries_recurse() returns a different |
| 1756 |
* jointree node than what we pass it; if it does, the important thing |
| 1757 |
* is that it replaced the child relid in the AppendRelInfo node. |
| 1758 |
*/ |
| 1759 |
rtr = makeNode(RangeTblRef); |
| 1760 |
rtr->rtindex = childRTindex; |
| 1761 |
(void) pull_up_subqueries_recurse(root, (Node *) rtr, |
| 1762 |
NULL, appinfo); |
| 1763 |
} |
| 1764 |
else if (IsA(setOp, SetOperationStmt)) |
| 1765 |
{ |
| 1766 |
SetOperationStmt *op = (SetOperationStmt *) setOp; |
| 1767 |
|
| 1768 |
/* Recurse to reach leaf queries */ |
| 1769 |
pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery, |
| 1770 |
childRToffset); |
| 1771 |
pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery, |
| 1772 |
childRToffset); |
| 1773 |
} |
| 1774 |
else |
| 1775 |
{ |
| 1776 |
elog(ERROR, "unrecognized node type: %d", |
| 1777 |
(int) nodeTag(setOp)); |
| 1778 |
} |
| 1779 |
} |
| 1780 |
|
| 1781 |
/* |
| 1782 |
* make_setop_translation_list |
| 1783 |
* Build the list of translations from parent Vars to child Vars for |
| 1784 |
* a UNION ALL member. (At this point it's just a simple list of |
| 1785 |
* referencing Vars, but if we succeed in pulling up the member |
| 1786 |
* subquery, the Vars will get replaced by pulled-up expressions.) |
| 1787 |
* Also create the rather trivial reverse-translation array. |
| 1788 |
*/ |
| 1789 |
static void |
| 1790 |
make_setop_translation_list(Query *query, int newvarno, |
| 1791 |
AppendRelInfo *appinfo) |
| 1792 |
{ |
| 1793 |
List *vars = NIL; |
| 1794 |
AttrNumber *pcolnos; |
| 1795 |
ListCell *l; |
| 1796 |
|
| 1797 |
/* Initialize reverse-translation array with all entries zero */ |
| 1798 |
/* (entries for resjunk columns will stay that way) */ |
| 1799 |
appinfo->num_child_cols = list_length(query->targetList); |
| 1800 |
appinfo->parent_colnos = pcolnos = |
| 1801 |
(AttrNumber *) palloc0(appinfo->num_child_cols * sizeof(AttrNumber)); |
| 1802 |
|
| 1803 |
foreach(l, query->targetList) |
| 1804 |
{ |
| 1805 |
TargetEntry *tle = (TargetEntry *) lfirst(l); |
| 1806 |
|
| 1807 |
if (tle->resjunk) |
| 1808 |
continue; |
| 1809 |
|
| 1810 |
vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle)); |
| 1811 |
pcolnos[tle->resno - 1] = tle->resno; |
| 1812 |
} |
| 1813 |
|
| 1814 |
appinfo->translated_vars = vars; |
| 1815 |
} |
| 1816 |
|
| 1817 |
/* |
| 1818 |
* is_simple_subquery |
| 1819 |
* Check a subquery in the range table to see if it's simple enough |
| 1820 |
* to pull up into the parent query. |
| 1821 |
* |
| 1822 |
* rte is the RTE_SUBQUERY RangeTblEntry that contained the subquery. |
| 1823 |
* (Note subquery is not necessarily equal to rte->subquery; it could be a |
| 1824 |
* processed copy of that.) |
| 1825 |
* lowest_outer_join is the lowest outer join above the subquery, or NULL. |
| 1826 |
*/ |
| 1827 |
static bool |
| 1828 |
is_simple_subquery(PlannerInfo *root, Query *subquery, RangeTblEntry *rte, |
| 1829 |
JoinExpr *lowest_outer_join) |
| 1830 |
{ |
| 1831 |
/* |
| 1832 |
* Let's just make sure it's a valid subselect ... |
| 1833 |
*/ |
| 1834 |
if (!IsA(subquery, Query) || |
| 1835 |
subquery->commandType != CMD_SELECT) |
| 1836 |
elog(ERROR, "subquery is bogus"); |
| 1837 |
|
| 1838 |
/* |
| 1839 |
* Can't currently pull up a query with setops (unless it's simple UNION |
| 1840 |
* ALL, which is handled by a different code path). Maybe after querytree |
| 1841 |
* redesign... |
| 1842 |
*/ |
| 1843 |
if (subquery->setOperations) |
| 1844 |
return false; |
| 1845 |
|
| 1846 |
/* |
| 1847 |
* Can't pull up a subquery involving grouping, aggregation, SRFs, |
| 1848 |
* sorting, limiting, or WITH. (XXX WITH could possibly be allowed later) |
| 1849 |
* |
| 1850 |
* We also don't pull up a subquery that has explicit FOR UPDATE/SHARE |
| 1851 |
* clauses, because pullup would cause the locking to occur semantically |
| 1852 |
* higher than it should. Implicit FOR UPDATE/SHARE is okay because in |
| 1853 |
* that case the locking was originally declared in the upper query |
| 1854 |
* anyway. |
| 1855 |
*/ |
| 1856 |
if (subquery->hasAggs || |
| 1857 |
subquery->hasWindowFuncs || |
| 1858 |
subquery->hasTargetSRFs || |
| 1859 |
subquery->groupClause || |
| 1860 |
subquery->groupingSets || |
| 1861 |
subquery->havingQual || |
| 1862 |
subquery->sortClause || |
| 1863 |
subquery->distinctClause || |
| 1864 |
subquery->limitOffset || |
| 1865 |
subquery->limitCount || |
| 1866 |
subquery->hasForUpdate || |
| 1867 |
subquery->cteList) |
| 1868 |
return false; |
| 1869 |
|
| 1870 |
/* |
| 1871 |
* Don't pull up if the RTE represents a security-barrier view; we |
| 1872 |
* couldn't prevent information leakage once the RTE's Vars are scattered |
| 1873 |
* about in the upper query. |
| 1874 |
*/ |
| 1875 |
if (rte->security_barrier) |
| 1876 |
return false; |
| 1877 |
|
| 1878 |
/* |
| 1879 |
* If the subquery is LATERAL, check for pullup restrictions from that. |
| 1880 |
*/ |
| 1881 |
if (rte->lateral) |
| 1882 |
{ |
| 1883 |
bool restricted; |
| 1884 |
Relids safe_upper_varnos; |
| 1885 |
|
| 1886 |
/* |
| 1887 |
* The subquery's WHERE and JOIN/ON quals mustn't contain any lateral |
| 1888 |
* references to rels outside a higher outer join (including the case |
| 1889 |
* where the outer join is within the subquery itself). In such a |
| 1890 |
* case, pulling up would result in a situation where we need to |
| 1891 |
* postpone quals from below an outer join to above it, which is |
| 1892 |
* probably completely wrong and in any case is a complication that |
| 1893 |
* doesn't seem worth addressing at the moment. |
| 1894 |
*/ |
| 1895 |
if (lowest_outer_join != NULL) |
| 1896 |
{ |
| 1897 |
restricted = true; |
| 1898 |
safe_upper_varnos = get_relids_in_jointree((Node *) lowest_outer_join, |
| 1899 |
true, true); |
| 1900 |
} |
| 1901 |
else |
| 1902 |
{ |
| 1903 |
restricted = false; |
| 1904 |
safe_upper_varnos = NULL; /* doesn't matter */ |
| 1905 |
} |
| 1906 |
|
| 1907 |
if (jointree_contains_lateral_outer_refs(root, |
| 1908 |
(Node *) subquery->jointree, |
| 1909 |
restricted, safe_upper_varnos)) |
| 1910 |
return false; |
| 1911 |
|
| 1912 |
/* |
| 1913 |
* If there's an outer join above the LATERAL subquery, also disallow |
| 1914 |
* pullup if the subquery's targetlist has any references to rels |
| 1915 |
* outside the outer join, since these might get pulled into quals |
| 1916 |
* above the subquery (but in or below the outer join) and then lead |
| 1917 |
* to qual-postponement issues similar to the case checked for above. |
| 1918 |
* (We wouldn't need to prevent pullup if no such references appear in |
| 1919 |
* outer-query quals, but we don't have enough info here to check |
| 1920 |
* that. Also, maybe this restriction could be removed if we forced |
| 1921 |
* such refs to be wrapped in PlaceHolderVars, even when they're below |
| 1922 |
* the nearest outer join? But it's a pretty hokey usage, so not |
| 1923 |
* clear this is worth sweating over.) |
| 1924 |
* |
| 1925 |
* If you change this, see also the comments about lateral references |
| 1926 |
* in pullup_replace_vars_callback(). |
| 1927 |
*/ |
| 1928 |
if (lowest_outer_join != NULL) |
| 1929 |
{ |
| 1930 |
Relids lvarnos = pull_varnos_of_level(root, |
| 1931 |
(Node *) subquery->targetList, |
| 1932 |
1); |
| 1933 |
|
| 1934 |
if (!bms_is_subset(lvarnos, safe_upper_varnos)) |
| 1935 |
return false; |
| 1936 |
} |
| 1937 |
} |
| 1938 |
|
| 1939 |
/* |
| 1940 |
* Don't pull up a subquery that has any volatile functions in its |
| 1941 |
* targetlist. Otherwise we might introduce multiple evaluations of these |
| 1942 |
* functions, if they get copied to multiple places in the upper query, |
| 1943 |
* leading to surprising results. (Note: the PlaceHolderVar mechanism |
| 1944 |
* doesn't quite guarantee single evaluation; else we could pull up anyway |
| 1945 |
* and just wrap such items in PlaceHolderVars ...) |
| 1946 |
*/ |
| 1947 |
if (contain_volatile_functions((Node *) subquery->targetList)) |
| 1948 |
return false; |
| 1949 |
|
| 1950 |
return true; |
| 1951 |
} |
| 1952 |
|
| 1953 |
/* |
| 1954 |
* pull_up_simple_values |
| 1955 |
* Pull up a single simple VALUES RTE. |
| 1956 |
* |
| 1957 |
* jtnode is a RangeTblRef that has been identified as a simple VALUES RTE |
| 1958 |
* by pull_up_subqueries. We always return a RangeTblRef representing a |
| 1959 |
* RESULT RTE to replace it (all failure cases should have been detected by |
| 1960 |
* is_simple_values()). Actually, what we return is just jtnode, because |
| 1961 |
* we replace the VALUES RTE in the rangetable with the RESULT RTE. |
| 1962 |
* |
| 1963 |
* rte is the RangeTblEntry referenced by jtnode. Because of the limited |
| 1964 |
* possible usage of VALUES RTEs, we do not need the remaining parameters |
| 1965 |
* of pull_up_subqueries_recurse. |
| 1966 |
*/ |
| 1967 |
static Node * |
| 1968 |
pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) |
| 1969 |
{ |
| 1970 |
Query *parse = root->parse; |
| 1971 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 1972 |
List *values_list; |
| 1973 |
List *tlist; |
| 1974 |
AttrNumber attrno; |
| 1975 |
pullup_replace_vars_context rvcontext; |
| 1976 |
ListCell *lc; |
| 1977 |
|
| 1978 |
Assert(rte->rtekind == RTE_VALUES); |
| 1979 |
Assert(list_length(rte->values_lists) == 1); |
| 1980 |
|
| 1981 |
/* |
| 1982 |
* Need a modifiable copy of the VALUES list to hack on, just in case it's |
| 1983 |
* multiply referenced. |
| 1984 |
*/ |
| 1985 |
values_list = copyObject(linitial(rte->values_lists)); |
| 1986 |
|
| 1987 |
/* |
| 1988 |
* The VALUES RTE can't contain any Vars of level zero, let alone any that |
| 1989 |
* are join aliases, so no need to flatten join alias Vars. |
| 1990 |
*/ |
| 1991 |
Assert(!contain_vars_of_level((Node *) values_list, 0)); |
| 1992 |
|
| 1993 |
/* |
| 1994 |
* Set up required context data for pullup_replace_vars. In particular, |
| 1995 |
* we have to make the VALUES list look like a subquery targetlist. |
| 1996 |
*/ |
| 1997 |
tlist = NIL; |
| 1998 |
attrno = 1; |
| 1999 |
foreach(lc, values_list) |
| 2000 |
{ |
| 2001 |
tlist = lappend(tlist, |
| 2002 |
makeTargetEntry((Expr *) lfirst(lc), |
| 2003 |
attrno, |
| 2004 |
NULL, |
| 2005 |
false)); |
| 2006 |
attrno++; |
| 2007 |
} |
| 2008 |
rvcontext.root = root; |
| 2009 |
rvcontext.targetlist = tlist; |
| 2010 |
rvcontext.target_rte = rte; |
| 2011 |
rvcontext.result_relation = 0; |
| 2012 |
rvcontext.relids = NULL; /* can't be any lateral references here */ |
| 2013 |
rvcontext.nullinfo = NULL; |
| 2014 |
rvcontext.outer_hasSubLinks = &parse->hasSubLinks; |
| 2015 |
rvcontext.varno = varno; |
| 2016 |
rvcontext.wrap_option = REPLACE_WRAP_NONE; |
| 2017 |
/* initialize cache array with indexes 0 .. length(tlist) */ |
| 2018 |
rvcontext.rv_cache = palloc0((list_length(tlist) + 1) * |
| 2019 |
sizeof(Node *)); |
| 2020 |
|
| 2021 |
/* |
| 2022 |
* Replace all of the top query's references to the RTE's outputs with |
| 2023 |
* copies of the adjusted VALUES expressions, being careful not to replace |
| 2024 |
* any of the jointree structure. We can assume there's no outer joins or |
| 2025 |
* appendrels in the dummy Query that surrounds a VALUES RTE. |
| 2026 |
*/ |
| 2027 |
perform_pullup_replace_vars(root, &rvcontext, NULL); |
| 2028 |
|
| 2029 |
/* |
| 2030 |
* There should be no appendrels to fix, nor any outer joins and hence no |
| 2031 |
* PlaceHolderVars. |
| 2032 |
*/ |
| 2033 |
Assert(root->append_rel_list == NIL); |
| 2034 |
Assert(root->join_info_list == NIL); |
| 2035 |
Assert(root->placeholder_list == NIL); |
| 2036 |
|
| 2037 |
/* |
| 2038 |
* Replace the VALUES RTE with a RESULT RTE. The VALUES RTE is the only |
| 2039 |
* rtable entry in the current query level, so this is easy. |
| 2040 |
*/ |
| 2041 |
Assert(list_length(parse->rtable) == 1); |
| 2042 |
|
| 2043 |
/* Create suitable RTE */ |
| 2044 |
rte = makeNode(RangeTblEntry); |
| 2045 |
rte->rtekind = RTE_RESULT; |
| 2046 |
rte->eref = makeAlias("*RESULT*", NIL); |
| 2047 |
|
| 2048 |
/* Replace rangetable */ |
| 2049 |
parse->rtable = list_make1(rte); |
| 2050 |
|
| 2051 |
/* We could manufacture a new RangeTblRef, but the one we have is fine */ |
| 2052 |
Assert(varno == 1); |
| 2053 |
|
| 2054 |
return jtnode; |
| 2055 |
} |
| 2056 |
|
| 2057 |
/* |
| 2058 |
* is_simple_values |
| 2059 |
* Check a VALUES RTE in the range table to see if it's simple enough |
| 2060 |
* to pull up into the parent query. |
| 2061 |
* |
| 2062 |
* rte is the RTE_VALUES RangeTblEntry to check. |
| 2063 |
*/ |
| 2064 |
static bool |
| 2065 |
is_simple_values(PlannerInfo *root, RangeTblEntry *rte) |
| 2066 |
{ |
| 2067 |
Assert(rte->rtekind == RTE_VALUES); |
| 2068 |
|
| 2069 |
/* |
| 2070 |
* There must be exactly one VALUES list, else it's not semantically |
| 2071 |
* correct to replace the VALUES RTE with a RESULT RTE, nor would we have |
| 2072 |
* a unique set of expressions to substitute into the parent query. |
| 2073 |
*/ |
| 2074 |
if (list_length(rte->values_lists) != 1) |
| 2075 |
return false; |
| 2076 |
|
| 2077 |
/* |
| 2078 |
* Because VALUES can't appear under an outer join (or at least, we won't |
| 2079 |
* try to pull it up if it does), we need not worry about LATERAL, nor |
| 2080 |
* about validity of PHVs for the VALUES' outputs. |
| 2081 |
*/ |
| 2082 |
|
| 2083 |
/* |
| 2084 |
* Don't pull up a VALUES that contains any set-returning or volatile |
| 2085 |
* functions. The considerations here are basically identical to the |
| 2086 |
* restrictions on a pull-able subquery's targetlist. |
| 2087 |
*/ |
| 2088 |
if (expression_returns_set((Node *) rte->values_lists) || |
| 2089 |
contain_volatile_functions((Node *) rte->values_lists)) |
| 2090 |
return false; |
| 2091 |
|
| 2092 |
/* |
| 2093 |
* Do not pull up a VALUES that's not the only RTE in its parent query. |
| 2094 |
* This is actually the only case that the parser will generate at the |
| 2095 |
* moment, and assuming this is true greatly simplifies |
| 2096 |
* pull_up_simple_values(). |
| 2097 |
*/ |
| 2098 |
if (list_length(root->parse->rtable) != 1 || |
| 2099 |
rte != (RangeTblEntry *) linitial(root->parse->rtable)) |
| 2100 |
return false; |
| 2101 |
|
| 2102 |
return true; |
| 2103 |
} |
| 2104 |
|
| 2105 |
/* |
| 2106 |
* pull_up_constant_function |
| 2107 |
* Pull up an RTE_FUNCTION expression that was simplified to a constant. |
| 2108 |
* |
| 2109 |
* jtnode is a RangeTblRef that has been identified as a FUNCTION RTE by |
| 2110 |
* pull_up_subqueries. If its expression is just a Const, hoist that value |
| 2111 |
* up into the parent query, and replace the RTE_FUNCTION with RTE_RESULT. |
| 2112 |
* |
| 2113 |
* In principle we could pull up any immutable expression, but we don't. |
| 2114 |
* That might result in multiple evaluations of the expression, which could |
| 2115 |
* be costly if it's not just a Const. Also, the main value of this is |
| 2116 |
* to let the constant participate in further const-folding, and of course |
| 2117 |
* that won't happen for a non-Const. |
| 2118 |
* |
| 2119 |
* The pulled-up value might need to be wrapped in a PlaceHolderVar if the |
| 2120 |
* RTE is below an outer join or is part of an appendrel; the extra |
| 2121 |
* parameters show whether that's needed. |
| 2122 |
*/ |
| 2123 |
static Node * |
| 2124 |
pull_up_constant_function(PlannerInfo *root, Node *jtnode, |
| 2125 |
RangeTblEntry *rte, |
| 2126 |
AppendRelInfo *containing_appendrel) |
| 2127 |
{ |
| 2128 |
Query *parse = root->parse; |
| 2129 |
RangeTblFunction *rtf; |
| 2130 |
TypeFuncClass functypclass; |
| 2131 |
Oid funcrettype; |
| 2132 |
TupleDesc tupdesc; |
| 2133 |
pullup_replace_vars_context rvcontext; |
| 2134 |
|
| 2135 |
/* Fail if the RTE has ORDINALITY - we don't implement that here. */ |
| 2136 |
if (rte->funcordinality) |
| 2137 |
return jtnode; |
| 2138 |
|
| 2139 |
/* Fail if RTE isn't a single, simple Const expr */ |
| 2140 |
if (list_length(rte->functions) != 1) |
| 2141 |
return jtnode; |
| 2142 |
rtf = linitial_node(RangeTblFunction, rte->functions); |
| 2143 |
if (!IsA(rtf->funcexpr, Const)) |
| 2144 |
return jtnode; |
| 2145 |
|
| 2146 |
/* |
| 2147 |
* If the function's result is not a scalar, we punt. In principle we |
| 2148 |
* could break the composite constant value apart into per-column |
| 2149 |
* constants, but for now it seems not worth the work. |
| 2150 |
*/ |
| 2151 |
if (rtf->funccolcount != 1) |
| 2152 |
return jtnode; /* definitely composite */ |
| 2153 |
|
| 2154 |
/* If it has a coldeflist, it certainly returns RECORD */ |
| 2155 |
if (rtf->funccolnames != NIL) |
| 2156 |
return jtnode; /* must be a one-column RECORD type */ |
| 2157 |
|
| 2158 |
functypclass = get_expr_result_type(rtf->funcexpr, |
| 2159 |
&funcrettype, |
| 2160 |
&tupdesc); |
| 2161 |
if (functypclass != TYPEFUNC_SCALAR) |
| 2162 |
return jtnode; /* must be a one-column composite type */ |
| 2163 |
|
| 2164 |
/* Create context for applying pullup_replace_vars */ |
| 2165 |
rvcontext.root = root; |
| 2166 |
rvcontext.targetlist = list_make1(makeTargetEntry((Expr *) rtf->funcexpr, |
| 2167 |
1, /* resno */ |
| 2168 |
NULL, /* resname */ |
| 2169 |
false)); /* resjunk */ |
| 2170 |
rvcontext.target_rte = rte; |
| 2171 |
rvcontext.result_relation = 0; |
| 2172 |
|
| 2173 |
/* |
| 2174 |
* Since this function was reduced to a Const, it doesn't contain any |
| 2175 |
* lateral references, even if it's marked as LATERAL. This means we |
| 2176 |
* don't need to fill relids or nullinfo. |
| 2177 |
*/ |
| 2178 |
rvcontext.relids = NULL; |
| 2179 |
rvcontext.nullinfo = NULL; |
| 2180 |
|
| 2181 |
rvcontext.outer_hasSubLinks = &parse->hasSubLinks; |
| 2182 |
rvcontext.varno = ((RangeTblRef *) jtnode)->rtindex; |
| 2183 |
/* this flag will be set below, if needed */ |
| 2184 |
rvcontext.wrap_option = REPLACE_WRAP_NONE; |
| 2185 |
/* initialize cache array with indexes 0 .. length(tlist) */ |
| 2186 |
rvcontext.rv_cache = palloc0((list_length(rvcontext.targetlist) + 1) * |
| 2187 |
sizeof(Node *)); |
| 2188 |
|
| 2189 |
/* |
| 2190 |
* If the parent query uses grouping sets, we need a PlaceHolderVar for |
| 2191 |
* each expression of the subquery's targetlist items. (See comments in |
| 2192 |
* pull_up_simple_subquery().) |
| 2193 |
*/ |
| 2194 |
if (parse->groupingSets) |
| 2195 |
rvcontext.wrap_option = REPLACE_WRAP_ALL; |
| 2196 |
|
| 2197 |
/* |
| 2198 |
* Replace all of the top query's references to the RTE's output with |
| 2199 |
* copies of the funcexpr, being careful not to replace any of the |
| 2200 |
* jointree structure. |
| 2201 |
*/ |
| 2202 |
perform_pullup_replace_vars(root, &rvcontext, |
| 2203 |
containing_appendrel); |
| 2204 |
|
| 2205 |
/* |
| 2206 |
* We don't need to bother with changing PlaceHolderVars in the parent |
| 2207 |
* query. Their references to the RT index are still good for now, and |
| 2208 |
* will get removed later if we're able to drop the RTE_RESULT. |
| 2209 |
*/ |
| 2210 |
|
| 2211 |
/* |
| 2212 |
* Convert the RTE to be RTE_RESULT type, signifying that we don't need to |
| 2213 |
* scan it anymore, and zero out RTE_FUNCTION-specific fields. Also make |
| 2214 |
* sure the RTE is not marked LATERAL, since elsewhere we don't expect |
| 2215 |
* RTE_RESULTs to be LATERAL. |
| 2216 |
*/ |
| 2217 |
rte->rtekind = RTE_RESULT; |
| 2218 |
rte->functions = NIL; |
| 2219 |
rte->lateral = false; |
| 2220 |
|
| 2221 |
/* |
| 2222 |
* We can reuse the RangeTblRef node. |
| 2223 |
*/ |
| 2224 |
return jtnode; |
| 2225 |
} |
| 2226 |
|
| 2227 |
/* |
| 2228 |
* is_simple_union_all |
| 2229 |
* Check a subquery to see if it's a simple UNION ALL. |
| 2230 |
* |
| 2231 |
* We require all the setops to be UNION ALL (no mixing) and there can't be |
| 2232 |
* any datatype coercions involved, ie, all the leaf queries must emit the |
| 2233 |
* same datatypes. |
| 2234 |
*/ |
| 2235 |
static bool |
| 2236 |
is_simple_union_all(Query *subquery) |
| 2237 |
{ |
| 2238 |
SetOperationStmt *topop; |
| 2239 |
|
| 2240 |
/* Let's just make sure it's a valid subselect ... */ |
| 2241 |
if (!IsA(subquery, Query) || |
| 2242 |
subquery->commandType != CMD_SELECT) |
| 2243 |
elog(ERROR, "subquery is bogus"); |
| 2244 |
|
| 2245 |
/* Is it a set-operation query at all? */ |
| 2246 |
topop = castNode(SetOperationStmt, subquery->setOperations); |
| 2247 |
if (!topop) |
| 2248 |
return false; |
| 2249 |
|
| 2250 |
/* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */ |
| 2251 |
if (subquery->sortClause || |
| 2252 |
subquery->limitOffset || |
| 2253 |
subquery->limitCount || |
| 2254 |
subquery->rowMarks || |
| 2255 |
subquery->cteList) |
| 2256 |
return false; |
| 2257 |
|
| 2258 |
/* Recursively check the tree of set operations */ |
| 2259 |
return is_simple_union_all_recurse((Node *) topop, subquery, |
| 2260 |
topop->colTypes); |
| 2261 |
} |
| 2262 |
|
| 2263 |
static bool |
| 2264 |
is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes) |
| 2265 |
{ |
| 2266 |
/* Since this function recurses, it could be driven to stack overflow. */ |
| 2267 |
check_stack_depth(); |
| 2268 |
|
| 2269 |
if (IsA(setOp, RangeTblRef)) |
| 2270 |
{ |
| 2271 |
RangeTblRef *rtr = (RangeTblRef *) setOp; |
| 2272 |
RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable); |
| 2273 |
Query *subquery = rte->subquery; |
| 2274 |
|
| 2275 |
Assert(subquery != NULL); |
| 2276 |
|
| 2277 |
/* Leaf nodes are OK if they match the toplevel column types */ |
| 2278 |
/* We don't have to compare typmods or collations here */ |
| 2279 |
return tlist_same_datatypes(subquery->targetList, colTypes, true); |
| 2280 |
} |
| 2281 |
else if (IsA(setOp, SetOperationStmt)) |
| 2282 |
{ |
| 2283 |
SetOperationStmt *op = (SetOperationStmt *) setOp; |
| 2284 |
|
| 2285 |
/* Must be UNION ALL */ |
| 2286 |
if (op->op != SETOP_UNION || !op->all) |
| 2287 |
return false; |
| 2288 |
|
| 2289 |
/* Recurse to check inputs */ |
| 2290 |
return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) && |
| 2291 |
is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes); |
| 2292 |
} |
| 2293 |
else |
| 2294 |
{ |
| 2295 |
elog(ERROR, "unrecognized node type: %d", |
| 2296 |
(int) nodeTag(setOp)); |
| 2297 |
return false; /* keep compiler quiet */ |
| 2298 |
} |
| 2299 |
} |
| 2300 |
|
| 2301 |
/* |
| 2302 |
* is_safe_append_member |
| 2303 |
* Check a subquery that is a leaf of a UNION ALL appendrel to see if it's |
| 2304 |
* safe to pull up. |
| 2305 |
*/ |
| 2306 |
static bool |
| 2307 |
is_safe_append_member(Query *subquery) |
| 2308 |
{ |
| 2309 |
FromExpr *jtnode; |
| 2310 |
|
| 2311 |
/* |
| 2312 |
* It's only safe to pull up the child if its jointree contains exactly |
| 2313 |
* one RTE, else the AppendRelInfo data structure breaks. The one base RTE |
| 2314 |
* could be buried in several levels of FromExpr, however. Also, if the |
| 2315 |
* child's jointree is completely empty, we can pull up because |
| 2316 |
* pull_up_simple_subquery will insert a single RTE_RESULT RTE instead. |
| 2317 |
* |
| 2318 |
* Also, the child can't have any WHERE quals because there's no place to |
| 2319 |
* put them in an appendrel. (This is a bit annoying...) If we didn't |
| 2320 |
* need to check this, we'd just test whether get_relids_in_jointree() |
| 2321 |
* yields a singleton set, to be more consistent with the coding of |
| 2322 |
* fix_append_rel_relids(). |
| 2323 |
*/ |
| 2324 |
jtnode = subquery->jointree; |
| 2325 |
Assert(IsA(jtnode, FromExpr)); |
| 2326 |
/* Check the completely-empty case */ |
| 2327 |
if (jtnode->fromlist == NIL && jtnode->quals == NULL) |
| 2328 |
return true; |
| 2329 |
/* Check the more general case */ |
| 2330 |
while (IsA(jtnode, FromExpr)) |
| 2331 |
{ |
| 2332 |
if (jtnode->quals != NULL) |
| 2333 |
return false; |
| 2334 |
if (list_length(jtnode->fromlist) != 1) |
| 2335 |
return false; |
| 2336 |
jtnode = linitial(jtnode->fromlist); |
| 2337 |
} |
| 2338 |
if (!IsA(jtnode, RangeTblRef)) |
| 2339 |
return false; |
| 2340 |
|
| 2341 |
return true; |
| 2342 |
} |
| 2343 |
|
| 2344 |
/* |
| 2345 |
* jointree_contains_lateral_outer_refs |
| 2346 |
* Check for disallowed lateral references in a jointree's quals |
| 2347 |
* |
| 2348 |
* If restricted is false, all level-1 Vars are allowed (but we still must |
| 2349 |
* search the jointree, since it might contain outer joins below which there |
| 2350 |
* will be restrictions). If restricted is true, return true when any qual |
| 2351 |
* in the jointree contains level-1 Vars coming from outside the rels listed |
| 2352 |
* in safe_upper_varnos. |
| 2353 |
*/ |
| 2354 |
static bool |
| 2355 |
jointree_contains_lateral_outer_refs(PlannerInfo *root, Node *jtnode, |
| 2356 |
bool restricted, |
| 2357 |
Relids safe_upper_varnos) |
| 2358 |
{ |
| 2359 |
if (jtnode == NULL) |
| 2360 |
return false; |
| 2361 |
if (IsA(jtnode, RangeTblRef)) |
| 2362 |
return false; |
| 2363 |
else if (IsA(jtnode, FromExpr)) |
| 2364 |
{ |
| 2365 |
FromExpr *f = (FromExpr *) jtnode; |
| 2366 |
ListCell *l; |
| 2367 |
|
| 2368 |
/* First, recurse to check child joins */ |
| 2369 |
foreach(l, f->fromlist) |
| 2370 |
{ |
| 2371 |
if (jointree_contains_lateral_outer_refs(root, |
| 2372 |
lfirst(l), |
| 2373 |
restricted, |
| 2374 |
safe_upper_varnos)) |
| 2375 |
return true; |
| 2376 |
} |
| 2377 |
|
| 2378 |
/* Then check the top-level quals */ |
| 2379 |
if (restricted && |
| 2380 |
!bms_is_subset(pull_varnos_of_level(root, f->quals, 1), |
| 2381 |
safe_upper_varnos)) |
| 2382 |
return true; |
| 2383 |
} |
| 2384 |
else if (IsA(jtnode, JoinExpr)) |
| 2385 |
{ |
| 2386 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 2387 |
|
| 2388 |
/* |
| 2389 |
* If this is an outer join, we mustn't allow any upper lateral |
| 2390 |
* references in or below it. |
| 2391 |
*/ |
| 2392 |
if (j->jointype != JOIN_INNER) |
| 2393 |
{ |
| 2394 |
restricted = true; |
| 2395 |
safe_upper_varnos = NULL; |
| 2396 |
} |
| 2397 |
|
| 2398 |
/* Check the child joins */ |
| 2399 |
if (jointree_contains_lateral_outer_refs(root, |
| 2400 |
j->larg, |
| 2401 |
restricted, |
| 2402 |
safe_upper_varnos)) |
| 2403 |
return true; |
| 2404 |
if (jointree_contains_lateral_outer_refs(root, |
| 2405 |
j->rarg, |
| 2406 |
restricted, |
| 2407 |
safe_upper_varnos)) |
| 2408 |
return true; |
| 2409 |
|
| 2410 |
/* Check the JOIN's qual clauses */ |
| 2411 |
if (restricted && |
| 2412 |
!bms_is_subset(pull_varnos_of_level(root, j->quals, 1), |
| 2413 |
safe_upper_varnos)) |
| 2414 |
return true; |
| 2415 |
} |
| 2416 |
else |
| 2417 |
elog(ERROR, "unrecognized node type: %d", |
| 2418 |
(int) nodeTag(jtnode)); |
| 2419 |
return false; |
| 2420 |
} |
| 2421 |
|
| 2422 |
/* |
| 2423 |
* Perform pullup_replace_vars everyplace it's needed in the query tree. |
| 2424 |
* |
| 2425 |
* Caller has already filled *rvcontext with data describing what to |
| 2426 |
* substitute for Vars referencing the target subquery. In addition |
| 2427 |
* we need the identity of the containing appendrel if any. |
| 2428 |
*/ |
| 2429 |
static void |
| 2430 |
perform_pullup_replace_vars(PlannerInfo *root, |
| 2431 |
pullup_replace_vars_context *rvcontext, |
| 2432 |
AppendRelInfo *containing_appendrel) |
| 2433 |
{ |
| 2434 |
Query *parse = root->parse; |
| 2435 |
ListCell *lc; |
| 2436 |
|
| 2437 |
/* |
| 2438 |
* If we are considering an appendrel child subquery (that is, a UNION ALL |
| 2439 |
* member query that we're pulling up), then the only part of the upper |
| 2440 |
* query that could reference the child yet is the translated_vars list of |
| 2441 |
* the associated AppendRelInfo. Furthermore, we do not want to force use |
| 2442 |
* of PHVs in the AppendRelInfo --- there isn't any outer join between. |
| 2443 |
*/ |
| 2444 |
if (containing_appendrel) |
| 2445 |
{ |
| 2446 |
ReplaceWrapOption save_wrap_option = rvcontext->wrap_option; |
| 2447 |
|
| 2448 |
rvcontext->wrap_option = REPLACE_WRAP_NONE; |
| 2449 |
containing_appendrel->translated_vars = (List *) |
| 2450 |
pullup_replace_vars((Node *) containing_appendrel->translated_vars, |
| 2451 |
rvcontext); |
| 2452 |
rvcontext->wrap_option = save_wrap_option; |
| 2453 |
return; |
| 2454 |
} |
| 2455 |
|
| 2456 |
/* |
| 2457 |
* Replace all of the top query's references to the subquery's outputs |
| 2458 |
* with copies of the adjusted subtlist items, being careful not to |
| 2459 |
* replace any of the jointree structure. (This'd be a lot cleaner if we |
| 2460 |
* could use query_tree_mutator.) We have to use PHVs in the targetList, |
| 2461 |
* returningList, and havingQual, since those are certainly above any |
| 2462 |
* outer join. replace_vars_in_jointree tracks its location in the |
| 2463 |
* jointree and uses PHVs or not appropriately. |
| 2464 |
*/ |
| 2465 |
parse->targetList = (List *) |
| 2466 |
pullup_replace_vars((Node *) parse->targetList, rvcontext); |
| 2467 |
parse->returningList = (List *) |
| 2468 |
pullup_replace_vars((Node *) parse->returningList, rvcontext); |
| 2469 |
|
| 2470 |
if (parse->onConflict) |
| 2471 |
{ |
| 2472 |
parse->onConflict->onConflictSet = (List *) |
| 2473 |
pullup_replace_vars((Node *) parse->onConflict->onConflictSet, |
| 2474 |
rvcontext); |
| 2475 |
parse->onConflict->onConflictWhere = |
| 2476 |
pullup_replace_vars(parse->onConflict->onConflictWhere, |
| 2477 |
rvcontext); |
| 2478 |
|
| 2479 |
/* |
| 2480 |
* We assume ON CONFLICT's arbiterElems, arbiterWhere, exclRelTlist |
| 2481 |
* can't contain any references to a subquery. |
| 2482 |
*/ |
| 2483 |
} |
| 2484 |
if (parse->mergeActionList) |
| 2485 |
{ |
| 2486 |
foreach(lc, parse->mergeActionList) |
| 2487 |
{ |
| 2488 |
MergeAction *action = lfirst(lc); |
| 2489 |
|
| 2490 |
action->qual = pullup_replace_vars(action->qual, rvcontext); |
| 2491 |
action->targetList = (List *) |
| 2492 |
pullup_replace_vars((Node *) action->targetList, rvcontext); |
| 2493 |
} |
| 2494 |
} |
| 2495 |
parse->mergeJoinCondition = pullup_replace_vars(parse->mergeJoinCondition, |
| 2496 |
rvcontext); |
| 2497 |
replace_vars_in_jointree((Node *) parse->jointree, rvcontext); |
| 2498 |
Assert(parse->setOperations == NULL); |
| 2499 |
parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext); |
| 2500 |
|
| 2501 |
/* |
| 2502 |
* Replace references in the translated_vars lists of appendrels. |
| 2503 |
*/ |
| 2504 |
foreach(lc, root->append_rel_list) |
| 2505 |
{ |
| 2506 |
AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc); |
| 2507 |
|
| 2508 |
appinfo->translated_vars = (List *) |
| 2509 |
pullup_replace_vars((Node *) appinfo->translated_vars, rvcontext); |
| 2510 |
} |
| 2511 |
|
| 2512 |
/* |
| 2513 |
* Replace references in the joinaliasvars lists of join RTEs and the |
| 2514 |
* groupexprs list of group RTE. |
| 2515 |
*/ |
| 2516 |
foreach(lc, parse->rtable) |
| 2517 |
{ |
| 2518 |
RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc); |
| 2519 |
|
| 2520 |
if (otherrte->rtekind == RTE_JOIN) |
| 2521 |
otherrte->joinaliasvars = (List *) |
| 2522 |
pullup_replace_vars((Node *) otherrte->joinaliasvars, |
| 2523 |
rvcontext); |
| 2524 |
else if (otherrte->rtekind == RTE_GROUP) |
| 2525 |
otherrte->groupexprs = (List *) |
| 2526 |
pullup_replace_vars((Node *) otherrte->groupexprs, |
| 2527 |
rvcontext); |
| 2528 |
} |
| 2529 |
} |
| 2530 |
|
| 2531 |
/* |
| 2532 |
* Helper routine for perform_pullup_replace_vars: do pullup_replace_vars on |
| 2533 |
* every expression in the jointree, without changing the jointree structure |
| 2534 |
* itself. Ugly, but there's no other way... |
| 2535 |
*/ |
| 2536 |
static void |
| 2537 |
replace_vars_in_jointree(Node *jtnode, |
| 2538 |
pullup_replace_vars_context *context) |
| 2539 |
{ |
| 2540 |
if (jtnode == NULL) |
| 2541 |
return; |
| 2542 |
if (IsA(jtnode, RangeTblRef)) |
| 2543 |
{ |
| 2544 |
/* |
| 2545 |
* If the RangeTblRef refers to a LATERAL subquery (that isn't the |
| 2546 |
* same subquery we're pulling up), it might contain references to the |
| 2547 |
* target subquery, which we must replace. We drive this from the |
| 2548 |
* jointree scan, rather than a scan of the rtable, so that we can |
| 2549 |
* avoid processing no-longer-referenced RTEs. |
| 2550 |
*/ |
| 2551 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 2552 |
|
| 2553 |
if (varno != context->varno) /* ignore target subquery itself */ |
| 2554 |
{ |
| 2555 |
RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable); |
| 2556 |
|
| 2557 |
Assert(rte != context->target_rte); |
| 2558 |
if (rte->lateral) |
| 2559 |
{ |
| 2560 |
switch (rte->rtekind) |
| 2561 |
{ |
| 2562 |
case RTE_RELATION: |
| 2563 |
/* shouldn't be marked LATERAL unless tablesample */ |
| 2564 |
Assert(rte->tablesample); |
| 2565 |
rte->tablesample = (TableSampleClause *) |
| 2566 |
pullup_replace_vars((Node *) rte->tablesample, |
| 2567 |
context); |
| 2568 |
break; |
| 2569 |
case RTE_SUBQUERY: |
| 2570 |
rte->subquery = |
| 2571 |
pullup_replace_vars_subquery(rte->subquery, |
| 2572 |
context); |
| 2573 |
break; |
| 2574 |
case RTE_FUNCTION: |
| 2575 |
rte->functions = (List *) |
| 2576 |
pullup_replace_vars((Node *) rte->functions, |
| 2577 |
context); |
| 2578 |
break; |
| 2579 |
case RTE_TABLEFUNC: |
| 2580 |
rte->tablefunc = (TableFunc *) |
| 2581 |
pullup_replace_vars((Node *) rte->tablefunc, |
| 2582 |
context); |
| 2583 |
break; |
| 2584 |
case RTE_VALUES: |
| 2585 |
rte->values_lists = (List *) |
| 2586 |
pullup_replace_vars((Node *) rte->values_lists, |
| 2587 |
context); |
| 2588 |
break; |
| 2589 |
case RTE_JOIN: |
| 2590 |
case RTE_CTE: |
| 2591 |
case RTE_NAMEDTUPLESTORE: |
| 2592 |
case RTE_RESULT: |
| 2593 |
case RTE_GROUP: |
| 2594 |
/* these shouldn't be marked LATERAL */ |
| 2595 |
Assert(false); |
| 2596 |
break; |
| 2597 |
} |
| 2598 |
} |
| 2599 |
} |
| 2600 |
} |
| 2601 |
else if (IsA(jtnode, FromExpr)) |
| 2602 |
{ |
| 2603 |
FromExpr *f = (FromExpr *) jtnode; |
| 2604 |
ListCell *l; |
| 2605 |
|
| 2606 |
foreach(l, f->fromlist) |
| 2607 |
replace_vars_in_jointree(lfirst(l), context); |
| 2608 |
f->quals = pullup_replace_vars(f->quals, context); |
| 2609 |
} |
| 2610 |
else if (IsA(jtnode, JoinExpr)) |
| 2611 |
{ |
| 2612 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 2613 |
ReplaceWrapOption save_wrap_option = context->wrap_option; |
| 2614 |
|
| 2615 |
replace_vars_in_jointree(j->larg, context); |
| 2616 |
replace_vars_in_jointree(j->rarg, context); |
| 2617 |
|
| 2618 |
/* |
| 2619 |
* Use PHVs within the join quals of a full join for variable-free |
| 2620 |
* expressions. Otherwise, we cannot identify which side of the join |
| 2621 |
* a pulled-up variable-free expression came from, which can lead to |
| 2622 |
* failure to make a plan at all because none of the quals appear to |
| 2623 |
* be mergeable or hashable conditions. |
| 2624 |
*/ |
| 2625 |
if (j->jointype == JOIN_FULL) |
| 2626 |
context->wrap_option = REPLACE_WRAP_VARFREE; |
| 2627 |
|
| 2628 |
j->quals = pullup_replace_vars(j->quals, context); |
| 2629 |
|
| 2630 |
context->wrap_option = save_wrap_option; |
| 2631 |
} |
| 2632 |
else |
| 2633 |
elog(ERROR, "unrecognized node type: %d", |
| 2634 |
(int) nodeTag(jtnode)); |
| 2635 |
} |
| 2636 |
|
| 2637 |
/* |
| 2638 |
* Apply pullup variable replacement throughout an expression tree |
| 2639 |
* |
| 2640 |
* Returns a modified copy of the tree, so this can't be used where we |
| 2641 |
* need to do in-place replacement. |
| 2642 |
*/ |
| 2643 |
static Node * |
| 2644 |
pullup_replace_vars(Node *expr, pullup_replace_vars_context *context) |
| 2645 |
{ |
| 2646 |
return replace_rte_variables(expr, |
| 2647 |
context->varno, 0, |
| 2648 |
pullup_replace_vars_callback, |
| 2649 |
context, |
| 2650 |
context->outer_hasSubLinks); |
| 2651 |
} |
| 2652 |
|
| 2653 |
static Node * |
| 2654 |
pullup_replace_vars_callback(Var *var, |
| 2655 |
replace_rte_variables_context *context) |
| 2656 |
{ |
| 2657 |
pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg; |
| 2658 |
int varattno = var->varattno; |
| 2659 |
bool need_phv; |
| 2660 |
Node *newnode; |
| 2661 |
|
| 2662 |
/* System columns are not replaced. */ |
| 2663 |
if (varattno < InvalidAttrNumber) |
| 2664 |
return (Node *) copyObject(var); |
| 2665 |
|
| 2666 |
/* |
| 2667 |
* We need a PlaceHolderVar if the Var-to-be-replaced has nonempty |
| 2668 |
* varnullingrels (unless we find below that the replacement expression is |
| 2669 |
* a Var or PlaceHolderVar that we can just add the nullingrels to). We |
| 2670 |
* also need one if the caller has instructed us that certain expression |
| 2671 |
* replacements need to be wrapped for identification purposes. |
| 2672 |
*/ |
| 2673 |
need_phv = (var->varnullingrels != NULL) || |
| 2674 |
(rcon->wrap_option != REPLACE_WRAP_NONE); |
| 2675 |
|
| 2676 |
/* |
| 2677 |
* If PlaceHolderVars are needed, we cache the modified expressions in |
| 2678 |
* rcon->rv_cache[]. This is not in hopes of any material speed gain |
| 2679 |
* within this function, but to avoid generating identical PHVs with |
| 2680 |
* different IDs. That would result in duplicate evaluations at runtime, |
| 2681 |
* and possibly prevent optimizations that rely on recognizing different |
| 2682 |
* references to the same subquery output as being equal(). So it's worth |
| 2683 |
* a bit of extra effort to avoid it. |
| 2684 |
* |
| 2685 |
* The cached items have phlevelsup = 0 and phnullingrels = NULL; we'll |
| 2686 |
* copy them and adjust those values for this reference site below. |
| 2687 |
*/ |
| 2688 |
if (need_phv && |
| 2689 |
varattno >= InvalidAttrNumber && |
| 2690 |
varattno <= list_length(rcon->targetlist) && |
| 2691 |
rcon->rv_cache[varattno] != NULL) |
| 2692 |
{ |
| 2693 |
/* Just copy the entry and fall through to adjust phlevelsup etc */ |
| 2694 |
newnode = copyObject(rcon->rv_cache[varattno]); |
| 2695 |
} |
| 2696 |
else |
| 2697 |
{ |
| 2698 |
/* |
| 2699 |
* Generate the replacement expression. This takes care of expanding |
| 2700 |
* wholerow references and dealing with non-default varreturningtype. |
| 2701 |
*/ |
| 2702 |
newnode = ReplaceVarFromTargetList(var, |
| 2703 |
rcon->target_rte, |
| 2704 |
rcon->targetlist, |
| 2705 |
rcon->result_relation, |
| 2706 |
REPLACEVARS_REPORT_ERROR, |
| 2707 |
0); |
| 2708 |
|
| 2709 |
/* Insert PlaceHolderVar if needed */ |
| 2710 |
if (need_phv) |
| 2711 |
{ |
| 2712 |
bool wrap; |
| 2713 |
|
| 2714 |
if (rcon->wrap_option == REPLACE_WRAP_ALL) |
| 2715 |
{ |
| 2716 |
/* Caller told us to wrap all expressions in a PlaceHolderVar */ |
| 2717 |
wrap = true; |
| 2718 |
} |
| 2719 |
else if (varattno == InvalidAttrNumber) |
| 2720 |
{ |
| 2721 |
/* |
| 2722 |
* Insert PlaceHolderVar for whole-tuple reference. Notice |
| 2723 |
* that we are wrapping one PlaceHolderVar around the whole |
| 2724 |
* RowExpr, rather than putting one around each element of the |
| 2725 |
* row. This is because we need the expression to yield NULL, |
| 2726 |
* not ROW(NULL,NULL,...) when it is forced to null by an |
| 2727 |
* outer join. |
| 2728 |
*/ |
| 2729 |
wrap = true; |
| 2730 |
} |
| 2731 |
else if (newnode && IsA(newnode, Var) && |
| 2732 |
((Var *) newnode)->varlevelsup == 0) |
| 2733 |
{ |
| 2734 |
/* |
| 2735 |
* Simple Vars always escape being wrapped, unless they are |
| 2736 |
* lateral references to something outside the subquery being |
| 2737 |
* pulled up and the referenced rel is not under the same |
| 2738 |
* lowest nulling outer join. |
| 2739 |
*/ |
| 2740 |
wrap = false; |
| 2741 |
if (rcon->target_rte->lateral && |
| 2742 |
!bms_is_member(((Var *) newnode)->varno, rcon->relids)) |
| 2743 |
{ |
| 2744 |
nullingrel_info *nullinfo = rcon->nullinfo; |
| 2745 |
int lvarno = ((Var *) newnode)->varno; |
| 2746 |
|
| 2747 |
Assert(lvarno > 0 && lvarno <= nullinfo->rtlength); |
| 2748 |
if (!bms_is_subset(nullinfo->nullingrels[rcon->varno], |
| 2749 |
nullinfo->nullingrels[lvarno])) |
| 2750 |
wrap = true; |
| 2751 |
} |
| 2752 |
} |
| 2753 |
else if (newnode && IsA(newnode, PlaceHolderVar) && |
| 2754 |
((PlaceHolderVar *) newnode)->phlevelsup == 0) |
| 2755 |
{ |
| 2756 |
/* The same rules apply for a PlaceHolderVar */ |
| 2757 |
wrap = false; |
| 2758 |
if (rcon->target_rte->lateral && |
| 2759 |
!bms_is_subset(((PlaceHolderVar *) newnode)->phrels, |
| 2760 |
rcon->relids)) |
| 2761 |
{ |
| 2762 |
nullingrel_info *nullinfo = rcon->nullinfo; |
| 2763 |
Relids lvarnos = ((PlaceHolderVar *) newnode)->phrels; |
| 2764 |
int lvarno; |
| 2765 |
|
| 2766 |
lvarno = -1; |
| 2767 |
while ((lvarno = bms_next_member(lvarnos, lvarno)) >= 0) |
| 2768 |
{ |
| 2769 |
Assert(lvarno > 0 && lvarno <= nullinfo->rtlength); |
| 2770 |
if (!bms_is_subset(nullinfo->nullingrels[rcon->varno], |
| 2771 |
nullinfo->nullingrels[lvarno])) |
| 2772 |
{ |
| 2773 |
wrap = true; |
| 2774 |
break; |
| 2775 |
} |
| 2776 |
} |
| 2777 |
} |
| 2778 |
} |
| 2779 |
else |
| 2780 |
{ |
| 2781 |
/* |
| 2782 |
* If the node contains Var(s) or PlaceHolderVar(s) of the |
| 2783 |
* subquery being pulled up, or of rels that are under the |
| 2784 |
* same lowest nulling outer join as the subquery, and does |
| 2785 |
* not contain any non-strict constructs, then instead of |
| 2786 |
* adding a PHV on top we can add the required nullingrels to |
| 2787 |
* those Vars/PHVs. (This is fundamentally a generalization |
| 2788 |
* of the above cases for bare Vars and PHVs.) |
| 2789 |
* |
| 2790 |
* This test is somewhat expensive, but it avoids pessimizing |
| 2791 |
* the plan in cases where the nullingrels get removed again |
| 2792 |
* later by outer join reduction. |
| 2793 |
* |
| 2794 |
* Note that we don't force wrapping of expressions containing |
| 2795 |
* lateral references, so long as they also contain Vars/PHVs |
| 2796 |
* of the subquery, or of rels that are under the same lowest |
| 2797 |
* nulling outer join as the subquery. This is okay because |
| 2798 |
* of the restriction to strict constructs: if those Vars/PHVs |
| 2799 |
* have been forced to NULL by an outer join then the end |
| 2800 |
* result of the expression will be NULL too, regardless of |
| 2801 |
* the lateral references. So it's not necessary to force the |
| 2802 |
* expression to be evaluated below the outer join. This can |
| 2803 |
* be a very valuable optimization, because it may allow us to |
| 2804 |
* avoid using a nested loop to pass the lateral reference |
| 2805 |
* down. |
| 2806 |
* |
| 2807 |
* This analysis could be tighter: in particular, a non-strict |
| 2808 |
* construct hidden within a lower-level PlaceHolderVar is not |
| 2809 |
* reason to add another PHV. But for now it doesn't seem |
| 2810 |
* worth the code to be more exact. This is also why it's |
| 2811 |
* preferable to handle bare PHVs in the above branch, rather |
| 2812 |
* than this branch. We also prefer to handle bare Vars in a |
| 2813 |
* separate branch, as it's cheaper this way and parallels the |
| 2814 |
* handling of PHVs. |
| 2815 |
* |
| 2816 |
* For a LATERAL subquery, we have to check the actual var |
| 2817 |
* membership of the node, but if it's non-lateral then any |
| 2818 |
* level-zero var must belong to the subquery. |
| 2819 |
*/ |
| 2820 |
bool contain_nullable_vars = false; |
| 2821 |
|
| 2822 |
if (!rcon->target_rte->lateral) |
| 2823 |
{ |
| 2824 |
if (contain_vars_of_level(newnode, 0)) |
| 2825 |
contain_nullable_vars = true; |
| 2826 |
} |
| 2827 |
else |
| 2828 |
{ |
| 2829 |
Relids all_varnos; |
| 2830 |
|
| 2831 |
all_varnos = pull_varnos(rcon->root, newnode); |
| 2832 |
if (bms_overlap(all_varnos, rcon->relids)) |
| 2833 |
contain_nullable_vars = true; |
| 2834 |
else |
| 2835 |
{ |
| 2836 |
nullingrel_info *nullinfo = rcon->nullinfo; |
| 2837 |
int varno; |
| 2838 |
|
| 2839 |
varno = -1; |
| 2840 |
while ((varno = bms_next_member(all_varnos, varno)) >= 0) |
| 2841 |
{ |
| 2842 |
Assert(varno > 0 && varno <= nullinfo->rtlength); |
| 2843 |
if (bms_is_subset(nullinfo->nullingrels[rcon->varno], |
| 2844 |
nullinfo->nullingrels[varno])) |
| 2845 |
{ |
| 2846 |
contain_nullable_vars = true; |
| 2847 |
break; |
| 2848 |
} |
| 2849 |
} |
| 2850 |
} |
| 2851 |
} |
| 2852 |
|
| 2853 |
if (contain_nullable_vars && |
| 2854 |
!contain_nonstrict_functions(newnode)) |
| 2855 |
{ |
| 2856 |
/* No wrap needed */ |
| 2857 |
wrap = false; |
| 2858 |
} |
| 2859 |
else |
| 2860 |
{ |
| 2861 |
/* Else wrap it in a PlaceHolderVar */ |
| 2862 |
wrap = true; |
| 2863 |
} |
| 2864 |
} |
| 2865 |
|
| 2866 |
if (wrap) |
| 2867 |
{ |
| 2868 |
newnode = (Node *) |
| 2869 |
make_placeholder_expr(rcon->root, |
| 2870 |
(Expr *) newnode, |
| 2871 |
bms_make_singleton(rcon->varno)); |
| 2872 |
|
| 2873 |
/* |
| 2874 |
* Cache it if possible (ie, if the attno is in range, which |
| 2875 |
* it probably always should be). |
| 2876 |
*/ |
| 2877 |
if (varattno >= InvalidAttrNumber && |
| 2878 |
varattno <= list_length(rcon->targetlist)) |
| 2879 |
rcon->rv_cache[varattno] = copyObject(newnode); |
| 2880 |
} |
| 2881 |
} |
| 2882 |
} |
| 2883 |
|
| 2884 |
/* Propagate any varnullingrels into the replacement expression */ |
| 2885 |
if (var->varnullingrels != NULL) |
| 2886 |
{ |
| 2887 |
if (IsA(newnode, Var)) |
| 2888 |
{ |
| 2889 |
Var *newvar = (Var *) newnode; |
| 2890 |
|
| 2891 |
Assert(newvar->varlevelsup == 0); |
| 2892 |
newvar->varnullingrels = bms_add_members(newvar->varnullingrels, |
| 2893 |
var->varnullingrels); |
| 2894 |
} |
| 2895 |
else if (IsA(newnode, PlaceHolderVar)) |
| 2896 |
{ |
| 2897 |
PlaceHolderVar *newphv = (PlaceHolderVar *) newnode; |
| 2898 |
|
| 2899 |
Assert(newphv->phlevelsup == 0); |
| 2900 |
newphv->phnullingrels = bms_add_members(newphv->phnullingrels, |
| 2901 |
var->varnullingrels); |
| 2902 |
} |
| 2903 |
else |
| 2904 |
{ |
| 2905 |
/* |
| 2906 |
* There should be Vars/PHVs within the expression that we can |
| 2907 |
* modify. Vars/PHVs of the subquery should have the full |
| 2908 |
* var->varnullingrels added to them, but if there are lateral |
| 2909 |
* references within the expression, those must be marked with |
| 2910 |
* only the nullingrels that potentially apply to them. (This |
| 2911 |
* corresponds to the fact that the expression will now be |
| 2912 |
* evaluated at the join level of the Var that we are replacing: |
| 2913 |
* the lateral references may have bubbled up through fewer outer |
| 2914 |
* joins than the subquery's Vars have. Per the discussion above, |
| 2915 |
* we'll still get the right answers.) That relid set could be |
| 2916 |
* different for different lateral relations, so we have to do |
| 2917 |
* this work for each one. |
| 2918 |
* |
| 2919 |
* (Currently, the restrictions in is_simple_subquery() mean that |
| 2920 |
* at most we have to remove the lowest outer join's relid from |
| 2921 |
* the nullingrels of a lateral reference. However, we might |
| 2922 |
* relax those restrictions someday, so let's do this right.) |
| 2923 |
*/ |
| 2924 |
if (rcon->target_rte->lateral) |
| 2925 |
{ |
| 2926 |
nullingrel_info *nullinfo = rcon->nullinfo; |
| 2927 |
Relids lvarnos; |
| 2928 |
int lvarno; |
| 2929 |
|
| 2930 |
/* |
| 2931 |
* Identify lateral varnos used within newnode. We must do |
| 2932 |
* this before injecting var->varnullingrels into the tree. |
| 2933 |
*/ |
| 2934 |
lvarnos = pull_varnos(rcon->root, newnode); |
| 2935 |
lvarnos = bms_del_members(lvarnos, rcon->relids); |
| 2936 |
/* For each one, add relevant nullingrels if any */ |
| 2937 |
lvarno = -1; |
| 2938 |
while ((lvarno = bms_next_member(lvarnos, lvarno)) >= 0) |
| 2939 |
{ |
| 2940 |
Relids lnullingrels; |
| 2941 |
|
| 2942 |
Assert(lvarno > 0 && lvarno <= nullinfo->rtlength); |
| 2943 |
lnullingrels = bms_intersect(var->varnullingrels, |
| 2944 |
nullinfo->nullingrels[lvarno]); |
| 2945 |
if (!bms_is_empty(lnullingrels)) |
| 2946 |
newnode = add_nulling_relids(newnode, |
| 2947 |
bms_make_singleton(lvarno), |
| 2948 |
lnullingrels); |
| 2949 |
} |
| 2950 |
} |
| 2951 |
|
| 2952 |
/* Finally, deal with Vars/PHVs of the subquery itself */ |
| 2953 |
newnode = add_nulling_relids(newnode, |
| 2954 |
rcon->relids, |
| 2955 |
var->varnullingrels); |
| 2956 |
/* Assert we did put the varnullingrels into the expression */ |
| 2957 |
Assert(bms_is_subset(var->varnullingrels, |
| 2958 |
pull_varnos(rcon->root, newnode))); |
| 2959 |
} |
| 2960 |
} |
| 2961 |
|
| 2962 |
/* Must adjust varlevelsup if replaced Var is within a subquery */ |
| 2963 |
if (var->varlevelsup > 0) |
| 2964 |
IncrementVarSublevelsUp(newnode, var->varlevelsup, 0); |
| 2965 |
|
| 2966 |
return newnode; |
| 2967 |
} |
| 2968 |
|
| 2969 |
/* |
| 2970 |
* Apply pullup variable replacement to a subquery |
| 2971 |
* |
| 2972 |
* This needs to be different from pullup_replace_vars() because |
| 2973 |
* replace_rte_variables will think that it shouldn't increment sublevels_up |
| 2974 |
* before entering the Query; so we need to call it with sublevels_up == 1. |
| 2975 |
*/ |
| 2976 |
static Query * |
| 2977 |
pullup_replace_vars_subquery(Query *query, |
| 2978 |
pullup_replace_vars_context *context) |
| 2979 |
{ |
| 2980 |
Assert(IsA(query, Query)); |
| 2981 |
return (Query *) replace_rte_variables((Node *) query, |
| 2982 |
context->varno, 1, |
| 2983 |
pullup_replace_vars_callback, |
| 2984 |
context, |
| 2985 |
NULL); |
| 2986 |
} |
| 2987 |
|
| 2988 |
|
| 2989 |
/* |
| 2990 |
* flatten_simple_union_all |
| 2991 |
* Try to optimize top-level UNION ALL structure into an appendrel |
| 2992 |
* |
| 2993 |
* If a query's setOperations tree consists entirely of simple UNION ALL |
| 2994 |
* operations, flatten it into an append relation, which we can process more |
| 2995 |
* intelligently than the general setops case. Otherwise, do nothing. |
| 2996 |
* |
| 2997 |
* In most cases, this can succeed only for a top-level query, because for a |
| 2998 |
* subquery in FROM, the parent query's invocation of pull_up_subqueries would |
| 2999 |
* already have flattened the UNION via pull_up_simple_union_all. But there |
| 3000 |
* are a few cases we can support here but not in that code path, for example |
| 3001 |
* when the subquery also contains ORDER BY. |
| 3002 |
*/ |
| 3003 |
void |
| 3004 |
flatten_simple_union_all(PlannerInfo *root) |
| 3005 |
{ |
| 3006 |
Query *parse = root->parse; |
| 3007 |
SetOperationStmt *topop; |
| 3008 |
Node *leftmostjtnode; |
| 3009 |
int leftmostRTI; |
| 3010 |
RangeTblEntry *leftmostRTE; |
| 3011 |
int childRTI; |
| 3012 |
RangeTblEntry *childRTE; |
| 3013 |
RangeTblRef *rtr; |
| 3014 |
|
| 3015 |
/* Shouldn't be called unless query has setops */ |
| 3016 |
topop = castNode(SetOperationStmt, parse->setOperations); |
| 3017 |
Assert(topop); |
| 3018 |
|
| 3019 |
/* Can't optimize away a recursive UNION */ |
| 3020 |
if (root->hasRecursion) |
| 3021 |
return; |
| 3022 |
|
| 3023 |
/* |
| 3024 |
* Recursively check the tree of set operations. If not all UNION ALL |
| 3025 |
* with identical column types, punt. |
| 3026 |
*/ |
| 3027 |
if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes)) |
| 3028 |
return; |
| 3029 |
|
| 3030 |
/* |
| 3031 |
* Locate the leftmost leaf query in the setops tree. The upper query's |
| 3032 |
* Vars all refer to this RTE (see transformSetOperationStmt). |
| 3033 |
*/ |
| 3034 |
leftmostjtnode = topop->larg; |
| 3035 |
while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt)) |
| 3036 |
leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg; |
| 3037 |
Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef)); |
| 3038 |
leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex; |
| 3039 |
leftmostRTE = rt_fetch(leftmostRTI, parse->rtable); |
| 3040 |
Assert(leftmostRTE->rtekind == RTE_SUBQUERY); |
| 3041 |
|
| 3042 |
/* |
| 3043 |
* Make a copy of the leftmost RTE and add it to the rtable. This copy |
| 3044 |
* will represent the leftmost leaf query in its capacity as a member of |
| 3045 |
* the appendrel. The original will represent the appendrel as a whole. |
| 3046 |
* (We must do things this way because the upper query's Vars have to be |
| 3047 |
* seen as referring to the whole appendrel.) |
| 3048 |
*/ |
| 3049 |
childRTE = copyObject(leftmostRTE); |
| 3050 |
parse->rtable = lappend(parse->rtable, childRTE); |
| 3051 |
childRTI = list_length(parse->rtable); |
| 3052 |
|
| 3053 |
/* Modify the setops tree to reference the child copy */ |
| 3054 |
((RangeTblRef *) leftmostjtnode)->rtindex = childRTI; |
| 3055 |
|
| 3056 |
/* Modify the formerly-leftmost RTE to mark it as an appendrel parent */ |
| 3057 |
leftmostRTE->inh = true; |
| 3058 |
|
| 3059 |
/* |
| 3060 |
* Form a RangeTblRef for the appendrel, and insert it into FROM. The top |
| 3061 |
* Query of a setops tree should have had an empty FromClause initially. |
| 3062 |
*/ |
| 3063 |
rtr = makeNode(RangeTblRef); |
| 3064 |
rtr->rtindex = leftmostRTI; |
| 3065 |
Assert(parse->jointree->fromlist == NIL); |
| 3066 |
parse->jointree->fromlist = list_make1(rtr); |
| 3067 |
|
| 3068 |
/* |
| 3069 |
* Now pretend the query has no setops. We must do this before trying to |
| 3070 |
* do subquery pullup, because of Assert in pull_up_simple_subquery. |
| 3071 |
*/ |
| 3072 |
parse->setOperations = NULL; |
| 3073 |
|
| 3074 |
/* |
| 3075 |
* Build AppendRelInfo information, and apply pull_up_subqueries to the |
| 3076 |
* leaf queries of the UNION ALL. (We must do that now because they |
| 3077 |
* weren't previously referenced by the jointree, and so were missed by |
| 3078 |
* the main invocation of pull_up_subqueries.) |
| 3079 |
*/ |
| 3080 |
pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0); |
| 3081 |
} |
| 3082 |
|
| 3083 |
|
| 3084 |
/* |
| 3085 |
* reduce_outer_joins |
| 3086 |
* Attempt to reduce outer joins to plain inner joins. |
| 3087 |
* |
| 3088 |
* The idea here is that given a query like |
| 3089 |
* SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42; |
| 3090 |
* we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE |
| 3091 |
* is strict. The strict operator will always return NULL, causing the outer |
| 3092 |
* WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's |
| 3093 |
* columns. Therefore, there's no need for the join to produce null-extended |
| 3094 |
* rows in the first place --- which makes it a plain join not an outer join. |
| 3095 |
* (This scenario may not be very likely in a query written out by hand, but |
| 3096 |
* it's reasonably likely when pushing quals down into complex views.) |
| 3097 |
* |
| 3098 |
* More generally, an outer join can be reduced in strength if there is a |
| 3099 |
* strict qual above it in the qual tree that constrains a Var from the |
| 3100 |
* nullable side of the join to be non-null. (For FULL joins this applies |
| 3101 |
* to each side separately.) |
| 3102 |
* |
| 3103 |
* Another transformation we apply here is to recognize cases like |
| 3104 |
* SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL; |
| 3105 |
* If the join clause is strict for b.y, then only null-extended rows could |
| 3106 |
* pass the upper WHERE, and we can conclude that what the query is really |
| 3107 |
* specifying is an anti-semijoin. We change the join type from JOIN_LEFT |
| 3108 |
* to JOIN_ANTI. The IS NULL clause then becomes redundant, and must be |
| 3109 |
* removed to prevent bogus selectivity calculations, but we leave it to |
| 3110 |
* distribute_qual_to_rels to get rid of such clauses. |
| 3111 |
* |
| 3112 |
* Also, we get rid of JOIN_RIGHT cases by flipping them around to become |
| 3113 |
* JOIN_LEFT. This saves some code here and in some later planner routines; |
| 3114 |
* the main benefit is to reduce the number of jointypes that can appear in |
| 3115 |
* SpecialJoinInfo nodes. Note that we can still generate Paths and Plans |
| 3116 |
* that use JOIN_RIGHT (or JOIN_RIGHT_ANTI) by switching the inputs again. |
| 3117 |
* |
| 3118 |
* To ease recognition of strict qual clauses, we require this routine to be |
| 3119 |
* run after expression preprocessing (i.e., qual canonicalization and JOIN |
| 3120 |
* alias-var expansion). |
| 3121 |
*/ |
| 3122 |
void |
| 3123 |
reduce_outer_joins(PlannerInfo *root) |
| 3124 |
{ |
| 3125 |
reduce_outer_joins_pass1_state *state1; |
| 3126 |
reduce_outer_joins_pass2_state state2; |
| 3127 |
ListCell *lc; |
| 3128 |
|
| 3129 |
/* |
| 3130 |
* To avoid doing strictness checks on more quals than necessary, we want |
| 3131 |
* to stop descending the jointree as soon as there are no outer joins |
| 3132 |
* below our current point. This consideration forces a two-pass process. |
| 3133 |
* The first pass gathers information about which base rels appear below |
| 3134 |
* each side of each join clause, and about whether there are outer |
| 3135 |
* join(s) below each side of each join clause. The second pass examines |
| 3136 |
* qual clauses and changes join types as it descends the tree. |
| 3137 |
*/ |
| 3138 |
state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree); |
| 3139 |
|
| 3140 |
/* planner.c shouldn't have called me if no outer joins */ |
| 3141 |
if (state1 == NULL || !state1->contains_outer) |
| 3142 |
elog(ERROR, "so where are the outer joins?"); |
| 3143 |
|
| 3144 |
state2.inner_reduced = NULL; |
| 3145 |
state2.partial_reduced = NIL; |
| 3146 |
|
| 3147 |
reduce_outer_joins_pass2((Node *) root->parse->jointree, |
| 3148 |
state1, &state2, |
| 3149 |
root, NULL, NIL); |
| 3150 |
|
| 3151 |
/* |
| 3152 |
* If we successfully reduced the strength of any outer joins, we must |
| 3153 |
* remove references to those joins as nulling rels. This is handled as |
| 3154 |
* an additional pass, for simplicity and because we can handle all |
| 3155 |
* fully-reduced joins in a single pass over the parse tree. |
| 3156 |
*/ |
| 3157 |
if (!bms_is_empty(state2.inner_reduced)) |
| 3158 |
{ |
| 3159 |
root->parse = (Query *) |
| 3160 |
remove_nulling_relids((Node *) root->parse, |
| 3161 |
state2.inner_reduced, |
| 3162 |
NULL); |
| 3163 |
/* There could be references in the append_rel_list, too */ |
| 3164 |
root->append_rel_list = (List *) |
| 3165 |
remove_nulling_relids((Node *) root->append_rel_list, |
| 3166 |
state2.inner_reduced, |
| 3167 |
NULL); |
| 3168 |
} |
| 3169 |
|
| 3170 |
/* |
| 3171 |
* Partially-reduced full joins have to be done one at a time, since |
| 3172 |
* they'll each need a different setting of except_relids. |
| 3173 |
*/ |
| 3174 |
foreach(lc, state2.partial_reduced) |
| 3175 |
{ |
| 3176 |
reduce_outer_joins_partial_state *statep = lfirst(lc); |
| 3177 |
Relids full_join_relids = bms_make_singleton(statep->full_join_rti); |
| 3178 |
|
| 3179 |
root->parse = (Query *) |
| 3180 |
remove_nulling_relids((Node *) root->parse, |
| 3181 |
full_join_relids, |
| 3182 |
statep->unreduced_side); |
| 3183 |
root->append_rel_list = (List *) |
| 3184 |
remove_nulling_relids((Node *) root->append_rel_list, |
| 3185 |
full_join_relids, |
| 3186 |
statep->unreduced_side); |
| 3187 |
} |
| 3188 |
} |
| 3189 |
|
| 3190 |
/* |
| 3191 |
* reduce_outer_joins_pass1 - phase 1 data collection |
| 3192 |
* |
| 3193 |
* Returns a state node describing the given jointree node. |
| 3194 |
*/ |
| 3195 |
static reduce_outer_joins_pass1_state * |
| 3196 |
reduce_outer_joins_pass1(Node *jtnode) |
| 3197 |
{ |
| 3198 |
reduce_outer_joins_pass1_state *result; |
| 3199 |
|
| 3200 |
result = (reduce_outer_joins_pass1_state *) |
| 3201 |
palloc(sizeof(reduce_outer_joins_pass1_state)); |
| 3202 |
result->relids = NULL; |
| 3203 |
result->contains_outer = false; |
| 3204 |
result->sub_states = NIL; |
| 3205 |
|
| 3206 |
if (jtnode == NULL) |
| 3207 |
return result; |
| 3208 |
if (IsA(jtnode, RangeTblRef)) |
| 3209 |
{ |
| 3210 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 3211 |
|
| 3212 |
result->relids = bms_make_singleton(varno); |
| 3213 |
} |
| 3214 |
else if (IsA(jtnode, FromExpr)) |
| 3215 |
{ |
| 3216 |
FromExpr *f = (FromExpr *) jtnode; |
| 3217 |
ListCell *l; |
| 3218 |
|
| 3219 |
foreach(l, f->fromlist) |
| 3220 |
{ |
| 3221 |
reduce_outer_joins_pass1_state *sub_state; |
| 3222 |
|
| 3223 |
sub_state = reduce_outer_joins_pass1(lfirst(l)); |
| 3224 |
result->relids = bms_add_members(result->relids, |
| 3225 |
sub_state->relids); |
| 3226 |
result->contains_outer |= sub_state->contains_outer; |
| 3227 |
result->sub_states = lappend(result->sub_states, sub_state); |
| 3228 |
} |
| 3229 |
} |
| 3230 |
else if (IsA(jtnode, JoinExpr)) |
| 3231 |
{ |
| 3232 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 3233 |
reduce_outer_joins_pass1_state *sub_state; |
| 3234 |
|
| 3235 |
/* join's own RT index is not wanted in result->relids */ |
| 3236 |
if (IS_OUTER_JOIN(j->jointype)) |
| 3237 |
result->contains_outer = true; |
| 3238 |
|
| 3239 |
sub_state = reduce_outer_joins_pass1(j->larg); |
| 3240 |
result->relids = bms_add_members(result->relids, |
| 3241 |
sub_state->relids); |
| 3242 |
result->contains_outer |= sub_state->contains_outer; |
| 3243 |
result->sub_states = lappend(result->sub_states, sub_state); |
| 3244 |
|
| 3245 |
sub_state = reduce_outer_joins_pass1(j->rarg); |
| 3246 |
result->relids = bms_add_members(result->relids, |
| 3247 |
sub_state->relids); |
| 3248 |
result->contains_outer |= sub_state->contains_outer; |
| 3249 |
result->sub_states = lappend(result->sub_states, sub_state); |
| 3250 |
} |
| 3251 |
else |
| 3252 |
elog(ERROR, "unrecognized node type: %d", |
| 3253 |
(int) nodeTag(jtnode)); |
| 3254 |
return result; |
| 3255 |
} |
| 3256 |
|
| 3257 |
/* |
| 3258 |
* reduce_outer_joins_pass2 - phase 2 processing |
| 3259 |
* |
| 3260 |
* jtnode: current jointree node |
| 3261 |
* state1: state data collected by phase 1 for this node |
| 3262 |
* state2: where to accumulate info about successfully-reduced joins |
| 3263 |
* root: toplevel planner state |
| 3264 |
* nonnullable_rels: set of base relids forced non-null by upper quals |
| 3265 |
* forced_null_vars: multibitmapset of Vars forced null by upper quals |
| 3266 |
* |
| 3267 |
* Returns info in state2 about outer joins that were successfully simplified. |
| 3268 |
* Joins that were fully reduced to inner joins are all added to |
| 3269 |
* state2->inner_reduced. If a full join is reduced to a left join, |
| 3270 |
* it needs its own entry in state2->partial_reduced, since that will |
| 3271 |
* require custom processing to remove only the correct nullingrel markers. |
| 3272 |
*/ |
| 3273 |
static void |
| 3274 |
reduce_outer_joins_pass2(Node *jtnode, |
| 3275 |
reduce_outer_joins_pass1_state *state1, |
| 3276 |
reduce_outer_joins_pass2_state *state2, |
| 3277 |
PlannerInfo *root, |
| 3278 |
Relids nonnullable_rels, |
| 3279 |
List *forced_null_vars) |
| 3280 |
{ |
| 3281 |
/* |
| 3282 |
* pass 2 should never descend as far as an empty subnode or base rel, |
| 3283 |
* because it's only called on subtrees marked as contains_outer. |
| 3284 |
*/ |
| 3285 |
if (jtnode == NULL) |
| 3286 |
elog(ERROR, "reached empty jointree"); |
| 3287 |
if (IsA(jtnode, RangeTblRef)) |
| 3288 |
elog(ERROR, "reached base rel"); |
| 3289 |
else if (IsA(jtnode, FromExpr)) |
| 3290 |
{ |
| 3291 |
FromExpr *f = (FromExpr *) jtnode; |
| 3292 |
ListCell *l; |
| 3293 |
ListCell *s; |
| 3294 |
Relids pass_nonnullable_rels; |
| 3295 |
List *pass_forced_null_vars; |
| 3296 |
|
| 3297 |
/* Scan quals to see if we can add any constraints */ |
| 3298 |
pass_nonnullable_rels = find_nonnullable_rels(f->quals); |
| 3299 |
pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels, |
| 3300 |
nonnullable_rels); |
| 3301 |
pass_forced_null_vars = find_forced_null_vars(f->quals); |
| 3302 |
pass_forced_null_vars = mbms_add_members(pass_forced_null_vars, |
| 3303 |
forced_null_vars); |
| 3304 |
/* And recurse --- but only into interesting subtrees */ |
| 3305 |
Assert(list_length(f->fromlist) == list_length(state1->sub_states)); |
| 3306 |
forboth(l, f->fromlist, s, state1->sub_states) |
| 3307 |
{ |
| 3308 |
reduce_outer_joins_pass1_state *sub_state = lfirst(s); |
| 3309 |
|
| 3310 |
if (sub_state->contains_outer) |
| 3311 |
reduce_outer_joins_pass2(lfirst(l), sub_state, |
| 3312 |
state2, root, |
| 3313 |
pass_nonnullable_rels, |
| 3314 |
pass_forced_null_vars); |
| 3315 |
} |
| 3316 |
bms_free(pass_nonnullable_rels); |
| 3317 |
/* can't so easily clean up var lists, unfortunately */ |
| 3318 |
} |
| 3319 |
else if (IsA(jtnode, JoinExpr)) |
| 3320 |
{ |
| 3321 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 3322 |
int rtindex = j->rtindex; |
| 3323 |
JoinType jointype = j->jointype; |
| 3324 |
reduce_outer_joins_pass1_state *left_state = linitial(state1->sub_states); |
| 3325 |
reduce_outer_joins_pass1_state *right_state = lsecond(state1->sub_states); |
| 3326 |
|
| 3327 |
/* Can we simplify this join? */ |
| 3328 |
switch (jointype) |
| 3329 |
{ |
| 3330 |
case JOIN_INNER: |
| 3331 |
break; |
| 3332 |
case JOIN_LEFT: |
| 3333 |
if (bms_overlap(nonnullable_rels, right_state->relids)) |
| 3334 |
jointype = JOIN_INNER; |
| 3335 |
break; |
| 3336 |
case JOIN_RIGHT: |
| 3337 |
if (bms_overlap(nonnullable_rels, left_state->relids)) |
| 3338 |
jointype = JOIN_INNER; |
| 3339 |
break; |
| 3340 |
case JOIN_FULL: |
| 3341 |
if (bms_overlap(nonnullable_rels, left_state->relids)) |
| 3342 |
{ |
| 3343 |
if (bms_overlap(nonnullable_rels, right_state->relids)) |
| 3344 |
jointype = JOIN_INNER; |
| 3345 |
else |
| 3346 |
{ |
| 3347 |
jointype = JOIN_LEFT; |
| 3348 |
/* Also report partial reduction in state2 */ |
| 3349 |
report_reduced_full_join(state2, rtindex, |
| 3350 |
right_state->relids); |
| 3351 |
} |
| 3352 |
} |
| 3353 |
else |
| 3354 |
{ |
| 3355 |
if (bms_overlap(nonnullable_rels, right_state->relids)) |
| 3356 |
{ |
| 3357 |
jointype = JOIN_RIGHT; |
| 3358 |
/* Also report partial reduction in state2 */ |
| 3359 |
report_reduced_full_join(state2, rtindex, |
| 3360 |
left_state->relids); |
| 3361 |
} |
| 3362 |
} |
| 3363 |
break; |
| 3364 |
case JOIN_SEMI: |
| 3365 |
case JOIN_ANTI: |
| 3366 |
|
| 3367 |
/* |
| 3368 |
* These could only have been introduced by pull_up_sublinks, |
| 3369 |
* so there's no way that upper quals could refer to their |
| 3370 |
* righthand sides, and no point in checking. We don't expect |
| 3371 |
* to see JOIN_RIGHT_SEMI or JOIN_RIGHT_ANTI yet. |
| 3372 |
*/ |
| 3373 |
break; |
| 3374 |
default: |
| 3375 |
elog(ERROR, "unrecognized join type: %d", |
| 3376 |
(int) jointype); |
| 3377 |
break; |
| 3378 |
} |
| 3379 |
|
| 3380 |
/* |
| 3381 |
* Convert JOIN_RIGHT to JOIN_LEFT. Note that in the case where we |
| 3382 |
* reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no |
| 3383 |
* longer matches the internal ordering of any CoalesceExpr's built to |
| 3384 |
* represent merged join variables. We don't care about that at |
| 3385 |
* present, but be wary of it ... |
| 3386 |
*/ |
| 3387 |
if (jointype == JOIN_RIGHT) |
| 3388 |
{ |
| 3389 |
Node *tmparg; |
| 3390 |
|
| 3391 |
tmparg = j->larg; |
| 3392 |
j->larg = j->rarg; |
| 3393 |
j->rarg = tmparg; |
| 3394 |
jointype = JOIN_LEFT; |
| 3395 |
right_state = linitial(state1->sub_states); |
| 3396 |
left_state = lsecond(state1->sub_states); |
| 3397 |
} |
| 3398 |
|
| 3399 |
/* |
| 3400 |
* See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if |
| 3401 |
* the join's own quals are strict for any var that was forced null by |
| 3402 |
* higher qual levels. NOTE: there are other ways that we could |
| 3403 |
* detect an anti-join, in particular if we were to check whether Vars |
| 3404 |
* coming from the RHS must be non-null because of table constraints. |
| 3405 |
* That seems complicated and expensive though (in particular, one |
| 3406 |
* would have to be wary of lower outer joins). For the moment this |
| 3407 |
* seems sufficient. |
| 3408 |
*/ |
| 3409 |
if (jointype == JOIN_LEFT) |
| 3410 |
{ |
| 3411 |
List *nonnullable_vars; |
| 3412 |
Bitmapset *overlap; |
| 3413 |
|
| 3414 |
/* Find Vars in j->quals that must be non-null in joined rows */ |
| 3415 |
nonnullable_vars = find_nonnullable_vars(j->quals); |
| 3416 |
|
| 3417 |
/* |
| 3418 |
* It's not sufficient to check whether nonnullable_vars and |
| 3419 |
* forced_null_vars overlap: we need to know if the overlap |
| 3420 |
* includes any RHS variables. |
| 3421 |
*/ |
| 3422 |
overlap = mbms_overlap_sets(nonnullable_vars, forced_null_vars); |
| 3423 |
if (bms_overlap(overlap, right_state->relids)) |
| 3424 |
jointype = JOIN_ANTI; |
| 3425 |
} |
| 3426 |
|
| 3427 |
/* |
| 3428 |
* Apply the jointype change, if any, to both jointree node and RTE. |
| 3429 |
* Also, if we changed an RTE to INNER, add its RTI to inner_reduced. |
| 3430 |
*/ |
| 3431 |
if (rtindex && jointype != j->jointype) |
| 3432 |
{ |
| 3433 |
RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable); |
| 3434 |
|
| 3435 |
Assert(rte->rtekind == RTE_JOIN); |
| 3436 |
Assert(rte->jointype == j->jointype); |
| 3437 |
rte->jointype = jointype; |
| 3438 |
if (jointype == JOIN_INNER) |
| 3439 |
state2->inner_reduced = bms_add_member(state2->inner_reduced, |
| 3440 |
rtindex); |
| 3441 |
} |
| 3442 |
j->jointype = jointype; |
| 3443 |
|
| 3444 |
/* Only recurse if there's more to do below here */ |
| 3445 |
if (left_state->contains_outer || right_state->contains_outer) |
| 3446 |
{ |
| 3447 |
Relids local_nonnullable_rels; |
| 3448 |
List *local_forced_null_vars; |
| 3449 |
Relids pass_nonnullable_rels; |
| 3450 |
List *pass_forced_null_vars; |
| 3451 |
|
| 3452 |
/* |
| 3453 |
* If this join is (now) inner, we can add any constraints its |
| 3454 |
* quals provide to those we got from above. But if it is outer, |
| 3455 |
* we can pass down the local constraints only into the nullable |
| 3456 |
* side, because an outer join never eliminates any rows from its |
| 3457 |
* non-nullable side. Also, there is no point in passing upper |
| 3458 |
* constraints into the nullable side, since if there were any |
| 3459 |
* we'd have been able to reduce the join. (In the case of upper |
| 3460 |
* forced-null constraints, we *must not* pass them into the |
| 3461 |
* nullable side --- they either applied here, or not.) The upshot |
| 3462 |
* is that we pass either the local or the upper constraints, |
| 3463 |
* never both, to the children of an outer join. |
| 3464 |
* |
| 3465 |
* Note that a SEMI join works like an inner join here: it's okay |
| 3466 |
* to pass down both local and upper constraints. (There can't be |
| 3467 |
* any upper constraints affecting its inner side, but it's not |
| 3468 |
* worth having a separate code path to avoid passing them.) |
| 3469 |
* |
| 3470 |
* At a FULL join we just punt and pass nothing down --- is it |
| 3471 |
* possible to be smarter? |
| 3472 |
*/ |
| 3473 |
if (jointype != JOIN_FULL) |
| 3474 |
{ |
| 3475 |
local_nonnullable_rels = find_nonnullable_rels(j->quals); |
| 3476 |
local_forced_null_vars = find_forced_null_vars(j->quals); |
| 3477 |
if (jointype == JOIN_INNER || jointype == JOIN_SEMI) |
| 3478 |
{ |
| 3479 |
/* OK to merge upper and local constraints */ |
| 3480 |
local_nonnullable_rels = bms_add_members(local_nonnullable_rels, |
| 3481 |
nonnullable_rels); |
| 3482 |
local_forced_null_vars = mbms_add_members(local_forced_null_vars, |
| 3483 |
forced_null_vars); |
| 3484 |
} |
| 3485 |
} |
| 3486 |
else |
| 3487 |
{ |
| 3488 |
/* no use in calculating these */ |
| 3489 |
local_nonnullable_rels = NULL; |
| 3490 |
local_forced_null_vars = NIL; |
| 3491 |
} |
| 3492 |
|
| 3493 |
if (left_state->contains_outer) |
| 3494 |
{ |
| 3495 |
if (jointype == JOIN_INNER || jointype == JOIN_SEMI) |
| 3496 |
{ |
| 3497 |
/* pass union of local and upper constraints */ |
| 3498 |
pass_nonnullable_rels = local_nonnullable_rels; |
| 3499 |
pass_forced_null_vars = local_forced_null_vars; |
| 3500 |
} |
| 3501 |
else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */ |
| 3502 |
{ |
| 3503 |
/* can't pass local constraints to non-nullable side */ |
| 3504 |
pass_nonnullable_rels = nonnullable_rels; |
| 3505 |
pass_forced_null_vars = forced_null_vars; |
| 3506 |
} |
| 3507 |
else |
| 3508 |
{ |
| 3509 |
/* no constraints pass through JOIN_FULL */ |
| 3510 |
pass_nonnullable_rels = NULL; |
| 3511 |
pass_forced_null_vars = NIL; |
| 3512 |
} |
| 3513 |
reduce_outer_joins_pass2(j->larg, left_state, |
| 3514 |
state2, root, |
| 3515 |
pass_nonnullable_rels, |
| 3516 |
pass_forced_null_vars); |
| 3517 |
} |
| 3518 |
|
| 3519 |
if (right_state->contains_outer) |
| 3520 |
{ |
| 3521 |
if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */ |
| 3522 |
{ |
| 3523 |
/* pass appropriate constraints, per comment above */ |
| 3524 |
pass_nonnullable_rels = local_nonnullable_rels; |
| 3525 |
pass_forced_null_vars = local_forced_null_vars; |
| 3526 |
} |
| 3527 |
else |
| 3528 |
{ |
| 3529 |
/* no constraints pass through JOIN_FULL */ |
| 3530 |
pass_nonnullable_rels = NULL; |
| 3531 |
pass_forced_null_vars = NIL; |
| 3532 |
} |
| 3533 |
reduce_outer_joins_pass2(j->rarg, right_state, |
| 3534 |
state2, root, |
| 3535 |
pass_nonnullable_rels, |
| 3536 |
pass_forced_null_vars); |
| 3537 |
} |
| 3538 |
bms_free(local_nonnullable_rels); |
| 3539 |
} |
| 3540 |
} |
| 3541 |
else |
| 3542 |
elog(ERROR, "unrecognized node type: %d", |
| 3543 |
(int) nodeTag(jtnode)); |
| 3544 |
} |
| 3545 |
|
| 3546 |
/* Helper for reduce_outer_joins_pass2 */ |
| 3547 |
static void |
| 3548 |
report_reduced_full_join(reduce_outer_joins_pass2_state *state2, |
| 3549 |
int rtindex, Relids relids) |
| 3550 |
{ |
| 3551 |
reduce_outer_joins_partial_state *statep; |
| 3552 |
|
| 3553 |
statep = palloc(sizeof(reduce_outer_joins_partial_state)); |
| 3554 |
statep->full_join_rti = rtindex; |
| 3555 |
statep->unreduced_side = relids; |
| 3556 |
state2->partial_reduced = lappend(state2->partial_reduced, statep); |
| 3557 |
} |
| 3558 |
|
| 3559 |
|
| 3560 |
/* |
| 3561 |
* remove_useless_result_rtes |
| 3562 |
* Attempt to remove RTE_RESULT RTEs from the join tree. |
| 3563 |
* Also, elide single-child FromExprs where possible. |
| 3564 |
* |
| 3565 |
* We can remove RTE_RESULT entries from the join tree using the knowledge |
| 3566 |
* that RTE_RESULT returns exactly one row and has no output columns. Hence, |
| 3567 |
* if one is inner-joined to anything else, we can delete it. Optimizations |
| 3568 |
* are also possible for some outer-join cases, as detailed below. |
| 3569 |
* |
| 3570 |
* This pass also replaces single-child FromExprs with their child node |
| 3571 |
* where possible. It's appropriate to do that here and not earlier because |
| 3572 |
* RTE_RESULT removal might reduce a multiple-child FromExpr to have only one |
| 3573 |
* child. We can remove such a FromExpr if its quals are empty, or if it's |
| 3574 |
* semantically valid to merge the quals into those of the parent node. |
| 3575 |
* While removing unnecessary join tree nodes has some micro-efficiency value, |
| 3576 |
* the real reason to do this is to eliminate cases where the nullable side of |
| 3577 |
* an outer join node is a FromExpr whose single child is another outer join. |
| 3578 |
* To correctly determine whether the two outer joins can commute, |
| 3579 |
* deconstruct_jointree() must treat any quals of such a FromExpr as being |
| 3580 |
* degenerate quals of the upper outer join. The best way to do that is to |
| 3581 |
* make them actually *be* quals of the upper join, by dropping the FromExpr |
| 3582 |
* and hoisting the quals up into the upper join's quals. (Note that there is |
| 3583 |
* no hazard when the intermediate FromExpr has multiple children, since then |
| 3584 |
* it represents an inner join that cannot commute with the upper outer join.) |
| 3585 |
* As long as we have to do that, we might as well elide such FromExprs |
| 3586 |
* everywhere. |
| 3587 |
* |
| 3588 |
* Some of these optimizations depend on recognizing empty (constant-true) |
| 3589 |
* quals for FromExprs and JoinExprs. That makes it useful to apply this |
| 3590 |
* optimization pass after expression preprocessing, since that will have |
| 3591 |
* eliminated constant-true quals, allowing more cases to be recognized as |
| 3592 |
* optimizable. What's more, the usual reason for an RTE_RESULT to be present |
| 3593 |
* is that we pulled up a subquery or VALUES clause, thus very possibly |
| 3594 |
* replacing Vars with constants, making it more likely that a qual can be |
| 3595 |
* reduced to constant true. Also, because some optimizations depend on |
| 3596 |
* the outer-join type, it's best to have done reduce_outer_joins() first. |
| 3597 |
* |
| 3598 |
* A PlaceHolderVar referencing an RTE_RESULT RTE poses an obstacle to this |
| 3599 |
* process: we must remove the RTE_RESULT's relid from the PHV's phrels, but |
| 3600 |
* we must not reduce the phrels set to empty. If that would happen, and |
| 3601 |
* the RTE_RESULT is an immediate child of an outer join, we have to give up |
| 3602 |
* and not remove the RTE_RESULT: there is noplace else to evaluate the |
| 3603 |
* PlaceHolderVar. (That is, in such cases the RTE_RESULT *does* have output |
| 3604 |
* columns.) But if the RTE_RESULT is an immediate child of an inner join, |
| 3605 |
* we can usually change the PlaceHolderVar's phrels so as to evaluate it at |
| 3606 |
* the inner join instead. This is OK because we really only care that PHVs |
| 3607 |
* are evaluated above or below the correct outer joins. We can't, however, |
| 3608 |
* postpone the evaluation of a PHV to above where it is used; so there are |
| 3609 |
* some checks below on whether output PHVs are laterally referenced in the |
| 3610 |
* other join input rel(s). |
| 3611 |
* |
| 3612 |
* We used to try to do this work as part of pull_up_subqueries() where the |
| 3613 |
* potentially-optimizable cases get introduced; but it's way simpler, and |
| 3614 |
* more effective, to do it separately. |
| 3615 |
*/ |
| 3616 |
void |
| 3617 |
remove_useless_result_rtes(PlannerInfo *root) |
| 3618 |
{ |
| 3619 |
Relids baserels = NULL; |
| 3620 |
Relids dropped_outer_joins = NULL; |
| 3621 |
ListCell *cell; |
| 3622 |
|
| 3623 |
/* |
| 3624 |
* We'll need the set of baserels in the jointree to perform |
| 3625 |
* find_dependent_phvs() checks. But if there are no PHVs anywhere in the |
| 3626 |
* query, those checks are no-ops, so we can skip the work. |
| 3627 |
*/ |
| 3628 |
if (root->glob->lastPHId != 0) |
| 3629 |
baserels = get_relids_in_jointree((Node *) root->parse->jointree, |
| 3630 |
false, false); |
| 3631 |
|
| 3632 |
/* Top level of jointree must always be a FromExpr */ |
| 3633 |
Assert(IsA(root->parse->jointree, FromExpr)); |
| 3634 |
/* Recurse ... */ |
| 3635 |
root->parse->jointree = (FromExpr *) |
| 3636 |
remove_useless_results_recurse(root, |
| 3637 |
(Node *) root->parse->jointree, |
| 3638 |
baserels, |
| 3639 |
NULL, |
| 3640 |
&dropped_outer_joins); |
| 3641 |
/* We should still have a FromExpr */ |
| 3642 |
Assert(IsA(root->parse->jointree, FromExpr)); |
| 3643 |
|
| 3644 |
/* |
| 3645 |
* If we removed any outer-join nodes from the jointree, run around and |
| 3646 |
* remove references to those joins as nulling rels. (There could be such |
| 3647 |
* references in PHVs that we pulled up out of the original subquery that |
| 3648 |
* the RESULT rel replaced. This is kosher on the grounds that we now |
| 3649 |
* know that such an outer join wouldn't really have nulled anything.) We |
| 3650 |
* don't do this during the main recursion, for simplicity and because we |
| 3651 |
* can handle all such joins in a single pass over the parse tree. |
| 3652 |
*/ |
| 3653 |
if (!bms_is_empty(dropped_outer_joins)) |
| 3654 |
{ |
| 3655 |
root->parse = (Query *) |
| 3656 |
remove_nulling_relids((Node *) root->parse, |
| 3657 |
dropped_outer_joins, |
| 3658 |
NULL); |
| 3659 |
/* There could be references in the append_rel_list, too */ |
| 3660 |
root->append_rel_list = (List *) |
| 3661 |
remove_nulling_relids((Node *) root->append_rel_list, |
| 3662 |
dropped_outer_joins, |
| 3663 |
NULL); |
| 3664 |
} |
| 3665 |
|
| 3666 |
/* |
| 3667 |
* Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously |
| 3668 |
* must do that for any RTE_RESULT that we just removed. But one for a |
| 3669 |
* RTE that we did not remove can be dropped anyway: since the RTE has |
| 3670 |
* only one possible output row, there is no need for EPQ to mark and |
| 3671 |
* restore that row. |
| 3672 |
* |
| 3673 |
* It's necessary, not optional, to remove the PlanRowMark for a surviving |
| 3674 |
* RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the |
| 3675 |
* RTE_RESULT, which the executor has no support for. |
| 3676 |
*/ |
| 3677 |
foreach(cell, root->rowMarks) |
| 3678 |
{ |
| 3679 |
PlanRowMark *rc = (PlanRowMark *) lfirst(cell); |
| 3680 |
|
| 3681 |
if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT) |
| 3682 |
root->rowMarks = foreach_delete_current(root->rowMarks, cell); |
| 3683 |
} |
| 3684 |
} |
| 3685 |
|
| 3686 |
/* |
| 3687 |
* remove_useless_results_recurse |
| 3688 |
* Recursive guts of remove_useless_result_rtes. |
| 3689 |
* |
| 3690 |
* This recursively processes the jointree and returns a modified jointree. |
| 3691 |
* In addition, the RT indexes of any removed outer-join nodes are added to |
| 3692 |
* *dropped_outer_joins. |
| 3693 |
* |
| 3694 |
* jtnode is the current jointree node. If it could be valid to merge |
| 3695 |
* its quals into those of the parent node, parent_quals should point to |
| 3696 |
* the parent's quals list; otherwise, pass NULL for parent_quals. |
| 3697 |
* (Note that in some cases, parent_quals points to the quals of a parent |
| 3698 |
* more than one level up in the tree.) |
| 3699 |
* |
| 3700 |
* baserels is the set of base (non-join) RT indexes in the whole jointree; |
| 3701 |
* it can be NULL if the query contains no PHVs. |
| 3702 |
*/ |
| 3703 |
static Node * |
| 3704 |
remove_useless_results_recurse(PlannerInfo *root, Node *jtnode, |
| 3705 |
Relids baserels, |
| 3706 |
Node **parent_quals, |
| 3707 |
Relids *dropped_outer_joins) |
| 3708 |
{ |
| 3709 |
Assert(jtnode != NULL); |
| 3710 |
if (IsA(jtnode, RangeTblRef)) |
| 3711 |
{ |
| 3712 |
/* Can't immediately do anything with a RangeTblRef */ |
| 3713 |
} |
| 3714 |
else if (IsA(jtnode, FromExpr)) |
| 3715 |
{ |
| 3716 |
FromExpr *f = (FromExpr *) jtnode; |
| 3717 |
Relids result_relids = NULL; |
| 3718 |
ListCell *cell; |
| 3719 |
|
| 3720 |
/* |
| 3721 |
* We can drop RTE_RESULT rels from the fromlist so long as at least |
| 3722 |
* one child remains, since joining to a one-row table changes |
| 3723 |
* nothing. (But we can't drop a RTE_RESULT that computes PHV(s) that |
| 3724 |
* are needed by some sibling. The cleanup transformation below would |
| 3725 |
* reassign the PHVs to be computed at the join, which is too late for |
| 3726 |
* the sibling's use.) The easiest way to mechanize this rule is to |
| 3727 |
* modify the list in-place. |
| 3728 |
*/ |
| 3729 |
foreach(cell, f->fromlist) |
| 3730 |
{ |
| 3731 |
Node *child = (Node *) lfirst(cell); |
| 3732 |
int varno; |
| 3733 |
|
| 3734 |
/* Recursively transform child, allowing it to push up quals ... */ |
| 3735 |
child = remove_useless_results_recurse(root, child, |
| 3736 |
baserels, |
| 3737 |
&f->quals, |
| 3738 |
dropped_outer_joins); |
| 3739 |
/* ... and stick it back into the tree */ |
| 3740 |
lfirst(cell) = child; |
| 3741 |
|
| 3742 |
/* |
| 3743 |
* If it's an RTE_RESULT with at least one sibling, and no sibling |
| 3744 |
* references dependent PHVs, we can drop it. We don't yet know |
| 3745 |
* what the inner join's final relid set will be, so postpone |
| 3746 |
* cleanup of PHVs etc till after this loop. |
| 3747 |
*/ |
| 3748 |
if (list_length(f->fromlist) > 1 && |
| 3749 |
(varno = get_result_relid(root, child)) != 0 && |
| 3750 |
!find_dependent_phvs_in_jointree(root, (Node *) f, varno, |
| 3751 |
baserels)) |
| 3752 |
{ |
| 3753 |
f->fromlist = foreach_delete_current(f->fromlist, cell); |
| 3754 |
result_relids = bms_add_member(result_relids, varno); |
| 3755 |
} |
| 3756 |
} |
| 3757 |
|
| 3758 |
/* |
| 3759 |
* Clean up if we dropped any RTE_RESULT RTEs. This is a bit |
| 3760 |
* inefficient if there's more than one, but it seems better to |
| 3761 |
* optimize the support code for the single-relid case. |
| 3762 |
*/ |
| 3763 |
if (result_relids) |
| 3764 |
{ |
| 3765 |
int varno = -1; |
| 3766 |
|
| 3767 |
while ((varno = bms_next_member(result_relids, varno)) >= 0) |
| 3768 |
remove_result_refs(root, varno, (Node *) f); |
| 3769 |
} |
| 3770 |
|
| 3771 |
/* |
| 3772 |
* If the FromExpr now has only one child, see if we can elide it. |
| 3773 |
* This is always valid if there are no quals, except at the top of |
| 3774 |
* the jointree (since Query.jointree is required to point to a |
| 3775 |
* FromExpr). Otherwise, we can do it if we can push the quals up to |
| 3776 |
* the parent node. |
| 3777 |
* |
| 3778 |
* Note: while it would not be terribly hard to generalize this |
| 3779 |
* transformation to merge multi-child FromExprs into their parent |
| 3780 |
* FromExpr, that risks making the parent join too expensive to plan. |
| 3781 |
* We leave it to later processing to decide heuristically whether |
| 3782 |
* that's a good idea. Pulling up a single child is always OK, |
| 3783 |
* however. |
| 3784 |
*/ |
| 3785 |
if (list_length(f->fromlist) == 1 && |
| 3786 |
f != root->parse->jointree && |
| 3787 |
(f->quals == NULL || parent_quals != NULL)) |
| 3788 |
{ |
| 3789 |
/* |
| 3790 |
* Merge any quals up to parent. They should be in implicit-AND |
| 3791 |
* format by now, so we just need to concatenate lists. Put the |
| 3792 |
* child quals at the front, on the grounds that they should |
| 3793 |
* nominally be evaluated earlier. |
| 3794 |
*/ |
| 3795 |
if (f->quals != NULL) |
| 3796 |
*parent_quals = (Node *) |
| 3797 |
list_concat(castNode(List, f->quals), |
| 3798 |
castNode(List, *parent_quals)); |
| 3799 |
return (Node *) linitial(f->fromlist); |
| 3800 |
} |
| 3801 |
} |
| 3802 |
else if (IsA(jtnode, JoinExpr)) |
| 3803 |
{ |
| 3804 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 3805 |
int varno; |
| 3806 |
|
| 3807 |
/* |
| 3808 |
* First, recurse. We can absorb pushed-up FromExpr quals from either |
| 3809 |
* child into this node if the jointype is INNER, since then this is |
| 3810 |
* equivalent to a FromExpr. When the jointype is LEFT, we can absorb |
| 3811 |
* quals from the RHS child into the current node, as they're |
| 3812 |
* essentially degenerate quals of the outer join. Moreover, if we've |
| 3813 |
* been passed down a parent_quals pointer then we can allow quals of |
| 3814 |
* the LHS child to be absorbed into the parent. (This is important |
| 3815 |
* to ensure we remove single-child FromExprs immediately below |
| 3816 |
* commutable left joins.) For other jointypes, we can't move child |
| 3817 |
* quals up, or at least there's no particular reason to. |
| 3818 |
*/ |
| 3819 |
j->larg = remove_useless_results_recurse(root, j->larg, |
| 3820 |
baserels, |
| 3821 |
(j->jointype == JOIN_INNER) ? |
| 3822 |
&j->quals : |
| 3823 |
(j->jointype == JOIN_LEFT) ? |
| 3824 |
parent_quals : NULL, |
| 3825 |
dropped_outer_joins); |
| 3826 |
j->rarg = remove_useless_results_recurse(root, j->rarg, |
| 3827 |
baserels, |
| 3828 |
(j->jointype == JOIN_INNER || |
| 3829 |
j->jointype == JOIN_LEFT) ? |
| 3830 |
&j->quals : NULL, |
| 3831 |
dropped_outer_joins); |
| 3832 |
|
| 3833 |
/* Apply join-type-specific optimization rules */ |
| 3834 |
switch (j->jointype) |
| 3835 |
{ |
| 3836 |
case JOIN_INNER: |
| 3837 |
|
| 3838 |
/* |
| 3839 |
* An inner join is equivalent to a FromExpr, so if either |
| 3840 |
* side was simplified to an RTE_RESULT rel, we can replace |
| 3841 |
* the join with a FromExpr with just the other side. |
| 3842 |
* Furthermore, we can elide that FromExpr according to the |
| 3843 |
* same rules as above. |
| 3844 |
* |
| 3845 |
* Just as in the FromExpr case, we can't simplify if the |
| 3846 |
* other input rel references any PHVs that are marked as to |
| 3847 |
* be evaluated at the RTE_RESULT rel, because we can't |
| 3848 |
* postpone their evaluation in that case. But we only have |
| 3849 |
* to check this in cases where it's syntactically legal for |
| 3850 |
* the other input to have a LATERAL reference to the |
| 3851 |
* RTE_RESULT rel. Only RHSes of inner and left joins are |
| 3852 |
* allowed to have such refs. |
| 3853 |
*/ |
| 3854 |
if ((varno = get_result_relid(root, j->larg)) != 0 && |
| 3855 |
!find_dependent_phvs_in_jointree(root, j->rarg, varno, |
| 3856 |
baserels)) |
| 3857 |
{ |
| 3858 |
remove_result_refs(root, varno, j->rarg); |
| 3859 |
if (j->quals != NULL && parent_quals == NULL) |
| 3860 |
jtnode = (Node *) |
| 3861 |
makeFromExpr(list_make1(j->rarg), j->quals); |
| 3862 |
else |
| 3863 |
{ |
| 3864 |
/* Merge any quals up to parent */ |
| 3865 |
if (j->quals != NULL) |
| 3866 |
*parent_quals = (Node *) |
| 3867 |
list_concat(castNode(List, j->quals), |
| 3868 |
castNode(List, *parent_quals)); |
| 3869 |
jtnode = j->rarg; |
| 3870 |
} |
| 3871 |
} |
| 3872 |
else if ((varno = get_result_relid(root, j->rarg)) != 0) |
| 3873 |
{ |
| 3874 |
remove_result_refs(root, varno, j->larg); |
| 3875 |
if (j->quals != NULL && parent_quals == NULL) |
| 3876 |
jtnode = (Node *) |
| 3877 |
makeFromExpr(list_make1(j->larg), j->quals); |
| 3878 |
else |
| 3879 |
{ |
| 3880 |
/* Merge any quals up to parent */ |
| 3881 |
if (j->quals != NULL) |
| 3882 |
*parent_quals = (Node *) |
| 3883 |
list_concat(castNode(List, j->quals), |
| 3884 |
castNode(List, *parent_quals)); |
| 3885 |
jtnode = j->larg; |
| 3886 |
} |
| 3887 |
} |
| 3888 |
break; |
| 3889 |
case JOIN_LEFT: |
| 3890 |
|
| 3891 |
/* |
| 3892 |
* We can simplify this case if the RHS is an RTE_RESULT, with |
| 3893 |
* two different possibilities: |
| 3894 |
* |
| 3895 |
* If the qual is empty (JOIN ON TRUE), then the join can be |
| 3896 |
* strength-reduced to a plain inner join, since each LHS row |
| 3897 |
* necessarily has exactly one join partner. So we can always |
| 3898 |
* discard the RHS, much as in the JOIN_INNER case above. |
| 3899 |
* (Again, the LHS could not contain a lateral reference to |
| 3900 |
* the RHS.) |
| 3901 |
* |
| 3902 |
* Otherwise, it's still true that each LHS row should be |
| 3903 |
* returned exactly once, and since the RHS returns no columns |
| 3904 |
* (unless there are PHVs that have to be evaluated there), we |
| 3905 |
* don't much care if it's null-extended or not. So in this |
| 3906 |
* case also, we can just ignore the qual and discard the left |
| 3907 |
* join. |
| 3908 |
*/ |
| 3909 |
if ((varno = get_result_relid(root, j->rarg)) != 0 && |
| 3910 |
(j->quals == NULL || |
| 3911 |
!find_dependent_phvs(root, varno, baserels))) |
| 3912 |
{ |
| 3913 |
remove_result_refs(root, varno, j->larg); |
| 3914 |
*dropped_outer_joins = bms_add_member(*dropped_outer_joins, |
| 3915 |
j->rtindex); |
| 3916 |
jtnode = j->larg; |
| 3917 |
} |
| 3918 |
break; |
| 3919 |
case JOIN_SEMI: |
| 3920 |
|
| 3921 |
/* |
| 3922 |
* We may simplify this case if the RHS is an RTE_RESULT; the |
| 3923 |
* join qual becomes effectively just a filter qual for the |
| 3924 |
* LHS, since we should either return the LHS row or not. The |
| 3925 |
* filter clause must go into a new FromExpr if we can't push |
| 3926 |
* it up to the parent. |
| 3927 |
* |
| 3928 |
* There is a fine point about PHVs that are supposed to be |
| 3929 |
* evaluated at the RHS. Such PHVs could only appear in the |
| 3930 |
* semijoin's qual, since the rest of the query cannot |
| 3931 |
* reference any outputs of the semijoin's RHS. Therefore, |
| 3932 |
* they can't actually go to null before being examined, and |
| 3933 |
* it'd be OK to just remove the PHV wrapping. We don't have |
| 3934 |
* infrastructure for that, but remove_result_refs() will |
| 3935 |
* relabel them as to be evaluated at the LHS, which is fine. |
| 3936 |
* |
| 3937 |
* Also, we don't need to worry about removing traces of the |
| 3938 |
* join's rtindex, since it hasn't got one. |
| 3939 |
*/ |
| 3940 |
if ((varno = get_result_relid(root, j->rarg)) != 0) |
| 3941 |
{ |
| 3942 |
Assert(j->rtindex == 0); |
| 3943 |
remove_result_refs(root, varno, j->larg); |
| 3944 |
if (j->quals != NULL && parent_quals == NULL) |
| 3945 |
jtnode = (Node *) |
| 3946 |
makeFromExpr(list_make1(j->larg), j->quals); |
| 3947 |
else |
| 3948 |
{ |
| 3949 |
/* Merge any quals up to parent */ |
| 3950 |
if (j->quals != NULL) |
| 3951 |
*parent_quals = (Node *) |
| 3952 |
list_concat(castNode(List, j->quals), |
| 3953 |
castNode(List, *parent_quals)); |
| 3954 |
jtnode = j->larg; |
| 3955 |
} |
| 3956 |
} |
| 3957 |
break; |
| 3958 |
case JOIN_FULL: |
| 3959 |
case JOIN_ANTI: |
| 3960 |
/* We have no special smarts for these cases */ |
| 3961 |
break; |
| 3962 |
default: |
| 3963 |
/* Note: JOIN_RIGHT should be gone at this point */ |
| 3964 |
elog(ERROR, "unrecognized join type: %d", |
| 3965 |
(int) j->jointype); |
| 3966 |
break; |
| 3967 |
} |
| 3968 |
} |
| 3969 |
else |
| 3970 |
elog(ERROR, "unrecognized node type: %d", |
| 3971 |
(int) nodeTag(jtnode)); |
| 3972 |
return jtnode; |
| 3973 |
} |
| 3974 |
|
| 3975 |
/* |
| 3976 |
* get_result_relid |
| 3977 |
* If jtnode is a RangeTblRef for an RTE_RESULT RTE, return its relid; |
| 3978 |
* otherwise return 0. |
| 3979 |
*/ |
| 3980 |
static int |
| 3981 |
get_result_relid(PlannerInfo *root, Node *jtnode) |
| 3982 |
{ |
| 3983 |
int varno; |
| 3984 |
|
| 3985 |
if (!IsA(jtnode, RangeTblRef)) |
| 3986 |
return 0; |
| 3987 |
varno = ((RangeTblRef *) jtnode)->rtindex; |
| 3988 |
if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT) |
| 3989 |
return 0; |
| 3990 |
return varno; |
| 3991 |
} |
| 3992 |
|
| 3993 |
/* |
| 3994 |
* remove_result_refs |
| 3995 |
* Helper routine for dropping an unneeded RTE_RESULT RTE. |
| 3996 |
* |
| 3997 |
* This doesn't physically remove the RTE from the jointree, because that's |
| 3998 |
* more easily handled in remove_useless_results_recurse. What it does do |
| 3999 |
* is the necessary cleanup in the rest of the tree: we must adjust any PHVs |
| 4000 |
* that may reference the RTE. Be sure to call this at a point where the |
| 4001 |
* jointree is valid (no disconnected nodes). |
| 4002 |
* |
| 4003 |
* Note that we don't need to process the append_rel_list, since RTEs |
| 4004 |
* referenced directly in the jointree won't be appendrel members. |
| 4005 |
* |
| 4006 |
* varno is the RTE_RESULT's relid. |
| 4007 |
* newjtloc is the jointree location at which any PHVs referencing the |
| 4008 |
* RTE_RESULT should be evaluated instead. |
| 4009 |
*/ |
| 4010 |
static void |
| 4011 |
remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc) |
| 4012 |
{ |
| 4013 |
/* Fix up PlaceHolderVars as needed */ |
| 4014 |
/* If there are no PHVs anywhere, we can skip this bit */ |
| 4015 |
if (root->glob->lastPHId != 0) |
| 4016 |
{ |
| 4017 |
Relids subrelids; |
| 4018 |
|
| 4019 |
subrelids = get_relids_in_jointree(newjtloc, true, false); |
| 4020 |
Assert(!bms_is_empty(subrelids)); |
| 4021 |
substitute_phv_relids((Node *) root->parse, varno, subrelids); |
| 4022 |
fix_append_rel_relids(root, varno, subrelids); |
| 4023 |
} |
| 4024 |
|
| 4025 |
/* |
| 4026 |
* We also need to remove any PlanRowMark referencing the RTE, but we |
| 4027 |
* postpone that work until we return to remove_useless_result_rtes. |
| 4028 |
*/ |
| 4029 |
} |
| 4030 |
|
| 4031 |
|
| 4032 |
/* |
| 4033 |
* find_dependent_phvs - are there any PlaceHolderVars whose base relids are |
| 4034 |
* exactly the given varno? |
| 4035 |
* |
| 4036 |
* We ignore outer-join relids present in a PHV's phrels, by intersecting |
| 4037 |
* with the caller-supplied "baserels" set. This is necessary in part |
| 4038 |
* because some of the OJ relids may be stale, that is we may have |
| 4039 |
* already decided to remove those joins in remove_useless_result_rtes |
| 4040 |
* and not yet have cleaned their relid bits out of upper PHVs. |
| 4041 |
* But in general, it's the set of baserels that identify possible places |
| 4042 |
* to evaluate a PHV, and we mustn't let that go to empty. (The caller is |
| 4043 |
* allowed to pass baserels as NULL if the query contains no PHVs at all, |
| 4044 |
* since then there is no work to do anyway.) |
| 4045 |
* |
| 4046 |
* find_dependent_phvs should be used when we want to see if there are |
| 4047 |
* any such PHVs anywhere in the Query. Another use-case is to see if |
| 4048 |
* a subtree of the join tree contains such PHVs; but for that, we have |
| 4049 |
* to look not only at the join tree nodes themselves but at the |
| 4050 |
* referenced RTEs. For that, use find_dependent_phvs_in_jointree. |
| 4051 |
*/ |
| 4052 |
|
| 4053 |
typedef struct |
| 4054 |
{ |
| 4055 |
Relids relids; /* target relid, represented as a relid set */ |
| 4056 |
Relids baserels; /* base RT indexes in query, NULL if no PHVs */ |
| 4057 |
int sublevels_up; /* current nesting level */ |
| 4058 |
} find_dependent_phvs_context; |
| 4059 |
|
| 4060 |
static bool |
| 4061 |
find_dependent_phvs_walker(Node *node, |
| 4062 |
find_dependent_phvs_context *context) |
| 4063 |
{ |
| 4064 |
if (node == NULL) |
| 4065 |
return false; |
| 4066 |
if (IsA(node, PlaceHolderVar)) |
| 4067 |
{ |
| 4068 |
PlaceHolderVar *phv = (PlaceHolderVar *) node; |
| 4069 |
|
| 4070 |
if (phv->phlevelsup == context->sublevels_up) |
| 4071 |
{ |
| 4072 |
Relids phbaserels = bms_intersect(phv->phrels, |
| 4073 |
context->baserels); |
| 4074 |
bool match = bms_equal(context->relids, phbaserels); |
| 4075 |
|
| 4076 |
bms_free(phbaserels); |
| 4077 |
if (match) |
| 4078 |
return true; |
| 4079 |
} |
| 4080 |
/* fall through to examine children */ |
| 4081 |
} |
| 4082 |
if (IsA(node, Query)) |
| 4083 |
{ |
| 4084 |
/* Recurse into subselects */ |
| 4085 |
bool result; |
| 4086 |
|
| 4087 |
context->sublevels_up++; |
| 4088 |
result = query_tree_walker((Query *) node, |
| 4089 |
find_dependent_phvs_walker, |
| 4090 |
context, 0); |
| 4091 |
context->sublevels_up--; |
| 4092 |
return result; |
| 4093 |
} |
| 4094 |
/* Shouldn't need to handle most planner auxiliary nodes here */ |
| 4095 |
Assert(!IsA(node, SpecialJoinInfo)); |
| 4096 |
Assert(!IsA(node, PlaceHolderInfo)); |
| 4097 |
Assert(!IsA(node, MinMaxAggInfo)); |
| 4098 |
|
| 4099 |
return expression_tree_walker(node, find_dependent_phvs_walker, context); |
| 4100 |
} |
| 4101 |
|
| 4102 |
static bool |
| 4103 |
find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels) |
| 4104 |
{ |
| 4105 |
find_dependent_phvs_context context; |
| 4106 |
|
| 4107 |
/* If there are no PHVs anywhere, we needn't work hard */ |
| 4108 |
if (root->glob->lastPHId == 0) |
| 4109 |
return false; |
| 4110 |
|
| 4111 |
context.relids = bms_make_singleton(varno); |
| 4112 |
context.baserels = baserels; |
| 4113 |
context.sublevels_up = 0; |
| 4114 |
|
| 4115 |
if (query_tree_walker(root->parse, find_dependent_phvs_walker, &context, 0)) |
| 4116 |
return true; |
| 4117 |
/* The append_rel_list could be populated already, so check it too */ |
| 4118 |
if (expression_tree_walker((Node *) root->append_rel_list, |
| 4119 |
find_dependent_phvs_walker, |
| 4120 |
&context)) |
| 4121 |
return true; |
| 4122 |
return false; |
| 4123 |
} |
| 4124 |
|
| 4125 |
static bool |
| 4126 |
find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno, |
| 4127 |
Relids baserels) |
| 4128 |
{ |
| 4129 |
find_dependent_phvs_context context; |
| 4130 |
Relids subrelids; |
| 4131 |
int relid; |
| 4132 |
|
| 4133 |
/* If there are no PHVs anywhere, we needn't work hard */ |
| 4134 |
if (root->glob->lastPHId == 0) |
| 4135 |
return false; |
| 4136 |
|
| 4137 |
context.relids = bms_make_singleton(varno); |
| 4138 |
context.baserels = baserels; |
| 4139 |
context.sublevels_up = 0; |
| 4140 |
|
| 4141 |
/* |
| 4142 |
* See if the jointree fragment itself contains references (in join quals) |
| 4143 |
*/ |
| 4144 |
if (find_dependent_phvs_walker(node, &context)) |
| 4145 |
return true; |
| 4146 |
|
| 4147 |
/* |
| 4148 |
* Otherwise, identify the set of referenced RTEs (we can ignore joins, |
| 4149 |
* since they should be flattened already, so their join alias lists no |
| 4150 |
* longer matter), and tediously check each RTE. We can ignore RTEs that |
| 4151 |
* are not marked LATERAL, though, since they couldn't possibly contain |
| 4152 |
* any cross-references to other RTEs. |
| 4153 |
*/ |
| 4154 |
subrelids = get_relids_in_jointree(node, false, false); |
| 4155 |
relid = -1; |
| 4156 |
while ((relid = bms_next_member(subrelids, relid)) >= 0) |
| 4157 |
{ |
| 4158 |
RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable); |
| 4159 |
|
| 4160 |
if (rte->lateral && |
| 4161 |
range_table_entry_walker(rte, find_dependent_phvs_walker, &context, 0)) |
| 4162 |
return true; |
| 4163 |
} |
| 4164 |
|
| 4165 |
return false; |
| 4166 |
} |
| 4167 |
|
| 4168 |
/* |
| 4169 |
* substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up |
| 4170 |
* a subquery or removing an RTE_RESULT jointree item |
| 4171 |
* |
| 4172 |
* Find any PlaceHolderVar nodes in the given tree that reference the |
| 4173 |
* pulled-up relid, and change them to reference the replacement relid(s). |
| 4174 |
* |
| 4175 |
* NOTE: although this has the form of a walker, we cheat and modify the |
| 4176 |
* nodes in-place. This should be OK since the tree was copied by |
| 4177 |
* pullup_replace_vars earlier. Avoid scribbling on the original values of |
| 4178 |
* the bitmapsets, though, because expression_tree_mutator doesn't copy those. |
| 4179 |
*/ |
| 4180 |
|
| 4181 |
typedef struct |
| 4182 |
{ |
| 4183 |
int varno; |
| 4184 |
int sublevels_up; |
| 4185 |
Relids subrelids; |
| 4186 |
} substitute_phv_relids_context; |
| 4187 |
|
| 4188 |
static bool |
| 4189 |
substitute_phv_relids_walker(Node *node, |
| 4190 |
substitute_phv_relids_context *context) |
| 4191 |
{ |
| 4192 |
if (node == NULL) |
| 4193 |
return false; |
| 4194 |
if (IsA(node, PlaceHolderVar)) |
| 4195 |
{ |
| 4196 |
PlaceHolderVar *phv = (PlaceHolderVar *) node; |
| 4197 |
|
| 4198 |
if (phv->phlevelsup == context->sublevels_up && |
| 4199 |
bms_is_member(context->varno, phv->phrels)) |
| 4200 |
{ |
| 4201 |
phv->phrels = bms_union(phv->phrels, |
| 4202 |
context->subrelids); |
| 4203 |
phv->phrels = bms_del_member(phv->phrels, |
| 4204 |
context->varno); |
| 4205 |
/* Assert we haven't broken the PHV */ |
| 4206 |
Assert(!bms_is_empty(phv->phrels)); |
| 4207 |
} |
| 4208 |
/* fall through to examine children */ |
| 4209 |
} |
| 4210 |
if (IsA(node, Query)) |
| 4211 |
{ |
| 4212 |
/* Recurse into subselects */ |
| 4213 |
bool result; |
| 4214 |
|
| 4215 |
context->sublevels_up++; |
| 4216 |
result = query_tree_walker((Query *) node, |
| 4217 |
substitute_phv_relids_walker, |
| 4218 |
context, 0); |
| 4219 |
context->sublevels_up--; |
| 4220 |
return result; |
| 4221 |
} |
| 4222 |
/* Shouldn't need to handle planner auxiliary nodes here */ |
| 4223 |
Assert(!IsA(node, SpecialJoinInfo)); |
| 4224 |
Assert(!IsA(node, AppendRelInfo)); |
| 4225 |
Assert(!IsA(node, PlaceHolderInfo)); |
| 4226 |
Assert(!IsA(node, MinMaxAggInfo)); |
| 4227 |
|
| 4228 |
return expression_tree_walker(node, substitute_phv_relids_walker, context); |
| 4229 |
} |
| 4230 |
|
| 4231 |
static void |
| 4232 |
substitute_phv_relids(Node *node, int varno, Relids subrelids) |
| 4233 |
{ |
| 4234 |
substitute_phv_relids_context context; |
| 4235 |
|
| 4236 |
context.varno = varno; |
| 4237 |
context.sublevels_up = 0; |
| 4238 |
context.subrelids = subrelids; |
| 4239 |
|
| 4240 |
/* |
| 4241 |
* Must be prepared to start with a Query or a bare expression tree. |
| 4242 |
*/ |
| 4243 |
query_or_expression_tree_walker(node, |
| 4244 |
substitute_phv_relids_walker, |
| 4245 |
&context, |
| 4246 |
0); |
| 4247 |
} |
| 4248 |
|
| 4249 |
/* |
| 4250 |
* fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes |
| 4251 |
* |
| 4252 |
* When we pull up a subquery, any AppendRelInfo references to the subquery's |
| 4253 |
* RT index have to be replaced by the substituted relid (and there had better |
| 4254 |
* be only one). We also need to apply substitute_phv_relids to their |
| 4255 |
* translated_vars lists, since those might contain PlaceHolderVars. |
| 4256 |
* |
| 4257 |
* We assume we may modify the AppendRelInfo nodes in-place. |
| 4258 |
*/ |
| 4259 |
static void |
| 4260 |
fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids) |
| 4261 |
{ |
| 4262 |
ListCell *l; |
| 4263 |
int subvarno = -1; |
| 4264 |
|
| 4265 |
/* |
| 4266 |
* We only want to extract the member relid once, but we mustn't fail |
| 4267 |
* immediately if there are multiple members; it could be that none of the |
| 4268 |
* AppendRelInfo nodes refer to it. So compute it on first use. Note that |
| 4269 |
* bms_singleton_member will complain if set is not singleton. |
| 4270 |
*/ |
| 4271 |
foreach(l, root->append_rel_list) |
| 4272 |
{ |
| 4273 |
AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l); |
| 4274 |
|
| 4275 |
/* The parent_relid shouldn't ever be a pullup target */ |
| 4276 |
Assert(appinfo->parent_relid != varno); |
| 4277 |
|
| 4278 |
if (appinfo->child_relid == varno) |
| 4279 |
{ |
| 4280 |
if (subvarno < 0) |
| 4281 |
subvarno = bms_singleton_member(subrelids); |
| 4282 |
appinfo->child_relid = subvarno; |
| 4283 |
} |
| 4284 |
|
| 4285 |
/* Also fix up any PHVs in its translated vars */ |
| 4286 |
if (root->glob->lastPHId != 0) |
| 4287 |
substitute_phv_relids((Node *) appinfo->translated_vars, |
| 4288 |
varno, subrelids); |
| 4289 |
} |
| 4290 |
} |
| 4291 |
|
| 4292 |
/* |
| 4293 |
* get_relids_in_jointree: get set of RT indexes present in a jointree |
| 4294 |
* |
| 4295 |
* Base-relation relids are always included in the result. |
| 4296 |
* If include_outer_joins is true, outer-join RT indexes are included. |
| 4297 |
* If include_inner_joins is true, inner-join RT indexes are included. |
| 4298 |
* |
| 4299 |
* Note that for most purposes in the planner, outer joins are included |
| 4300 |
* in standard relid sets. Setting include_inner_joins true is only |
| 4301 |
* appropriate for special purposes during subquery flattening. |
| 4302 |
*/ |
| 4303 |
Relids |
| 4304 |
get_relids_in_jointree(Node *jtnode, bool include_outer_joins, |
| 4305 |
bool include_inner_joins) |
| 4306 |
{ |
| 4307 |
Relids result = NULL; |
| 4308 |
|
| 4309 |
if (jtnode == NULL) |
| 4310 |
return result; |
| 4311 |
if (IsA(jtnode, RangeTblRef)) |
| 4312 |
{ |
| 4313 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 4314 |
|
| 4315 |
result = bms_make_singleton(varno); |
| 4316 |
} |
| 4317 |
else if (IsA(jtnode, FromExpr)) |
| 4318 |
{ |
| 4319 |
FromExpr *f = (FromExpr *) jtnode; |
| 4320 |
ListCell *l; |
| 4321 |
|
| 4322 |
foreach(l, f->fromlist) |
| 4323 |
{ |
| 4324 |
result = bms_join(result, |
| 4325 |
get_relids_in_jointree(lfirst(l), |
| 4326 |
include_outer_joins, |
| 4327 |
include_inner_joins)); |
| 4328 |
} |
| 4329 |
} |
| 4330 |
else if (IsA(jtnode, JoinExpr)) |
| 4331 |
{ |
| 4332 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 4333 |
|
| 4334 |
result = get_relids_in_jointree(j->larg, |
| 4335 |
include_outer_joins, |
| 4336 |
include_inner_joins); |
| 4337 |
result = bms_join(result, |
| 4338 |
get_relids_in_jointree(j->rarg, |
| 4339 |
include_outer_joins, |
| 4340 |
include_inner_joins)); |
| 4341 |
if (j->rtindex) |
| 4342 |
{ |
| 4343 |
if (j->jointype == JOIN_INNER) |
| 4344 |
{ |
| 4345 |
if (include_inner_joins) |
| 4346 |
result = bms_add_member(result, j->rtindex); |
| 4347 |
} |
| 4348 |
else |
| 4349 |
{ |
| 4350 |
if (include_outer_joins) |
| 4351 |
result = bms_add_member(result, j->rtindex); |
| 4352 |
} |
| 4353 |
} |
| 4354 |
} |
| 4355 |
else |
| 4356 |
elog(ERROR, "unrecognized node type: %d", |
| 4357 |
(int) nodeTag(jtnode)); |
| 4358 |
return result; |
| 4359 |
} |
| 4360 |
|
| 4361 |
/* |
| 4362 |
* get_relids_for_join: get set of base+OJ RT indexes making up a join |
| 4363 |
*/ |
| 4364 |
Relids |
| 4365 |
get_relids_for_join(Query *query, int joinrelid) |
| 4366 |
{ |
| 4367 |
Node *jtnode; |
| 4368 |
|
| 4369 |
jtnode = find_jointree_node_for_rel((Node *) query->jointree, |
| 4370 |
joinrelid); |
| 4371 |
if (!jtnode) |
| 4372 |
elog(ERROR, "could not find join node %d", joinrelid); |
| 4373 |
return get_relids_in_jointree(jtnode, true, false); |
| 4374 |
} |
| 4375 |
|
| 4376 |
/* |
| 4377 |
* find_jointree_node_for_rel: locate jointree node for a base or join RT index |
| 4378 |
* |
| 4379 |
* Returns NULL if not found |
| 4380 |
*/ |
| 4381 |
static Node * |
| 4382 |
find_jointree_node_for_rel(Node *jtnode, int relid) |
| 4383 |
{ |
| 4384 |
if (jtnode == NULL) |
| 4385 |
return NULL; |
| 4386 |
if (IsA(jtnode, RangeTblRef)) |
| 4387 |
{ |
| 4388 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 4389 |
|
| 4390 |
if (relid == varno) |
| 4391 |
return jtnode; |
| 4392 |
} |
| 4393 |
else if (IsA(jtnode, FromExpr)) |
| 4394 |
{ |
| 4395 |
FromExpr *f = (FromExpr *) jtnode; |
| 4396 |
ListCell *l; |
| 4397 |
|
| 4398 |
foreach(l, f->fromlist) |
| 4399 |
{ |
| 4400 |
jtnode = find_jointree_node_for_rel(lfirst(l), relid); |
| 4401 |
if (jtnode) |
| 4402 |
return jtnode; |
| 4403 |
} |
| 4404 |
} |
| 4405 |
else if (IsA(jtnode, JoinExpr)) |
| 4406 |
{ |
| 4407 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 4408 |
|
| 4409 |
if (relid == j->rtindex) |
| 4410 |
return jtnode; |
| 4411 |
jtnode = find_jointree_node_for_rel(j->larg, relid); |
| 4412 |
if (jtnode) |
| 4413 |
return jtnode; |
| 4414 |
jtnode = find_jointree_node_for_rel(j->rarg, relid); |
| 4415 |
if (jtnode) |
| 4416 |
return jtnode; |
| 4417 |
} |
| 4418 |
else |
| 4419 |
elog(ERROR, "unrecognized node type: %d", |
| 4420 |
(int) nodeTag(jtnode)); |
| 4421 |
return NULL; |
| 4422 |
} |
| 4423 |
|
| 4424 |
/* |
| 4425 |
* get_nullingrels: collect info about which outer joins null which relations |
| 4426 |
* |
| 4427 |
* The result struct contains, for each leaf relation used in the query, |
| 4428 |
* the set of relids of outer joins that potentially null that rel. |
| 4429 |
*/ |
| 4430 |
static nullingrel_info * |
| 4431 |
get_nullingrels(Query *parse) |
| 4432 |
{ |
| 4433 |
nullingrel_info *result = palloc_object(nullingrel_info); |
| 4434 |
|
| 4435 |
result->rtlength = list_length(parse->rtable); |
| 4436 |
result->nullingrels = palloc0_array(Relids, result->rtlength + 1); |
| 4437 |
get_nullingrels_recurse((Node *) parse->jointree, NULL, result); |
| 4438 |
return result; |
| 4439 |
} |
| 4440 |
|
| 4441 |
/* |
| 4442 |
* Recursive guts of get_nullingrels(). |
| 4443 |
* |
| 4444 |
* Note: at any recursion level, the passed-down upper_nullingrels must be |
| 4445 |
* treated as a constant, but it can be stored directly into *info |
| 4446 |
* if we're at leaf level. Upper recursion levels do not free their mutated |
| 4447 |
* copies of the nullingrels, because those are probably referenced by |
| 4448 |
* at least one leaf rel. |
| 4449 |
*/ |
| 4450 |
static void |
| 4451 |
get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels, |
| 4452 |
nullingrel_info *info) |
| 4453 |
{ |
| 4454 |
if (jtnode == NULL) |
| 4455 |
return; |
| 4456 |
if (IsA(jtnode, RangeTblRef)) |
| 4457 |
{ |
| 4458 |
int varno = ((RangeTblRef *) jtnode)->rtindex; |
| 4459 |
|
| 4460 |
Assert(varno > 0 && varno <= info->rtlength); |
| 4461 |
info->nullingrels[varno] = upper_nullingrels; |
| 4462 |
} |
| 4463 |
else if (IsA(jtnode, FromExpr)) |
| 4464 |
{ |
| 4465 |
FromExpr *f = (FromExpr *) jtnode; |
| 4466 |
ListCell *l; |
| 4467 |
|
| 4468 |
foreach(l, f->fromlist) |
| 4469 |
{ |
| 4470 |
get_nullingrels_recurse(lfirst(l), upper_nullingrels, info); |
| 4471 |
} |
| 4472 |
} |
| 4473 |
else if (IsA(jtnode, JoinExpr)) |
| 4474 |
{ |
| 4475 |
JoinExpr *j = (JoinExpr *) jtnode; |
| 4476 |
Relids local_nullingrels; |
| 4477 |
|
| 4478 |
switch (j->jointype) |
| 4479 |
{ |
| 4480 |
case JOIN_INNER: |
| 4481 |
get_nullingrels_recurse(j->larg, upper_nullingrels, info); |
| 4482 |
get_nullingrels_recurse(j->rarg, upper_nullingrels, info); |
| 4483 |
break; |
| 4484 |
case JOIN_LEFT: |
| 4485 |
case JOIN_SEMI: |
| 4486 |
case JOIN_ANTI: |
| 4487 |
local_nullingrels = bms_add_member(bms_copy(upper_nullingrels), |
| 4488 |
j->rtindex); |
| 4489 |
get_nullingrels_recurse(j->larg, upper_nullingrels, info); |
| 4490 |
get_nullingrels_recurse(j->rarg, local_nullingrels, info); |
| 4491 |
break; |
| 4492 |
case JOIN_FULL: |
| 4493 |
local_nullingrels = bms_add_member(bms_copy(upper_nullingrels), |
| 4494 |
j->rtindex); |
| 4495 |
get_nullingrels_recurse(j->larg, local_nullingrels, info); |
| 4496 |
get_nullingrels_recurse(j->rarg, local_nullingrels, info); |
| 4497 |
break; |
| 4498 |
case JOIN_RIGHT: |
| 4499 |
local_nullingrels = bms_add_member(bms_copy(upper_nullingrels), |
| 4500 |
j->rtindex); |
| 4501 |
get_nullingrels_recurse(j->larg, local_nullingrels, info); |
| 4502 |
get_nullingrels_recurse(j->rarg, upper_nullingrels, info); |
| 4503 |
break; |
| 4504 |
default: |
| 4505 |
elog(ERROR, "unrecognized join type: %d", |
| 4506 |
(int) j->jointype); |
| 4507 |
break; |
| 4508 |
} |
| 4509 |
} |
| 4510 |
else |
| 4511 |
elog(ERROR, "unrecognized node type: %d", |
| 4512 |
(int) nodeTag(jtnode)); |
| 4513 |
} |