Debian Codegraph @

contrib/postgres_fdw/postgres_fdw.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * postgres_fdw.c
4 * Foreign-data wrapper for remote PostgreSQL servers
5 *
6 * Portions Copyright (c) 2012-2025, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * contrib/postgres_fdw/postgres_fdw.c
10 *
11 *-------------------------------------------------------------------------
12 */
13 #include "postgres.h"
14
15 #include <limits.h>
16
17 #include "access/htup_details.h"
18 #include "access/sysattr.h"
19 #include "access/table.h"
20 #include "catalog/pg_opfamily.h"
21 #include "commands/defrem.h"
22 #include "commands/explain_format.h"
23 #include "commands/explain_state.h"
24 #include "executor/execAsync.h"
25 #include "foreign/fdwapi.h"
26 #include "funcapi.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/appendinfo.h"
31 #include "optimizer/cost.h"
32 #include "optimizer/inherit.h"
33 #include "optimizer/optimizer.h"
34 #include "optimizer/pathnode.h"
35 #include "optimizer/paths.h"
36 #include "optimizer/planmain.h"
37 #include "optimizer/prep.h"
38 #include "optimizer/restrictinfo.h"
39 #include "optimizer/tlist.h"
40 #include "parser/parsetree.h"
41 #include "postgres_fdw.h"
42 #include "storage/latch.h"
43 #include "utils/builtins.h"
44 #include "utils/float.h"
45 #include "utils/guc.h"
46 #include "utils/lsyscache.h"
47 #include "utils/memutils.h"
48 #include "utils/rel.h"
49 #include "utils/sampling.h"
50 #include "utils/selfuncs.h"
51
52 PG_MODULE_MAGIC_EXT(
53 .name = "postgres_fdw",
54 .version = PG_VERSION
55 );
56
57 /* Default CPU cost to start up a foreign query. */
58 #define DEFAULT_FDW_STARTUP_COST 100.0
59
60 /* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
61 #define DEFAULT_FDW_TUPLE_COST 0.2
62
63 /* If no remote estimates, assume a sort costs 20% extra */
64 #define DEFAULT_FDW_SORT_MULTIPLIER 1.2
65
66 /*
67 * Indexes of FDW-private information stored in fdw_private lists.
68 *
69 * These items are indexed with the enum FdwScanPrivateIndex, so an item
70 * can be fetched with list_nth(). For example, to get the SELECT statement:
71 * sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
72 */
73 enum FdwScanPrivateIndex
74 {
75 /* SQL statement to execute remotely (as a String node) */
76 FdwScanPrivateSelectSql,
77 /* Integer list of attribute numbers retrieved by the SELECT */
78 FdwScanPrivateRetrievedAttrs,
79 /* Integer representing the desired fetch_size */
80 FdwScanPrivateFetchSize,
81
82 /*
83 * String describing join i.e. names of relations being joined and types
84 * of join, added when the scan is join
85 */
86 FdwScanPrivateRelations,
87 };
88
89 /*
90 * Similarly, this enum describes what's kept in the fdw_private list for
91 * a ModifyTable node referencing a postgres_fdw foreign table. We store:
92 *
93 * 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server
94 * 2) Integer list of target attribute numbers for INSERT/UPDATE
95 * (NIL for a DELETE)
96 * 3) Length till the end of VALUES clause for INSERT
97 * (-1 for a DELETE/UPDATE)
98 * 4) Boolean flag showing if the remote query has a RETURNING clause
99 * 5) Integer list of attribute numbers retrieved by RETURNING, if any
100 */
101 enum FdwModifyPrivateIndex
102 {
103 /* SQL statement to execute remotely (as a String node) */
104 FdwModifyPrivateUpdateSql,
105 /* Integer list of target attribute numbers for INSERT/UPDATE */
106 FdwModifyPrivateTargetAttnums,
107 /* Length till the end of VALUES clause (as an Integer node) */
108 FdwModifyPrivateLen,
109 /* has-returning flag (as a Boolean node) */
110 FdwModifyPrivateHasReturning,
111 /* Integer list of attribute numbers retrieved by RETURNING */
112 FdwModifyPrivateRetrievedAttrs,
113 };
114
115 /*
116 * Similarly, this enum describes what's kept in the fdw_private list for
117 * a ForeignScan node that modifies a foreign table directly. We store:
118 *
119 * 1) UPDATE/DELETE statement text to be sent to the remote server
120 * 2) Boolean flag showing if the remote query has a RETURNING clause
121 * 3) Integer list of attribute numbers retrieved by RETURNING, if any
122 * 4) Boolean flag showing if we set the command es_processed
123 */
124 enum FdwDirectModifyPrivateIndex
125 {
126 /* SQL statement to execute remotely (as a String node) */
127 FdwDirectModifyPrivateUpdateSql,
128 /* has-returning flag (as a Boolean node) */
129 FdwDirectModifyPrivateHasReturning,
130 /* Integer list of attribute numbers retrieved by RETURNING */
131 FdwDirectModifyPrivateRetrievedAttrs,
132 /* set-processed flag (as a Boolean node) */
133 FdwDirectModifyPrivateSetProcessed,
134 };
135
136 /*
137 * Execution state of a foreign scan using postgres_fdw.
138 */
139 typedef struct PgFdwScanState
140 {
141 Relation rel; /* relcache entry for the foreign table. NULL
142 * for a foreign join scan. */
143 TupleDesc tupdesc; /* tuple descriptor of scan */
144 AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
145
146 /* extracted fdw_private data */
147 char *query; /* text of SELECT command */
148 List *retrieved_attrs; /* list of retrieved attribute numbers */
149
150 /* for remote query execution */
151 PGconn *conn; /* connection for the scan */
152 PgFdwConnState *conn_state; /* extra per-connection state */
153 unsigned int cursor_number; /* quasi-unique ID for my cursor */
154 bool cursor_exists; /* have we created the cursor? */
155 int numParams; /* number of parameters passed to query */
156 FmgrInfo *param_flinfo; /* output conversion functions for them */
157 List *param_exprs; /* executable expressions for param values */
158 const char **param_values; /* textual values of query parameters */
159
160 /* for storing result tuples */
161 HeapTuple *tuples; /* array of currently-retrieved tuples */
162 int num_tuples; /* # of tuples in array */
163 int next_tuple; /* index of next one to return */
164
165 /* batch-level state, for optimizing rewinds and avoiding useless fetch */
166 int fetch_ct_2; /* Min(# of fetches done, 2) */
167 bool eof_reached; /* true if last fetch reached EOF */
168
169 /* for asynchronous execution */
170 bool async_capable; /* engage asynchronous-capable logic? */
171
172 /* working memory contexts */
173 MemoryContext batch_cxt; /* context holding current batch of tuples */
174 MemoryContext temp_cxt; /* context for per-tuple temporary data */
175
176 int fetch_size; /* number of tuples per fetch */
177 } PgFdwScanState;
178
179 /*
180 * Execution state of a foreign insert/update/delete operation.
181 */
182 typedef struct PgFdwModifyState
183 {
184 Relation rel; /* relcache entry for the foreign table */
185 AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
186
187 /* for remote query execution */
188 PGconn *conn; /* connection for the scan */
189 PgFdwConnState *conn_state; /* extra per-connection state */
190 char *p_name; /* name of prepared statement, if created */
191
192 /* extracted fdw_private data */
193 char *query; /* text of INSERT/UPDATE/DELETE command */
194 char *orig_query; /* original text of INSERT command */
195 List *target_attrs; /* list of target attribute numbers */
196 int values_end; /* length up to the end of VALUES */
197 int batch_size; /* value of FDW option "batch_size" */
198 bool has_returning; /* is there a RETURNING clause? */
199 List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
200
201 /* info about parameters for prepared statement */
202 AttrNumber ctidAttno; /* attnum of input resjunk ctid column */
203 int p_nums; /* number of parameters to transmit */
204 FmgrInfo *p_flinfo; /* output conversion functions for them */
205
206 /* batch operation stuff */
207 int num_slots; /* number of slots to insert */
208
209 /* working memory context */
210 MemoryContext temp_cxt; /* context for per-tuple temporary data */
211
212 /* for update row movement if subplan result rel */
213 struct PgFdwModifyState *aux_fmstate; /* foreign-insert state, if
214 * created */
215 } PgFdwModifyState;
216
217 /*
218 * Execution state of a foreign scan that modifies a foreign table directly.
219 */
220 typedef struct PgFdwDirectModifyState
221 {
222 Relation rel; /* relcache entry for the foreign table */
223 AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
224
225 /* extracted fdw_private data */
226 char *query; /* text of UPDATE/DELETE command */
227 bool has_returning; /* is there a RETURNING clause? */
228 List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
229 bool set_processed; /* do we set the command es_processed? */
230
231 /* for remote query execution */
232 PGconn *conn; /* connection for the update */
233 PgFdwConnState *conn_state; /* extra per-connection state */
234 int numParams; /* number of parameters passed to query */
235 FmgrInfo *param_flinfo; /* output conversion functions for them */
236 List *param_exprs; /* executable expressions for param values */
237 const char **param_values; /* textual values of query parameters */
238
239 /* for storing result tuples */
240 PGresult *result; /* result for query */
241 int num_tuples; /* # of result tuples */
242 int next_tuple; /* index of next one to return */
243 MemoryContextCallback result_cb; /* ensures result will get freed */
244 Relation resultRel; /* relcache entry for the target relation */
245 AttrNumber *attnoMap; /* array of attnums of input user columns */
246 AttrNumber ctidAttno; /* attnum of input ctid column */
247 AttrNumber oidAttno; /* attnum of input oid column */
248 bool hasSystemCols; /* are there system columns of resultRel? */
249
250 /* working memory context */
251 MemoryContext temp_cxt; /* context for per-tuple temporary data */
252 } PgFdwDirectModifyState;
253
254 /*
255 * Workspace for analyzing a foreign table.
256 */
257 typedef struct PgFdwAnalyzeState
258 {
259 Relation rel; /* relcache entry for the foreign table */
260 AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
261 List *retrieved_attrs; /* attr numbers retrieved by query */
262
263 /* collected sample rows */
264 HeapTuple *rows; /* array of size targrows */
265 int targrows; /* target # of sample rows */
266 int numrows; /* # of sample rows collected */
267
268 /* for random sampling */
269 double samplerows; /* # of rows fetched */
270 double rowstoskip; /* # of rows to skip before next sample */
271 ReservoirStateData rstate; /* state for reservoir sampling */
272
273 /* working memory contexts */
274 MemoryContext anl_cxt; /* context for per-analyze lifespan data */
275 MemoryContext temp_cxt; /* context for per-tuple temporary data */
276 } PgFdwAnalyzeState;
277
278 /*
279 * This enum describes what's kept in the fdw_private list for a ForeignPath.
280 * We store:
281 *
282 * 1) Boolean flag showing if the remote query has the final sort
283 * 2) Boolean flag showing if the remote query has the LIMIT clause
284 */
285 enum FdwPathPrivateIndex
286 {
287 /* has-final-sort flag (as a Boolean node) */
288 FdwPathPrivateHasFinalSort,
289 /* has-limit flag (as a Boolean node) */
290 FdwPathPrivateHasLimit,
291 };
292
293 /* Struct for extra information passed to estimate_path_cost_size() */
294 typedef struct
295 {
296 PathTarget *target;
297 bool has_final_sort;
298 bool has_limit;
299 double limit_tuples;
300 int64 count_est;
301 int64 offset_est;
302 } PgFdwPathExtraData;
303
304 /*
305 * Identify the attribute where data conversion fails.
306 */
307 typedef struct ConversionLocation
308 {
309 AttrNumber cur_attno; /* attribute number being processed, or 0 */
310 Relation rel; /* foreign table being processed, or NULL */
311 ForeignScanState *fsstate; /* plan node being processed, or NULL */
312 } ConversionLocation;
313
314 /* Callback argument for ec_member_matches_foreign */
315 typedef struct
316 {
317 Expr *current; /* current expr, or NULL if not yet found */
318 List *already_used; /* expressions already dealt with */
319 } ec_member_foreign_arg;
320
321 /*
322 * SQL functions
323 */
324 PG_FUNCTION_INFO_V1(postgres_fdw_handler);
325
326 /*
327 * FDW callback routines
328 */
329 static void postgresGetForeignRelSize(PlannerInfo *root,
330 RelOptInfo *baserel,
331 Oid foreigntableid);
332 static void postgresGetForeignPaths(PlannerInfo *root,
333 RelOptInfo *baserel,
334 Oid foreigntableid);
335 static ForeignScan *postgresGetForeignPlan(PlannerInfo *root,
336 RelOptInfo *foreignrel,
337 Oid foreigntableid,
338 ForeignPath *best_path,
339 List *tlist,
340 List *scan_clauses,
341 Plan *outer_plan);
342 static void postgresBeginForeignScan(ForeignScanState *node, int eflags);
343 static TupleTableSlot *postgresIterateForeignScan(ForeignScanState *node);
344 static void postgresReScanForeignScan(ForeignScanState *node);
345 static void postgresEndForeignScan(ForeignScanState *node);
346 static void postgresAddForeignUpdateTargets(PlannerInfo *root,
347 Index rtindex,
348 RangeTblEntry *target_rte,
349 Relation target_relation);
350 static List *postgresPlanForeignModify(PlannerInfo *root,
351 ModifyTable *plan,
352 Index resultRelation,
353 int subplan_index);
354 static void postgresBeginForeignModify(ModifyTableState *mtstate,
355 ResultRelInfo *resultRelInfo,
356 List *fdw_private,
357 int subplan_index,
358 int eflags);
359 static TupleTableSlot *postgresExecForeignInsert(EState *estate,
360 ResultRelInfo *resultRelInfo,
361 TupleTableSlot *slot,
362 TupleTableSlot *planSlot);
363 static TupleTableSlot **postgresExecForeignBatchInsert(EState *estate,
364 ResultRelInfo *resultRelInfo,
365 TupleTableSlot **slots,
366 TupleTableSlot **planSlots,
367 int *numSlots);
368 static int postgresGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo);
369 static TupleTableSlot *postgresExecForeignUpdate(EState *estate,
370 ResultRelInfo *resultRelInfo,
371 TupleTableSlot *slot,
372 TupleTableSlot *planSlot);
373 static TupleTableSlot *postgresExecForeignDelete(EState *estate,
374 ResultRelInfo *resultRelInfo,
375 TupleTableSlot *slot,
376 TupleTableSlot *planSlot);
377 static void postgresEndForeignModify(EState *estate,
378 ResultRelInfo *resultRelInfo);
379 static void postgresBeginForeignInsert(ModifyTableState *mtstate,
380 ResultRelInfo *resultRelInfo);
381 static void postgresEndForeignInsert(EState *estate,
382 ResultRelInfo *resultRelInfo);
383 static int postgresIsForeignRelUpdatable(Relation rel);
384 static bool postgresPlanDirectModify(PlannerInfo *root,
385 ModifyTable *plan,
386 Index resultRelation,
387 int subplan_index);
388 static void postgresBeginDirectModify(ForeignScanState *node, int eflags);
389 static TupleTableSlot *postgresIterateDirectModify(ForeignScanState *node);
390 static void postgresEndDirectModify(ForeignScanState *node);
391 static void postgresExplainForeignScan(ForeignScanState *node,
392 ExplainState *es);
393 static void postgresExplainForeignModify(ModifyTableState *mtstate,
394 ResultRelInfo *rinfo,
395 List *fdw_private,
396 int subplan_index,
397 ExplainState *es);
398 static void postgresExplainDirectModify(ForeignScanState *node,
399 ExplainState *es);
400 static void postgresExecForeignTruncate(List *rels,
401 DropBehavior behavior,
402 bool restart_seqs);
403 static bool postgresAnalyzeForeignTable(Relation relation,
404 AcquireSampleRowsFunc *func,
405 BlockNumber *totalpages);
406 static List *postgresImportForeignSchema(ImportForeignSchemaStmt *stmt,
407 Oid serverOid);
408 static void postgresGetForeignJoinPaths(PlannerInfo *root,
409 RelOptInfo *joinrel,
410 RelOptInfo *outerrel,
411 RelOptInfo *innerrel,
412 JoinType jointype,
413 JoinPathExtraData *extra);
414 static bool postgresRecheckForeignScan(ForeignScanState *node,
415 TupleTableSlot *slot);
416 static void postgresGetForeignUpperPaths(PlannerInfo *root,
417 UpperRelationKind stage,
418 RelOptInfo *input_rel,
419 RelOptInfo *output_rel,
420 void *extra);
421 static bool postgresIsForeignPathAsyncCapable(ForeignPath *path);
422 static void postgresForeignAsyncRequest(AsyncRequest *areq);
423 static void postgresForeignAsyncConfigureWait(AsyncRequest *areq);
424 static void postgresForeignAsyncNotify(AsyncRequest *areq);
425
426 /*
427 * Helper functions
428 */
429 static void estimate_path_cost_size(PlannerInfo *root,
430 RelOptInfo *foreignrel,
431 List *param_join_conds,
432 List *pathkeys,
433 PgFdwPathExtraData *fpextra,
434 double *p_rows, int *p_width,
435 int *p_disabled_nodes,
436 Cost *p_startup_cost, Cost *p_total_cost);
437 static void get_remote_estimate(const char *sql,
438 PGconn *conn,
439 double *rows,
440 int *width,
441 Cost *startup_cost,
442 Cost *total_cost);
443 static void adjust_foreign_grouping_path_cost(PlannerInfo *root,
444 List *pathkeys,
445 double retrieved_rows,
446 double width,
447 double limit_tuples,
448 int *p_disabled_nodes,
449 Cost *p_startup_cost,
450 Cost *p_run_cost);
451 static bool ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
452 EquivalenceClass *ec, EquivalenceMember *em,
453 void *arg);
454 static void create_cursor(ForeignScanState *node);
455 static void fetch_more_data(ForeignScanState *node);
456 static void close_cursor(PGconn *conn, unsigned int cursor_number,
457 PgFdwConnState *conn_state);
458 static PgFdwModifyState *create_foreign_modify(EState *estate,
459 RangeTblEntry *rte,
460 ResultRelInfo *resultRelInfo,
461 CmdType operation,
462 Plan *subplan,
463 char *query,
464 List *target_attrs,
465 int values_end,
466 bool has_returning,
467 List *retrieved_attrs);
468 static TupleTableSlot **execute_foreign_modify(EState *estate,
469 ResultRelInfo *resultRelInfo,
470 CmdType operation,
471 TupleTableSlot **slots,
472 TupleTableSlot **planSlots,
473 int *numSlots);
474 static void prepare_foreign_modify(PgFdwModifyState *fmstate);
475 static const char **convert_prep_stmt_params(PgFdwModifyState *fmstate,
476 ItemPointer tupleid,
477 TupleTableSlot **slots,
478 int numSlots);
479 static void store_returning_result(PgFdwModifyState *fmstate,
480 TupleTableSlot *slot, PGresult *res);
481 static void finish_foreign_modify(PgFdwModifyState *fmstate);
482 static void deallocate_query(PgFdwModifyState *fmstate);
483 static List *build_remote_returning(Index rtindex, Relation rel,
484 List *returningList);
485 static void rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist);
486 static void execute_dml_stmt(ForeignScanState *node);
487 static TupleTableSlot *get_returning_data(ForeignScanState *node);
488 static void init_returning_filter(PgFdwDirectModifyState *dmstate,
489 List *fdw_scan_tlist,
490 Index rtindex);
491 static TupleTableSlot *apply_returning_filter(PgFdwDirectModifyState *dmstate,
492 ResultRelInfo *resultRelInfo,
493 TupleTableSlot *slot,
494 EState *estate);
495 static void prepare_query_params(PlanState *node,
496 List *fdw_exprs,
497 int numParams,
498 FmgrInfo **param_flinfo,
499 List **param_exprs,
500 const char ***param_values);
501 static void process_query_params(ExprContext *econtext,
502 FmgrInfo *param_flinfo,
503 List *param_exprs,
504 const char **param_values);
505 static int postgresAcquireSampleRowsFunc(Relation relation, int elevel,
506 HeapTuple *rows, int targrows,
507 double *totalrows,
508 double *totaldeadrows);
509 static void analyze_row_processor(PGresult *res, int row,
510 PgFdwAnalyzeState *astate);
511 static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch);
512 static void fetch_more_data_begin(AsyncRequest *areq);
513 static void complete_pending_request(AsyncRequest *areq);
514 static HeapTuple make_tuple_from_result_row(PGresult *res,
515 int row,
516 Relation rel,
517 AttInMetadata *attinmeta,
518 List *retrieved_attrs,
519 ForeignScanState *fsstate,
520 MemoryContext temp_context);
521 static void conversion_error_callback(void *arg);
522 static bool foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
523 JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel,
524 JoinPathExtraData *extra);
525 static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel,
526 Node *havingQual);
527 static List *get_useful_pathkeys_for_relation(PlannerInfo *root,
528 RelOptInfo *rel);
529 static List *get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel);
530 static void add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
531 Path *epq_path, List *restrictlist);
532 static void add_foreign_grouping_paths(PlannerInfo *root,
533 RelOptInfo *input_rel,
534 RelOptInfo *grouped_rel,
535 GroupPathExtraData *extra);
536 static void add_foreign_ordered_paths(PlannerInfo *root,
537 RelOptInfo *input_rel,
538 RelOptInfo *ordered_rel);
539 static void add_foreign_final_paths(PlannerInfo *root,
540 RelOptInfo *input_rel,
541 RelOptInfo *final_rel,
542 FinalPathExtraData *extra);
543 static void apply_server_options(PgFdwRelationInfo *fpinfo);
544 static void apply_table_options(PgFdwRelationInfo *fpinfo);
545 static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
546 const PgFdwRelationInfo *fpinfo_o,
547 const PgFdwRelationInfo *fpinfo_i);
548 static int get_batch_size_option(Relation rel);
549
550
551 /*
552 * Foreign-data wrapper handler function: return a struct with pointers
553 * to my callback routines.
554 */
555 Datum
556 postgres_fdw_handler(PG_FUNCTION_ARGS)
557 {
558 FdwRoutine *routine = makeNode(FdwRoutine);
559
560 /* Functions for scanning foreign tables */
561 routine->GetForeignRelSize = postgresGetForeignRelSize;
562 routine->GetForeignPaths = postgresGetForeignPaths;
563 routine->GetForeignPlan = postgresGetForeignPlan;
564 routine->BeginForeignScan = postgresBeginForeignScan;
565 routine->IterateForeignScan = postgresIterateForeignScan;
566 routine->ReScanForeignScan = postgresReScanForeignScan;
567 routine->EndForeignScan = postgresEndForeignScan;
568
569 /* Functions for updating foreign tables */
570 routine->AddForeignUpdateTargets = postgresAddForeignUpdateTargets;
571 routine->PlanForeignModify = postgresPlanForeignModify;
572 routine->BeginForeignModify = postgresBeginForeignModify;
573 routine->ExecForeignInsert = postgresExecForeignInsert;
574 routine->ExecForeignBatchInsert = postgresExecForeignBatchInsert;
575 routine->GetForeignModifyBatchSize = postgresGetForeignModifyBatchSize;
576 routine->ExecForeignUpdate = postgresExecForeignUpdate;
577 routine->ExecForeignDelete = postgresExecForeignDelete;
578 routine->EndForeignModify = postgresEndForeignModify;
579 routine->BeginForeignInsert = postgresBeginForeignInsert;
580 routine->EndForeignInsert = postgresEndForeignInsert;
581 routine->IsForeignRelUpdatable = postgresIsForeignRelUpdatable;
582 routine->PlanDirectModify = postgresPlanDirectModify;
583 routine->BeginDirectModify = postgresBeginDirectModify;
584 routine->IterateDirectModify = postgresIterateDirectModify;
585 routine->EndDirectModify = postgresEndDirectModify;
586
587 /* Function for EvalPlanQual rechecks */
588 routine->RecheckForeignScan = postgresRecheckForeignScan;
589 /* Support functions for EXPLAIN */
590 routine->ExplainForeignScan = postgresExplainForeignScan;
591 routine->ExplainForeignModify = postgresExplainForeignModify;
592 routine->ExplainDirectModify = postgresExplainDirectModify;
593
594 /* Support function for TRUNCATE */
595 routine->ExecForeignTruncate = postgresExecForeignTruncate;
596
597 /* Support functions for ANALYZE */
598 routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
599
600 /* Support functions for IMPORT FOREIGN SCHEMA */
601 routine->ImportForeignSchema = postgresImportForeignSchema;
602
603 /* Support functions for join push-down */
604 routine->GetForeignJoinPaths = postgresGetForeignJoinPaths;
605
606 /* Support functions for upper relation push-down */
607 routine->GetForeignUpperPaths = postgresGetForeignUpperPaths;
608
609 /* Support functions for asynchronous execution */
610 routine->IsForeignPathAsyncCapable = postgresIsForeignPathAsyncCapable;
611 routine->ForeignAsyncRequest = postgresForeignAsyncRequest;
612 routine->ForeignAsyncConfigureWait = postgresForeignAsyncConfigureWait;
613 routine->ForeignAsyncNotify = postgresForeignAsyncNotify;
614
615 PG_RETURN_POINTER(routine);
616 }
617
618 /*
619 * postgresGetForeignRelSize
620 * Estimate # of rows and width of the result of the scan
621 *
622 * We should consider the effect of all baserestrictinfo clauses here, but
623 * not any join clauses.
624 */
625 static void
626 postgresGetForeignRelSize(PlannerInfo *root,
627 RelOptInfo *baserel,
628 Oid foreigntableid)
629 {
630 PgFdwRelationInfo *fpinfo;
631 ListCell *lc;
632
633 /*
634 * We use PgFdwRelationInfo to pass various information to subsequent
635 * functions.
636 */
637 fpinfo = (PgFdwRelationInfo *) palloc0(sizeof(PgFdwRelationInfo));
638 baserel->fdw_private = fpinfo;
639
640 /* Base foreign tables need to be pushed down always. */
641 fpinfo->pushdown_safe = true;
642
643 /* Look up foreign-table catalog info. */
644 fpinfo->table = GetForeignTable(foreigntableid);
645 fpinfo->server = GetForeignServer(fpinfo->table->serverid);
646
647 /*
648 * Extract user-settable option values. Note that per-table settings of
649 * use_remote_estimate, fetch_size and async_capable override per-server
650 * settings of them, respectively.
651 */
652 fpinfo->use_remote_estimate = false;
653 fpinfo->fdw_startup_cost = DEFAULT_FDW_STARTUP_COST;
654 fpinfo->fdw_tuple_cost = DEFAULT_FDW_TUPLE_COST;
655 fpinfo->shippable_extensions = NIL;
656 fpinfo->fetch_size = 100;
657 fpinfo->async_capable = false;
658
659 apply_server_options(fpinfo);
660 apply_table_options(fpinfo);
661
662 /*
663 * If the table or the server is configured to use remote estimates,
664 * identify which user to do remote access as during planning. This
665 * should match what ExecCheckPermissions() does. If we fail due to lack
666 * of permissions, the query would have failed at runtime anyway.
667 */
668 if (fpinfo->use_remote_estimate)
669 {
670 Oid userid;
671
672 userid = OidIsValid(baserel->userid) ? baserel->userid : GetUserId();
673 fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid);
674 }
675 else
676 fpinfo->user = NULL;
677
678 /*
679 * Identify which baserestrictinfo clauses can be sent to the remote
680 * server and which can't.
681 */
682 classifyConditions(root, baserel, baserel->baserestrictinfo,
683 &fpinfo->remote_conds, &fpinfo->local_conds);
684
685 /*
686 * Identify which attributes will need to be retrieved from the remote
687 * server. These include all attrs needed for joins or final output, plus
688 * all attrs used in the local_conds. (Note: if we end up using a
689 * parameterized scan, it's possible that some of the join clauses will be
690 * sent to the remote and thus we wouldn't really need to retrieve the
691 * columns used in them. Doesn't seem worth detecting that case though.)
692 */
693 fpinfo->attrs_used = NULL;
694 pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
695 &fpinfo->attrs_used);
696 foreach(lc, fpinfo->local_conds)
697 {
698 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
699
700 pull_varattnos((Node *) rinfo->clause, baserel->relid,
701 &fpinfo->attrs_used);
702 }
703
704 /*
705 * Compute the selectivity and cost of the local_conds, so we don't have
706 * to do it over again for each path. The best we can do for these
707 * conditions is to estimate selectivity on the basis of local statistics.
708 */
709 fpinfo->local_conds_sel = clauselist_selectivity(root,
710 fpinfo->local_conds,
711 baserel->relid,
712 JOIN_INNER,
713 NULL);
714
715 cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
716
717 /*
718 * Set # of retrieved rows and cached relation costs to some negative
719 * value, so that we can detect when they are set to some sensible values,
720 * during one (usually the first) of the calls to estimate_path_cost_size.
721 */
722 fpinfo->retrieved_rows = -1;
723 fpinfo->rel_startup_cost = -1;
724 fpinfo->rel_total_cost = -1;
725
726 /*
727 * If the table or the server is configured to use remote estimates,
728 * connect to the foreign server and execute EXPLAIN to estimate the
729 * number of rows selected by the restriction clauses, as well as the
730 * average row width. Otherwise, estimate using whatever statistics we
731 * have locally, in a way similar to ordinary tables.
732 */
733 if (fpinfo->use_remote_estimate)
734 {
735 /*
736 * Get cost/size estimates with help of remote server. Save the
737 * values in fpinfo so we don't need to do it again to generate the
738 * basic foreign path.
739 */
740 estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
741 &fpinfo->rows, &fpinfo->width,
742 &fpinfo->disabled_nodes,
743 &fpinfo->startup_cost, &fpinfo->total_cost);
744
745 /* Report estimated baserel size to planner. */
746 baserel->rows = fpinfo->rows;
747 baserel->reltarget->width = fpinfo->width;
748 }
749 else
750 {
751 /*
752 * If the foreign table has never been ANALYZEd, it will have
753 * reltuples < 0, meaning "unknown". We can't do much if we're not
754 * allowed to consult the remote server, but we can use a hack similar
755 * to plancat.c's treatment of empty relations: use a minimum size
756 * estimate of 10 pages, and divide by the column-datatype-based width
757 * estimate to get the corresponding number of tuples.
758 */
759 if (baserel->tuples < 0)
760 {
761 baserel->pages = 10;
762 baserel->tuples =
763 (10 * BLCKSZ) / (baserel->reltarget->width +
764 MAXALIGN(SizeofHeapTupleHeader));
765 }
766
767 /* Estimate baserel size as best we can with local statistics. */
768 set_baserel_size_estimates(root, baserel);
769
770 /* Fill in basically-bogus cost estimates for use later. */
771 estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
772 &fpinfo->rows, &fpinfo->width,
773 &fpinfo->disabled_nodes,
774 &fpinfo->startup_cost, &fpinfo->total_cost);
775 }
776
777 /*
778 * fpinfo->relation_name gets the numeric rangetable index of the foreign
779 * table RTE. (If this query gets EXPLAIN'd, we'll convert that to a
780 * human-readable string at that time.)
781 */
782 fpinfo->relation_name = psprintf("%u", baserel->relid);
783
784 /* No outer and inner relations. */
785 fpinfo->make_outerrel_subquery = false;
786 fpinfo->make_innerrel_subquery = false;
787 fpinfo->lower_subquery_rels = NULL;
788 fpinfo->hidden_subquery_rels = NULL;
789 /* Set the relation index. */
790 fpinfo->relation_index = baserel->relid;
791 }
792
793 /*
794 * get_useful_ecs_for_relation
795 * Determine which EquivalenceClasses might be involved in useful
796 * orderings of this relation.
797 *
798 * This function is in some respects a mirror image of the core function
799 * pathkeys_useful_for_merging: for a regular table, we know what indexes
800 * we have and want to test whether any of them are useful. For a foreign
801 * table, we don't know what indexes are present on the remote side but
802 * want to speculate about which ones we'd like to use if they existed.
803 *
804 * This function returns a list of potentially-useful equivalence classes,
805 * but it does not guarantee that an EquivalenceMember exists which contains
806 * Vars only from the given relation. For example, given ft1 JOIN t1 ON
807 * ft1.x + t1.x = 0, this function will say that the equivalence class
808 * containing ft1.x + t1.x is potentially useful. Supposing ft1 is remote and
809 * t1 is local (or on a different server), it will turn out that no useful
810 * ORDER BY clause can be generated. It's not our job to figure that out
811 * here; we're only interested in identifying relevant ECs.
812 */
813 static List *
814 get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel)
815 {
816 List *useful_eclass_list = NIL;
817 ListCell *lc;
818 Relids relids;
819
820 /*
821 * First, consider whether any active EC is potentially useful for a merge
822 * join against this relation.
823 */
824 if (rel->has_eclass_joins)
825 {
826 foreach(lc, root->eq_classes)
827 {
828 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc);
829
830 if (eclass_useful_for_merging(root, cur_ec, rel))
831 useful_eclass_list = lappend(useful_eclass_list, cur_ec);
832 }
833 }
834
835 /*
836 * Next, consider whether there are any non-EC derivable join clauses that
837 * are merge-joinable. If the joininfo list is empty, we can exit
838 * quickly.
839 */
840 if (rel->joininfo == NIL)
841 return useful_eclass_list;
842
843 /* If this is a child rel, we must use the topmost parent rel to search. */
844 if (IS_OTHER_REL(rel))
845 {
846 Assert(!bms_is_empty(rel->top_parent_relids));
847 relids = rel->top_parent_relids;
848 }
849 else
850 relids = rel->relids;
851
852 /* Check each join clause in turn. */
853 foreach(lc, rel->joininfo)
854 {
855 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
856
857 /* Consider only mergejoinable clauses */
858 if (restrictinfo->mergeopfamilies == NIL)
859 continue;
860
861 /* Make sure we've got canonical ECs. */
862 update_mergeclause_eclasses(root, restrictinfo);
863
864 /*
865 * restrictinfo->mergeopfamilies != NIL is sufficient to guarantee
866 * that left_ec and right_ec will be initialized, per comments in
867 * distribute_qual_to_rels.
868 *
869 * We want to identify which side of this merge-joinable clause
870 * contains columns from the relation produced by this RelOptInfo. We
871 * test for overlap, not containment, because there could be extra
872 * relations on either side. For example, suppose we've got something
873 * like ((A JOIN B ON A.x = B.x) JOIN C ON A.y = C.y) LEFT JOIN D ON
874 * A.y = D.y. The input rel might be the joinrel between A and B, and
875 * we'll consider the join clause A.y = D.y. relids contains a
876 * relation not involved in the join class (B) and the equivalence
877 * class for the left-hand side of the clause contains a relation not
878 * involved in the input rel (C). Despite the fact that we have only
879 * overlap and not containment in either direction, A.y is potentially
880 * useful as a sort column.
881 *
882 * Note that it's even possible that relids overlaps neither side of
883 * the join clause. For example, consider A LEFT JOIN B ON A.x = B.x
884 * AND A.x = 1. The clause A.x = 1 will appear in B's joininfo list,
885 * but overlaps neither side of B. In that case, we just skip this
886 * join clause, since it doesn't suggest a useful sort order for this
887 * relation.
888 */
889 if (bms_overlap(relids, restrictinfo->right_ec->ec_relids))
890 useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
891 restrictinfo->right_ec);
892 else if (bms_overlap(relids, restrictinfo->left_ec->ec_relids))
893 useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
894 restrictinfo->left_ec);
895 }
896
897 return useful_eclass_list;
898 }
899
900 /*
901 * get_useful_pathkeys_for_relation
902 * Determine which orderings of a relation might be useful.
903 *
904 * Getting data in sorted order can be useful either because the requested
905 * order matches the final output ordering for the overall query we're
906 * planning, or because it enables an efficient merge join. Here, we try
907 * to figure out which pathkeys to consider.
908 */
909 static List *
910 get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
911 {
912 List *useful_pathkeys_list = NIL;
913 List *useful_eclass_list;
914 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
915 EquivalenceClass *query_ec = NULL;
916 ListCell *lc;
917
918 /*
919 * Pushing the query_pathkeys to the remote server is always worth
920 * considering, because it might let us avoid a local sort.
921 */
922 fpinfo->qp_is_pushdown_safe = false;
923 if (root->query_pathkeys)
924 {
925 bool query_pathkeys_ok = true;
926
927 foreach(lc, root->query_pathkeys)
928 {
929 PathKey *pathkey = (PathKey *) lfirst(lc);
930
931 /*
932 * The planner and executor don't have any clever strategy for
933 * taking data sorted by a prefix of the query's pathkeys and
934 * getting it to be sorted by all of those pathkeys. We'll just
935 * end up resorting the entire data set. So, unless we can push
936 * down all of the query pathkeys, forget it.
937 */
938 if (!is_foreign_pathkey(root, rel, pathkey))
939 {
940 query_pathkeys_ok = false;
941 break;
942 }
943 }
944
945 if (query_pathkeys_ok)
946 {
947 useful_pathkeys_list = list_make1(list_copy(root->query_pathkeys));
948 fpinfo->qp_is_pushdown_safe = true;
949 }
950 }
951
952 /*
953 * Even if we're not using remote estimates, having the remote side do the
954 * sort generally won't be any worse than doing it locally, and it might
955 * be much better if the remote side can generate data in the right order
956 * without needing a sort at all. However, what we're going to do next is
957 * try to generate pathkeys that seem promising for possible merge joins,
958 * and that's more speculative. A wrong choice might hurt quite a bit, so
959 * bail out if we can't use remote estimates.
960 */
961 if (!fpinfo->use_remote_estimate)
962 return useful_pathkeys_list;
963
964 /* Get the list of interesting EquivalenceClasses. */
965 useful_eclass_list = get_useful_ecs_for_relation(root, rel);
966
967 /* Extract unique EC for query, if any, so we don't consider it again. */
968 if (list_length(root->query_pathkeys) == 1)
969 {
970 PathKey *query_pathkey = linitial(root->query_pathkeys);
971
972 query_ec = query_pathkey->pk_eclass;
973 }
974
975 /*
976 * As a heuristic, the only pathkeys we consider here are those of length
977 * one. It's surely possible to consider more, but since each one we
978 * choose to consider will generate a round-trip to the remote side, we
979 * need to be a bit cautious here. It would sure be nice to have a local
980 * cache of information about remote index definitions...
981 */
982 foreach(lc, useful_eclass_list)
983 {
984 EquivalenceClass *cur_ec = lfirst(lc);
985 PathKey *pathkey;
986
987 /* If redundant with what we did above, skip it. */
988 if (cur_ec == query_ec)
989 continue;
990
991 /* Can't push down the sort if the EC's opfamily is not shippable. */
992 if (!is_shippable(linitial_oid(cur_ec->ec_opfamilies),
993 OperatorFamilyRelationId, fpinfo))
994 continue;
995
996 /* If no pushable expression for this rel, skip it. */
997 if (find_em_for_rel(root, cur_ec, rel) == NULL)
998 continue;
999
1000 /* Looks like we can generate a pathkey, so let's do it. */
1001 pathkey = make_canonical_pathkey(root, cur_ec,
1002 linitial_oid(cur_ec->ec_opfamilies),
1003 COMPARE_LT,
1004 false);
1005 useful_pathkeys_list = lappend(useful_pathkeys_list,
1006 list_make1(pathkey));
1007 }
1008
1009 return useful_pathkeys_list;
1010 }
1011
1012 /*
1013 * postgresGetForeignPaths
1014 * Create possible scan paths for a scan on the foreign table
1015 */
1016 static void
1017 postgresGetForeignPaths(PlannerInfo *root,
1018 RelOptInfo *baserel,
1019 Oid foreigntableid)
1020 {
1021 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
1022 ForeignPath *path;
1023 List *ppi_list;
1024 ListCell *lc;
1025
1026 /*
1027 * Create simplest ForeignScan path node and add it to baserel. This path
1028 * corresponds to SeqScan path of regular tables (though depending on what
1029 * baserestrict conditions we were able to send to remote, there might
1030 * actually be an indexscan happening there). We already did all the work
1031 * to estimate cost and size of this path.
1032 *
1033 * Although this path uses no join clauses, it could still have required
1034 * parameterization due to LATERAL refs in its tlist.
1035 */
1036 path = create_foreignscan_path(root, baserel,
1037 NULL, /* default pathtarget */
1038 fpinfo->rows,
1039 fpinfo->disabled_nodes,
1040 fpinfo->startup_cost,
1041 fpinfo->total_cost,
1042 NIL, /* no pathkeys */
1043 baserel->lateral_relids,
1044 NULL, /* no extra plan */
1045 NIL, /* no fdw_restrictinfo list */
1046 NIL); /* no fdw_private list */
1047 add_path(baserel, (Path *) path);
1048
1049 /* Add paths with pathkeys */
1050 add_paths_with_pathkeys_for_rel(root, baserel, NULL, NIL);
1051
1052 /*
1053 * If we're not using remote estimates, stop here. We have no way to
1054 * estimate whether any join clauses would be worth sending across, so
1055 * don't bother building parameterized paths.
1056 */
1057 if (!fpinfo->use_remote_estimate)
1058 return;
1059
1060 /*
1061 * Thumb through all join clauses for the rel to identify which outer
1062 * relations could supply one or more safe-to-send-to-remote join clauses.
1063 * We'll build a parameterized path for each such outer relation.
1064 *
1065 * It's convenient to manage this by representing each candidate outer
1066 * relation by the ParamPathInfo node for it. We can then use the
1067 * ppi_clauses list in the ParamPathInfo node directly as a list of the
1068 * interesting join clauses for that rel. This takes care of the
1069 * possibility that there are multiple safe join clauses for such a rel,
1070 * and also ensures that we account for unsafe join clauses that we'll
1071 * still have to enforce locally (since the parameterized-path machinery
1072 * insists that we handle all movable clauses).
1073 */
1074 ppi_list = NIL;
1075 foreach(lc, baserel->joininfo)
1076 {
1077 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1078 Relids required_outer;
1079 ParamPathInfo *param_info;
1080
1081 /* Check if clause can be moved to this rel */
1082 if (!join_clause_is_movable_to(rinfo, baserel))
1083 continue;
1084
1085 /* See if it is safe to send to remote */
1086 if (!is_foreign_expr(root, baserel, rinfo->clause))
1087 continue;
1088
1089 /* Calculate required outer rels for the resulting path */
1090 required_outer = bms_union(rinfo->clause_relids,
1091 baserel->lateral_relids);
1092 /* We do not want the foreign rel itself listed in required_outer */
1093 required_outer = bms_del_member(required_outer, baserel->relid);
1094
1095 /*
1096 * required_outer probably can't be empty here, but if it were, we
1097 * couldn't make a parameterized path.
1098 */
1099 if (bms_is_empty(required_outer))
1100 continue;
1101
1102 /* Get the ParamPathInfo */
1103 param_info = get_baserel_parampathinfo(root, baserel,
1104 required_outer);
1105 Assert(param_info != NULL);
1106
1107 /*
1108 * Add it to list unless we already have it. Testing pointer equality
1109 * is OK since get_baserel_parampathinfo won't make duplicates.
1110 */
1111 ppi_list = list_append_unique_ptr(ppi_list, param_info);
1112 }
1113
1114 /*
1115 * The above scan examined only "generic" join clauses, not those that
1116 * were absorbed into EquivalenceClauses. See if we can make anything out
1117 * of EquivalenceClauses.
1118 */
1119 if (baserel->has_eclass_joins)
1120 {
1121 /*
1122 * We repeatedly scan the eclass list looking for column references
1123 * (or expressions) belonging to the foreign rel. Each time we find
1124 * one, we generate a list of equivalence joinclauses for it, and then
1125 * see if any are safe to send to the remote. Repeat till there are
1126 * no more candidate EC members.
1127 */
1128 ec_member_foreign_arg arg;
1129
1130 arg.already_used = NIL;
1131 for (;;)
1132 {
1133 List *clauses;
1134
1135 /* Make clauses, skipping any that join to lateral_referencers */
1136 arg.current = NULL;
1137 clauses = generate_implied_equalities_for_column(root,
1138 baserel,
1139 ec_member_matches_foreign,
1140 &arg,
1141 baserel->lateral_referencers);
1142
1143 /* Done if there are no more expressions in the foreign rel */
1144 if (arg.current == NULL)
1145 {
1146 Assert(clauses == NIL);
1147 break;
1148 }
1149
1150 /* Scan the extracted join clauses */
1151 foreach(lc, clauses)
1152 {
1153 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1154 Relids required_outer;
1155 ParamPathInfo *param_info;
1156
1157 /* Check if clause can be moved to this rel */
1158 if (!join_clause_is_movable_to(rinfo, baserel))
1159 continue;
1160
1161 /* See if it is safe to send to remote */
1162 if (!is_foreign_expr(root, baserel, rinfo->clause))
1163 continue;
1164
1165 /* Calculate required outer rels for the resulting path */
1166 required_outer = bms_union(rinfo->clause_relids,
1167 baserel->lateral_relids);
1168 required_outer = bms_del_member(required_outer, baserel->relid);
1169 if (bms_is_empty(required_outer))
1170 continue;
1171
1172 /* Get the ParamPathInfo */
1173 param_info = get_baserel_parampathinfo(root, baserel,
1174 required_outer);
1175 Assert(param_info != NULL);
1176
1177 /* Add it to list unless we already have it */
1178 ppi_list = list_append_unique_ptr(ppi_list, param_info);
1179 }
1180
1181 /* Try again, now ignoring the expression we found this time */
1182 arg.already_used = lappend(arg.already_used, arg.current);
1183 }
1184 }
1185
1186 /*
1187 * Now build a path for each useful outer relation.
1188 */
1189 foreach(lc, ppi_list)
1190 {
1191 ParamPathInfo *param_info = (ParamPathInfo *) lfirst(lc);
1192 double rows;
1193 int width;
1194 int disabled_nodes;
1195 Cost startup_cost;
1196 Cost total_cost;
1197
1198 /* Get a cost estimate from the remote */
1199 estimate_path_cost_size(root, baserel,
1200 param_info->ppi_clauses, NIL, NULL,
1201 &rows, &width, &disabled_nodes,
1202 &startup_cost, &total_cost);
1203
1204 /*
1205 * ppi_rows currently won't get looked at by anything, but still we
1206 * may as well ensure that it matches our idea of the rowcount.
1207 */
1208 param_info->ppi_rows = rows;
1209
1210 /* Make the path */
1211 path = create_foreignscan_path(root, baserel,
1212 NULL, /* default pathtarget */
1213 rows,
1214 disabled_nodes,
1215 startup_cost,
1216 total_cost,
1217 NIL, /* no pathkeys */
1218 param_info->ppi_req_outer,
1219 NULL,
1220 NIL, /* no fdw_restrictinfo list */
1221 NIL); /* no fdw_private list */
1222 add_path(baserel, (Path *) path);
1223 }
1224 }
1225
1226 /*
1227 * postgresGetForeignPlan
1228 * Create ForeignScan plan node which implements selected best path
1229 */
1230 static ForeignScan *
1231 postgresGetForeignPlan(PlannerInfo *root,
1232 RelOptInfo *foreignrel,
1233 Oid foreigntableid,
1234 ForeignPath *best_path,
1235 List *tlist,
1236 List *scan_clauses,
1237 Plan *outer_plan)
1238 {
1239 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1240 Index scan_relid;
1241 List *fdw_private;
1242 List *remote_exprs = NIL;
1243 List *local_exprs = NIL;
1244 List *params_list = NIL;
1245 List *fdw_scan_tlist = NIL;
1246 List *fdw_recheck_quals = NIL;
1247 List *retrieved_attrs;
1248 StringInfoData sql;
1249 bool has_final_sort = false;
1250 bool has_limit = false;
1251 ListCell *lc;
1252
1253 /*
1254 * Get FDW private data created by postgresGetForeignUpperPaths(), if any.
1255 */
1256 if (best_path->fdw_private)
1257 {
1258 has_final_sort = boolVal(list_nth(best_path->fdw_private,
1259 FdwPathPrivateHasFinalSort));
1260 has_limit = boolVal(list_nth(best_path->fdw_private,
1261 FdwPathPrivateHasLimit));
1262 }
1263
1264 if (IS_SIMPLE_REL(foreignrel))
1265 {
1266 /*
1267 * For base relations, set scan_relid as the relid of the relation.
1268 */
1269 scan_relid = foreignrel->relid;
1270
1271 /*
1272 * In a base-relation scan, we must apply the given scan_clauses.
1273 *
1274 * Separate the scan_clauses into those that can be executed remotely
1275 * and those that can't. baserestrictinfo clauses that were
1276 * previously determined to be safe or unsafe by classifyConditions
1277 * are found in fpinfo->remote_conds and fpinfo->local_conds. Anything
1278 * else in the scan_clauses list will be a join clause, which we have
1279 * to check for remote-safety.
1280 *
1281 * Note: the join clauses we see here should be the exact same ones
1282 * previously examined by postgresGetForeignPaths. Possibly it'd be
1283 * worth passing forward the classification work done then, rather
1284 * than repeating it here.
1285 *
1286 * This code must match "extract_actual_clauses(scan_clauses, false)"
1287 * except for the additional decision about remote versus local
1288 * execution.
1289 */
1290 foreach(lc, scan_clauses)
1291 {
1292 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1293
1294 /* Ignore any pseudoconstants, they're dealt with elsewhere */
1295 if (rinfo->pseudoconstant)
1296 continue;
1297
1298 if (list_member_ptr(fpinfo->remote_conds, rinfo))
1299 remote_exprs = lappend(remote_exprs, rinfo->clause);
1300 else if (list_member_ptr(fpinfo->local_conds, rinfo))
1301 local_exprs = lappend(local_exprs, rinfo->clause);
1302 else if (is_foreign_expr(root, foreignrel, rinfo->clause))
1303 remote_exprs = lappend(remote_exprs, rinfo->clause);
1304 else
1305 local_exprs = lappend(local_exprs, rinfo->clause);
1306 }
1307
1308 /*
1309 * For a base-relation scan, we have to support EPQ recheck, which
1310 * should recheck all the remote quals.
1311 */
1312 fdw_recheck_quals = remote_exprs;
1313 }
1314 else
1315 {
1316 /*
1317 * Join relation or upper relation - set scan_relid to 0.
1318 */
1319 scan_relid = 0;
1320
1321 /*
1322 * For a join rel, baserestrictinfo is NIL and we are not considering
1323 * parameterization right now, so there should be no scan_clauses for
1324 * a joinrel or an upper rel either.
1325 */
1326 Assert(!scan_clauses);
1327
1328 /*
1329 * Instead we get the conditions to apply from the fdw_private
1330 * structure.
1331 */
1332 remote_exprs = extract_actual_clauses(fpinfo->remote_conds, false);
1333 local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
1334
1335 /*
1336 * We leave fdw_recheck_quals empty in this case, since we never need
1337 * to apply EPQ recheck clauses. In the case of a joinrel, EPQ
1338 * recheck is handled elsewhere --- see postgresGetForeignJoinPaths().
1339 * If we're planning an upperrel (ie, remote grouping or aggregation)
1340 * then there's no EPQ to do because SELECT FOR UPDATE wouldn't be
1341 * allowed, and indeed we *can't* put the remote clauses into
1342 * fdw_recheck_quals because the unaggregated Vars won't be available
1343 * locally.
1344 */
1345
1346 /* Build the list of columns to be fetched from the foreign server. */
1347 fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
1348
1349 /*
1350 * Ensure that the outer plan produces a tuple whose descriptor
1351 * matches our scan tuple slot. Also, remove the local conditions
1352 * from outer plan's quals, lest they be evaluated twice, once by the
1353 * local plan and once by the scan.
1354 */
1355 if (outer_plan)
1356 {
1357 /*
1358 * Right now, we only consider grouping and aggregation beyond
1359 * joins. Queries involving aggregates or grouping do not require
1360 * EPQ mechanism, hence should not have an outer plan here.
1361 */
1362 Assert(!IS_UPPER_REL(foreignrel));
1363
1364 /*
1365 * First, update the plan's qual list if possible. In some cases
1366 * the quals might be enforced below the topmost plan level, in
1367 * which case we'll fail to remove them; it's not worth working
1368 * harder than this.
1369 */
1370 foreach(lc, local_exprs)
1371 {
1372 Node *qual = lfirst(lc);
1373
1374 outer_plan->qual = list_delete(outer_plan->qual, qual);
1375
1376 /*
1377 * For an inner join the local conditions of foreign scan plan
1378 * can be part of the joinquals as well. (They might also be
1379 * in the mergequals or hashquals, but we can't touch those
1380 * without breaking the plan.)
1381 */
1382 if (IsA(outer_plan, NestLoop) ||
1383 IsA(outer_plan, MergeJoin) ||
1384 IsA(outer_plan, HashJoin))
1385 {
1386 Join *join_plan = (Join *) outer_plan;
1387
1388 if (join_plan->jointype == JOIN_INNER)
1389 join_plan->joinqual = list_delete(join_plan->joinqual,
1390 qual);
1391 }
1392 }
1393
1394 /*
1395 * Now fix the subplan's tlist --- this might result in inserting
1396 * a Result node atop the plan tree.
1397 */
1398 outer_plan = change_plan_targetlist(outer_plan, fdw_scan_tlist,
1399 best_path->path.parallel_safe);
1400 }
1401 }
1402
1403 /*
1404 * Build the query string to be sent for execution, and identify
1405 * expressions to be sent as parameters.
1406 */
1407 initStringInfo(&sql);
1408 deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
1409 remote_exprs, best_path->path.pathkeys,
1410 has_final_sort, has_limit, false,
1411 &retrieved_attrs, &params_list);
1412
1413 /* Remember remote_exprs for possible use by postgresPlanDirectModify */
1414 fpinfo->final_remote_exprs = remote_exprs;
1415
1416 /*
1417 * Build the fdw_private list that will be available to the executor.
1418 * Items in the list must match order in enum FdwScanPrivateIndex.
1419 */
1420 fdw_private = list_make3(makeString(sql.data),
1421 retrieved_attrs,
1422 makeInteger(fpinfo->fetch_size));
1423 if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
1424 fdw_private = lappend(fdw_private,
1425 makeString(fpinfo->relation_name));
1426
1427 /*
1428 * Create the ForeignScan node for the given relation.
1429 *
1430 * Note that the remote parameter expressions are stored in the fdw_exprs
1431 * field of the finished plan node; we can't keep them in private state
1432 * because then they wouldn't be subject to later planner processing.
1433 */
1434 return make_foreignscan(tlist,
1435 local_exprs,
1436 scan_relid,
1437 params_list,
1438 fdw_private,
1439 fdw_scan_tlist,
1440 fdw_recheck_quals,
1441 outer_plan);
1442 }
1443
1444 /*
1445 * Construct a tuple descriptor for the scan tuples handled by a foreign join.
1446 */
1447 static TupleDesc
1448 get_tupdesc_for_join_scan_tuples(ForeignScanState *node)
1449 {
1450 ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1451 EState *estate = node->ss.ps.state;
1452 TupleDesc tupdesc;
1453
1454 /*
1455 * The core code has already set up a scan tuple slot based on
1456 * fsplan->fdw_scan_tlist, and this slot's tupdesc is mostly good enough,
1457 * but there's one case where it isn't. If we have any whole-row row
1458 * identifier Vars, they may have vartype RECORD, and we need to replace
1459 * that with the associated table's actual composite type. This ensures
1460 * that when we read those ROW() expression values from the remote server,
1461 * we can convert them to a composite type the local server knows.
1462 */
1463 tupdesc = CreateTupleDescCopy(node->ss.ss_ScanTupleSlot->tts_tupleDescriptor);
1464 for (int i = 0; i < tupdesc->natts; i++)
1465 {
1466 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1467 Var *var;
1468 RangeTblEntry *rte;
1469 Oid reltype;
1470
1471 /* Nothing to do if it's not a generic RECORD attribute */
1472 if (att->atttypid != RECORDOID || att->atttypmod >= 0)
1473 continue;
1474
1475 /*
1476 * If we can't identify the referenced table, do nothing. This'll
1477 * likely lead to failure later, but perhaps we can muddle through.
1478 */
1479 var = (Var *) list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
1480 i)->expr;
1481 if (!IsA(var, Var) || var->varattno != 0)
1482 continue;
1483 rte = list_nth(estate->es_range_table, var->varno - 1);
1484 if (rte->rtekind != RTE_RELATION)
1485 continue;
1486 reltype = get_rel_type_id(rte->relid);
1487 if (!OidIsValid(reltype))
1488 continue;
1489 att->atttypid = reltype;
1490 /* shouldn't need to change anything else */
1491 }
1492 return tupdesc;
1493 }
1494
1495 /*
1496 * postgresBeginForeignScan
1497 * Initiate an executor scan of a foreign PostgreSQL table.
1498 */
1499 static void
1500 postgresBeginForeignScan(ForeignScanState *node, int eflags)
1501 {
1502 ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1503 EState *estate = node->ss.ps.state;
1504 PgFdwScanState *fsstate;
1505 RangeTblEntry *rte;
1506 Oid userid;
1507 ForeignTable *table;
1508 UserMapping *user;
1509 int rtindex;
1510 int numParams;
1511
1512 /*
1513 * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
1514 */
1515 if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
1516 return;
1517
1518 /*
1519 * We'll save private state in node->fdw_state.
1520 */
1521 fsstate = (PgFdwScanState *) palloc0(sizeof(PgFdwScanState));
1522 node->fdw_state = fsstate;
1523
1524 /*
1525 * Identify which user to do the remote access as. This should match what
1526 * ExecCheckPermissions() does.
1527 */
1528 userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
1529 if (fsplan->scan.scanrelid > 0)
1530 rtindex = fsplan->scan.scanrelid;
1531 else
1532 rtindex = bms_next_member(fsplan->fs_base_relids, -1);
1533 rte = exec_rt_fetch(rtindex, estate);
1534
1535 /* Get info about foreign table. */
1536 table = GetForeignTable(rte->relid);
1537 user = GetUserMapping(userid, table->serverid);
1538
1539 /*
1540 * Get connection to the foreign server. Connection manager will
1541 * establish new connection if necessary.
1542 */
1543 fsstate->conn = GetConnection(user, false, &fsstate->conn_state);
1544
1545 /* Assign a unique ID for my cursor */
1546 fsstate->cursor_number = GetCursorNumber(fsstate->conn);
1547 fsstate->cursor_exists = false;
1548
1549 /* Get private info created by planner functions. */
1550 fsstate->query = strVal(list_nth(fsplan->fdw_private,
1551 FdwScanPrivateSelectSql));
1552 fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
1553 FdwScanPrivateRetrievedAttrs);
1554 fsstate->fetch_size = intVal(list_nth(fsplan->fdw_private,
1555 FdwScanPrivateFetchSize));
1556
1557 /* Create contexts for batches of tuples and per-tuple temp workspace. */
1558 fsstate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt,
1559 "postgres_fdw tuple data",
1560 ALLOCSET_DEFAULT_SIZES);
1561 fsstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
1562 "postgres_fdw temporary data",
1563 ALLOCSET_SMALL_SIZES);
1564
1565 /*
1566 * Get info we'll need for converting data fetched from the foreign server
1567 * into local representation and error reporting during that process.
1568 */
1569 if (fsplan->scan.scanrelid > 0)
1570 {
1571 fsstate->rel = node->ss.ss_currentRelation;
1572 fsstate->tupdesc = RelationGetDescr(fsstate->rel);
1573 }
1574 else
1575 {
1576 fsstate->rel = NULL;
1577 fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node);
1578 }
1579
1580 fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc);
1581
1582 /*
1583 * Prepare for processing of parameters used in remote query, if any.
1584 */
1585 numParams = list_length(fsplan->fdw_exprs);
1586 fsstate->numParams = numParams;
1587 if (numParams > 0)
1588 prepare_query_params((PlanState *) node,
1589 fsplan->fdw_exprs,
1590 numParams,
1591 &fsstate->param_flinfo,
1592 &fsstate->param_exprs,
1593 &fsstate->param_values);
1594
1595 /* Set the async-capable flag */
1596 fsstate->async_capable = node->ss.ps.async_capable;
1597 }
1598
1599 /*
1600 * postgresIterateForeignScan
1601 * Retrieve next row from the result set, or clear tuple slot to indicate
1602 * EOF.
1603 */
1604 static TupleTableSlot *
1605 postgresIterateForeignScan(ForeignScanState *node)
1606 {
1607 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1608 TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
1609
1610 /*
1611 * In sync mode, if this is the first call after Begin or ReScan, we need
1612 * to create the cursor on the remote side. In async mode, we would have
1613 * already created the cursor before we get here, even if this is the
1614 * first call after Begin or ReScan.
1615 */
1616 if (!fsstate->cursor_exists)
1617 create_cursor(node);
1618
1619 /*
1620 * Get some more tuples, if we've run out.
1621 */
1622 if (fsstate->next_tuple >= fsstate->num_tuples)
1623 {
1624 /* In async mode, just clear tuple slot. */
1625 if (fsstate->async_capable)
1626 return ExecClearTuple(slot);
1627 /* No point in another fetch if we already detected EOF, though. */
1628 if (!fsstate->eof_reached)
1629 fetch_more_data(node);
1630 /* If we didn't get any tuples, must be end of data. */
1631 if (fsstate->next_tuple >= fsstate->num_tuples)
1632 return ExecClearTuple(slot);
1633 }
1634
1635 /*
1636 * Return the next tuple.
1637 */
1638 ExecStoreHeapTuple(fsstate->tuples[fsstate->next_tuple++],
1639 slot,
1640 false);
1641
1642 return slot;
1643 }
1644
1645 /*
1646 * postgresReScanForeignScan
1647 * Restart the scan.
1648 */
1649 static void
1650 postgresReScanForeignScan(ForeignScanState *node)
1651 {
1652 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1653 char sql[64];
1654 PGresult *res;
1655
1656 /* If we haven't created the cursor yet, nothing to do. */
1657 if (!fsstate->cursor_exists)
1658 return;
1659
1660 /*
1661 * If the node is async-capable, any asynchronous fetch made for it should
1662 * have been processed before we get here (see ExecAppendAsyncReset()).
1663 */
1664 Assert(!fsstate->async_capable || !fsstate->conn_state->pendingAreq ||
1665 fsstate->conn_state->pendingAreq->requestee != (PlanState *) node);
1666
1667 /*
1668 * If any internal parameters affecting this node have changed, we'd
1669 * better destroy and recreate the cursor. Otherwise, if the remote
1670 * server is v14 or older, rewinding it should be good enough; if not,
1671 * rewind is only allowed for scrollable cursors, but we don't have a way
1672 * to check the scrollability of it, so destroy and recreate it in any
1673 * case. If we've only fetched zero or one batch, we needn't even rewind
1674 * the cursor, just rescan what we have.
1675 */
1676 if (node->ss.ps.chgParam != NULL)
1677 {
1678 fsstate->cursor_exists = false;
1679 snprintf(sql, sizeof(sql), "CLOSE c%u",
1680 fsstate->cursor_number);
1681 }
1682 else if (fsstate->fetch_ct_2 > 1)
1683 {
1684 if (PQserverVersion(fsstate->conn) < 150000)
1685 snprintf(sql, sizeof(sql), "MOVE BACKWARD ALL IN c%u",
1686 fsstate->cursor_number);
1687 else
1688 {
1689 fsstate->cursor_exists = false;
1690 snprintf(sql, sizeof(sql), "CLOSE c%u",
1691 fsstate->cursor_number);
1692 }
1693 }
1694 else
1695 {
1696 /* Easy: just rescan what we already have in memory, if anything */
1697 fsstate->next_tuple = 0;
1698 return;
1699 }
1700
1701 /*
1702 * We don't use a PG_TRY block here, so be careful not to throw error
1703 * without releasing the PGresult.
1704 */
1705 res = pgfdw_exec_query(fsstate->conn, sql, fsstate->conn_state);
1706 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1707 pgfdw_report_error(ERROR, res, fsstate->conn, true, sql);
1708 PQclear(res);
1709
1710 /* Now force a fresh FETCH. */
1711 fsstate->tuples = NULL;
1712 fsstate->num_tuples = 0;
1713 fsstate->next_tuple = 0;
1714 fsstate->fetch_ct_2 = 0;
1715 fsstate->eof_reached = false;
1716 }
1717
1718 /*
1719 * postgresEndForeignScan
1720 * Finish scanning foreign table and dispose objects used for this scan
1721 */
1722 static void
1723 postgresEndForeignScan(ForeignScanState *node)
1724 {
1725 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1726
1727 /* if fsstate is NULL, we are in EXPLAIN; nothing to do */
1728 if (fsstate == NULL)
1729 return;
1730
1731 /* Close the cursor if open, to prevent accumulation of cursors */
1732 if (fsstate->cursor_exists)
1733 close_cursor(fsstate->conn, fsstate->cursor_number,
1734 fsstate->conn_state);
1735
1736 /* Release remote connection */
1737 ReleaseConnection(fsstate->conn);
1738 fsstate->conn = NULL;
1739
1740 /* MemoryContexts will be deleted automatically. */
1741 }
1742
1743 /*
1744 * postgresAddForeignUpdateTargets
1745 * Add resjunk column(s) needed for update/delete on a foreign table
1746 */
1747 static void
1748 postgresAddForeignUpdateTargets(PlannerInfo *root,
1749 Index rtindex,
1750 RangeTblEntry *target_rte,
1751 Relation target_relation)
1752 {
1753 Var *var;
1754
1755 /*
1756 * In postgres_fdw, what we need is the ctid, same as for a regular table.
1757 */
1758
1759 /* Make a Var representing the desired value */
1760 var = makeVar(rtindex,
1761 SelfItemPointerAttributeNumber,
1762 TIDOID,
1763 -1,
1764 InvalidOid,
1765 0);
1766
1767 /* Register it as a row-identity column needed by this target rel */
1768 add_row_identity_var(root, var, rtindex, "ctid");
1769 }
1770
1771 /*
1772 * postgresPlanForeignModify
1773 * Plan an insert/update/delete operation on a foreign table
1774 */
1775 static List *
1776 postgresPlanForeignModify(PlannerInfo *root,
1777 ModifyTable *plan,
1778 Index resultRelation,
1779 int subplan_index)
1780 {
1781 CmdType operation = plan->operation;
1782 RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
1783 Relation rel;
1784 StringInfoData sql;
1785 List *targetAttrs = NIL;
1786 List *withCheckOptionList = NIL;
1787 List *returningList = NIL;
1788 List *retrieved_attrs = NIL;
1789 bool doNothing = false;
1790 int values_end_len = -1;
1791
1792 initStringInfo(&sql);
1793
1794 /*
1795 * Core code already has some lock on each rel being planned, so we can
1796 * use NoLock here.
1797 */
1798 rel = table_open(rte->relid, NoLock);
1799
1800 /*
1801 * In an INSERT, we transmit all columns that are defined in the foreign
1802 * table. In an UPDATE, if there are BEFORE ROW UPDATE triggers on the
1803 * foreign table, we transmit all columns like INSERT; else we transmit
1804 * only columns that were explicitly targets of the UPDATE, so as to avoid
1805 * unnecessary data transmission. (We can't do that for INSERT since we
1806 * would miss sending default values for columns not listed in the source
1807 * statement, and for UPDATE if there are BEFORE ROW UPDATE triggers since
1808 * those triggers might change values for non-target columns, in which
1809 * case we would miss sending changed values for those columns.)
1810 */
1811 if (operation == CMD_INSERT ||
1812 (operation == CMD_UPDATE &&
1813 rel->trigdesc &&
1814 rel->trigdesc->trig_update_before_row))
1815 {
1816 TupleDesc tupdesc = RelationGetDescr(rel);
1817 int attnum;
1818
1819 for (attnum = 1; attnum <= tupdesc->natts; attnum++)
1820 {
1821 CompactAttribute *attr = TupleDescCompactAttr(tupdesc, attnum - 1);
1822
1823 if (!attr->attisdropped)
1824 targetAttrs = lappend_int(targetAttrs, attnum);
1825 }
1826 }
1827 else if (operation == CMD_UPDATE)
1828 {
1829 int col;
1830 RelOptInfo *rel = find_base_rel(root, resultRelation);
1831 Bitmapset *allUpdatedCols = get_rel_all_updated_cols(root, rel);
1832
1833 col = -1;
1834 while ((col = bms_next_member(allUpdatedCols, col)) >= 0)
1835 {
1836 /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
1837 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
1838
1839 if (attno <= InvalidAttrNumber) /* shouldn't happen */
1840 elog(ERROR, "system-column update is not supported");
1841 targetAttrs = lappend_int(targetAttrs, attno);
1842 }
1843 }
1844
1845 /*
1846 * Extract the relevant WITH CHECK OPTION list if any.
1847 */
1848 if (plan->withCheckOptionLists)
1849 withCheckOptionList = (List *) list_nth(plan->withCheckOptionLists,
1850 subplan_index);
1851
1852 /*
1853 * Extract the relevant RETURNING list if any.
1854 */
1855 if (plan->returningLists)
1856 returningList = (List *) list_nth(plan->returningLists, subplan_index);
1857
1858 /*
1859 * ON CONFLICT DO UPDATE and DO NOTHING case with inference specification
1860 * should have already been rejected in the optimizer, as presently there
1861 * is no way to recognize an arbiter index on a foreign table. Only DO
1862 * NOTHING is supported without an inference specification.
1863 */
1864 if (plan->onConflictAction == ONCONFLICT_NOTHING)
1865 doNothing = true;
1866 else if (plan->onConflictAction != ONCONFLICT_NONE)
1867 elog(ERROR, "unexpected ON CONFLICT specification: %d",
1868 (int) plan->onConflictAction);
1869
1870 /*
1871 * Construct the SQL command string.
1872 */
1873 switch (operation)
1874 {
1875 case CMD_INSERT:
1876 deparseInsertSql(&sql, rte, resultRelation, rel,
1877 targetAttrs, doNothing,
1878 withCheckOptionList, returningList,
1879 &retrieved_attrs, &values_end_len);
1880 break;
1881 case CMD_UPDATE:
1882 deparseUpdateSql(&sql, rte, resultRelation, rel,
1883 targetAttrs,
1884 withCheckOptionList, returningList,
1885 &retrieved_attrs);
1886 break;
1887 case CMD_DELETE:
1888 deparseDeleteSql(&sql, rte, resultRelation, rel,
1889 returningList,
1890 &retrieved_attrs);
1891 break;
1892 default:
1893 elog(ERROR, "unexpected operation: %d", (int) operation);
1894 break;
1895 }
1896
1897 table_close(rel, NoLock);
1898
1899 /*
1900 * Build the fdw_private list that will be available to the executor.
1901 * Items in the list must match enum FdwModifyPrivateIndex, above.
1902 */
1903 return list_make5(makeString(sql.data),
1904 targetAttrs,
1905 makeInteger(values_end_len),
1906 makeBoolean((retrieved_attrs != NIL)),
1907 retrieved_attrs);
1908 }
1909
1910 /*
1911 * postgresBeginForeignModify
1912 * Begin an insert/update/delete operation on a foreign table
1913 */
1914 static void
1915 postgresBeginForeignModify(ModifyTableState *mtstate,
1916 ResultRelInfo *resultRelInfo,
1917 List *fdw_private,
1918 int subplan_index,
1919 int eflags)
1920 {
1921 PgFdwModifyState *fmstate;
1922 char *query;
1923 List *target_attrs;
1924 bool has_returning;
1925 int values_end_len;
1926 List *retrieved_attrs;
1927 RangeTblEntry *rte;
1928
1929 /*
1930 * Do nothing in EXPLAIN (no ANALYZE) case. resultRelInfo->ri_FdwState
1931 * stays NULL.
1932 */
1933 if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
1934 return;
1935
1936 /* Deconstruct fdw_private data. */
1937 query = strVal(list_nth(fdw_private,
1938 FdwModifyPrivateUpdateSql));
1939 target_attrs = (List *) list_nth(fdw_private,
1940 FdwModifyPrivateTargetAttnums);
1941 values_end_len = intVal(list_nth(fdw_private,
1942 FdwModifyPrivateLen));
1943 has_returning = boolVal(list_nth(fdw_private,
1944 FdwModifyPrivateHasReturning));
1945 retrieved_attrs = (List *) list_nth(fdw_private,
1946 FdwModifyPrivateRetrievedAttrs);
1947
1948 /* Find RTE. */
1949 rte = exec_rt_fetch(resultRelInfo->ri_RangeTableIndex,
1950 mtstate->ps.state);
1951
1952 /* Construct an execution state. */
1953 fmstate = create_foreign_modify(mtstate->ps.state,
1954 rte,
1955 resultRelInfo,
1956 mtstate->operation,
1957 outerPlanState(mtstate)->plan,
1958 query,
1959 target_attrs,
1960 values_end_len,
1961 has_returning,
1962 retrieved_attrs);
1963
1964 resultRelInfo->ri_FdwState = fmstate;
1965 }
1966
1967 /*
1968 * postgresExecForeignInsert
1969 * Insert one row into a foreign table
1970 */
1971 static TupleTableSlot *
1972 postgresExecForeignInsert(EState *estate,
1973 ResultRelInfo *resultRelInfo,
1974 TupleTableSlot *slot,
1975 TupleTableSlot *planSlot)
1976 {
1977 PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
1978 TupleTableSlot **rslot;
1979 int numSlots = 1;
1980
1981 /*
1982 * If the fmstate has aux_fmstate set, use the aux_fmstate (see
1983 * postgresBeginForeignInsert())
1984 */
1985 if (fmstate->aux_fmstate)
1986 resultRelInfo->ri_FdwState = fmstate->aux_fmstate;
1987 rslot = execute_foreign_modify(estate, resultRelInfo, CMD_INSERT,
1988 &slot, &planSlot, &numSlots);
1989 /* Revert that change */
1990 if (fmstate->aux_fmstate)
1991 resultRelInfo->ri_FdwState = fmstate;
1992
1993 return rslot ? *rslot : NULL;
1994 }
1995
1996 /*
1997 * postgresExecForeignBatchInsert
1998 * Insert multiple rows into a foreign table
1999 */
2000 static TupleTableSlot **
2001 postgresExecForeignBatchInsert(EState *estate,
2002 ResultRelInfo *resultRelInfo,
2003 TupleTableSlot **slots,
2004 TupleTableSlot **planSlots,
2005 int *numSlots)
2006 {
2007 PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2008 TupleTableSlot **rslot;
2009
2010 /*
2011 * If the fmstate has aux_fmstate set, use the aux_fmstate (see
2012 * postgresBeginForeignInsert())
2013 */
2014 if (fmstate->aux_fmstate)
2015 resultRelInfo->ri_FdwState = fmstate->aux_fmstate;
2016 rslot = execute_foreign_modify(estate, resultRelInfo, CMD_INSERT,
2017 slots, planSlots, numSlots);
2018 /* Revert that change */
2019 if (fmstate->aux_fmstate)
2020 resultRelInfo->ri_FdwState = fmstate;
2021
2022 return rslot;
2023 }
2024
2025 /*
2026 * postgresGetForeignModifyBatchSize
2027 * Determine the maximum number of tuples that can be inserted in bulk
2028 *
2029 * Returns the batch size specified for server or table. When batching is not
2030 * allowed (e.g. for tables with BEFORE/AFTER ROW triggers or with RETURNING
2031 * clause), returns 1.
2032 */
2033 static int
2034 postgresGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo)
2035 {
2036 int batch_size;
2037 PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2038
2039 /* should be called only once */
2040 Assert(resultRelInfo->ri_BatchSize == 0);
2041
2042 /*
2043 * Should never get called when the insert is being performed on a table
2044 * that is also among the target relations of an UPDATE operation, because
2045 * postgresBeginForeignInsert() currently rejects such insert attempts.
2046 */
2047 Assert(fmstate == NULL || fmstate->aux_fmstate == NULL);
2048
2049 /*
2050 * In EXPLAIN without ANALYZE, ri_FdwState is NULL, so we have to lookup
2051 * the option directly in server/table options. Otherwise just use the
2052 * value we determined earlier.
2053 */
2054 if (fmstate)
2055 batch_size = fmstate->batch_size;
2056 else
2057 batch_size = get_batch_size_option(resultRelInfo->ri_RelationDesc);
2058
2059 /*
2060 * Disable batching when we have to use RETURNING, there are any
2061 * BEFORE/AFTER ROW INSERT triggers on the foreign table, or there are any
2062 * WITH CHECK OPTION constraints from parent views.
2063 *
2064 * When there are any BEFORE ROW INSERT triggers on the table, we can't
2065 * support it, because such triggers might query the table we're inserting
2066 * into and act differently if the tuples that have already been processed
2067 * and prepared for insertion are not there.
2068 */
2069 if (resultRelInfo->ri_projectReturning != NULL ||
2070 resultRelInfo->ri_WithCheckOptions != NIL ||
2071 (resultRelInfo->ri_TrigDesc &&
2072 (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
2073 resultRelInfo->ri_TrigDesc->trig_insert_after_row)))
2074 return 1;
2075
2076 /*
2077 * If the foreign table has no columns, disable batching as the INSERT
2078 * syntax doesn't allow batching multiple empty rows into a zero-column
2079 * table in a single statement. This is needed for COPY FROM, in which
2080 * case fmstate must be non-NULL.
2081 */
2082 if (fmstate && list_length(fmstate->target_attrs) == 0)
2083 return 1;
2084
2085 /*
2086 * Otherwise use the batch size specified for server/table. The number of
2087 * parameters in a batch is limited to 65535 (uint16), so make sure we
2088 * don't exceed this limit by using the maximum batch_size possible.
2089 */
2090 if (fmstate && fmstate->p_nums > 0)
2091 batch_size = Min(batch_size, PQ_QUERY_PARAM_MAX_LIMIT / fmstate->p_nums);
2092
2093 return batch_size;
2094 }
2095
2096 /*
2097 * postgresExecForeignUpdate
2098 * Update one row in a foreign table
2099 */
2100 static TupleTableSlot *
2101 postgresExecForeignUpdate(EState *estate,
2102 ResultRelInfo *resultRelInfo,
2103 TupleTableSlot *slot,
2104 TupleTableSlot *planSlot)
2105 {
2106 TupleTableSlot **rslot;
2107 int numSlots = 1;
2108
2109 rslot = execute_foreign_modify(estate, resultRelInfo, CMD_UPDATE,
2110 &slot, &planSlot, &numSlots);
2111
2112 return rslot ? rslot[0] : NULL;
2113 }
2114
2115 /*
2116 * postgresExecForeignDelete
2117 * Delete one row from a foreign table
2118 */
2119 static TupleTableSlot *
2120 postgresExecForeignDelete(EState *estate,
2121 ResultRelInfo *resultRelInfo,
2122 TupleTableSlot *slot,
2123 TupleTableSlot *planSlot)
2124 {
2125 TupleTableSlot **rslot;
2126 int numSlots = 1;
2127
2128 rslot = execute_foreign_modify(estate, resultRelInfo, CMD_DELETE,
2129 &slot, &planSlot, &numSlots);
2130
2131 return rslot ? rslot[0] : NULL;
2132 }
2133
2134 /*
2135 * postgresEndForeignModify
2136 * Finish an insert/update/delete operation on a foreign table
2137 */
2138 static void
2139 postgresEndForeignModify(EState *estate,
2140 ResultRelInfo *resultRelInfo)
2141 {
2142 PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2143
2144 /* If fmstate is NULL, we are in EXPLAIN; nothing to do */
2145 if (fmstate == NULL)
2146 return;
2147
2148 /* Destroy the execution state */
2149 finish_foreign_modify(fmstate);
2150 }
2151
2152 /*
2153 * postgresBeginForeignInsert
2154 * Begin an insert operation on a foreign table
2155 */
2156 static void
2157 postgresBeginForeignInsert(ModifyTableState *mtstate,
2158 ResultRelInfo *resultRelInfo)
2159 {
2160 PgFdwModifyState *fmstate;
2161 ModifyTable *plan = castNode(ModifyTable, mtstate->ps.plan);
2162 EState *estate = mtstate->ps.state;
2163 Index resultRelation;
2164 Relation rel = resultRelInfo->ri_RelationDesc;
2165 RangeTblEntry *rte;
2166 TupleDesc tupdesc = RelationGetDescr(rel);
2167 int attnum;
2168 int values_end_len;
2169 StringInfoData sql;
2170 List *targetAttrs = NIL;
2171 List *retrieved_attrs = NIL;
2172 bool doNothing = false;
2173
2174 /*
2175 * If the foreign table we are about to insert routed rows into is also an
2176 * UPDATE subplan result rel that will be updated later, proceeding with
2177 * the INSERT will result in the later UPDATE incorrectly modifying those
2178 * routed rows, so prevent the INSERT --- it would be nice if we could
2179 * handle this case; but for now, throw an error for safety.
2180 */
2181 if (plan && plan->operation == CMD_UPDATE &&
2182 (resultRelInfo->ri_usesFdwDirectModify ||
2183 resultRelInfo->ri_FdwState))
2184 ereport(ERROR,
2185 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2186 errmsg("cannot route tuples into foreign table to be updated \"%s\"",
2187 RelationGetRelationName(rel))));
2188
2189 initStringInfo(&sql);
2190
2191 /* We transmit all columns that are defined in the foreign table. */
2192 for (attnum = 1; attnum <= tupdesc->natts; attnum++)
2193 {
2194 CompactAttribute *attr = TupleDescCompactAttr(tupdesc, attnum - 1);
2195
2196 if (!attr->attisdropped)
2197 targetAttrs = lappend_int(targetAttrs, attnum);
2198 }
2199
2200 /* Check if we add the ON CONFLICT clause to the remote query. */
2201 if (plan)
2202 {
2203 OnConflictAction onConflictAction = plan->onConflictAction;
2204
2205 /* We only support DO NOTHING without an inference specification. */
2206 if (onConflictAction == ONCONFLICT_NOTHING)
2207 doNothing = true;
2208 else if (onConflictAction != ONCONFLICT_NONE)
2209 elog(ERROR, "unexpected ON CONFLICT specification: %d",
2210 (int) onConflictAction);
2211 }
2212
2213 /*
2214 * If the foreign table is a partition that doesn't have a corresponding
2215 * RTE entry, we need to create a new RTE describing the foreign table for
2216 * use by deparseInsertSql and create_foreign_modify() below, after first
2217 * copying the parent's RTE and modifying some fields to describe the
2218 * foreign partition to work on. However, if this is invoked by UPDATE,
2219 * the existing RTE may already correspond to this partition if it is one
2220 * of the UPDATE subplan target rels; in that case, we can just use the
2221 * existing RTE as-is.
2222 */
2223 if (resultRelInfo->ri_RangeTableIndex == 0)
2224 {
2225 ResultRelInfo *rootResultRelInfo = resultRelInfo->ri_RootResultRelInfo;
2226
2227 rte = exec_rt_fetch(rootResultRelInfo->ri_RangeTableIndex, estate);
2228 rte = copyObject(rte);
2229 rte->relid = RelationGetRelid(rel);
2230 rte->relkind = RELKIND_FOREIGN_TABLE;
2231
2232 /*
2233 * For UPDATE, we must use the RT index of the first subplan target
2234 * rel's RTE, because the core code would have built expressions for
2235 * the partition, such as RETURNING, using that RT index as varno of
2236 * Vars contained in those expressions.
2237 */
2238 if (plan && plan->operation == CMD_UPDATE &&
2239 rootResultRelInfo->ri_RangeTableIndex == plan->rootRelation)
2240 resultRelation = mtstate->resultRelInfo[0].ri_RangeTableIndex;
2241 else
2242 resultRelation = rootResultRelInfo->ri_RangeTableIndex;
2243 }
2244 else
2245 {
2246 resultRelation = resultRelInfo->ri_RangeTableIndex;
2247 rte = exec_rt_fetch(resultRelation, estate);
2248 }
2249
2250 /* Construct the SQL command string. */
2251 deparseInsertSql(&sql, rte, resultRelation, rel, targetAttrs, doNothing,
2252 resultRelInfo->ri_WithCheckOptions,
2253 resultRelInfo->ri_returningList,
2254 &retrieved_attrs, &values_end_len);
2255
2256 /* Construct an execution state. */
2257 fmstate = create_foreign_modify(mtstate->ps.state,
2258 rte,
2259 resultRelInfo,
2260 CMD_INSERT,
2261 NULL,
2262 sql.data,
2263 targetAttrs,
2264 values_end_len,
2265 retrieved_attrs != NIL,
2266 retrieved_attrs);
2267
2268 /*
2269 * If the given resultRelInfo already has PgFdwModifyState set, it means
2270 * the foreign table is an UPDATE subplan result rel; in which case, store
2271 * the resulting state into the aux_fmstate of the PgFdwModifyState.
2272 */
2273 if (resultRelInfo->ri_FdwState)
2274 {
2275 Assert(plan && plan->operation == CMD_UPDATE);
2276 Assert(resultRelInfo->ri_usesFdwDirectModify == false);
2277 ((PgFdwModifyState *) resultRelInfo->ri_FdwState)->aux_fmstate = fmstate;
2278 }
2279 else
2280 resultRelInfo->ri_FdwState = fmstate;
2281 }
2282
2283 /*
2284 * postgresEndForeignInsert
2285 * Finish an insert operation on a foreign table
2286 */
2287 static void
2288 postgresEndForeignInsert(EState *estate,
2289 ResultRelInfo *resultRelInfo)
2290 {
2291 PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2292
2293 Assert(fmstate != NULL);
2294
2295 /*
2296 * If the fmstate has aux_fmstate set, get the aux_fmstate (see
2297 * postgresBeginForeignInsert())
2298 */
2299 if (fmstate->aux_fmstate)
2300 fmstate = fmstate->aux_fmstate;
2301
2302 /* Destroy the execution state */
2303 finish_foreign_modify(fmstate);
2304 }
2305
2306 /*
2307 * postgresIsForeignRelUpdatable
2308 * Determine whether a foreign table supports INSERT, UPDATE and/or
2309 * DELETE.
2310 */
2311 static int
2312 postgresIsForeignRelUpdatable(Relation rel)
2313 {
2314 bool updatable;
2315 ForeignTable *table;
2316 ForeignServer *server;
2317 ListCell *lc;
2318
2319 /*
2320 * By default, all postgres_fdw foreign tables are assumed updatable. This
2321 * can be overridden by a per-server setting, which in turn can be
2322 * overridden by a per-table setting.
2323 */
2324 updatable = true;
2325
2326 table = GetForeignTable(RelationGetRelid(rel));
2327 server = GetForeignServer(table->serverid);
2328
2329 foreach(lc, server->options)
2330 {
2331 DefElem *def = (DefElem *) lfirst(lc);
2332
2333 if (strcmp(def->defname, "updatable") == 0)
2334 updatable = defGetBoolean(def);
2335 }
2336 foreach(lc, table->options)
2337 {
2338 DefElem *def = (DefElem *) lfirst(lc);
2339
2340 if (strcmp(def->defname, "updatable") == 0)
2341 updatable = defGetBoolean(def);
2342 }
2343
2344 /*
2345 * Currently "updatable" means support for INSERT, UPDATE and DELETE.
2346 */
2347 return updatable ?
2348 (1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE) : 0;
2349 }
2350
2351 /*
2352 * postgresRecheckForeignScan
2353 * Execute a local join execution plan for a foreign join
2354 */
2355 static bool
2356 postgresRecheckForeignScan(ForeignScanState *node, TupleTableSlot *slot)
2357 {
2358 Index scanrelid = ((Scan *) node->ss.ps.plan)->scanrelid;
2359 PlanState *outerPlan = outerPlanState(node);
2360 TupleTableSlot *result;
2361
2362 /* For base foreign relations, it suffices to set fdw_recheck_quals */
2363 if (scanrelid > 0)
2364 return true;
2365
2366 Assert(outerPlan != NULL);
2367
2368 /* Execute a local join execution plan */
2369 result = ExecProcNode(outerPlan);
2370 if (TupIsNull(result))
2371 return false;
2372
2373 /* Store result in the given slot */
2374 ExecCopySlot(slot, result);
2375
2376 return true;
2377 }
2378
2379 /*
2380 * find_modifytable_subplan
2381 * Helper routine for postgresPlanDirectModify to find the
2382 * ModifyTable subplan node that scans the specified RTI.
2383 *
2384 * Returns NULL if the subplan couldn't be identified. That's not a fatal
2385 * error condition, we just abandon trying to do the update directly.
2386 */
2387 static ForeignScan *
2388 find_modifytable_subplan(PlannerInfo *root,
2389 ModifyTable *plan,
2390 Index rtindex,
2391 int subplan_index)
2392 {
2393 Plan *subplan = outerPlan(plan);
2394
2395 /*
2396 * The cases we support are (1) the desired ForeignScan is the immediate
2397 * child of ModifyTable, or (2) it is the subplan_index'th child of an
2398 * Append node that is the immediate child of ModifyTable. There is no
2399 * point in looking further down, as that would mean that local joins are
2400 * involved, so we can't do the update directly.
2401 *
2402 * There could be a Result atop the Append too, acting to compute the
2403 * UPDATE targetlist values. We ignore that here; the tlist will be
2404 * checked by our caller.
2405 *
2406 * In principle we could examine all the children of the Append, but it's
2407 * currently unlikely that the core planner would generate such a plan
2408 * with the children out-of-order. Moreover, such a search risks costing
2409 * O(N^2) time when there are a lot of children.
2410 */
2411 if (IsA(subplan, Append))
2412 {
2413 Append *appendplan = (Append *) subplan;
2414
2415 if (subplan_index < list_length(appendplan->appendplans))
2416 subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2417 }
2418 else if (IsA(subplan, Result) &&
2419 outerPlan(subplan) != NULL &&
2420 IsA(outerPlan(subplan), Append))
2421 {
2422 Append *appendplan = (Append *) outerPlan(subplan);
2423
2424 if (subplan_index < list_length(appendplan->appendplans))
2425 subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2426 }
2427
2428 /* Now, have we got a ForeignScan on the desired rel? */
2429 if (IsA(subplan, ForeignScan))
2430 {
2431 ForeignScan *fscan = (ForeignScan *) subplan;
2432
2433 if (bms_is_member(rtindex, fscan->fs_base_relids))
2434 return fscan;
2435 }
2436
2437 return NULL;
2438 }
2439
2440 /*
2441 * postgresPlanDirectModify
2442 * Consider a direct foreign table modification
2443 *
2444 * Decide whether it is safe to modify a foreign table directly, and if so,
2445 * rewrite subplan accordingly.
2446 */
2447 static bool
2448 postgresPlanDirectModify(PlannerInfo *root,
2449 ModifyTable *plan,
2450 Index resultRelation,
2451 int subplan_index)
2452 {
2453 CmdType operation = plan->operation;
2454 RelOptInfo *foreignrel;
2455 RangeTblEntry *rte;
2456 PgFdwRelationInfo *fpinfo;
2457 Relation rel;
2458 StringInfoData sql;
2459 ForeignScan *fscan;
2460 List *processed_tlist = NIL;
2461 List *targetAttrs = NIL;
2462 List *remote_exprs;
2463 List *params_list = NIL;
2464 List *returningList = NIL;
2465 List *retrieved_attrs = NIL;
2466
2467 /*
2468 * Decide whether it is safe to modify a foreign table directly.
2469 */
2470
2471 /*
2472 * The table modification must be an UPDATE or DELETE.
2473 */
2474 if (operation != CMD_UPDATE && operation != CMD_DELETE)
2475 return false;
2476
2477 /*
2478 * Try to locate the ForeignScan subplan that's scanning resultRelation.
2479 */
2480 fscan = find_modifytable_subplan(root, plan, resultRelation, subplan_index);
2481 if (!fscan)
2482 return false;
2483
2484 /*
2485 * It's unsafe to modify a foreign table directly if there are any quals
2486 * that should be evaluated locally.
2487 */
2488 if (fscan->scan.plan.qual != NIL)
2489 return false;
2490
2491 /* Safe to fetch data about the target foreign rel */
2492 if (fscan->scan.scanrelid == 0)
2493 {
2494 foreignrel = find_join_rel(root, fscan->fs_relids);
2495 /* We should have a rel for this foreign join. */
2496 Assert(foreignrel);
2497 }
2498 else
2499 foreignrel = root->simple_rel_array[resultRelation];
2500 rte = root->simple_rte_array[resultRelation];
2501 fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
2502
2503 /*
2504 * It's unsafe to update a foreign table directly, if any expressions to
2505 * assign to the target columns are unsafe to evaluate remotely.
2506 */
2507 if (operation == CMD_UPDATE)
2508 {
2509 ListCell *lc,
2510 *lc2;
2511
2512 /*
2513 * The expressions of concern are the first N columns of the processed
2514 * targetlist, where N is the length of the rel's update_colnos.
2515 */
2516 get_translated_update_targetlist(root, resultRelation,
2517 &processed_tlist, &targetAttrs);
2518 forboth(lc, processed_tlist, lc2, targetAttrs)
2519 {
2520 TargetEntry *tle = lfirst_node(TargetEntry, lc);
2521 AttrNumber attno = lfirst_int(lc2);
2522
2523 /* update's new-value expressions shouldn't be resjunk */
2524 Assert(!tle->resjunk);
2525
2526 if (attno <= InvalidAttrNumber) /* shouldn't happen */
2527 elog(ERROR, "system-column update is not supported");
2528
2529 if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr))
2530 return false;
2531 }
2532 }
2533
2534 /*
2535 * Ok, rewrite subplan so as to modify the foreign table directly.
2536 */
2537 initStringInfo(&sql);
2538
2539 /*
2540 * Core code already has some lock on each rel being planned, so we can
2541 * use NoLock here.
2542 */
2543 rel = table_open(rte->relid, NoLock);
2544
2545 /*
2546 * Recall the qual clauses that must be evaluated remotely. (These are
2547 * bare clauses not RestrictInfos, but deparse.c's appendConditions()
2548 * doesn't care.)
2549 */
2550 remote_exprs = fpinfo->final_remote_exprs;
2551
2552 /*
2553 * Extract the relevant RETURNING list if any.
2554 */
2555 if (plan->returningLists)
2556 {
2557 returningList = (List *) list_nth(plan->returningLists, subplan_index);
2558
2559 /*
2560 * When performing an UPDATE/DELETE .. RETURNING on a join directly,
2561 * we fetch from the foreign server any Vars specified in RETURNING
2562 * that refer not only to the target relation but to non-target
2563 * relations. So we'll deparse them into the RETURNING clause of the
2564 * remote query; use a targetlist consisting of them instead, which
2565 * will be adjusted to be new fdw_scan_tlist of the foreign-scan plan
2566 * node below.
2567 */
2568 if (fscan->scan.scanrelid == 0)
2569 returningList = build_remote_returning(resultRelation, rel,
2570 returningList);
2571 }
2572
2573 /*
2574 * Construct the SQL command string.
2575 */
2576 switch (operation)
2577 {
2578 case CMD_UPDATE:
2579 deparseDirectUpdateSql(&sql, root, resultRelation, rel,
2580 foreignrel,
2581 processed_tlist,
2582 targetAttrs,
2583 remote_exprs, &params_list,
2584 returningList, &retrieved_attrs);
2585 break;
2586 case CMD_DELETE:
2587 deparseDirectDeleteSql(&sql, root, resultRelation, rel,
2588 foreignrel,
2589 remote_exprs, &params_list,
2590 returningList, &retrieved_attrs);
2591 break;
2592 default:
2593 elog(ERROR, "unexpected operation: %d", (int) operation);
2594 break;
2595 }
2596
2597 /*
2598 * Update the operation and target relation info.
2599 */
2600 fscan->operation = operation;
2601 fscan->resultRelation = resultRelation;
2602
2603 /*
2604 * Update the fdw_exprs list that will be available to the executor.
2605 */
2606 fscan->fdw_exprs = params_list;
2607
2608 /*
2609 * Update the fdw_private list that will be available to the executor.
2610 * Items in the list must match enum FdwDirectModifyPrivateIndex, above.
2611 */
2612 fscan->fdw_private = list_make4(makeString(sql.data),
2613 makeBoolean((retrieved_attrs != NIL)),
2614 retrieved_attrs,
2615 makeBoolean(plan->canSetTag));
2616
2617 /*
2618 * Update the foreign-join-related fields.
2619 */
2620 if (fscan->scan.scanrelid == 0)
2621 {
2622 /* No need for the outer subplan. */
2623 fscan->scan.plan.lefttree = NULL;
2624
2625 /* Build new fdw_scan_tlist if UPDATE/DELETE .. RETURNING. */
2626 if (returningList)
2627 rebuild_fdw_scan_tlist(fscan, returningList);
2628 }
2629
2630 /*
2631 * Finally, unset the async-capable flag if it is set, as we currently
2632 * don't support asynchronous execution of direct modifications.
2633 */
2634 if (fscan->scan.plan.async_capable)
2635 fscan->scan.plan.async_capable = false;
2636
2637 table_close(rel, NoLock);
2638 return true;
2639 }
2640
2641 /*
2642 * postgresBeginDirectModify
2643 * Prepare a direct foreign table modification
2644 */
2645 static void
2646 postgresBeginDirectModify(ForeignScanState *node, int eflags)
2647 {
2648 ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
2649 EState *estate = node->ss.ps.state;
2650 PgFdwDirectModifyState *dmstate;
2651 Index rtindex;
2652 Oid userid;
2653 ForeignTable *table;
2654 UserMapping *user;
2655 int numParams;
2656
2657 /*
2658 * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
2659 */
2660 if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
2661 return;
2662
2663 /*
2664 * We'll save private state in node->fdw_state.
2665 */
2666 dmstate = (PgFdwDirectModifyState *) palloc0(sizeof(PgFdwDirectModifyState));
2667 node->fdw_state = dmstate;
2668
2669 /*
2670 * We use a memory context callback to ensure that the dmstate's PGresult
2671 * (if any) will be released, even if the query fails somewhere that's
2672 * outside our control. The callback is always armed for the duration of
2673 * the query; this relies on PQclear(NULL) being a no-op.
2674 */
2675 dmstate->result_cb.func = (MemoryContextCallbackFunction) PQclear;
2676 dmstate->result_cb.arg = NULL;
2677 MemoryContextRegisterResetCallback(CurrentMemoryContext,
2678 &dmstate->result_cb);
2679
2680 /*
2681 * Identify which user to do the remote access as. This should match what
2682 * ExecCheckPermissions() does.
2683 */
2684 userid = OidIsValid(fsplan->checkAsUser) ? fsplan->checkAsUser : GetUserId();
2685
2686 /* Get info about foreign table. */
2687 rtindex = node->resultRelInfo->ri_RangeTableIndex;
2688 if (fsplan->scan.scanrelid == 0)
2689 dmstate->rel = ExecOpenScanRelation(estate, rtindex, eflags);
2690 else
2691 dmstate->rel = node->ss.ss_currentRelation;
2692 table = GetForeignTable(RelationGetRelid(dmstate->rel));
2693 user = GetUserMapping(userid, table->serverid);
2694
2695 /*
2696 * Get connection to the foreign server. Connection manager will
2697 * establish new connection if necessary.
2698 */
2699 dmstate->conn = GetConnection(user, false, &dmstate->conn_state);
2700
2701 /* Update the foreign-join-related fields. */
2702 if (fsplan->scan.scanrelid == 0)
2703 {
2704 /* Save info about foreign table. */
2705 dmstate->resultRel = dmstate->rel;
2706
2707 /*
2708 * Set dmstate->rel to NULL to teach get_returning_data() and
2709 * make_tuple_from_result_row() that columns fetched from the remote
2710 * server are described by fdw_scan_tlist of the foreign-scan plan
2711 * node, not the tuple descriptor for the target relation.
2712 */
2713 dmstate->rel = NULL;
2714 }
2715
2716 /* Initialize state variable */
2717 dmstate->num_tuples = -1; /* -1 means not set yet */
2718
2719 /* Get private info created by planner functions. */
2720 dmstate->query = strVal(list_nth(fsplan->fdw_private,
2721 FdwDirectModifyPrivateUpdateSql));
2722 dmstate->has_returning = boolVal(list_nth(fsplan->fdw_private,
2723 FdwDirectModifyPrivateHasReturning));
2724 dmstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
2725 FdwDirectModifyPrivateRetrievedAttrs);
2726 dmstate->set_processed = boolVal(list_nth(fsplan->fdw_private,
2727 FdwDirectModifyPrivateSetProcessed));
2728
2729 /* Create context for per-tuple temp workspace. */
2730 dmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
2731 "postgres_fdw temporary data",
2732 ALLOCSET_SMALL_SIZES);
2733
2734 /* Prepare for input conversion of RETURNING results. */
2735 if (dmstate->has_returning)
2736 {
2737 TupleDesc tupdesc;
2738
2739 if (fsplan->scan.scanrelid == 0)
2740 tupdesc = get_tupdesc_for_join_scan_tuples(node);
2741 else
2742 tupdesc = RelationGetDescr(dmstate->rel);
2743
2744 dmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2745
2746 /*
2747 * When performing an UPDATE/DELETE .. RETURNING on a join directly,
2748 * initialize a filter to extract an updated/deleted tuple from a scan
2749 * tuple.
2750 */
2751 if (fsplan->scan.scanrelid == 0)
2752 init_returning_filter(dmstate, fsplan->fdw_scan_tlist, rtindex);
2753 }
2754
2755 /*
2756 * Prepare for processing of parameters used in remote query, if any.
2757 */
2758 numParams = list_length(fsplan->fdw_exprs);
2759 dmstate->numParams = numParams;
2760 if (numParams > 0)
2761 prepare_query_params((PlanState *) node,
2762 fsplan->fdw_exprs,
2763 numParams,
2764 &dmstate->param_flinfo,
2765 &dmstate->param_exprs,
2766 &dmstate->param_values);
2767 }
2768
2769 /*
2770 * postgresIterateDirectModify
2771 * Execute a direct foreign table modification
2772 */
2773 static TupleTableSlot *
2774 postgresIterateDirectModify(ForeignScanState *node)
2775 {
2776 PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
2777 EState *estate = node->ss.ps.state;
2778 ResultRelInfo *resultRelInfo = node->resultRelInfo;
2779
2780 /*
2781 * If this is the first call after Begin, execute the statement.
2782 */
2783 if (dmstate->num_tuples == -1)
2784 execute_dml_stmt(node);
2785
2786 /*
2787 * If the local query doesn't specify RETURNING, just clear tuple slot.
2788 */
2789 if (!resultRelInfo->ri_projectReturning)
2790 {
2791 TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
2792 Instrumentation *instr = node->ss.ps.instrument;
2793
2794 Assert(!dmstate->has_returning);
2795
2796 /* Increment the command es_processed count if necessary. */
2797 if (dmstate->set_processed)
2798 estate->es_processed += dmstate->num_tuples;
2799
2800 /* Increment the tuple count for EXPLAIN ANALYZE if necessary. */
2801 if (instr)
2802 instr->tuplecount += dmstate->num_tuples;
2803
2804 return ExecClearTuple(slot);
2805 }
2806
2807 /*
2808 * Get the next RETURNING tuple.
2809 */
2810 return get_returning_data(node);
2811 }
2812
2813 /*
2814 * postgresEndDirectModify
2815 * Finish a direct foreign table modification
2816 */
2817 static void
2818 postgresEndDirectModify(ForeignScanState *node)
2819 {
2820 PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
2821
2822 /* if dmstate is NULL, we are in EXPLAIN; nothing to do */
2823 if (dmstate == NULL)
2824 return;
2825
2826 /* Release PGresult */
2827 if (dmstate->result)
2828 {
2829 PQclear(dmstate->result);
2830 dmstate->result = NULL;
2831 /* ... and don't forget to disable the callback */
2832 dmstate->result_cb.arg = NULL;
2833 }
2834
2835 /* Release remote connection */
2836 ReleaseConnection(dmstate->conn);
2837 dmstate->conn = NULL;
2838
2839 /* MemoryContext will be deleted automatically. */
2840 }
2841
2842 /*
2843 * postgresExplainForeignScan
2844 * Produce extra output for EXPLAIN of a ForeignScan on a foreign table
2845 */
2846 static void
2847 postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
2848 {
2849 ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
2850 List *fdw_private = plan->fdw_private;
2851
2852 /*
2853 * Identify foreign scans that are really joins or upper relations. The
2854 * input looks something like "(1) LEFT JOIN (2)", and we must replace the
2855 * digit string(s), which are RT indexes, with the correct relation names.
2856 * We do that here, not when the plan is created, because we can't know
2857 * what aliases ruleutils.c will assign at plan creation time.
2858 */
2859 if (list_length(fdw_private) > FdwScanPrivateRelations)
2860 {
2861 StringInfo relations;
2862 char *rawrelations;
2863 char *ptr;
2864 int minrti,
2865 rtoffset;
2866
2867 rawrelations = strVal(list_nth(fdw_private, FdwScanPrivateRelations));
2868
2869 /*
2870 * A difficulty with using a string representation of RT indexes is
2871 * that setrefs.c won't update the string when flattening the
2872 * rangetable. To find out what rtoffset was applied, identify the
2873 * minimum RT index appearing in the string and compare it to the
2874 * minimum member of plan->fs_base_relids. (We expect all the relids
2875 * in the join will have been offset by the same amount; the Asserts
2876 * below should catch it if that ever changes.)
2877 */
2878 minrti = INT_MAX;
2879 ptr = rawrelations;
2880 while (*ptr)
2881 {
2882 if (isdigit((unsigned char) *ptr))
2883 {
2884 int rti = strtol(ptr, &ptr, 10);
2885
2886 if (rti < minrti)
2887 minrti = rti;
2888 }
2889 else
2890 ptr++;
2891 }
2892 rtoffset = bms_next_member(plan->fs_base_relids, -1) - minrti;
2893
2894 /* Now we can translate the string */
2895 relations = makeStringInfo();
2896 ptr = rawrelations;
2897 while (*ptr)
2898 {
2899 if (isdigit((unsigned char) *ptr))
2900 {
2901 int rti = strtol(ptr, &ptr, 10);
2902 RangeTblEntry *rte;
2903 char *relname;
2904 char *refname;
2905
2906 rti += rtoffset;
2907 Assert(bms_is_member(rti, plan->fs_base_relids));
2908 rte = rt_fetch(rti, es->rtable);
2909 Assert(rte->rtekind == RTE_RELATION);
2910 /* This logic should agree with explain.c's ExplainTargetRel */
2911 relname = get_rel_name(rte->relid);
2912 if (es->verbose)
2913 {
2914 char *namespace;
2915
2916 namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid));
2917 appendStringInfo(relations, "%s.%s",
2918 quote_identifier(namespace),
2919 quote_identifier(relname));
2920 }
2921 else
2922 appendStringInfoString(relations,
2923 quote_identifier(relname));
2924 refname = (char *) list_nth(es->rtable_names, rti - 1);
2925 if (refname == NULL)
2926 refname = rte->eref->aliasname;
2927 if (strcmp(refname, relname) != 0)
2928 appendStringInfo(relations, " %s",
2929 quote_identifier(refname));
2930 }
2931 else
2932 appendStringInfoChar(relations, *ptr++);
2933 }
2934 ExplainPropertyText("Relations", relations->data, es);
2935 }
2936
2937 /*
2938 * Add remote query, when VERBOSE option is specified.
2939 */
2940 if (es->verbose)
2941 {
2942 char *sql;
2943
2944 sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
2945 ExplainPropertyText("Remote SQL", sql, es);
2946 }
2947 }
2948
2949 /*
2950 * postgresExplainForeignModify
2951 * Produce extra output for EXPLAIN of a ModifyTable on a foreign table
2952 */
2953 static void
2954 postgresExplainForeignModify(ModifyTableState *mtstate,
2955 ResultRelInfo *rinfo,
2956 List *fdw_private,
2957 int subplan_index,
2958 ExplainState *es)
2959 {
2960 if (es->verbose)
2961 {
2962 char *sql = strVal(list_nth(fdw_private,
2963 FdwModifyPrivateUpdateSql));
2964
2965 ExplainPropertyText("Remote SQL", sql, es);
2966
2967 /*
2968 * For INSERT we should always have batch size >= 1, but UPDATE and
2969 * DELETE don't support batching so don't show the property.
2970 */
2971 if (rinfo->ri_BatchSize > 0)
2972 ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
2973 }
2974 }
2975
2976 /*
2977 * postgresExplainDirectModify
2978 * Produce extra output for EXPLAIN of a ForeignScan that modifies a
2979 * foreign table directly
2980 */
2981 static void
2982 postgresExplainDirectModify(ForeignScanState *node, ExplainState *es)
2983 {
2984 List *fdw_private;
2985 char *sql;
2986
2987 if (es->verbose)
2988 {
2989 fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
2990 sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
2991 ExplainPropertyText("Remote SQL", sql, es);
2992 }
2993 }
2994
2995 /*
2996 * postgresExecForeignTruncate
2997 * Truncate one or more foreign tables
2998 */
2999 static void
3000 postgresExecForeignTruncate(List *rels,
3001 DropBehavior behavior,
3002 bool restart_seqs)
3003 {
3004 Oid serverid = InvalidOid;
3005 UserMapping *user = NULL;
3006 PGconn *conn = NULL;
3007 StringInfoData sql;
3008 ListCell *lc;
3009 bool server_truncatable = true;
3010
3011 /*
3012 * By default, all postgres_fdw foreign tables are assumed truncatable.
3013 * This can be overridden by a per-server setting, which in turn can be
3014 * overridden by a per-table setting.
3015 */
3016 foreach(lc, rels)
3017 {
3018 ForeignServer *server = NULL;
3019 Relation rel = lfirst(lc);
3020 ForeignTable *table = GetForeignTable(RelationGetRelid(rel));
3021 ListCell *cell;
3022 bool truncatable;
3023
3024 /*
3025 * First time through, determine whether the foreign server allows
3026 * truncates. Since all specified foreign tables are assumed to belong
3027 * to the same foreign server, this result can be used for other
3028 * foreign tables.
3029 */
3030 if (!OidIsValid(serverid))
3031 {
3032 serverid = table->serverid;
3033 server = GetForeignServer(serverid);
3034
3035 foreach(cell, server->options)
3036 {
3037 DefElem *defel = (DefElem *) lfirst(cell);
3038
3039 if (strcmp(defel->defname, "truncatable") == 0)
3040 {
3041 server_truncatable = defGetBoolean(defel);
3042 break;
3043 }
3044 }
3045 }
3046
3047 /*
3048 * Confirm that all specified foreign tables belong to the same
3049 * foreign server.
3050 */
3051 Assert(table->serverid == serverid);
3052
3053 /* Determine whether this foreign table allows truncations */
3054 truncatable = server_truncatable;
3055 foreach(cell, table->options)
3056 {
3057 DefElem *defel = (DefElem *) lfirst(cell);
3058
3059 if (strcmp(defel->defname, "truncatable") == 0)
3060 {
3061 truncatable = defGetBoolean(defel);
3062 break;
3063 }
3064 }
3065
3066 if (!truncatable)
3067 ereport(ERROR,
3068 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3069 errmsg("foreign table \"%s\" does not allow truncates",
3070 RelationGetRelationName(rel))));
3071 }
3072 Assert(OidIsValid(serverid));
3073
3074 /*
3075 * Get connection to the foreign server. Connection manager will
3076 * establish new connection if necessary.
3077 */
3078 user = GetUserMapping(GetUserId(), serverid);
3079 conn = GetConnection(user, false, NULL);
3080
3081 /* Construct the TRUNCATE command string */
3082 initStringInfo(&sql);
3083 deparseTruncateSql(&sql, rels, behavior, restart_seqs);
3084
3085 /* Issue the TRUNCATE command to remote server */
3086 do_sql_command(conn, sql.data);
3087
3088 pfree(sql.data);
3089 }
3090
3091 /*
3092 * estimate_path_cost_size
3093 * Get cost and size estimates for a foreign scan on given foreign relation
3094 * either a base relation or a join between foreign relations or an upper
3095 * relation containing foreign relations.
3096 *
3097 * param_join_conds are the parameterization clauses with outer relations.
3098 * pathkeys specify the expected sort order if any for given path being costed.
3099 * fpextra specifies additional post-scan/join-processing steps such as the
3100 * final sort and the LIMIT restriction.
3101 *
3102 * The function returns the cost and size estimates in p_rows, p_width,
3103 * p_disabled_nodes, p_startup_cost and p_total_cost variables.
3104 */
3105 static void
3106 estimate_path_cost_size(PlannerInfo *root,
3107 RelOptInfo *foreignrel,
3108 List *param_join_conds,
3109 List *pathkeys,
3110 PgFdwPathExtraData *fpextra,
3111 double *p_rows, int *p_width,
3112 int *p_disabled_nodes,
3113 Cost *p_startup_cost, Cost *p_total_cost)
3114 {
3115 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
3116 double rows;
3117 double retrieved_rows;
3118 int width;
3119 int disabled_nodes = 0;
3120 Cost startup_cost;
3121 Cost total_cost;
3122
3123 /* Make sure the core code has set up the relation's reltarget */
3124 Assert(foreignrel->reltarget);
3125
3126 /*
3127 * If the table or the server is configured to use remote estimates,
3128 * connect to the foreign server and execute EXPLAIN to estimate the
3129 * number of rows selected by the restriction+join clauses. Otherwise,
3130 * estimate rows using whatever statistics we have locally, in a way
3131 * similar to ordinary tables.
3132 */
3133 if (fpinfo->use_remote_estimate)
3134 {
3135 List *remote_param_join_conds;
3136 List *local_param_join_conds;
3137 StringInfoData sql;
3138 PGconn *conn;
3139 Selectivity local_sel;
3140 QualCost local_cost;
3141 List *fdw_scan_tlist = NIL;
3142 List *remote_conds;
3143
3144 /* Required only to be passed to deparseSelectStmtForRel */
3145 List *retrieved_attrs;
3146
3147 /*
3148 * param_join_conds might contain both clauses that are safe to send
3149 * across, and clauses that aren't.
3150 */
3151 classifyConditions(root, foreignrel, param_join_conds,
3152 &remote_param_join_conds, &local_param_join_conds);
3153
3154 /* Build the list of columns to be fetched from the foreign server. */
3155 if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
3156 fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
3157 else
3158 fdw_scan_tlist = NIL;
3159
3160 /*
3161 * The complete list of remote conditions includes everything from
3162 * baserestrictinfo plus any extra join_conds relevant to this
3163 * particular path.
3164 */
3165 remote_conds = list_concat(remote_param_join_conds,
3166 fpinfo->remote_conds);
3167
3168 /*
3169 * Construct EXPLAIN query including the desired SELECT, FROM, and
3170 * WHERE clauses. Params and other-relation Vars are replaced by dummy
3171 * values, so don't request params_list.
3172 */
3173 initStringInfo(&sql);
3174 appendStringInfoString(&sql, "EXPLAIN ");
3175 deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
3176 remote_conds, pathkeys,
3177 fpextra ? fpextra->has_final_sort : false,
3178 fpextra ? fpextra->has_limit : false,
3179 false, &retrieved_attrs, NULL);
3180
3181 /* Get the remote estimate */
3182 conn = GetConnection(fpinfo->user, false, NULL);
3183 get_remote_estimate(sql.data, conn, &rows, &width,
3184 &startup_cost, &total_cost);
3185 ReleaseConnection(conn);
3186
3187 retrieved_rows = rows;
3188
3189 /* Factor in the selectivity of the locally-checked quals */
3190 local_sel = clauselist_selectivity(root,
3191 local_param_join_conds,
3192 foreignrel->relid,
3193 JOIN_INNER,
3194 NULL);
3195 local_sel *= fpinfo->local_conds_sel;
3196
3197 rows = clamp_row_est(rows * local_sel);
3198
3199 /* Add in the eval cost of the locally-checked quals */
3200 startup_cost += fpinfo->local_conds_cost.startup;
3201 total_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3202 cost_qual_eval(&local_cost, local_param_join_conds, root);
3203 startup_cost += local_cost.startup;
3204 total_cost += local_cost.per_tuple * retrieved_rows;
3205
3206 /*
3207 * Add in tlist eval cost for each output row. In case of an
3208 * aggregate, some of the tlist expressions such as grouping
3209 * expressions will be evaluated remotely, so adjust the costs.
3210 */
3211 startup_cost += foreignrel->reltarget->cost.startup;
3212 total_cost += foreignrel->reltarget->cost.startup;
3213 total_cost += foreignrel->reltarget->cost.per_tuple * rows;
3214 if (IS_UPPER_REL(foreignrel))
3215 {
3216 QualCost tlist_cost;
3217
3218 cost_qual_eval(&tlist_cost, fdw_scan_tlist, root);
3219 startup_cost -= tlist_cost.startup;
3220 total_cost -= tlist_cost.startup;
3221 total_cost -= tlist_cost.per_tuple * rows;
3222 }
3223 }
3224 else
3225 {
3226 Cost run_cost = 0;
3227
3228 /*
3229 * We don't support join conditions in this mode (hence, no
3230 * parameterized paths can be made).
3231 */
3232 Assert(param_join_conds == NIL);
3233
3234 /*
3235 * We will come here again and again with different set of pathkeys or
3236 * additional post-scan/join-processing steps that caller wants to
3237 * cost. We don't need to calculate the cost/size estimates for the
3238 * underlying scan, join, or grouping each time. Instead, use those
3239 * estimates if we have cached them already.
3240 */
3241 if (fpinfo->rel_startup_cost >= 0 && fpinfo->rel_total_cost >= 0)
3242 {
3243 Assert(fpinfo->retrieved_rows >= 0);
3244
3245 rows = fpinfo->rows;
3246 retrieved_rows = fpinfo->retrieved_rows;
3247 width = fpinfo->width;
3248 startup_cost = fpinfo->rel_startup_cost;
3249 run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
3250
3251 /*
3252 * If we estimate the costs of a foreign scan or a foreign join
3253 * with additional post-scan/join-processing steps, the scan or
3254 * join costs obtained from the cache wouldn't yet contain the
3255 * eval costs for the final scan/join target, which would've been
3256 * updated by apply_scanjoin_target_to_paths(); add the eval costs
3257 * now.
3258 */
3259 if (fpextra && !IS_UPPER_REL(foreignrel))
3260 {
3261 /* Shouldn't get here unless we have LIMIT */
3262 Assert(fpextra->has_limit);
3263 Assert(foreignrel->reloptkind == RELOPT_BASEREL ||
3264 foreignrel->reloptkind == RELOPT_JOINREL);
3265 startup_cost += foreignrel->reltarget->cost.startup;
3266 run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3267 }
3268 }
3269 else if (IS_JOIN_REL(foreignrel))
3270 {
3271 PgFdwRelationInfo *fpinfo_i;
3272 PgFdwRelationInfo *fpinfo_o;
3273 QualCost join_cost;
3274 QualCost remote_conds_cost;
3275 double nrows;
3276
3277 /* Use rows/width estimates made by the core code. */
3278 rows = foreignrel->rows;
3279 width = foreignrel->reltarget->width;
3280
3281 /* For join we expect inner and outer relations set */
3282 Assert(fpinfo->innerrel && fpinfo->outerrel);
3283
3284 fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private;
3285 fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
3286
3287 /* Estimate of number of rows in cross product */
3288 nrows = fpinfo_i->rows * fpinfo_o->rows;
3289
3290 /*
3291 * Back into an estimate of the number of retrieved rows. Just in
3292 * case this is nuts, clamp to at most nrows.
3293 */
3294 retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3295 retrieved_rows = Min(retrieved_rows, nrows);
3296
3297 /*
3298 * The cost of foreign join is estimated as cost of generating
3299 * rows for the joining relations + cost for applying quals on the
3300 * rows.
3301 */
3302
3303 /*
3304 * Calculate the cost of clauses pushed down to the foreign server
3305 */
3306 cost_qual_eval(&remote_conds_cost, fpinfo->remote_conds, root);
3307 /* Calculate the cost of applying join clauses */
3308 cost_qual_eval(&join_cost, fpinfo->joinclauses, root);
3309
3310 /*
3311 * Startup cost includes startup cost of joining relations and the
3312 * startup cost for join and other clauses. We do not include the
3313 * startup cost specific to join strategy (e.g. setting up hash
3314 * tables) since we do not know what strategy the foreign server
3315 * is going to use.
3316 */
3317 startup_cost = fpinfo_i->rel_startup_cost + fpinfo_o->rel_startup_cost;
3318 startup_cost += join_cost.startup;
3319 startup_cost += remote_conds_cost.startup;
3320 startup_cost += fpinfo->local_conds_cost.startup;
3321
3322 /*
3323 * Run time cost includes:
3324 *
3325 * 1. Run time cost (total_cost - startup_cost) of relations being
3326 * joined
3327 *
3328 * 2. Run time cost of applying join clauses on the cross product
3329 * of the joining relations.
3330 *
3331 * 3. Run time cost of applying pushed down other clauses on the
3332 * result of join
3333 *
3334 * 4. Run time cost of applying nonpushable other clauses locally
3335 * on the result fetched from the foreign server.
3336 */
3337 run_cost = fpinfo_i->rel_total_cost - fpinfo_i->rel_startup_cost;
3338 run_cost += fpinfo_o->rel_total_cost - fpinfo_o->rel_startup_cost;
3339 run_cost += nrows * join_cost.per_tuple;
3340 nrows = clamp_row_est(nrows * fpinfo->joinclause_sel);
3341 run_cost += nrows * remote_conds_cost.per_tuple;
3342 run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3343
3344 /* Add in tlist eval cost for each output row */
3345 startup_cost += foreignrel->reltarget->cost.startup;
3346 run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3347 }
3348 else if (IS_UPPER_REL(foreignrel))
3349 {
3350 RelOptInfo *outerrel = fpinfo->outerrel;
3351 PgFdwRelationInfo *ofpinfo;
3352 AggClauseCosts aggcosts = {0};
3353 double input_rows;
3354 int numGroupCols;
3355 double numGroups = 1;
3356
3357 /* The upper relation should have its outer relation set */
3358 Assert(outerrel);
3359 /* and that outer relation should have its reltarget set */
3360 Assert(outerrel->reltarget);
3361
3362 /*
3363 * This cost model is mixture of costing done for sorted and
3364 * hashed aggregates in cost_agg(). We are not sure which
3365 * strategy will be considered at remote side, thus for
3366 * simplicity, we put all startup related costs in startup_cost
3367 * and all finalization and run cost are added in total_cost.
3368 */
3369
3370 ofpinfo = (PgFdwRelationInfo *) outerrel->fdw_private;
3371
3372 /* Get rows from input rel */
3373 input_rows = ofpinfo->rows;
3374
3375 /* Collect statistics about aggregates for estimating costs. */
3376 if (root->parse->hasAggs)
3377 {
3378 get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &aggcosts);
3379 }
3380
3381 /* Get number of grouping columns and possible number of groups */
3382 numGroupCols = list_length(root->processed_groupClause);
3383 numGroups = estimate_num_groups(root,
3384 get_sortgrouplist_exprs(root->processed_groupClause,
3385 fpinfo->grouped_tlist),
3386 input_rows, NULL, NULL);
3387
3388 /*
3389 * Get the retrieved_rows and rows estimates. If there are HAVING
3390 * quals, account for their selectivity.
3391 */
3392 if (root->hasHavingQual)
3393 {
3394 /* Factor in the selectivity of the remotely-checked quals */
3395 retrieved_rows =
3396 clamp_row_est(numGroups *
3397 clauselist_selectivity(root,
3398 fpinfo->remote_conds,
3399 0,
3400 JOIN_INNER,
3401 NULL));
3402 /* Factor in the selectivity of the locally-checked quals */
3403 rows = clamp_row_est(retrieved_rows * fpinfo->local_conds_sel);
3404 }
3405 else
3406 {
3407 rows = retrieved_rows = numGroups;
3408 }
3409
3410 /* Use width estimate made by the core code. */
3411 width = foreignrel->reltarget->width;
3412
3413 /*-----
3414 * Startup cost includes:
3415 * 1. Startup cost for underneath input relation, adjusted for
3416 * tlist replacement by apply_scanjoin_target_to_paths()
3417 * 2. Cost of performing aggregation, per cost_agg()
3418 *-----
3419 */
3420 startup_cost = ofpinfo->rel_startup_cost;
3421 startup_cost += outerrel->reltarget->cost.startup;
3422 startup_cost += aggcosts.transCost.startup;
3423 startup_cost += aggcosts.transCost.per_tuple * input_rows;
3424 startup_cost += aggcosts.finalCost.startup;
3425 startup_cost += (cpu_operator_cost * numGroupCols) * input_rows;
3426
3427 /*-----
3428 * Run time cost includes:
3429 * 1. Run time cost of underneath input relation, adjusted for
3430 * tlist replacement by apply_scanjoin_target_to_paths()
3431 * 2. Run time cost of performing aggregation, per cost_agg()
3432 *-----
3433 */
3434 run_cost = ofpinfo->rel_total_cost - ofpinfo->rel_startup_cost;
3435 run_cost += outerrel->reltarget->cost.per_tuple * input_rows;
3436 run_cost += aggcosts.finalCost.per_tuple * numGroups;
3437 run_cost += cpu_tuple_cost * numGroups;
3438
3439 /* Account for the eval cost of HAVING quals, if any */
3440 if (root->hasHavingQual)
3441 {
3442 QualCost remote_cost;
3443
3444 /* Add in the eval cost of the remotely-checked quals */
3445 cost_qual_eval(&remote_cost, fpinfo->remote_conds, root);
3446 startup_cost += remote_cost.startup;
3447 run_cost += remote_cost.per_tuple * numGroups;
3448 /* Add in the eval cost of the locally-checked quals */
3449 startup_cost += fpinfo->local_conds_cost.startup;
3450 run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3451 }
3452
3453 /* Add in tlist eval cost for each output row */
3454 startup_cost += foreignrel->reltarget->cost.startup;
3455 run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3456 }
3457 else
3458 {
3459 Cost cpu_per_tuple;
3460
3461 /* Use rows/width estimates made by set_baserel_size_estimates. */
3462 rows = foreignrel->rows;
3463 width = foreignrel->reltarget->width;
3464
3465 /*
3466 * Back into an estimate of the number of retrieved rows. Just in
3467 * case this is nuts, clamp to at most foreignrel->tuples.
3468 */
3469 retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3470 retrieved_rows = Min(retrieved_rows, foreignrel->tuples);
3471
3472 /*
3473 * Cost as though this were a seqscan, which is pessimistic. We
3474 * effectively imagine the local_conds are being evaluated
3475 * remotely, too.
3476 */
3477 startup_cost = 0;
3478 run_cost = 0;
3479 run_cost += seq_page_cost * foreignrel->pages;
3480
3481 startup_cost += foreignrel->baserestrictcost.startup;
3482 cpu_per_tuple = cpu_tuple_cost + foreignrel->baserestrictcost.per_tuple;
3483 run_cost += cpu_per_tuple * foreignrel->tuples;
3484
3485 /* Add in tlist eval cost for each output row */
3486 startup_cost += foreignrel->reltarget->cost.startup;
3487 run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3488 }
3489
3490 /*
3491 * Without remote estimates, we have no real way to estimate the cost
3492 * of generating sorted output. It could be free if the query plan
3493 * the remote side would have chosen generates properly-sorted output
3494 * anyway, but in most cases it will cost something. Estimate a value
3495 * high enough that we won't pick the sorted path when the ordering
3496 * isn't locally useful, but low enough that we'll err on the side of
3497 * pushing down the ORDER BY clause when it's useful to do so.
3498 */
3499 if (pathkeys != NIL)
3500 {
3501 if (IS_UPPER_REL(foreignrel))
3502 {
3503 Assert(foreignrel->reloptkind == RELOPT_UPPER_REL &&
3504 fpinfo->stage == UPPERREL_GROUP_AGG);
3505 adjust_foreign_grouping_path_cost(root, pathkeys,
3506 retrieved_rows, width,
3507 fpextra->limit_tuples,
3508 &disabled_nodes,
3509 &startup_cost, &run_cost);
3510 }
3511 else
3512 {
3513 startup_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3514 run_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3515 }
3516 }
3517
3518 total_cost = startup_cost + run_cost;
3519
3520 /* Adjust the cost estimates if we have LIMIT */
3521 if (fpextra && fpextra->has_limit)
3522 {
3523 adjust_limit_rows_costs(&rows, &startup_cost, &total_cost,
3524 fpextra->offset_est, fpextra->count_est);
3525 retrieved_rows = rows;
3526 }
3527 }
3528
3529 /*
3530 * If this includes the final sort step, the given target, which will be
3531 * applied to the resulting path, might have different expressions from
3532 * the foreignrel's reltarget (see make_sort_input_target()); adjust tlist
3533 * eval costs.
3534 */
3535 if (fpextra && fpextra->has_final_sort &&
3536 fpextra->target != foreignrel->reltarget)
3537 {
3538 QualCost oldcost = foreignrel->reltarget->cost;
3539 QualCost newcost = fpextra->target->cost;
3540
3541 startup_cost += newcost.startup - oldcost.startup;
3542 total_cost += newcost.startup - oldcost.startup;
3543 total_cost += (newcost.per_tuple - oldcost.per_tuple) * rows;
3544 }
3545
3546 /*
3547 * Cache the retrieved rows and cost estimates for scans, joins, or
3548 * groupings without any parameterization, pathkeys, or additional
3549 * post-scan/join-processing steps, before adding the costs for
3550 * transferring data from the foreign server. These estimates are useful
3551 * for costing remote joins involving this relation or costing other
3552 * remote operations on this relation such as remote sorts and remote
3553 * LIMIT restrictions, when the costs can not be obtained from the foreign
3554 * server. This function will be called at least once for every foreign
3555 * relation without any parameterization, pathkeys, or additional
3556 * post-scan/join-processing steps.
3557 */
3558 if (pathkeys == NIL && param_join_conds == NIL && fpextra == NULL)
3559 {
3560 fpinfo->retrieved_rows = retrieved_rows;
3561 fpinfo->rel_startup_cost = startup_cost;
3562 fpinfo->rel_total_cost = total_cost;
3563 }
3564
3565 /*
3566 * Add some additional cost factors to account for connection overhead
3567 * (fdw_startup_cost), transferring data across the network
3568 * (fdw_tuple_cost per retrieved row), and local manipulation of the data
3569 * (cpu_tuple_cost per retrieved row).
3570 */
3571 startup_cost += fpinfo->fdw_startup_cost;
3572 total_cost += fpinfo->fdw_startup_cost;
3573 total_cost += fpinfo->fdw_tuple_cost * retrieved_rows;
3574 total_cost += cpu_tuple_cost * retrieved_rows;
3575
3576 /*
3577 * If we have LIMIT, we should prefer performing the restriction remotely
3578 * rather than locally, as the former avoids extra row fetches from the
3579 * remote that the latter might cause. But since the core code doesn't
3580 * account for such fetches when estimating the costs of the local
3581 * restriction (see create_limit_path()), there would be no difference
3582 * between the costs of the local restriction and the costs of the remote
3583 * restriction estimated above if we don't use remote estimates (except
3584 * for the case where the foreignrel is a grouping relation, the given
3585 * pathkeys is not NIL, and the effects of a bounded sort for that rel is
3586 * accounted for in costing the remote restriction). Tweak the costs of
3587 * the remote restriction to ensure we'll prefer it if LIMIT is a useful
3588 * one.
3589 */
3590 if (!fpinfo->use_remote_estimate &&
3591 fpextra && fpextra->has_limit &&
3592 fpextra->limit_tuples > 0 &&
3593 fpextra->limit_tuples < fpinfo->rows)
3594 {
3595 Assert(fpinfo->rows > 0);
3596 total_cost -= (total_cost - startup_cost) * 0.05 *
3597 (fpinfo->rows - fpextra->limit_tuples) / fpinfo->rows;
3598 }
3599
3600 /* Return results. */
3601 *p_rows = rows;
3602 *p_width = width;
3603 *p_disabled_nodes = disabled_nodes;
3604 *p_startup_cost = startup_cost;
3605 *p_total_cost = total_cost;
3606 }
3607
3608 /*
3609 * Estimate costs of executing a SQL statement remotely.
3610 * The given "sql" must be an EXPLAIN command.
3611 */
3612 static void
3613 get_remote_estimate(const char *sql, PGconn *conn,
3614 double *rows, int *width,
3615 Cost *startup_cost, Cost *total_cost)
3616 {
3617 PGresult *volatile res = NULL;
3618
3619 /* PGresult must be released before leaving this function. */
3620 PG_TRY();
3621 {
3622 char *line;
3623 char *p;
3624 int n;
3625
3626 /*
3627 * Execute EXPLAIN remotely.
3628 */
3629 res = pgfdw_exec_query(conn, sql, NULL);
3630 if (PQresultStatus(res) != PGRES_TUPLES_OK)
3631 pgfdw_report_error(ERROR, res, conn, false, sql);
3632
3633 /*
3634 * Extract cost numbers for topmost plan node. Note we search for a
3635 * left paren from the end of the line to avoid being confused by
3636 * other uses of parentheses.
3637 */
3638 line = PQgetvalue(res, 0, 0);
3639 p = strrchr(line, '(');
3640 if (p == NULL)
3641 elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3642 n = sscanf(p, "(cost=%lf..%lf rows=%lf width=%d)",
3643 startup_cost, total_cost, rows, width);
3644 if (n != 4)
3645 elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3646 }
3647 PG_FINALLY();
3648 {
3649 PQclear(res);
3650 }
3651 PG_END_TRY();
3652 }
3653
3654 /*
3655 * Adjust the cost estimates of a foreign grouping path to include the cost of
3656 * generating properly-sorted output.
3657 */
3658 static void
3659 adjust_foreign_grouping_path_cost(PlannerInfo *root,
3660 List *pathkeys,
3661 double retrieved_rows,
3662 double width,
3663 double limit_tuples,
3664 int *p_disabled_nodes,
3665 Cost *p_startup_cost,
3666 Cost *p_run_cost)
3667 {
3668 /*
3669 * If the GROUP BY clause isn't sort-able, the plan chosen by the remote
3670 * side is unlikely to generate properly-sorted output, so it would need
3671 * an explicit sort; adjust the given costs with cost_sort(). Likewise,
3672 * if the GROUP BY clause is sort-able but isn't a superset of the given
3673 * pathkeys, adjust the costs with that function. Otherwise, adjust the
3674 * costs by applying the same heuristic as for the scan or join case.
3675 */
3676 if (!grouping_is_sortable(root->processed_groupClause) ||
3677 !pathkeys_contained_in(pathkeys, root->group_pathkeys))
3678 {
3679 Path sort_path; /* dummy for result of cost_sort */
3680
3681 cost_sort(&sort_path,
3682 root,
3683 pathkeys,
3684 0,
3685 *p_startup_cost + *p_run_cost,
3686 retrieved_rows,
3687 width,
3688 0.0,
3689 work_mem,
3690 limit_tuples);
3691
3692 *p_startup_cost = sort_path.startup_cost;
3693 *p_run_cost = sort_path.total_cost - sort_path.startup_cost;
3694 }
3695 else
3696 {
3697 /*
3698 * The default extra cost seems too large for foreign-grouping cases;
3699 * add 1/4th of that default.
3700 */
3701 double sort_multiplier = 1.0 + (DEFAULT_FDW_SORT_MULTIPLIER
3702 - 1.0) * 0.25;
3703
3704 *p_startup_cost *= sort_multiplier;
3705 *p_run_cost *= sort_multiplier;
3706 }
3707 }
3708
3709 /*
3710 * Detect whether we want to process an EquivalenceClass member.
3711 *
3712 * This is a callback for use by generate_implied_equalities_for_column.
3713 */
3714 static bool
3715 ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
3716 EquivalenceClass *ec, EquivalenceMember *em,
3717 void *arg)
3718 {
3719 ec_member_foreign_arg *state = (ec_member_foreign_arg *) arg;
3720 Expr *expr = em->em_expr;
3721
3722 /*
3723 * If we've identified what we're processing in the current scan, we only
3724 * want to match that expression.
3725 */
3726 if (state->current != NULL)
3727 return equal(expr, state->current);
3728
3729 /*
3730 * Otherwise, ignore anything we've already processed.
3731 */
3732 if (list_member(state->already_used, expr))
3733 return false;
3734
3735 /* This is the new target to process. */
3736 state->current = expr;
3737 return true;
3738 }
3739
3740 /*
3741 * Create cursor for node's query with current parameter values.
3742 */
3743 static void
3744 create_cursor(ForeignScanState *node)
3745 {
3746 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3747 ExprContext *econtext = node->ss.ps.ps_ExprContext;
3748 int numParams = fsstate->numParams;
3749 const char **values = fsstate->param_values;
3750 PGconn *conn = fsstate->conn;
3751 StringInfoData buf;
3752 PGresult *res;
3753
3754 /* First, process a pending asynchronous request, if any. */
3755 if (fsstate->conn_state->pendingAreq)
3756 process_pending_request(fsstate->conn_state->pendingAreq);
3757
3758 /*
3759 * Construct array of query parameter values in text format. We do the
3760 * conversions in the short-lived per-tuple context, so as not to cause a
3761 * memory leak over repeated scans.
3762 */
3763 if (numParams > 0)
3764 {
3765 MemoryContext oldcontext;
3766
3767 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3768
3769 process_query_params(econtext,
3770 fsstate->param_flinfo,
3771 fsstate->param_exprs,
3772 values);
3773
3774 MemoryContextSwitchTo(oldcontext);
3775 }
3776
3777 /* Construct the DECLARE CURSOR command */
3778 initStringInfo(&buf);
3779 appendStringInfo(&buf, "DECLARE c%u CURSOR FOR\n%s",
3780 fsstate->cursor_number, fsstate->query);
3781
3782 /*
3783 * Notice that we pass NULL for paramTypes, thus forcing the remote server
3784 * to infer types for all parameters. Since we explicitly cast every
3785 * parameter (see deparse.c), the "inference" is trivial and will produce
3786 * the desired result. This allows us to avoid assuming that the remote
3787 * server has the same OIDs we do for the parameters' types.
3788 */
3789 if (!PQsendQueryParams(conn, buf.data, numParams,
3790 NULL, values, NULL, NULL, 0))
3791 pgfdw_report_error(ERROR, NULL, conn, false, buf.data);
3792
3793 /*
3794 * Get the result, and check for success.
3795 *
3796 * We don't use a PG_TRY block here, so be careful not to throw error
3797 * without releasing the PGresult.
3798 */
3799 res = pgfdw_get_result(conn);
3800 if (PQresultStatus(res) != PGRES_COMMAND_OK)
3801 pgfdw_report_error(ERROR, res, conn, true, fsstate->query);
3802 PQclear(res);
3803
3804 /* Mark the cursor as created, and show no tuples have been retrieved */
3805 fsstate->cursor_exists = true;
3806 fsstate->tuples = NULL;
3807 fsstate->num_tuples = 0;
3808 fsstate->next_tuple = 0;
3809 fsstate->fetch_ct_2 = 0;
3810 fsstate->eof_reached = false;
3811
3812 /* Clean up */
3813 pfree(buf.data);
3814 }
3815
3816 /*
3817 * Fetch some more rows from the node's cursor.
3818 */
3819 static void
3820 fetch_more_data(ForeignScanState *node)
3821 {
3822 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3823 PGresult *volatile res = NULL;
3824 MemoryContext oldcontext;
3825
3826 /*
3827 * We'll store the tuples in the batch_cxt. First, flush the previous
3828 * batch.
3829 */
3830 fsstate->tuples = NULL;
3831 MemoryContextReset(fsstate->batch_cxt);
3832 oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
3833
3834 /* PGresult must be released before leaving this function. */
3835 PG_TRY();
3836 {
3837 PGconn *conn = fsstate->conn;
3838 int numrows;
3839 int i;
3840
3841 if (fsstate->async_capable)
3842 {
3843 Assert(fsstate->conn_state->pendingAreq);
3844
3845 /*
3846 * The query was already sent by an earlier call to
3847 * fetch_more_data_begin. So now we just fetch the result.
3848 */
3849 res = pgfdw_get_result(conn);
3850 /* On error, report the original query, not the FETCH. */
3851 if (PQresultStatus(res) != PGRES_TUPLES_OK)
3852 pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3853
3854 /* Reset per-connection state */
3855 fsstate->conn_state->pendingAreq = NULL;
3856 }
3857 else
3858 {
3859 char sql[64];
3860
3861 /* This is a regular synchronous fetch. */
3862 snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
3863 fsstate->fetch_size, fsstate->cursor_number);
3864
3865 res = pgfdw_exec_query(conn, sql, fsstate->conn_state);
3866 /* On error, report the original query, not the FETCH. */
3867 if (PQresultStatus(res) != PGRES_TUPLES_OK)
3868 pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3869 }
3870
3871 /* Convert the data into HeapTuples */
3872 numrows = PQntuples(res);
3873 fsstate->tuples = (HeapTuple *) palloc0(numrows * sizeof(HeapTuple));
3874 fsstate->num_tuples = numrows;
3875 fsstate->next_tuple = 0;
3876
3877 for (i = 0; i < numrows; i++)
3878 {
3879 Assert(IsA(node->ss.ps.plan, ForeignScan));
3880
3881 fsstate->tuples[i] =
3882 make_tuple_from_result_row(res, i,
3883 fsstate->rel,
3884 fsstate->attinmeta,
3885 fsstate->retrieved_attrs,
3886 node,
3887 fsstate->temp_cxt);
3888 }
3889
3890 /* Update fetch_ct_2 */
3891 if (fsstate->fetch_ct_2 < 2)
3892 fsstate->fetch_ct_2++;
3893
3894 /* Must be EOF if we didn't get as many tuples as we asked for. */
3895 fsstate->eof_reached = (numrows < fsstate->fetch_size);
3896 }
3897 PG_FINALLY();
3898 {
3899 PQclear(res);
3900 }
3901 PG_END_TRY();
3902
3903 MemoryContextSwitchTo(oldcontext);
3904 }
3905
3906 /*
3907 * Force assorted GUC parameters to settings that ensure that we'll output
3908 * data values in a form that is unambiguous to the remote server.
3909 *
3910 * This is rather expensive and annoying to do once per row, but there's
3911 * little choice if we want to be sure values are transmitted accurately;
3912 * we can't leave the settings in place between rows for fear of affecting
3913 * user-visible computations.
3914 *
3915 * We use the equivalent of a function SET option to allow the settings to
3916 * persist only until the caller calls reset_transmission_modes(). If an
3917 * error is thrown in between, guc.c will take care of undoing the settings.
3918 *
3919 * The return value is the nestlevel that must be passed to
3920 * reset_transmission_modes() to undo things.
3921 */
3922 int
3923 set_transmission_modes(void)
3924 {
3925 int nestlevel = NewGUCNestLevel();
3926
3927 /*
3928 * The values set here should match what pg_dump does. See also
3929 * configure_remote_session in connection.c.
3930 */
3931 if (DateStyle != USE_ISO_DATES)
3932 (void) set_config_option("datestyle", "ISO",
3933 PGC_USERSET, PGC_S_SESSION,
3934 GUC_ACTION_SAVE, true, 0, false);
3935 if (IntervalStyle != INTSTYLE_POSTGRES)
3936 (void) set_config_option("intervalstyle", "postgres",
3937 PGC_USERSET, PGC_S_SESSION,
3938 GUC_ACTION_SAVE, true, 0, false);
3939 if (extra_float_digits < 3)
3940 (void) set_config_option("extra_float_digits", "3",
3941 PGC_USERSET, PGC_S_SESSION,
3942 GUC_ACTION_SAVE, true, 0, false);
3943
3944 /*
3945 * In addition force restrictive search_path, in case there are any
3946 * regproc or similar constants to be printed.
3947 */
3948 (void) set_config_option("search_path", "pg_catalog",
3949 PGC_USERSET, PGC_S_SESSION,
3950 GUC_ACTION_SAVE, true, 0, false);
3951
3952 return nestlevel;
3953 }
3954
3955 /*
3956 * Undo the effects of set_transmission_modes().
3957 */
3958 void
3959 reset_transmission_modes(int nestlevel)
3960 {
3961 AtEOXact_GUC(true, nestlevel);
3962 }
3963
3964 /*
3965 * Utility routine to close a cursor.
3966 */
3967 static void
3968 close_cursor(PGconn *conn, unsigned int cursor_number,
3969 PgFdwConnState *conn_state)
3970 {
3971 char sql[64];
3972 PGresult *res;
3973
3974 snprintf(sql, sizeof(sql), "CLOSE c%u", cursor_number);
3975
3976 /*
3977 * We don't use a PG_TRY block here, so be careful not to throw error
3978 * without releasing the PGresult.
3979 */
3980 res = pgfdw_exec_query(conn, sql, conn_state);
3981 if (PQresultStatus(res) != PGRES_COMMAND_OK)
3982 pgfdw_report_error(ERROR, res, conn, true, sql);
3983 PQclear(res);
3984 }
3985
3986 /*
3987 * create_foreign_modify
3988 * Construct an execution state of a foreign insert/update/delete
3989 * operation
3990 */
3991 static PgFdwModifyState *
3992 create_foreign_modify(EState *estate,
3993 RangeTblEntry *rte,
3994 ResultRelInfo *resultRelInfo,
3995 CmdType operation,
3996 Plan *subplan,
3997 char *query,
3998 List *target_attrs,
3999 int values_end,
4000 bool has_returning,
4001 List *retrieved_attrs)
4002 {
4003 PgFdwModifyState *fmstate;
4004 Relation rel = resultRelInfo->ri_RelationDesc;
4005 TupleDesc tupdesc = RelationGetDescr(rel);
4006 Oid userid;
4007 ForeignTable *table;
4008 UserMapping *user;
4009 AttrNumber n_params;
4010 Oid typefnoid;
4011 bool isvarlena;
4012 ListCell *lc;
4013
4014 /* Begin constructing PgFdwModifyState. */
4015 fmstate = (PgFdwModifyState *) palloc0(sizeof(PgFdwModifyState));
4016 fmstate->rel = rel;
4017
4018 /* Identify which user to do the remote access as. */
4019 userid = ExecGetResultRelCheckAsUser(resultRelInfo, estate);
4020
4021 /* Get info about foreign table. */
4022 table = GetForeignTable(RelationGetRelid(rel));
4023 user = GetUserMapping(userid, table->serverid);
4024
4025 /* Open connection; report that we'll create a prepared statement. */
4026 fmstate->conn = GetConnection(user, true, &fmstate->conn_state);
4027 fmstate->p_name = NULL; /* prepared statement not made yet */
4028
4029 /* Set up remote query information. */
4030 fmstate->query = query;
4031 if (operation == CMD_INSERT)
4032 {
4033 fmstate->query = pstrdup(fmstate->query);
4034 fmstate->orig_query = pstrdup(fmstate->query);
4035 }
4036 fmstate->target_attrs = target_attrs;
4037 fmstate->values_end = values_end;
4038 fmstate->has_returning = has_returning;
4039 fmstate->retrieved_attrs = retrieved_attrs;
4040
4041 /* Create context for per-tuple temp workspace. */
4042 fmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
4043 "postgres_fdw temporary data",
4044 ALLOCSET_SMALL_SIZES);
4045
4046 /* Prepare for input conversion of RETURNING results. */
4047 if (fmstate->has_returning)
4048 fmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
4049
4050 /* Prepare for output conversion of parameters used in prepared stmt. */
4051 n_params = list_length(fmstate->target_attrs) + 1;
4052 fmstate->p_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * n_params);
4053 fmstate->p_nums = 0;
4054
4055 if (operation == CMD_UPDATE || operation == CMD_DELETE)
4056 {
4057 Assert(subplan != NULL);
4058
4059 /* Find the ctid resjunk column in the subplan's result */
4060 fmstate->ctidAttno = ExecFindJunkAttributeInTlist(subplan->targetlist,
4061 "ctid");
4062 if (!AttributeNumberIsValid(fmstate->ctidAttno))
4063 elog(ERROR, "could not find junk ctid column");
4064
4065 /* First transmittable parameter will be ctid */
4066 getTypeOutputInfo(TIDOID, &typefnoid, &isvarlena);
4067 fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4068 fmstate->p_nums++;
4069 }
4070
4071 if (operation == CMD_INSERT || operation == CMD_UPDATE)
4072 {
4073 /* Set up for remaining transmittable parameters */
4074 foreach(lc, fmstate->target_attrs)
4075 {
4076 int attnum = lfirst_int(lc);
4077 Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4078
4079 Assert(!attr->attisdropped);
4080
4081 /* Ignore generated columns; they are set to DEFAULT */
4082 if (attr->attgenerated)
4083 continue;
4084 getTypeOutputInfo(attr->atttypid, &typefnoid, &isvarlena);
4085 fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4086 fmstate->p_nums++;
4087 }
4088 }
4089
4090 Assert(fmstate->p_nums <= n_params);
4091
4092 /* Set batch_size from foreign server/table options. */
4093 if (operation == CMD_INSERT)
4094 fmstate->batch_size = get_batch_size_option(rel);
4095
4096 fmstate->num_slots = 1;
4097
4098 /* Initialize auxiliary state */
4099 fmstate->aux_fmstate = NULL;
4100
4101 return fmstate;
4102 }
4103
4104 /*
4105 * execute_foreign_modify
4106 * Perform foreign-table modification as required, and fetch RETURNING
4107 * result if any. (This is the shared guts of postgresExecForeignInsert,
4108 * postgresExecForeignBatchInsert, postgresExecForeignUpdate, and
4109 * postgresExecForeignDelete.)
4110 */
4111 static TupleTableSlot **
4112 execute_foreign_modify(EState *estate,
4113 ResultRelInfo *resultRelInfo,
4114 CmdType operation,
4115 TupleTableSlot **slots,
4116 TupleTableSlot **planSlots,
4117 int *numSlots)
4118 {
4119 PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
4120 ItemPointer ctid = NULL;
4121 const char **p_values;
4122 PGresult *res;
4123 int n_rows;
4124 StringInfoData sql;
4125
4126 /* The operation should be INSERT, UPDATE, or DELETE */
4127 Assert(operation == CMD_INSERT ||
4128 operation == CMD_UPDATE ||
4129 operation == CMD_DELETE);
4130
4131 /* First, process a pending asynchronous request, if any. */
4132 if (fmstate->conn_state->pendingAreq)
4133 process_pending_request(fmstate->conn_state->pendingAreq);
4134
4135 /*
4136 * If the existing query was deparsed and prepared for a different number
4137 * of rows, rebuild it for the proper number.
4138 */
4139 if (operation == CMD_INSERT && fmstate->num_slots != *numSlots)
4140 {
4141 /* Destroy the prepared statement created previously */
4142 if (fmstate->p_name)
4143 deallocate_query(fmstate);
4144
4145 /* Build INSERT string with numSlots records in its VALUES clause. */
4146 initStringInfo(&sql);
4147 rebuildInsertSql(&sql, fmstate->rel,
4148 fmstate->orig_query, fmstate->target_attrs,
4149 fmstate->values_end, fmstate->p_nums,
4150 *numSlots - 1);
4151 pfree(fmstate->query);
4152 fmstate->query = sql.data;
4153 fmstate->num_slots = *numSlots;
4154 }
4155
4156 /* Set up the prepared statement on the remote server, if we didn't yet */
4157 if (!fmstate->p_name)
4158 prepare_foreign_modify(fmstate);
4159
4160 /*
4161 * For UPDATE/DELETE, get the ctid that was passed up as a resjunk column
4162 */
4163 if (operation == CMD_UPDATE || operation == CMD_DELETE)
4164 {
4165 Datum datum;
4166 bool isNull;
4167
4168 datum = ExecGetJunkAttribute(planSlots[0],
4169 fmstate->ctidAttno,
4170 &isNull);
4171 /* shouldn't ever get a null result... */
4172 if (isNull)
4173 elog(ERROR, "ctid is NULL");
4174 ctid = (ItemPointer) DatumGetPointer(datum);
4175 }
4176
4177 /* Convert parameters needed by prepared statement to text form */
4178 p_values = convert_prep_stmt_params(fmstate, ctid, slots, *numSlots);
4179
4180 /*
4181 * Execute the prepared statement.
4182 */
4183 if (!PQsendQueryPrepared(fmstate->conn,
4184 fmstate->p_name,
4185 fmstate->p_nums * (*numSlots),
4186 p_values,
4187 NULL,
4188 NULL,
4189 0))
4190 pgfdw_report_error(ERROR, NULL, fmstate->conn, false, fmstate->query);
4191
4192 /*
4193 * Get the result, and check for success.
4194 *
4195 * We don't use a PG_TRY block here, so be careful not to throw error
4196 * without releasing the PGresult.
4197 */
4198 res = pgfdw_get_result(fmstate->conn);
4199 if (PQresultStatus(res) !=
4200 (fmstate->has_returning ? PGRES_TUPLES_OK : PGRES_COMMAND_OK))
4201 pgfdw_report_error(ERROR, res, fmstate->conn, true, fmstate->query);
4202
4203 /* Check number of rows affected, and fetch RETURNING tuple if any */
4204 if (fmstate->has_returning)
4205 {
4206 Assert(*numSlots == 1);
4207 n_rows = PQntuples(res);
4208 if (n_rows > 0)
4209 store_returning_result(fmstate, slots[0], res);
4210 }
4211 else
4212 n_rows = atoi(PQcmdTuples(res));
4213
4214 /* And clean up */
4215 PQclear(res);
4216
4217 MemoryContextReset(fmstate->temp_cxt);
4218
4219 *numSlots = n_rows;
4220
4221 /*
4222 * Return NULL if nothing was inserted/updated/deleted on the remote end
4223 */
4224 return (n_rows > 0) ? slots : NULL;
4225 }
4226
4227 /*
4228 * prepare_foreign_modify
4229 * Establish a prepared statement for execution of INSERT/UPDATE/DELETE
4230 */
4231 static void
4232 prepare_foreign_modify(PgFdwModifyState *fmstate)
4233 {
4234 char prep_name[NAMEDATALEN];
4235 char *p_name;
4236 PGresult *res;
4237
4238 /*
4239 * The caller would already have processed a pending asynchronous request
4240 * if any, so no need to do it here.
4241 */
4242
4243 /* Construct name we'll use for the prepared statement. */
4244 snprintf(prep_name, sizeof(prep_name), "pgsql_fdw_prep_%u",
4245 GetPrepStmtNumber(fmstate->conn));
4246 p_name = pstrdup(prep_name);
4247
4248 /*
4249 * We intentionally do not specify parameter types here, but leave the
4250 * remote server to derive them by default. This avoids possible problems
4251 * with the remote server using different type OIDs than we do. All of
4252 * the prepared statements we use in this module are simple enough that
4253 * the remote server will make the right choices.
4254 */
4255 if (!PQsendPrepare(fmstate->conn,
4256 p_name,
4257 fmstate->query,
4258 0,
4259 NULL))
4260 pgfdw_report_error(ERROR, NULL, fmstate->conn, false, fmstate->query);
4261
4262 /*
4263 * Get the result, and check for success.
4264 *
4265 * We don't use a PG_TRY block here, so be careful not to throw error
4266 * without releasing the PGresult.
4267 */
4268 res = pgfdw_get_result(fmstate->conn);
4269 if (PQresultStatus(res) != PGRES_COMMAND_OK)
4270 pgfdw_report_error(ERROR, res, fmstate->conn, true, fmstate->query);
4271 PQclear(res);
4272
4273 /* This action shows that the prepare has been done. */
4274 fmstate->p_name = p_name;
4275 }
4276
4277 /*
4278 * convert_prep_stmt_params
4279 * Create array of text strings representing parameter values
4280 *
4281 * tupleid is ctid to send, or NULL if none
4282 * slot is slot to get remaining parameters from, or NULL if none
4283 *
4284 * Data is constructed in temp_cxt; caller should reset that after use.
4285 */
4286 static const char **
4287 convert_prep_stmt_params(PgFdwModifyState *fmstate,
4288 ItemPointer tupleid,
4289 TupleTableSlot **slots,
4290 int numSlots)
4291 {
4292 const char **p_values;
4293 int i;
4294 int j;
4295 int pindex = 0;
4296 MemoryContext oldcontext;
4297
4298 oldcontext = MemoryContextSwitchTo(fmstate->temp_cxt);
4299
4300 p_values = (const char **) palloc(sizeof(char *) * fmstate->p_nums * numSlots);
4301
4302 /* ctid is provided only for UPDATE/DELETE, which don't allow batching */
4303 Assert(!(tupleid != NULL && numSlots > 1));
4304
4305 /* 1st parameter should be ctid, if it's in use */
4306 if (tupleid != NULL)
4307 {
4308 Assert(numSlots == 1);
4309 /* don't need set_transmission_modes for TID output */
4310 p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[pindex],
4311 PointerGetDatum(tupleid));
4312 pindex++;
4313 }
4314
4315 /* get following parameters from slots */
4316 if (slots != NULL && fmstate->target_attrs != NIL)
4317 {
4318 TupleDesc tupdesc = RelationGetDescr(fmstate->rel);
4319 int nestlevel;
4320 ListCell *lc;
4321
4322 nestlevel = set_transmission_modes();
4323
4324 for (i = 0; i < numSlots; i++)
4325 {
4326 j = (tupleid != NULL) ? 1 : 0;
4327 foreach(lc, fmstate->target_attrs)
4328 {
4329 int attnum = lfirst_int(lc);
4330 CompactAttribute *attr = TupleDescCompactAttr(tupdesc, attnum - 1);
4331 Datum value;
4332 bool isnull;
4333
4334 /* Ignore generated columns; they are set to DEFAULT */
4335 if (attr->attgenerated)
4336 continue;
4337 value = slot_getattr(slots[i], attnum, &isnull);
4338 if (isnull)
4339 p_values[pindex] = NULL;
4340 else
4341 p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[j],
4342 value);
4343 pindex++;
4344 j++;
4345 }
4346 }
4347
4348 reset_transmission_modes(nestlevel);
4349 }
4350
4351 Assert(pindex == fmstate->p_nums * numSlots);
4352
4353 MemoryContextSwitchTo(oldcontext);
4354
4355 return p_values;
4356 }
4357
4358 /*
4359 * store_returning_result
4360 * Store the result of a RETURNING clause
4361 *
4362 * On error, be sure to release the PGresult on the way out. Callers do not
4363 * have PG_TRY blocks to ensure this happens.
4364 */
4365 static void
4366 store_returning_result(PgFdwModifyState *fmstate,
4367 TupleTableSlot *slot, PGresult *res)
4368 {
4369 PG_TRY();
4370 {
4371 HeapTuple newtup;
4372
4373 newtup = make_tuple_from_result_row(res, 0,
4374 fmstate->rel,
4375 fmstate->attinmeta,
4376 fmstate->retrieved_attrs,
4377 NULL,
4378 fmstate->temp_cxt);
4379
4380 /*
4381 * The returning slot will not necessarily be suitable to store
4382 * heaptuples directly, so allow for conversion.
4383 */
4384 ExecForceStoreHeapTuple(newtup, slot, true);
4385 }
4386 PG_CATCH();
4387 {
4388 PQclear(res);
4389 PG_RE_THROW();
4390 }
4391 PG_END_TRY();
4392 }
4393
4394 /*
4395 * finish_foreign_modify
4396 * Release resources for a foreign insert/update/delete operation
4397 */
4398 static void
4399 finish_foreign_modify(PgFdwModifyState *fmstate)
4400 {
4401 Assert(fmstate != NULL);
4402
4403 /* If we created a prepared statement, destroy it */
4404 deallocate_query(fmstate);
4405
4406 /* Release remote connection */
4407 ReleaseConnection(fmstate->conn);
4408 fmstate->conn = NULL;
4409 }
4410
4411 /*
4412 * deallocate_query
4413 * Deallocate a prepared statement for a foreign insert/update/delete
4414 * operation
4415 */
4416 static void
4417 deallocate_query(PgFdwModifyState *fmstate)
4418 {
4419 char sql[64];
4420 PGresult *res;
4421
4422 /* do nothing if the query is not allocated */
4423 if (!fmstate->p_name)
4424 return;
4425
4426 snprintf(sql, sizeof(sql), "DEALLOCATE %s", fmstate->p_name);
4427
4428 /*
4429 * We don't use a PG_TRY block here, so be careful not to throw error
4430 * without releasing the PGresult.
4431 */
4432 res = pgfdw_exec_query(fmstate->conn, sql, fmstate->conn_state);
4433 if (PQresultStatus(res) != PGRES_COMMAND_OK)
4434 pgfdw_report_error(ERROR, res, fmstate->conn, true, sql);
4435 PQclear(res);
4436 pfree(fmstate->p_name);
4437 fmstate->p_name = NULL;
4438 }
4439
4440 /*
4441 * build_remote_returning
4442 * Build a RETURNING targetlist of a remote query for performing an
4443 * UPDATE/DELETE .. RETURNING on a join directly
4444 */
4445 static List *
4446 build_remote_returning(Index rtindex, Relation rel, List *returningList)
4447 {
4448 bool have_wholerow = false;
4449 List *tlist = NIL;
4450 List *vars;
4451 ListCell *lc;
4452
4453 Assert(returningList);
4454
4455 vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS);
4456
4457 /*
4458 * If there's a whole-row reference to the target relation, then we'll
4459 * need all the columns of the relation.
4460 */
4461 foreach(lc, vars)
4462 {
4463 Var *var = (Var *) lfirst(lc);
4464
4465 if (IsA(var, Var) &&
4466 var->varno == rtindex &&
4467 var->varattno == InvalidAttrNumber)
4468 {
4469 have_wholerow = true;
4470 break;
4471 }
4472 }
4473
4474 if (have_wholerow)
4475 {
4476 TupleDesc tupdesc = RelationGetDescr(rel);
4477 int i;
4478
4479 for (i = 1; i <= tupdesc->natts; i++)
4480 {
4481 Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
4482 Var *var;
4483
4484 /* Ignore dropped attributes. */
4485 if (attr->attisdropped)
4486 continue;
4487
4488 var = makeVar(rtindex,
4489 i,
4490 attr->atttypid,
4491 attr->atttypmod,
4492 attr->attcollation,
4493 0);
4494
4495 tlist = lappend(tlist,
4496 makeTargetEntry((Expr *) var,
4497 list_length(tlist) + 1,
4498 NULL,
4499 false));
4500 }
4501 }
4502
4503 /* Now add any remaining columns to tlist. */
4504 foreach(lc, vars)
4505 {
4506 Var *var = (Var *) lfirst(lc);
4507
4508 /*
4509 * No need for whole-row references to the target relation. We don't
4510 * need system columns other than ctid and oid either, since those are
4511 * set locally.
4512 */
4513 if (IsA(var, Var) &&
4514 var->varno == rtindex &&
4515 var->varattno <= InvalidAttrNumber &&
4516 var->varattno != SelfItemPointerAttributeNumber)
4517 continue; /* don't need it */
4518
4519 if (tlist_member((Expr *) var, tlist))
4520 continue; /* already got it */
4521
4522 tlist = lappend(tlist,
4523 makeTargetEntry((Expr *) var,
4524 list_length(tlist) + 1,
4525 NULL,
4526 false));
4527 }
4528
4529 list_free(vars);
4530
4531 return tlist;
4532 }
4533
4534 /*
4535 * rebuild_fdw_scan_tlist
4536 * Build new fdw_scan_tlist of given foreign-scan plan node from given
4537 * tlist
4538 *
4539 * There might be columns that the fdw_scan_tlist of the given foreign-scan
4540 * plan node contains that the given tlist doesn't. The fdw_scan_tlist would
4541 * have contained resjunk columns such as 'ctid' of the target relation and
4542 * 'wholerow' of non-target relations, but the tlist might not contain them,
4543 * for example. So, adjust the tlist so it contains all the columns specified
4544 * in the fdw_scan_tlist; else setrefs.c will get confused.
4545 */
4546 static void
4547 rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist)
4548 {
4549 List *new_tlist = tlist;
4550 List *old_tlist = fscan->fdw_scan_tlist;
4551 ListCell *lc;
4552
4553 foreach(lc, old_tlist)
4554 {
4555 TargetEntry *tle = (TargetEntry *) lfirst(lc);
4556
4557 if (tlist_member(tle->expr, new_tlist))
4558 continue; /* already got it */
4559
4560 new_tlist = lappend(new_tlist,
4561 makeTargetEntry(tle->expr,
4562 list_length(new_tlist) + 1,
4563 NULL,
4564 false));
4565 }
4566 fscan->fdw_scan_tlist = new_tlist;
4567 }
4568
4569 /*
4570 * Execute a direct UPDATE/DELETE statement.
4571 */
4572 static void
4573 execute_dml_stmt(ForeignScanState *node)
4574 {
4575 PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
4576 ExprContext *econtext = node->ss.ps.ps_ExprContext;
4577 int numParams = dmstate->numParams;
4578 const char **values = dmstate->param_values;
4579
4580 /* First, process a pending asynchronous request, if any. */
4581 if (dmstate->conn_state->pendingAreq)
4582 process_pending_request(dmstate->conn_state->pendingAreq);
4583
4584 /*
4585 * Construct array of query parameter values in text format.
4586 */
4587 if (numParams > 0)
4588 process_query_params(econtext,
4589 dmstate->param_flinfo,
4590 dmstate->param_exprs,
4591 values);
4592
4593 /*
4594 * Notice that we pass NULL for paramTypes, thus forcing the remote server
4595 * to infer types for all parameters. Since we explicitly cast every
4596 * parameter (see deparse.c), the "inference" is trivial and will produce
4597 * the desired result. This allows us to avoid assuming that the remote
4598 * server has the same OIDs we do for the parameters' types.
4599 */
4600 if (!PQsendQueryParams(dmstate->conn, dmstate->query, numParams,
4601 NULL, values, NULL, NULL, 0))
4602 pgfdw_report_error(ERROR, NULL, dmstate->conn, false, dmstate->query);
4603
4604 /*
4605 * Get the result, and check for success.
4606 *
4607 * We use a memory context callback to ensure that the PGresult will be
4608 * released, even if the query fails somewhere that's outside our control.
4609 * The callback is already registered, just need to fill in its arg.
4610 */
4611 Assert(dmstate->result == NULL);
4612 dmstate->result = pgfdw_get_result(dmstate->conn);
4613 dmstate->result_cb.arg = dmstate->result;
4614
4615 if (PQresultStatus(dmstate->result) !=
4616 (dmstate->has_returning ? PGRES_TUPLES_OK : PGRES_COMMAND_OK))
4617 pgfdw_report_error(ERROR, dmstate->result, dmstate->conn, false,
4618 dmstate->query);
4619
4620 /* Get the number of rows affected. */
4621 if (dmstate->has_returning)
4622 dmstate->num_tuples = PQntuples(dmstate->result);
4623 else
4624 dmstate->num_tuples = atoi(PQcmdTuples(dmstate->result));
4625 }
4626
4627 /*
4628 * Get the result of a RETURNING clause.
4629 */
4630 static TupleTableSlot *
4631 get_returning_data(ForeignScanState *node)
4632 {
4633 PgFdwDirectModifyState *dmstate = (PgFdwDirectModifyState *) node->fdw_state;
4634 EState *estate = node->ss.ps.state;
4635 ResultRelInfo *resultRelInfo = node->resultRelInfo;
4636 TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
4637 TupleTableSlot *resultSlot;
4638
4639 Assert(resultRelInfo->ri_projectReturning);
4640
4641 /* If we didn't get any tuples, must be end of data. */
4642 if (dmstate->next_tuple >= dmstate->num_tuples)
4643 return ExecClearTuple(slot);
4644
4645 /* Increment the command es_processed count if necessary. */
4646 if (dmstate->set_processed)
4647 estate->es_processed += 1;
4648
4649 /*
4650 * Store a RETURNING tuple. If has_returning is false, just emit a dummy
4651 * tuple. (has_returning is false when the local query is of the form
4652 * "UPDATE/DELETE .. RETURNING 1" for example.)
4653 */
4654 if (!dmstate->has_returning)
4655 {
4656 ExecStoreAllNullTuple(slot);
4657 resultSlot = slot;
4658 }
4659 else
4660 {
4661 HeapTuple newtup;
4662
4663 newtup = make_tuple_from_result_row(dmstate->result,
4664 dmstate->next_tuple,
4665 dmstate->rel,
4666 dmstate->attinmeta,
4667 dmstate->retrieved_attrs,
4668 node,
4669 dmstate->temp_cxt);
4670 ExecStoreHeapTuple(newtup, slot, false);
4671 /* Get the updated/deleted tuple. */
4672 if (dmstate->rel)
4673 resultSlot = slot;
4674 else
4675 resultSlot = apply_returning_filter(dmstate, resultRelInfo, slot, estate);
4676 }
4677 dmstate->next_tuple++;
4678
4679 /* Make slot available for evaluation of the local query RETURNING list. */
4680 resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple =
4681 resultSlot;
4682
4683 return slot;
4684 }
4685
4686 /*
4687 * Initialize a filter to extract an updated/deleted tuple from a scan tuple.
4688 */
4689 static void
4690 init_returning_filter(PgFdwDirectModifyState *dmstate,
4691 List *fdw_scan_tlist,
4692 Index rtindex)
4693 {
4694 TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4695 ListCell *lc;
4696 int i;
4697
4698 /*
4699 * Calculate the mapping between the fdw_scan_tlist's entries and the
4700 * result tuple's attributes.
4701 *
4702 * The "map" is an array of indexes of the result tuple's attributes in
4703 * fdw_scan_tlist, i.e., one entry for every attribute of the result
4704 * tuple. We store zero for any attributes that don't have the
4705 * corresponding entries in that list, marking that a NULL is needed in
4706 * the result tuple.
4707 *
4708 * Also get the indexes of the entries for ctid and oid if any.
4709 */
4710 dmstate->attnoMap = (AttrNumber *)
4711 palloc0(resultTupType->natts * sizeof(AttrNumber));
4712
4713 dmstate->ctidAttno = dmstate->oidAttno = 0;
4714
4715 i = 1;
4716 dmstate->hasSystemCols = false;
4717 foreach(lc, fdw_scan_tlist)
4718 {
4719 TargetEntry *tle = (TargetEntry *) lfirst(lc);
4720 Var *var = (Var *) tle->expr;
4721
4722 Assert(IsA(var, Var));
4723
4724 /*
4725 * If the Var is a column of the target relation to be retrieved from
4726 * the foreign server, get the index of the entry.
4727 */
4728 if (var->varno == rtindex &&
4729 list_member_int(dmstate->retrieved_attrs, i))
4730 {
4731 int attrno = var->varattno;
4732
4733 if (attrno < 0)
4734 {
4735 /*
4736 * We don't retrieve system columns other than ctid and oid.
4737 */
4738 if (attrno == SelfItemPointerAttributeNumber)
4739 dmstate->ctidAttno = i;
4740 else
4741 Assert(false);
4742 dmstate->hasSystemCols = true;
4743 }
4744 else
4745 {
4746 /*
4747 * We don't retrieve whole-row references to the target
4748 * relation either.
4749 */
4750 Assert(attrno > 0);
4751
4752 dmstate->attnoMap[attrno - 1] = i;
4753 }
4754 }
4755 i++;
4756 }
4757 }
4758
4759 /*
4760 * Extract and return an updated/deleted tuple from a scan tuple.
4761 */
4762 static TupleTableSlot *
4763 apply_returning_filter(PgFdwDirectModifyState *dmstate,
4764 ResultRelInfo *resultRelInfo,
4765 TupleTableSlot *slot,
4766 EState *estate)
4767 {
4768 TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4769 TupleTableSlot *resultSlot;
4770 Datum *values;
4771 bool *isnull;
4772 Datum *old_values;
4773 bool *old_isnull;
4774 int i;
4775
4776 /*
4777 * Use the return tuple slot as a place to store the result tuple.
4778 */
4779 resultSlot = ExecGetReturningSlot(estate, resultRelInfo);
4780
4781 /*
4782 * Extract all the values of the scan tuple.
4783 */
4784 slot_getallattrs(slot);
4785 old_values = slot->tts_values;
4786 old_isnull = slot->tts_isnull;
4787
4788 /*
4789 * Prepare to build the result tuple.
4790 */
4791 ExecClearTuple(resultSlot);
4792 values = resultSlot->tts_values;
4793 isnull = resultSlot->tts_isnull;
4794
4795 /*
4796 * Transpose data into proper fields of the result tuple.
4797 */
4798 for (i = 0; i < resultTupType->natts; i++)
4799 {
4800 int j = dmstate->attnoMap[i];
4801
4802 if (j == 0)
4803 {
4804 values[i] = (Datum) 0;
4805 isnull[i] = true;
4806 }
4807 else
4808 {
4809 values[i] = old_values[j - 1];
4810 isnull[i] = old_isnull[j - 1];
4811 }
4812 }
4813
4814 /*
4815 * Build the virtual tuple.
4816 */
4817 ExecStoreVirtualTuple(resultSlot);
4818
4819 /*
4820 * If we have any system columns to return, materialize a heap tuple in
4821 * the slot from column values set above and install system columns in
4822 * that tuple.
4823 */
4824 if (dmstate->hasSystemCols)
4825 {
4826 HeapTuple resultTup = ExecFetchSlotHeapTuple(resultSlot, true, NULL);
4827
4828 /* ctid */
4829 if (dmstate->ctidAttno)
4830 {
4831 ItemPointer ctid = NULL;
4832
4833 ctid = (ItemPointer) DatumGetPointer(old_values[dmstate->ctidAttno - 1]);
4834 resultTup->t_self = *ctid;
4835 }
4836
4837 /*
4838 * And remaining columns
4839 *
4840 * Note: since we currently don't allow the target relation to appear
4841 * on the nullable side of an outer join, any system columns wouldn't
4842 * go to NULL.
4843 *
4844 * Note: no need to care about tableoid here because it will be
4845 * initialized in ExecProcessReturning().
4846 */
4847 HeapTupleHeaderSetXmin(resultTup->t_data, InvalidTransactionId);
4848 HeapTupleHeaderSetXmax(resultTup->t_data, InvalidTransactionId);
4849 HeapTupleHeaderSetCmin(resultTup->t_data, InvalidTransactionId);
4850 }
4851
4852 /*
4853 * And return the result tuple.
4854 */
4855 return resultSlot;
4856 }
4857
4858 /*
4859 * Prepare for processing of parameters used in remote query.
4860 */
4861 static void
4862 prepare_query_params(PlanState *node,
4863 List *fdw_exprs,
4864 int numParams,
4865 FmgrInfo **param_flinfo,
4866 List **param_exprs,
4867 const char ***param_values)
4868 {
4869 int i;
4870 ListCell *lc;
4871
4872 Assert(numParams > 0);
4873
4874 /* Prepare for output conversion of parameters used in remote query. */
4875 *param_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * numParams);
4876
4877 i = 0;
4878 foreach(lc, fdw_exprs)
4879 {
4880 Node *param_expr = (Node *) lfirst(lc);
4881 Oid typefnoid;
4882 bool isvarlena;
4883
4884 getTypeOutputInfo(exprType(param_expr), &typefnoid, &isvarlena);
4885 fmgr_info(typefnoid, &(*param_flinfo)[i]);
4886 i++;
4887 }
4888
4889 /*
4890 * Prepare remote-parameter expressions for evaluation. (Note: in
4891 * practice, we expect that all these expressions will be just Params, so
4892 * we could possibly do something more efficient than using the full
4893 * expression-eval machinery for this. But probably there would be little
4894 * benefit, and it'd require postgres_fdw to know more than is desirable
4895 * about Param evaluation.)
4896 */
4897 *param_exprs = ExecInitExprList(fdw_exprs, node);
4898
4899 /* Allocate buffer for text form of query parameters. */
4900 *param_values = (const char **) palloc0(numParams * sizeof(char *));
4901 }
4902
4903 /*
4904 * Construct array of query parameter values in text format.
4905 */
4906 static void
4907 process_query_params(ExprContext *econtext,
4908 FmgrInfo *param_flinfo,
4909 List *param_exprs,
4910 const char **param_values)
4911 {
4912 int nestlevel;
4913 int i;
4914 ListCell *lc;
4915
4916 nestlevel = set_transmission_modes();
4917
4918 i = 0;
4919 foreach(lc, param_exprs)
4920 {
4921 ExprState *expr_state = (ExprState *) lfirst(lc);
4922 Datum expr_value;
4923 bool isNull;
4924
4925 /* Evaluate the parameter expression */
4926 expr_value = ExecEvalExpr(expr_state, econtext, &isNull);
4927
4928 /*
4929 * Get string representation of each parameter value by invoking
4930 * type-specific output function, unless the value is null.
4931 */
4932 if (isNull)
4933 param_values[i] = NULL;
4934 else
4935 param_values[i] = OutputFunctionCall(&param_flinfo[i], expr_value);
4936
4937 i++;
4938 }
4939
4940 reset_transmission_modes(nestlevel);
4941 }
4942
4943 /*
4944 * postgresAnalyzeForeignTable
4945 * Test whether analyzing this foreign table is supported
4946 */
4947 static bool
4948 postgresAnalyzeForeignTable(Relation relation,
4949 AcquireSampleRowsFunc *func,
4950 BlockNumber *totalpages)
4951 {
4952 ForeignTable *table;
4953 UserMapping *user;
4954 PGconn *conn;
4955 StringInfoData sql;
4956 PGresult *volatile res = NULL;
4957
4958 /* Return the row-analysis function pointer */
4959 *func = postgresAcquireSampleRowsFunc;
4960
4961 /*
4962 * Now we have to get the number of pages. It's annoying that the ANALYZE
4963 * API requires us to return that now, because it forces some duplication
4964 * of effort between this routine and postgresAcquireSampleRowsFunc. But
4965 * it's probably not worth redefining that API at this point.
4966 */
4967
4968 /*
4969 * Get the connection to use. We do the remote access as the table's
4970 * owner, even if the ANALYZE was started by some other user.
4971 */
4972 table = GetForeignTable(RelationGetRelid(relation));
4973 user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
4974 conn = GetConnection(user, false, NULL);
4975
4976 /*
4977 * Construct command to get page count for relation.
4978 */
4979 initStringInfo(&sql);
4980 deparseAnalyzeSizeSql(&sql, relation);
4981
4982 /* In what follows, do not risk leaking any PGresults. */
4983 PG_TRY();
4984 {
4985 res = pgfdw_exec_query(conn, sql.data, NULL);
4986 if (PQresultStatus(res) != PGRES_TUPLES_OK)
4987 pgfdw_report_error(ERROR, res, conn, false, sql.data);
4988
4989 if (PQntuples(res) != 1 || PQnfields(res) != 1)
4990 elog(ERROR, "unexpected result from deparseAnalyzeSizeSql query");
4991 *totalpages = strtoul(PQgetvalue(res, 0, 0), NULL, 10);
4992 }
4993 PG_FINALLY();
4994 {
4995 PQclear(res);
4996 }
4997 PG_END_TRY();
4998
4999 ReleaseConnection(conn);
5000
5001 return true;
5002 }
5003
5004 /*
5005 * postgresGetAnalyzeInfoForForeignTable
5006 * Count tuples in foreign table (just get pg_class.reltuples).
5007 *
5008 * can_tablesample determines if the remote relation supports acquiring the
5009 * sample using TABLESAMPLE.
5010 */
5011 static double
5012 postgresGetAnalyzeInfoForForeignTable(Relation relation, bool *can_tablesample)
5013 {
5014 ForeignTable *table;
5015 UserMapping *user;
5016 PGconn *conn;
5017 StringInfoData sql;
5018 PGresult *volatile res = NULL;
5019 volatile double reltuples = -1;
5020 volatile char relkind = 0;
5021
5022 /* assume the remote relation does not support TABLESAMPLE */
5023 *can_tablesample = false;
5024
5025 /*
5026 * Get the connection to use. We do the remote access as the table's
5027 * owner, even if the ANALYZE was started by some other user.
5028 */
5029 table = GetForeignTable(RelationGetRelid(relation));
5030 user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
5031 conn = GetConnection(user, false, NULL);
5032
5033 /*
5034 * Construct command to get page count for relation.
5035 */
5036 initStringInfo(&sql);
5037 deparseAnalyzeInfoSql(&sql, relation);
5038
5039 /* In what follows, do not risk leaking any PGresults. */
5040 PG_TRY();
5041 {
5042 res = pgfdw_exec_query(conn, sql.data, NULL);
5043 if (PQresultStatus(res) != PGRES_TUPLES_OK)
5044 pgfdw_report_error(ERROR, res, conn, false, sql.data);
5045
5046 if (PQntuples(res) != 1 || PQnfields(res) != 2)
5047 elog(ERROR, "unexpected result from deparseAnalyzeInfoSql query");
5048 reltuples = strtod(PQgetvalue(res, 0, 0), NULL);
5049 relkind = *(PQgetvalue(res, 0, 1));
5050 }
5051 PG_FINALLY();
5052 {
5053 if (res)
5054 PQclear(res);
5055 }
5056 PG_END_TRY();
5057
5058 ReleaseConnection(conn);
5059
5060 /* TABLESAMPLE is supported only for regular tables and matviews */
5061 *can_tablesample = (relkind == RELKIND_RELATION ||
5062 relkind == RELKIND_MATVIEW ||
5063 relkind == RELKIND_PARTITIONED_TABLE);
5064
5065 return reltuples;
5066 }
5067
5068 /*
5069 * Acquire a random sample of rows from foreign table managed by postgres_fdw.
5070 *
5071 * Selected rows are returned in the caller-allocated array rows[],
5072 * which must have at least targrows entries.
5073 * The actual number of rows selected is returned as the function result.
5074 * We also count the total number of rows in the table and return it into
5075 * *totalrows. Note that *totaldeadrows is always set to 0.
5076 *
5077 * Note that the returned list of rows is not always in order by physical
5078 * position in the table. Therefore, correlation estimates derived later
5079 * may be meaningless, but it's OK because we don't use the estimates
5080 * currently (the planner only pays attention to correlation for indexscans).
5081 */
5082 static int
5083 postgresAcquireSampleRowsFunc(Relation relation, int elevel,
5084 HeapTuple *rows, int targrows,
5085 double *totalrows,
5086 double *totaldeadrows)
5087 {
5088 PgFdwAnalyzeState astate;
5089 ForeignTable *table;
5090 ForeignServer *server;
5091 UserMapping *user;
5092 PGconn *conn;
5093 int server_version_num;
5094 PgFdwSamplingMethod method = ANALYZE_SAMPLE_AUTO; /* auto is default */
5095 double sample_frac = -1.0;
5096 double reltuples;
5097 unsigned int cursor_number;
5098 StringInfoData sql;
5099 PGresult *volatile res = NULL;
5100 ListCell *lc;
5101
5102 /* Initialize workspace state */
5103 astate.rel = relation;
5104 astate.attinmeta = TupleDescGetAttInMetadata(RelationGetDescr(relation));
5105
5106 astate.rows = rows;
5107 astate.targrows = targrows;
5108 astate.numrows = 0;
5109 astate.samplerows = 0;
5110 astate.rowstoskip = -1; /* -1 means not set yet */
5111 reservoir_init_selection_state(&astate.rstate, targrows);
5112
5113 /* Remember ANALYZE context, and create a per-tuple temp context */
5114 astate.anl_cxt = CurrentMemoryContext;
5115 astate.temp_cxt = AllocSetContextCreate(CurrentMemoryContext,
5116 "postgres_fdw temporary data",
5117 ALLOCSET_SMALL_SIZES);
5118
5119 /*
5120 * Get the connection to use. We do the remote access as the table's
5121 * owner, even if the ANALYZE was started by some other user.
5122 */
5123 table = GetForeignTable(RelationGetRelid(relation));
5124 server = GetForeignServer(table->serverid);
5125 user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
5126 conn = GetConnection(user, false, NULL);
5127
5128 /* We'll need server version, so fetch it now. */
5129 server_version_num = PQserverVersion(conn);
5130
5131 /*
5132 * What sampling method should we use?
5133 */
5134 foreach(lc, server->options)
5135 {
5136 DefElem *def = (DefElem *) lfirst(lc);
5137
5138 if (strcmp(def->defname, "analyze_sampling") == 0)
5139 {
5140 char *value = defGetString(def);
5141
5142 if (strcmp(value, "off") == 0)
5143 method = ANALYZE_SAMPLE_OFF;
5144 else if (strcmp(value, "auto") == 0)
5145 method = ANALYZE_SAMPLE_AUTO;
5146 else if (strcmp(value, "random") == 0)
5147 method = ANALYZE_SAMPLE_RANDOM;
5148 else if (strcmp(value, "system") == 0)
5149 method = ANALYZE_SAMPLE_SYSTEM;
5150 else if (strcmp(value, "bernoulli") == 0)
5151 method = ANALYZE_SAMPLE_BERNOULLI;
5152
5153 break;
5154 }
5155 }
5156
5157 foreach(lc, table->options)
5158 {
5159 DefElem *def = (DefElem *) lfirst(lc);
5160
5161 if (strcmp(def->defname, "analyze_sampling") == 0)
5162 {
5163 char *value = defGetString(def);
5164
5165 if (strcmp(value, "off") == 0)
5166 method = ANALYZE_SAMPLE_OFF;
5167 else if (strcmp(value, "auto") == 0)
5168 method = ANALYZE_SAMPLE_AUTO;
5169 else if (strcmp(value, "random") == 0)
5170 method = ANALYZE_SAMPLE_RANDOM;
5171 else if (strcmp(value, "system") == 0)
5172 method = ANALYZE_SAMPLE_SYSTEM;
5173 else if (strcmp(value, "bernoulli") == 0)
5174 method = ANALYZE_SAMPLE_BERNOULLI;
5175
5176 break;
5177 }
5178 }
5179
5180 /*
5181 * Error-out if explicitly required one of the TABLESAMPLE methods, but
5182 * the server does not support it.
5183 */
5184 if ((server_version_num < 95000) &&
5185 (method == ANALYZE_SAMPLE_SYSTEM ||
5186 method == ANALYZE_SAMPLE_BERNOULLI))
5187 ereport(ERROR,
5188 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5189 errmsg("remote server does not support TABLESAMPLE feature")));
5190
5191 /*
5192 * If we've decided to do remote sampling, calculate the sampling rate. We
5193 * need to get the number of tuples from the remote server, but skip that
5194 * network round-trip if not needed.
5195 */
5196 if (method != ANALYZE_SAMPLE_OFF)
5197 {
5198 bool can_tablesample;
5199
5200 reltuples = postgresGetAnalyzeInfoForForeignTable(relation,
5201 &can_tablesample);
5202
5203 /*
5204 * Make sure we're not choosing TABLESAMPLE when the remote relation
5205 * does not support that. But only do this for "auto" - if the user
5206 * explicitly requested BERNOULLI/SYSTEM, it's better to fail.
5207 */
5208 if (!can_tablesample && (method == ANALYZE_SAMPLE_AUTO))
5209 method = ANALYZE_SAMPLE_RANDOM;
5210
5211 /*
5212 * Remote's reltuples could be 0 or -1 if the table has never been
5213 * vacuumed/analyzed. In that case, disable sampling after all.
5214 */
5215 if ((reltuples <= 0) || (targrows >= reltuples))
5216 method = ANALYZE_SAMPLE_OFF;
5217 else
5218 {
5219 /*
5220 * All supported sampling methods require sampling rate, not
5221 * target rows directly, so we calculate that using the remote
5222 * reltuples value. That's imperfect, because it might be off a
5223 * good deal, but that's not something we can (or should) address
5224 * here.
5225 *
5226 * If reltuples is too low (i.e. when table grew), we'll end up
5227 * sampling more rows - but then we'll apply the local sampling,
5228 * so we get the expected sample size. This is the same outcome as
5229 * without remote sampling.
5230 *
5231 * If reltuples is too high (e.g. after bulk DELETE), we will end
5232 * up sampling too few rows.
5233 *
5234 * We can't really do much better here - we could try sampling a
5235 * bit more rows, but we don't know how off the reltuples value is
5236 * so how much is "a bit more"?
5237 *
5238 * Furthermore, the targrows value for partitions is determined
5239 * based on table size (relpages), which can be off in different
5240 * ways too. Adjusting the sampling rate here might make the issue
5241 * worse.
5242 */
5243 sample_frac = targrows / reltuples;
5244
5245 /*
5246 * We should never get sampling rate outside the valid range
5247 * (between 0.0 and 1.0), because those cases should be covered by
5248 * the previous branch that sets ANALYZE_SAMPLE_OFF.
5249 */
5250 Assert(sample_frac >= 0.0 && sample_frac <= 1.0);
5251 }
5252 }
5253
5254 /*
5255 * For "auto" method, pick the one we believe is best. For servers with
5256 * TABLESAMPLE support we pick BERNOULLI, for old servers we fall-back to
5257 * random() to at least reduce network transfer.
5258 */
5259 if (method == ANALYZE_SAMPLE_AUTO)
5260 {
5261 if (server_version_num < 95000)
5262 method = ANALYZE_SAMPLE_RANDOM;
5263 else
5264 method = ANALYZE_SAMPLE_BERNOULLI;
5265 }
5266
5267 /*
5268 * Construct cursor that retrieves whole rows from remote.
5269 */
5270 cursor_number = GetCursorNumber(conn);
5271 initStringInfo(&sql);
5272 appendStringInfo(&sql, "DECLARE c%u CURSOR FOR ", cursor_number);
5273
5274 deparseAnalyzeSql(&sql, relation, method, sample_frac, &astate.retrieved_attrs);
5275
5276 /* In what follows, do not risk leaking any PGresults. */
5277 PG_TRY();
5278 {
5279 char fetch_sql[64];
5280 int fetch_size;
5281
5282 res = pgfdw_exec_query(conn, sql.data, NULL);
5283 if (PQresultStatus(res) != PGRES_COMMAND_OK)
5284 pgfdw_report_error(ERROR, res, conn, false, sql.data);
5285 PQclear(res);
5286 res = NULL;
5287
5288 /*
5289 * Determine the fetch size. The default is arbitrary, but shouldn't
5290 * be enormous.
5291 */
5292 fetch_size = 100;
5293 foreach(lc, server->options)
5294 {
5295 DefElem *def = (DefElem *) lfirst(lc);
5296
5297 if (strcmp(def->defname, "fetch_size") == 0)
5298 {
5299 (void) parse_int(defGetString(def), &fetch_size, 0, NULL);
5300 break;
5301 }
5302 }
5303 foreach(lc, table->options)
5304 {
5305 DefElem *def = (DefElem *) lfirst(lc);
5306
5307 if (strcmp(def->defname, "fetch_size") == 0)
5308 {
5309 (void) parse_int(defGetString(def), &fetch_size, 0, NULL);
5310 break;
5311 }
5312 }
5313
5314 /* Construct command to fetch rows from remote. */
5315 snprintf(fetch_sql, sizeof(fetch_sql), "FETCH %d FROM c%u",
5316 fetch_size, cursor_number);
5317
5318 /* Retrieve and process rows a batch at a time. */
5319 for (;;)
5320 {
5321 int numrows;
5322 int i;
5323
5324 /* Allow users to cancel long query */
5325 CHECK_FOR_INTERRUPTS();
5326
5327 /*
5328 * XXX possible future improvement: if rowstoskip is large, we
5329 * could issue a MOVE rather than physically fetching the rows,
5330 * then just adjust rowstoskip and samplerows appropriately.
5331 */
5332
5333 /* Fetch some rows */
5334 res = pgfdw_exec_query(conn, fetch_sql, NULL);
5335 /* On error, report the original query, not the FETCH. */
5336 if (PQresultStatus(res) != PGRES_TUPLES_OK)
5337 pgfdw_report_error(ERROR, res, conn, false, sql.data);
5338
5339 /* Process whatever we got. */
5340 numrows = PQntuples(res);
5341 for (i = 0; i < numrows; i++)
5342 analyze_row_processor(res, i, &astate);
5343
5344 PQclear(res);
5345 res = NULL;
5346
5347 /* Must be EOF if we didn't get all the rows requested. */
5348 if (numrows < fetch_size)
5349 break;
5350 }
5351
5352 /* Close the cursor, just to be tidy. */
5353 close_cursor(conn, cursor_number, NULL);
5354 }
5355 PG_CATCH();
5356 {
5357 PQclear(res);
5358 PG_RE_THROW();
5359 }
5360 PG_END_TRY();
5361
5362 ReleaseConnection(conn);
5363
5364 /* We assume that we have no dead tuple. */
5365 *totaldeadrows = 0.0;
5366
5367 /*
5368 * Without sampling, we've retrieved all living tuples from foreign
5369 * server, so report that as totalrows. Otherwise use the reltuples
5370 * estimate we got from the remote side.
5371 */
5372 if (method == ANALYZE_SAMPLE_OFF)
5373 *totalrows = astate.samplerows;
5374 else
5375 *totalrows = reltuples;
5376
5377 /*
5378 * Emit some interesting relation info
5379 */
5380 ereport(elevel,
5381 (errmsg("\"%s\": table contains %.0f rows, %d rows in sample",
5382 RelationGetRelationName(relation),
5383 *totalrows, astate.numrows)));
5384
5385 return astate.numrows;
5386 }
5387
5388 /*
5389 * Collect sample rows from the result of query.
5390 * - Use all tuples in sample until target # of samples are collected.
5391 * - Subsequently, replace already-sampled tuples randomly.
5392 */
5393 static void
5394 analyze_row_processor(PGresult *res, int row, PgFdwAnalyzeState *astate)
5395 {
5396 int targrows = astate->targrows;
5397 int pos; /* array index to store tuple in */
5398 MemoryContext oldcontext;
5399
5400 /* Always increment sample row counter. */
5401 astate->samplerows += 1;
5402
5403 /*
5404 * Determine the slot where this sample row should be stored. Set pos to
5405 * negative value to indicate the row should be skipped.
5406 */
5407 if (astate->numrows < targrows)
5408 {
5409 /* First targrows rows are always included into the sample */
5410 pos = astate->numrows++;
5411 }
5412 else
5413 {
5414 /*
5415 * Now we start replacing tuples in the sample until we reach the end
5416 * of the relation. Same algorithm as in acquire_sample_rows in
5417 * analyze.c; see Jeff Vitter's paper.
5418 */
5419 if (astate->rowstoskip < 0)
5420 astate->rowstoskip = reservoir_get_next_S(&astate->rstate, astate->samplerows, targrows);
5421
5422 if (astate->rowstoskip <= 0)
5423 {
5424 /* Choose a random reservoir element to replace. */
5425 pos = (int) (targrows * sampler_random_fract(&astate->rstate.randstate));
5426 Assert(pos >= 0 && pos < targrows);
5427 heap_freetuple(astate->rows[pos]);
5428 }
5429 else
5430 {
5431 /* Skip this tuple. */
5432 pos = -1;
5433 }
5434
5435 astate->rowstoskip -= 1;
5436 }
5437
5438 if (pos >= 0)
5439 {
5440 /*
5441 * Create sample tuple from current result row, and store it in the
5442 * position determined above. The tuple has to be created in anl_cxt.
5443 */
5444 oldcontext = MemoryContextSwitchTo(astate->anl_cxt);
5445
5446 astate->rows[pos] = make_tuple_from_result_row(res, row,
5447 astate->rel,
5448 astate->attinmeta,
5449 astate->retrieved_attrs,
5450 NULL,
5451 astate->temp_cxt);
5452
5453 MemoryContextSwitchTo(oldcontext);
5454 }
5455 }
5456
5457 /*
5458 * Import a foreign schema
5459 */
5460 static List *
5461 postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid)
5462 {
5463 List *commands = NIL;
5464 bool import_collate = true;
5465 bool import_default = false;
5466 bool import_generated = true;
5467 bool import_not_null = true;
5468 ForeignServer *server;
5469 UserMapping *mapping;
5470 PGconn *conn;
5471 StringInfoData buf;
5472 PGresult *volatile res = NULL;
5473 int numrows,
5474 i;
5475 ListCell *lc;
5476
5477 /* Parse statement options */
5478 foreach(lc, stmt->options)
5479 {
5480 DefElem *def = (DefElem *) lfirst(lc);
5481
5482 if (strcmp(def->defname, "import_collate") == 0)
5483 import_collate = defGetBoolean(def);
5484 else if (strcmp(def->defname, "import_default") == 0)
5485 import_default = defGetBoolean(def);
5486 else if (strcmp(def->defname, "import_generated") == 0)
5487 import_generated = defGetBoolean(def);
5488 else if (strcmp(def->defname, "import_not_null") == 0)
5489 import_not_null = defGetBoolean(def);
5490 else
5491 ereport(ERROR,
5492 (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
5493 errmsg("invalid option \"%s\"", def->defname)));
5494 }
5495
5496 /*
5497 * Get connection to the foreign server. Connection manager will
5498 * establish new connection if necessary.
5499 */
5500 server = GetForeignServer(serverOid);
5501 mapping = GetUserMapping(GetUserId(), server->serverid);
5502 conn = GetConnection(mapping, false, NULL);
5503
5504 /* Don't attempt to import collation if remote server hasn't got it */
5505 if (PQserverVersion(conn) < 90100)
5506 import_collate = false;
5507
5508 /* Create workspace for strings */
5509 initStringInfo(&buf);
5510
5511 /* In what follows, do not risk leaking any PGresults. */
5512 PG_TRY();
5513 {
5514 /* Check that the schema really exists */
5515 appendStringInfoString(&buf, "SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ");
5516 deparseStringLiteral(&buf, stmt->remote_schema);
5517
5518 res = pgfdw_exec_query(conn, buf.data, NULL);
5519 if (PQresultStatus(res) != PGRES_TUPLES_OK)
5520 pgfdw_report_error(ERROR, res, conn, false, buf.data);
5521
5522 if (PQntuples(res) != 1)
5523 ereport(ERROR,
5524 (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
5525 errmsg("schema \"%s\" is not present on foreign server \"%s\"",
5526 stmt->remote_schema, server->servername)));
5527
5528 PQclear(res);
5529 res = NULL;
5530 resetStringInfo(&buf);
5531
5532 /*
5533 * Fetch all table data from this schema, possibly restricted by
5534 * EXCEPT or LIMIT TO. (We don't actually need to pay any attention
5535 * to EXCEPT/LIMIT TO here, because the core code will filter the
5536 * statements we return according to those lists anyway. But it
5537 * should save a few cycles to not process excluded tables in the
5538 * first place.)
5539 *
5540 * Import table data for partitions only when they are explicitly
5541 * specified in LIMIT TO clause. Otherwise ignore them and only
5542 * include the definitions of the root partitioned tables to allow
5543 * access to the complete remote data set locally in the schema
5544 * imported.
5545 *
5546 * Note: because we run the connection with search_path restricted to
5547 * pg_catalog, the format_type() and pg_get_expr() outputs will always
5548 * include a schema name for types/functions in other schemas, which
5549 * is what we want.
5550 */
5551 appendStringInfoString(&buf,
5552 "SELECT relname, "
5553 " attname, "
5554 " format_type(atttypid, atttypmod), "
5555 " attnotnull, "
5556 " pg_get_expr(adbin, adrelid), ");
5557
5558 /* Generated columns are supported since Postgres 12 */
5559 if (PQserverVersion(conn) >= 120000)
5560 appendStringInfoString(&buf,
5561 " attgenerated, ");
5562 else
5563 appendStringInfoString(&buf,
5564 " NULL, ");
5565
5566 if (import_collate)
5567 appendStringInfoString(&buf,
5568 " collname, "
5569 " collnsp.nspname ");
5570 else
5571 appendStringInfoString(&buf,
5572 " NULL, NULL ");
5573
5574 appendStringInfoString(&buf,
5575 "FROM pg_class c "
5576 " JOIN pg_namespace n ON "
5577 " relnamespace = n.oid "
5578 " LEFT JOIN pg_attribute a ON "
5579 " attrelid = c.oid AND attnum > 0 "
5580 " AND NOT attisdropped "
5581 " LEFT JOIN pg_attrdef ad ON "
5582 " adrelid = c.oid AND adnum = attnum ");
5583
5584 if (import_collate)
5585 appendStringInfoString(&buf,
5586 " LEFT JOIN pg_collation coll ON "
5587 " coll.oid = attcollation "
5588 " LEFT JOIN pg_namespace collnsp ON "
5589 " collnsp.oid = collnamespace ");
5590
5591 appendStringInfoString(&buf,
5592 "WHERE c.relkind IN ("
5593 CppAsString2(RELKIND_RELATION) ","
5594 CppAsString2(RELKIND_VIEW) ","
5595 CppAsString2(RELKIND_FOREIGN_TABLE) ","
5596 CppAsString2(RELKIND_MATVIEW) ","
5597 CppAsString2(RELKIND_PARTITIONED_TABLE) ") "
5598 " AND n.nspname = ");
5599 deparseStringLiteral(&buf, stmt->remote_schema);
5600
5601 /* Partitions are supported since Postgres 10 */
5602 if (PQserverVersion(conn) >= 100000 &&
5603 stmt->list_type != FDW_IMPORT_SCHEMA_LIMIT_TO)
5604 appendStringInfoString(&buf, " AND NOT c.relispartition ");
5605
5606 /* Apply restrictions for LIMIT TO and EXCEPT */
5607 if (stmt->list_type == FDW_IMPORT_SCHEMA_LIMIT_TO ||
5608 stmt->list_type == FDW_IMPORT_SCHEMA_EXCEPT)
5609 {
5610 bool first_item = true;
5611
5612 appendStringInfoString(&buf, " AND c.relname ");
5613 if (stmt->list_type == FDW_IMPORT_SCHEMA_EXCEPT)
5614 appendStringInfoString(&buf, "NOT ");
5615 appendStringInfoString(&buf, "IN (");
5616
5617 /* Append list of table names within IN clause */
5618 foreach(lc, stmt->table_list)
5619 {
5620 RangeVar *rv = (RangeVar *) lfirst(lc);
5621
5622 if (first_item)
5623 first_item = false;
5624 else
5625 appendStringInfoString(&buf, ", ");
5626 deparseStringLiteral(&buf, rv->relname);
5627 }
5628 appendStringInfoChar(&buf, ')');
5629 }
5630
5631 /* Append ORDER BY at the end of query to ensure output ordering */
5632 appendStringInfoString(&buf, " ORDER BY c.relname, a.attnum");
5633
5634 /* Fetch the data */
5635 res = pgfdw_exec_query(conn, buf.data, NULL);
5636 if (PQresultStatus(res) != PGRES_TUPLES_OK)
5637 pgfdw_report_error(ERROR, res, conn, false, buf.data);
5638
5639 /* Process results */
5640 numrows = PQntuples(res);
5641 /* note: incrementation of i happens in inner loop's while() test */
5642 for (i = 0; i < numrows;)
5643 {
5644 char *tablename = PQgetvalue(res, i, 0);
5645 bool first_item = true;
5646
5647 resetStringInfo(&buf);
5648 appendStringInfo(&buf, "CREATE FOREIGN TABLE %s (\n",
5649 quote_identifier(tablename));
5650
5651 /* Scan all rows for this table */
5652 do
5653 {
5654 char *attname;
5655 char *typename;
5656 char *attnotnull;
5657 char *attgenerated;
5658 char *attdefault;
5659 char *collname;
5660 char *collnamespace;
5661
5662 /* If table has no columns, we'll see nulls here */
5663 if (PQgetisnull(res, i, 1))
5664 continue;
5665
5666 attname = PQgetvalue(res, i, 1);
5667 typename = PQgetvalue(res, i, 2);
5668 attnotnull = PQgetvalue(res, i, 3);
5669 attdefault = PQgetisnull(res, i, 4) ? NULL :
5670 PQgetvalue(res, i, 4);
5671 attgenerated = PQgetisnull(res, i, 5) ? NULL :
5672 PQgetvalue(res, i, 5);
5673 collname = PQgetisnull(res, i, 6) ? NULL :
5674 PQgetvalue(res, i, 6);
5675 collnamespace = PQgetisnull(res, i, 7) ? NULL :
5676 PQgetvalue(res, i, 7);
5677
5678 if (first_item)
5679 first_item = false;
5680 else
5681 appendStringInfoString(&buf, ",\n");
5682
5683 /* Print column name and type */
5684 appendStringInfo(&buf, " %s %s",
5685 quote_identifier(attname),
5686 typename);
5687
5688 /*
5689 * Add column_name option so that renaming the foreign table's
5690 * column doesn't break the association to the underlying
5691 * column.
5692 */
5693 appendStringInfoString(&buf, " OPTIONS (column_name ");
5694 deparseStringLiteral(&buf, attname);
5695 appendStringInfoChar(&buf, ')');
5696
5697 /* Add COLLATE if needed */
5698 if (import_collate && collname != NULL && collnamespace != NULL)
5699 appendStringInfo(&buf, " COLLATE %s.%s",
5700 quote_identifier(collnamespace),
5701 quote_identifier(collname));
5702
5703 /* Add DEFAULT if needed */
5704 if (import_default && attdefault != NULL &&
5705 (!attgenerated || !attgenerated[0]))
5706 appendStringInfo(&buf, " DEFAULT %s", attdefault);
5707
5708 /* Add GENERATED if needed */
5709 if (import_generated && attgenerated != NULL &&
5710 attgenerated[0] == ATTRIBUTE_GENERATED_STORED)
5711 {
5712 Assert(attdefault != NULL);
5713 appendStringInfo(&buf,
5714 " GENERATED ALWAYS AS (%s) STORED",
5715 attdefault);
5716 }
5717
5718 /* Add NOT NULL if needed */
5719 if (import_not_null && attnotnull[0] == 't')
5720 appendStringInfoString(&buf, " NOT NULL");
5721 }
5722 while (++i < numrows &&
5723 strcmp(PQgetvalue(res, i, 0), tablename) == 0);
5724
5725 /*
5726 * Add server name and table-level options. We specify remote
5727 * schema and table name as options (the latter to ensure that
5728 * renaming the foreign table doesn't break the association).
5729 */
5730 appendStringInfo(&buf, "\n) SERVER %s\nOPTIONS (",
5731 quote_identifier(server->servername));
5732
5733 appendStringInfoString(&buf, "schema_name ");
5734 deparseStringLiteral(&buf, stmt->remote_schema);
5735 appendStringInfoString(&buf, ", table_name ");
5736 deparseStringLiteral(&buf, tablename);
5737
5738 appendStringInfoString(&buf, ");");
5739
5740 commands = lappend(commands, pstrdup(buf.data));
5741 }
5742 }
5743 PG_FINALLY();
5744 {
5745 PQclear(res);
5746 }
5747 PG_END_TRY();
5748
5749 ReleaseConnection(conn);
5750
5751 return commands;
5752 }
5753
5754 /*
5755 * Check if reltarget is safe enough to push down semi-join. Reltarget is not
5756 * safe, if it contains references to inner rel relids, which do not belong to
5757 * outer rel.
5758 */
5759 static bool
5760 semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel)
5761 {
5762 List *vars;
5763 ListCell *lc;
5764 bool ok = true;
5765
5766 Assert(joinrel->reltarget);
5767
5768 vars = pull_var_clause((Node *) joinrel->reltarget->exprs, PVC_INCLUDE_PLACEHOLDERS);
5769
5770 foreach(lc, vars)
5771 {
5772 Var *var = (Var *) lfirst(lc);
5773
5774 if (!IsA(var, Var))
5775 continue;
5776
5777 if (bms_is_member(var->varno, innerrel->relids))
5778 {
5779 /*
5780 * The planner can create semi-join, which refers to inner rel
5781 * vars in its target list. However, we deparse semi-join as an
5782 * exists() subquery, so can't handle references to inner rel in
5783 * the target list.
5784 */
5785 Assert(!bms_is_member(var->varno, outerrel->relids));
5786 ok = false;
5787 break;
5788 }
5789 }
5790 return ok;
5791 }
5792
5793 /*
5794 * Assess whether the join between inner and outer relations can be pushed down
5795 * to the foreign server. As a side effect, save information we obtain in this
5796 * function to PgFdwRelationInfo passed in.
5797 */
5798 static bool
5799 foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype,
5800 RelOptInfo *outerrel, RelOptInfo *innerrel,
5801 JoinPathExtraData *extra)
5802 {
5803 PgFdwRelationInfo *fpinfo;
5804 PgFdwRelationInfo *fpinfo_o;
5805 PgFdwRelationInfo *fpinfo_i;
5806 ListCell *lc;
5807 List *joinclauses;
5808
5809 /*
5810 * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins.
5811 * Constructing queries representing ANTI joins is hard, hence not
5812 * considered right now.
5813 */
5814 if (jointype != JOIN_INNER && jointype != JOIN_LEFT &&
5815 jointype != JOIN_RIGHT && jointype != JOIN_FULL &&
5816 jointype != JOIN_SEMI)
5817 return false;
5818
5819 /*
5820 * We can't push down semi-join if its reltarget is not safe
5821 */
5822 if ((jointype == JOIN_SEMI) && !semijoin_target_ok(root, joinrel, outerrel, innerrel))
5823 return false;
5824
5825 /*
5826 * If either of the joining relations is marked as unsafe to pushdown, the
5827 * join can not be pushed down.
5828 */
5829 fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private;
5830 fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private;
5831 fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private;
5832 if (!fpinfo_o || !fpinfo_o->pushdown_safe ||
5833 !fpinfo_i || !fpinfo_i->pushdown_safe)
5834 return false;
5835
5836 /*
5837 * If joining relations have local conditions, those conditions are
5838 * required to be applied before joining the relations. Hence the join can
5839 * not be pushed down.
5840 */
5841 if (fpinfo_o->local_conds || fpinfo_i->local_conds)
5842 return false;
5843
5844 /*
5845 * Merge FDW options. We might be tempted to do this after we have deemed
5846 * the foreign join to be OK. But we must do this beforehand so that we
5847 * know which quals can be evaluated on the foreign server, which might
5848 * depend on shippable_extensions.
5849 */
5850 fpinfo->server = fpinfo_o->server;
5851 merge_fdw_options(fpinfo, fpinfo_o, fpinfo_i);
5852
5853 /*
5854 * Separate restrict list into join quals and pushed-down (other) quals.
5855 *
5856 * Join quals belonging to an outer join must all be shippable, else we
5857 * cannot execute the join remotely. Add such quals to 'joinclauses'.
5858 *
5859 * Add other quals to fpinfo->remote_conds if they are shippable, else to
5860 * fpinfo->local_conds. In an inner join it's okay to execute conditions
5861 * either locally or remotely; the same is true for pushed-down conditions
5862 * at an outer join.
5863 *
5864 * Note we might return failure after having already scribbled on
5865 * fpinfo->remote_conds and fpinfo->local_conds. That's okay because we
5866 * won't consult those lists again if we deem the join unshippable.
5867 */
5868 joinclauses = NIL;
5869 foreach(lc, extra->restrictlist)
5870 {
5871 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
5872 bool is_remote_clause = is_foreign_expr(root, joinrel,
5873 rinfo->clause);
5874
5875 if (IS_OUTER_JOIN(jointype) &&
5876 !RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5877 {
5878 if (!is_remote_clause)
5879 return false;
5880 joinclauses = lappend(joinclauses, rinfo);
5881 }
5882 else
5883 {
5884 if (is_remote_clause)
5885 fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
5886 else
5887 fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
5888 }
5889 }
5890
5891 /*
5892 * deparseExplicitTargetList() isn't smart enough to handle anything other
5893 * than a Var. In particular, if there's some PlaceHolderVar that would
5894 * need to be evaluated within this join tree (because there's an upper
5895 * reference to a quantity that may go to NULL as a result of an outer
5896 * join), then we can't try to push the join down because we'll fail when
5897 * we get to deparseExplicitTargetList(). However, a PlaceHolderVar that
5898 * needs to be evaluated *at the top* of this join tree is OK, because we
5899 * can do that locally after fetching the results from the remote side.
5900 */
5901 foreach(lc, root->placeholder_list)
5902 {
5903 PlaceHolderInfo *phinfo = lfirst(lc);
5904 Relids relids;
5905
5906 /* PlaceHolderInfo refers to parent relids, not child relids. */
5907 relids = IS_OTHER_REL(joinrel) ?
5908 joinrel->top_parent_relids : joinrel->relids;
5909
5910 if (bms_is_subset(phinfo->ph_eval_at, relids) &&
5911 bms_nonempty_difference(relids, phinfo->ph_eval_at))
5912 return false;
5913 }
5914
5915 /* Save the join clauses, for later use. */
5916 fpinfo->joinclauses = joinclauses;
5917
5918 fpinfo->outerrel = outerrel;
5919 fpinfo->innerrel = innerrel;
5920 fpinfo->jointype = jointype;
5921
5922 /*
5923 * By default, both the input relations are not required to be deparsed as
5924 * subqueries, but there might be some relations covered by the input
5925 * relations that are required to be deparsed as subqueries, so save the
5926 * relids of those relations for later use by the deparser.
5927 */
5928 fpinfo->make_outerrel_subquery = false;
5929 fpinfo->make_innerrel_subquery = false;
5930 Assert(bms_is_subset(fpinfo_o->lower_subquery_rels, outerrel->relids));
5931 Assert(bms_is_subset(fpinfo_i->lower_subquery_rels, innerrel->relids));
5932 fpinfo->lower_subquery_rels = bms_union(fpinfo_o->lower_subquery_rels,
5933 fpinfo_i->lower_subquery_rels);
5934 fpinfo->hidden_subquery_rels = bms_union(fpinfo_o->hidden_subquery_rels,
5935 fpinfo_i->hidden_subquery_rels);
5936
5937 /*
5938 * Pull the other remote conditions from the joining relations into join
5939 * clauses or other remote clauses (remote_conds) of this relation
5940 * wherever possible. This avoids building subqueries at every join step.
5941 *
5942 * For an inner join, clauses from both the relations are added to the
5943 * other remote clauses. For LEFT and RIGHT OUTER join, the clauses from
5944 * the outer side are added to remote_conds since those can be evaluated
5945 * after the join is evaluated. The clauses from inner side are added to
5946 * the joinclauses, since they need to be evaluated while constructing the
5947 * join.
5948 *
5949 * For SEMI-JOIN clauses from inner relation can not be added to
5950 * remote_conds, but should be treated as join clauses (as they are
5951 * deparsed to EXISTS subquery, where inner relation can be referred). A
5952 * list of relation ids, which can't be referred to from higher levels, is
5953 * preserved as a hidden_subquery_rels list.
5954 *
5955 * For a FULL OUTER JOIN, the other clauses from either relation can not
5956 * be added to the joinclauses or remote_conds, since each relation acts
5957 * as an outer relation for the other.
5958 *
5959 * The joining sides can not have local conditions, thus no need to test
5960 * shippability of the clauses being pulled up.
5961 */
5962 switch (jointype)
5963 {
5964 case JOIN_INNER:
5965 fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5966 fpinfo_i->remote_conds);
5967 fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5968 fpinfo_o->remote_conds);
5969 break;
5970
5971 case JOIN_LEFT:
5972
5973 /*
5974 * When semi-join is involved in the inner or outer part of the
5975 * left join, it's deparsed as a subquery, and we can't refer to
5976 * its vars on the upper level.
5977 */
5978 if (bms_is_empty(fpinfo_i->hidden_subquery_rels))
5979 fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5980 fpinfo_i->remote_conds);
5981 if (bms_is_empty(fpinfo_o->hidden_subquery_rels))
5982 fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5983 fpinfo_o->remote_conds);
5984 break;
5985
5986 case JOIN_RIGHT:
5987
5988 /*
5989 * When semi-join is involved in the inner or outer part of the
5990 * right join, it's deparsed as a subquery, and we can't refer to
5991 * its vars on the upper level.
5992 */
5993 if (bms_is_empty(fpinfo_o->hidden_subquery_rels))
5994 fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5995 fpinfo_o->remote_conds);
5996 if (bms_is_empty(fpinfo_i->hidden_subquery_rels))
5997 fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5998 fpinfo_i->remote_conds);
5999 break;
6000
6001 case JOIN_SEMI:
6002 fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
6003 fpinfo_i->remote_conds);
6004 fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
6005 fpinfo->remote_conds);
6006 fpinfo->remote_conds = list_copy(fpinfo_o->remote_conds);
6007 fpinfo->hidden_subquery_rels = bms_union(fpinfo->hidden_subquery_rels,
6008 innerrel->relids);
6009 break;
6010
6011 case JOIN_FULL:
6012
6013 /*
6014 * In this case, if any of the input relations has conditions, we
6015 * need to deparse that relation as a subquery so that the
6016 * conditions can be evaluated before the join. Remember it in
6017 * the fpinfo of this relation so that the deparser can take
6018 * appropriate action. Also, save the relids of base relations
6019 * covered by that relation for later use by the deparser.
6020 */
6021 if (fpinfo_o->remote_conds)
6022 {
6023 fpinfo->make_outerrel_subquery = true;
6024 fpinfo->lower_subquery_rels =
6025 bms_add_members(fpinfo->lower_subquery_rels,
6026 outerrel->relids);
6027 }
6028 if (fpinfo_i->remote_conds)
6029 {
6030 fpinfo->make_innerrel_subquery = true;
6031 fpinfo->lower_subquery_rels =
6032 bms_add_members(fpinfo->lower_subquery_rels,
6033 innerrel->relids);
6034 }
6035 break;
6036
6037 default:
6038 /* Should not happen, we have just checked this above */
6039 elog(ERROR, "unsupported join type %d", jointype);
6040 }
6041
6042 /*
6043 * For an inner join, all restrictions can be treated alike. Treating the
6044 * pushed down conditions as join conditions allows a top level full outer
6045 * join to be deparsed without requiring subqueries.
6046 */
6047 if (jointype == JOIN_INNER)
6048 {
6049 Assert(!fpinfo->joinclauses);
6050 fpinfo->joinclauses = fpinfo->remote_conds;
6051 fpinfo->remote_conds = NIL;
6052 }
6053 else if (jointype == JOIN_LEFT || jointype == JOIN_RIGHT || jointype == JOIN_FULL)
6054 {
6055 /*
6056 * Conditions, generated from semi-joins, should be evaluated before
6057 * LEFT/RIGHT/FULL join.
6058 */
6059 if (!bms_is_empty(fpinfo_o->hidden_subquery_rels))
6060 {
6061 fpinfo->make_outerrel_subquery = true;
6062 fpinfo->lower_subquery_rels = bms_add_members(fpinfo->lower_subquery_rels, outerrel->relids);
6063 }
6064
6065 if (!bms_is_empty(fpinfo_i->hidden_subquery_rels))
6066 {
6067 fpinfo->make_innerrel_subquery = true;
6068 fpinfo->lower_subquery_rels = bms_add_members(fpinfo->lower_subquery_rels, innerrel->relids);
6069 }
6070 }
6071
6072 /* Mark that this join can be pushed down safely */
6073 fpinfo->pushdown_safe = true;
6074
6075 /* Get user mapping */
6076 if (fpinfo->use_remote_estimate)
6077 {
6078 if (fpinfo_o->use_remote_estimate)
6079 fpinfo->user = fpinfo_o->user;
6080 else
6081 fpinfo->user = fpinfo_i->user;
6082 }
6083 else
6084 fpinfo->user = NULL;
6085
6086 /*
6087 * Set # of retrieved rows and cached relation costs to some negative
6088 * value, so that we can detect when they are set to some sensible values,
6089 * during one (usually the first) of the calls to estimate_path_cost_size.
6090 */
6091 fpinfo->retrieved_rows = -1;
6092 fpinfo->rel_startup_cost = -1;
6093 fpinfo->rel_total_cost = -1;
6094
6095 /*
6096 * Set the string describing this join relation to be used in EXPLAIN
6097 * output of corresponding ForeignScan. Note that the decoration we add
6098 * to the base relation names mustn't include any digits, or it'll confuse
6099 * postgresExplainForeignScan.
6100 */
6101 fpinfo->relation_name = psprintf("(%s) %s JOIN (%s)",
6102 fpinfo_o->relation_name,
6103 get_jointype_name(fpinfo->jointype),
6104 fpinfo_i->relation_name);
6105
6106 /*
6107 * Set the relation index. This is defined as the position of this
6108 * joinrel in the join_rel_list list plus the length of the rtable list.
6109 * Note that since this joinrel is at the end of the join_rel_list list
6110 * when we are called, we can get the position by list_length.
6111 */
6112 Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */
6113 fpinfo->relation_index =
6114 list_length(root->parse->rtable) + list_length(root->join_rel_list);
6115
6116 return true;
6117 }
6118
6119 static void
6120 add_paths_with_pathkeys_for_rel(PlannerInfo *root, RelOptInfo *rel,
6121 Path *epq_path, List *restrictlist)
6122 {
6123 List *useful_pathkeys_list = NIL; /* List of all pathkeys */
6124 ListCell *lc;
6125
6126 useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel);
6127
6128 /*
6129 * Before creating sorted paths, arrange for the passed-in EPQ path, if
6130 * any, to return columns needed by the parent ForeignScan node so that
6131 * they will propagate up through Sort nodes injected below, if necessary.
6132 */
6133 if (epq_path != NULL && useful_pathkeys_list != NIL)
6134 {
6135 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
6136 PathTarget *target = copy_pathtarget(epq_path->pathtarget);
6137
6138 /* Include columns required for evaluating PHVs in the tlist. */
6139 add_new_columns_to_pathtarget(target,
6140 pull_var_clause((Node *) target->exprs,
6141 PVC_RECURSE_PLACEHOLDERS));
6142
6143 /* Include columns required for evaluating the local conditions. */
6144 foreach(lc, fpinfo->local_conds)
6145 {
6146 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
6147
6148 add_new_columns_to_pathtarget(target,
6149 pull_var_clause((Node *) rinfo->clause,
6150 PVC_RECURSE_PLACEHOLDERS));
6151 }
6152
6153 /*
6154 * If we have added any new columns, adjust the tlist of the EPQ path.
6155 *
6156 * Note: the plan created using this path will only be used to execute
6157 * EPQ checks, where accuracy of the plan cost and width estimates
6158 * would not be important, so we do not do set_pathtarget_cost_width()
6159 * for the new pathtarget here. See also postgresGetForeignPlan().
6160 */
6161 if (list_length(target->exprs) > list_length(epq_path->pathtarget->exprs))
6162 {
6163 /* The EPQ path is a join path, so it is projection-capable. */
6164 Assert(is_projection_capable_path(epq_path));
6165
6166 /*
6167 * Use create_projection_path() here, so as to avoid modifying it
6168 * in place.
6169 */
6170 epq_path = (Path *) create_projection_path(root,
6171 rel,
6172 epq_path,
6173 target);
6174 }
6175 }
6176
6177 /* Create one path for each set of pathkeys we found above. */
6178 foreach(lc, useful_pathkeys_list)
6179 {
6180 double rows;
6181 int width;
6182 int disabled_nodes;
6183 Cost startup_cost;
6184 Cost total_cost;
6185 List *useful_pathkeys = lfirst(lc);
6186 Path *sorted_epq_path;
6187
6188 estimate_path_cost_size(root, rel, NIL, useful_pathkeys, NULL,
6189 &rows, &width, &disabled_nodes,
6190 &startup_cost, &total_cost);
6191
6192 /*
6193 * The EPQ path must be at least as well sorted as the path itself, in
6194 * case it gets used as input to a mergejoin.
6195 */
6196 sorted_epq_path = epq_path;
6197 if (sorted_epq_path != NULL &&
6198 !pathkeys_contained_in(useful_pathkeys,
6199 sorted_epq_path->pathkeys))
6200 sorted_epq_path = (Path *)
6201 create_sort_path(root,
6202 rel,
6203 sorted_epq_path,
6204 useful_pathkeys,
6205 -1.0);
6206
6207 if (IS_SIMPLE_REL(rel))
6208 add_path(rel, (Path *)
6209 create_foreignscan_path(root, rel,
6210 NULL,
6211 rows,
6212 disabled_nodes,
6213 startup_cost,
6214 total_cost,
6215 useful_pathkeys,
6216 rel->lateral_relids,
6217 sorted_epq_path,
6218 NIL, /* no fdw_restrictinfo
6219 * list */
6220 NIL));
6221 else
6222 add_path(rel, (Path *)
6223 create_foreign_join_path(root, rel,
6224 NULL,
6225 rows,
6226 disabled_nodes,
6227 startup_cost,
6228 total_cost,
6229 useful_pathkeys,
6230 rel->lateral_relids,
6231 sorted_epq_path,
6232 restrictlist,
6233 NIL));
6234 }
6235 }
6236
6237 /*
6238 * Parse options from foreign server and apply them to fpinfo.
6239 *
6240 * New options might also require tweaking merge_fdw_options().
6241 */
6242 static void
6243 apply_server_options(PgFdwRelationInfo *fpinfo)
6244 {
6245 ListCell *lc;
6246
6247 foreach(lc, fpinfo->server->options)
6248 {
6249 DefElem *def = (DefElem *) lfirst(lc);
6250
6251 if (strcmp(def->defname, "use_remote_estimate") == 0)
6252 fpinfo->use_remote_estimate = defGetBoolean(def);
6253 else if (strcmp(def->defname, "fdw_startup_cost") == 0)
6254 (void) parse_real(defGetString(def), &fpinfo->fdw_startup_cost, 0,
6255 NULL);
6256 else if (strcmp(def->defname, "fdw_tuple_cost") == 0)
6257 (void) parse_real(defGetString(def), &fpinfo->fdw_tuple_cost, 0,
6258 NULL);
6259 else if (strcmp(def->defname, "extensions") == 0)
6260 fpinfo->shippable_extensions =
6261 ExtractExtensionList(defGetString(def), false);
6262 else if (strcmp(def->defname, "fetch_size") == 0)
6263 (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
6264 else if (strcmp(def->defname, "async_capable") == 0)
6265 fpinfo->async_capable = defGetBoolean(def);
6266 }
6267 }
6268
6269 /*
6270 * Parse options from foreign table and apply them to fpinfo.
6271 *
6272 * New options might also require tweaking merge_fdw_options().
6273 */
6274 static void
6275 apply_table_options(PgFdwRelationInfo *fpinfo)
6276 {
6277 ListCell *lc;
6278
6279 foreach(lc, fpinfo->table->options)
6280 {
6281 DefElem *def = (DefElem *) lfirst(lc);
6282
6283 if (strcmp(def->defname, "use_remote_estimate") == 0)
6284 fpinfo->use_remote_estimate = defGetBoolean(def);
6285 else if (strcmp(def->defname, "fetch_size") == 0)
6286 (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
6287 else if (strcmp(def->defname, "async_capable") == 0)
6288 fpinfo->async_capable = defGetBoolean(def);
6289 }
6290 }
6291
6292 /*
6293 * Merge FDW options from input relations into a new set of options for a join
6294 * or an upper rel.
6295 *
6296 * For a join relation, FDW-specific information about the inner and outer
6297 * relations is provided using fpinfo_i and fpinfo_o. For an upper relation,
6298 * fpinfo_o provides the information for the input relation; fpinfo_i is
6299 * expected to NULL.
6300 */
6301 static void
6302 merge_fdw_options(PgFdwRelationInfo *fpinfo,
6303 const PgFdwRelationInfo *fpinfo_o,
6304 const PgFdwRelationInfo *fpinfo_i)
6305 {
6306 /* We must always have fpinfo_o. */
6307 Assert(fpinfo_o);
6308
6309 /* fpinfo_i may be NULL, but if present the servers must both match. */
6310 Assert(!fpinfo_i ||
6311 fpinfo_i->server->serverid == fpinfo_o->server->serverid);
6312
6313 /*
6314 * Copy the server specific FDW options. (For a join, both relations come
6315 * from the same server, so the server options should have the same value
6316 * for both relations.)
6317 */
6318 fpinfo->fdw_startup_cost = fpinfo_o->fdw_startup_cost;
6319 fpinfo->fdw_tuple_cost = fpinfo_o->fdw_tuple_cost;
6320 fpinfo->shippable_extensions = fpinfo_o->shippable_extensions;
6321 fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate;
6322 fpinfo->fetch_size = fpinfo_o->fetch_size;
6323 fpinfo->async_capable = fpinfo_o->async_capable;
6324
6325 /* Merge the table level options from either side of the join. */
6326 if (fpinfo_i)
6327 {
6328 /*
6329 * We'll prefer to use remote estimates for this join if any table
6330 * from either side of the join is using remote estimates. This is
6331 * most likely going to be preferred since they're already willing to
6332 * pay the price of a round trip to get the remote EXPLAIN. In any
6333 * case it's not entirely clear how we might otherwise handle this
6334 * best.
6335 */
6336 fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate ||
6337 fpinfo_i->use_remote_estimate;
6338
6339 /*
6340 * Set fetch size to maximum of the joining sides, since we are
6341 * expecting the rows returned by the join to be proportional to the
6342 * relation sizes.
6343 */
6344 fpinfo->fetch_size = Max(fpinfo_o->fetch_size, fpinfo_i->fetch_size);
6345
6346 /*
6347 * We'll prefer to consider this join async-capable if any table from
6348 * either side of the join is considered async-capable. This would be
6349 * reasonable because in that case the foreign server would have its
6350 * own resources to scan that table asynchronously, and the join could
6351 * also be computed asynchronously using the resources.
6352 */
6353 fpinfo->async_capable = fpinfo_o->async_capable ||
6354 fpinfo_i->async_capable;
6355 }
6356 }
6357
6358 /*
6359 * postgresGetForeignJoinPaths
6360 * Add possible ForeignPath to joinrel, if join is safe to push down.
6361 */
6362 static void
6363 postgresGetForeignJoinPaths(PlannerInfo *root,
6364 RelOptInfo *joinrel,
6365 RelOptInfo *outerrel,
6366 RelOptInfo *innerrel,
6367 JoinType jointype,
6368 JoinPathExtraData *extra)
6369 {
6370 PgFdwRelationInfo *fpinfo;
6371 ForeignPath *joinpath;
6372 double rows;
6373 int width;
6374 int disabled_nodes;
6375 Cost startup_cost;
6376 Cost total_cost;
6377 Path *epq_path; /* Path to create plan to be executed when
6378 * EvalPlanQual gets triggered. */
6379
6380 /*
6381 * Skip if this join combination has been considered already.
6382 */
6383 if (joinrel->fdw_private)
6384 return;
6385
6386 /*
6387 * This code does not work for joins with lateral references, since those
6388 * must have parameterized paths, which we don't generate yet.
6389 */
6390 if (!bms_is_empty(joinrel->lateral_relids))
6391 return;
6392
6393 /*
6394 * Create unfinished PgFdwRelationInfo entry which is used to indicate
6395 * that the join relation is already considered, so that we won't waste
6396 * time in judging safety of join pushdown and adding the same paths again
6397 * if found safe. Once we know that this join can be pushed down, we fill
6398 * the entry.
6399 */
6400 fpinfo = (PgFdwRelationInfo *) palloc0(sizeof(PgFdwRelationInfo));
6401 fpinfo->pushdown_safe = false;
6402 joinrel->fdw_private = fpinfo;
6403 /* attrs_used is only for base relations. */
6404 fpinfo->attrs_used = NULL;
6405
6406 /*
6407 * If there is a possibility that EvalPlanQual will be executed, we need
6408 * to be able to reconstruct the row using scans of the base relations.
6409 * GetExistingLocalJoinPath will find a suitable path for this purpose in
6410 * the path list of the joinrel, if one exists. We must be careful to
6411 * call it before adding any ForeignPath, since the ForeignPath might
6412 * dominate the only suitable local path available. We also do it before
6413 * calling foreign_join_ok(), since that function updates fpinfo and marks
6414 * it as pushable if the join is found to be pushable.
6415 */
6416 if (root->parse->commandType == CMD_DELETE ||
6417 root->parse->commandType == CMD_UPDATE ||
6418 root->rowMarks)
6419 {
6420 epq_path = GetExistingLocalJoinPath(joinrel);
6421 if (!epq_path)
6422 {
6423 elog(DEBUG3, "could not push down foreign join because a local path suitable for EPQ checks was not found");
6424 return;
6425 }
6426 }
6427 else
6428 epq_path = NULL;
6429
6430 if (!foreign_join_ok(root, joinrel, jointype, outerrel, innerrel, extra))
6431 {
6432 /* Free path required for EPQ if we copied one; we don't need it now */
6433 if (epq_path)
6434 pfree(epq_path);
6435 return;
6436 }
6437
6438 /*
6439 * Compute the selectivity and cost of the local_conds, so we don't have
6440 * to do it over again for each path. The best we can do for these
6441 * conditions is to estimate selectivity on the basis of local statistics.
6442 * The local conditions are applied after the join has been computed on
6443 * the remote side like quals in WHERE clause, so pass jointype as
6444 * JOIN_INNER.
6445 */
6446 fpinfo->local_conds_sel = clauselist_selectivity(root,
6447 fpinfo->local_conds,
6448 0,
6449 JOIN_INNER,
6450 NULL);
6451 cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
6452
6453 /*
6454 * If we are going to estimate costs locally, estimate the join clause
6455 * selectivity here while we have special join info.
6456 */
6457 if (!fpinfo->use_remote_estimate)
6458 fpinfo->joinclause_sel = clauselist_selectivity(root, fpinfo->joinclauses,
6459 0, fpinfo->jointype,
6460 extra->sjinfo);
6461
6462 /* Estimate costs for bare join relation */
6463 estimate_path_cost_size(root, joinrel, NIL, NIL, NULL,
6464 &rows, &width, &disabled_nodes,
6465 &startup_cost, &total_cost);
6466 /* Now update this information in the joinrel */
6467 joinrel->rows = rows;
6468 joinrel->reltarget->width = width;
6469 fpinfo->rows = rows;
6470 fpinfo->width = width;
6471 fpinfo->disabled_nodes = disabled_nodes;
6472 fpinfo->startup_cost = startup_cost;
6473 fpinfo->total_cost = total_cost;
6474
6475 /*
6476 * Create a new join path and add it to the joinrel which represents a
6477 * join between foreign tables.
6478 */
6479 joinpath = create_foreign_join_path(root,
6480 joinrel,
6481 NULL, /* default pathtarget */
6482 rows,
6483 disabled_nodes,
6484 startup_cost,
6485 total_cost,
6486 NIL, /* no pathkeys */
6487 joinrel->lateral_relids,
6488 epq_path,
6489 extra->restrictlist,
6490 NIL); /* no fdw_private */
6491
6492 /* Add generated path into joinrel by add_path(). */
6493 add_path(joinrel, (Path *) joinpath);
6494
6495 /* Consider pathkeys for the join relation */
6496 add_paths_with_pathkeys_for_rel(root, joinrel, epq_path,
6497 extra->restrictlist);
6498
6499 /* XXX Consider parameterized paths for the join relation */
6500 }
6501
6502 /*
6503 * Assess whether the aggregation, grouping and having operations can be pushed
6504 * down to the foreign server. As a side effect, save information we obtain in
6505 * this function to PgFdwRelationInfo of the input relation.
6506 */
6507 static bool
6508 foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel,
6509 Node *havingQual)
6510 {
6511 Query *query = root->parse;
6512 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) grouped_rel->fdw_private;
6513 PathTarget *grouping_target = grouped_rel->reltarget;
6514 PgFdwRelationInfo *ofpinfo;
6515 ListCell *lc;
6516 int i;
6517 List *tlist = NIL;
6518
6519 /* We currently don't support pushing Grouping Sets. */
6520 if (query->groupingSets)
6521 return false;
6522
6523 /* Get the fpinfo of the underlying scan relation. */
6524 ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
6525
6526 /*
6527 * If underlying scan relation has any local conditions, those conditions
6528 * are required to be applied before performing aggregation. Hence the
6529 * aggregate cannot be pushed down.
6530 */
6531 if (ofpinfo->local_conds)
6532 return false;
6533
6534 /*
6535 * Examine grouping expressions, as well as other expressions we'd need to
6536 * compute, and check whether they are safe to push down to the foreign
6537 * server. All GROUP BY expressions will be part of the grouping target
6538 * and thus there is no need to search for them separately. Add grouping
6539 * expressions into target list which will be passed to foreign server.
6540 *
6541 * A tricky fine point is that we must not put any expression into the
6542 * target list that is just a foreign param (that is, something that
6543 * deparse.c would conclude has to be sent to the foreign server). If we
6544 * do, the expression will also appear in the fdw_exprs list of the plan
6545 * node, and setrefs.c will get confused and decide that the fdw_exprs
6546 * entry is actually a reference to the fdw_scan_tlist entry, resulting in
6547 * a broken plan. Somewhat oddly, it's OK if the expression contains such
6548 * a node, as long as it's not at top level; then no match is possible.
6549 */
6550 i = 0;
6551 foreach(lc, grouping_target->exprs)
6552 {
6553 Expr *expr = (Expr *) lfirst(lc);
6554 Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
6555 ListCell *l;
6556
6557 /*
6558 * Check whether this expression is part of GROUP BY clause. Note we
6559 * check the whole GROUP BY clause not just processed_groupClause,
6560 * because we will ship all of it, cf. appendGroupByClause.
6561 */
6562 if (sgref && get_sortgroupref_clause_noerr(sgref, query->groupClause))
6563 {
6564 TargetEntry *tle;
6565
6566 /*
6567 * If any GROUP BY expression is not shippable, then we cannot
6568 * push down aggregation to the foreign server.
6569 */
6570 if (!is_foreign_expr(root, grouped_rel, expr))
6571 return false;
6572
6573 /*
6574 * If it would be a foreign param, we can't put it into the tlist,
6575 * so we have to fail.
6576 */
6577 if (is_foreign_param(root, grouped_rel, expr))
6578 return false;
6579
6580 /*
6581 * Pushable, so add to tlist. We need to create a TLE for this
6582 * expression and apply the sortgroupref to it. We cannot use
6583 * add_to_flat_tlist() here because that avoids making duplicate
6584 * entries in the tlist. If there are duplicate entries with
6585 * distinct sortgrouprefs, we have to duplicate that situation in
6586 * the output tlist.
6587 */
6588 tle = makeTargetEntry(expr, list_length(tlist) + 1, NULL, false);
6589 tle->ressortgroupref = sgref;
6590 tlist = lappend(tlist, tle);
6591 }
6592 else
6593 {
6594 /*
6595 * Non-grouping expression we need to compute. Can we ship it
6596 * as-is to the foreign server?
6597 */
6598 if (is_foreign_expr(root, grouped_rel, expr) &&
6599 !is_foreign_param(root, grouped_rel, expr))
6600 {
6601 /* Yes, so add to tlist as-is; OK to suppress duplicates */
6602 tlist = add_to_flat_tlist(tlist, list_make1(expr));
6603 }
6604 else
6605 {
6606 /* Not pushable as a whole; extract its Vars and aggregates */
6607 List *aggvars;
6608
6609 aggvars = pull_var_clause((Node *) expr,
6610 PVC_INCLUDE_AGGREGATES);
6611
6612 /*
6613 * If any aggregate expression is not shippable, then we
6614 * cannot push down aggregation to the foreign server. (We
6615 * don't have to check is_foreign_param, since that certainly
6616 * won't return true for any such expression.)
6617 */
6618 if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars))
6619 return false;
6620
6621 /*
6622 * Add aggregates, if any, into the targetlist. Plain Vars
6623 * outside an aggregate can be ignored, because they should be
6624 * either same as some GROUP BY column or part of some GROUP
6625 * BY expression. In either case, they are already part of
6626 * the targetlist and thus no need to add them again. In fact
6627 * including plain Vars in the tlist when they do not match a
6628 * GROUP BY column would cause the foreign server to complain
6629 * that the shipped query is invalid.
6630 */
6631 foreach(l, aggvars)
6632 {
6633 Expr *aggref = (Expr *) lfirst(l);
6634
6635 if (IsA(aggref, Aggref))
6636 tlist = add_to_flat_tlist(tlist, list_make1(aggref));
6637 }
6638 }
6639 }
6640
6641 i++;
6642 }
6643
6644 /*
6645 * Classify the pushable and non-pushable HAVING clauses and save them in
6646 * remote_conds and local_conds of the grouped rel's fpinfo.
6647 */
6648 if (havingQual)
6649 {
6650 foreach(lc, (List *) havingQual)
6651 {
6652 Expr *expr = (Expr *) lfirst(lc);
6653 RestrictInfo *rinfo;
6654
6655 /*
6656 * Currently, the core code doesn't wrap havingQuals in
6657 * RestrictInfos, so we must make our own.
6658 */
6659 Assert(!IsA(expr, RestrictInfo));
6660 rinfo = make_restrictinfo(root,
6661 expr,
6662 true,
6663 false,
6664 false,
6665 false,
6666 root->qual_security_level,
6667 grouped_rel->relids,
6668 NULL,
6669 NULL);
6670 if (is_foreign_expr(root, grouped_rel, expr))
6671 fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
6672 else
6673 fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
6674 }
6675 }
6676
6677 /*
6678 * If there are any local conditions, pull Vars and aggregates from it and
6679 * check whether they are safe to pushdown or not.
6680 */
6681 if (fpinfo->local_conds)
6682 {
6683 List *aggvars = NIL;
6684
6685 foreach(lc, fpinfo->local_conds)
6686 {
6687 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
6688
6689 aggvars = list_concat(aggvars,
6690 pull_var_clause((Node *) rinfo->clause,
6691 PVC_INCLUDE_AGGREGATES));
6692 }
6693
6694 foreach(lc, aggvars)
6695 {
6696 Expr *expr = (Expr *) lfirst(lc);
6697
6698 /*
6699 * If aggregates within local conditions are not safe to push
6700 * down, then we cannot push down the query. Vars are already
6701 * part of GROUP BY clause which are checked above, so no need to
6702 * access them again here. Again, we need not check
6703 * is_foreign_param for a foreign aggregate.
6704 */
6705 if (IsA(expr, Aggref))
6706 {
6707 if (!is_foreign_expr(root, grouped_rel, expr))
6708 return false;
6709
6710 tlist = add_to_flat_tlist(tlist, list_make1(expr));
6711 }
6712 }
6713 }
6714
6715 /* Store generated targetlist */
6716 fpinfo->grouped_tlist = tlist;
6717
6718 /* Safe to pushdown */
6719 fpinfo->pushdown_safe = true;
6720
6721 /*
6722 * Set # of retrieved rows and cached relation costs to some negative
6723 * value, so that we can detect when they are set to some sensible values,
6724 * during one (usually the first) of the calls to estimate_path_cost_size.
6725 */
6726 fpinfo->retrieved_rows = -1;
6727 fpinfo->rel_startup_cost = -1;
6728 fpinfo->rel_total_cost = -1;
6729
6730 /*
6731 * Set the string describing this grouped relation to be used in EXPLAIN
6732 * output of corresponding ForeignScan. Note that the decoration we add
6733 * to the base relation name mustn't include any digits, or it'll confuse
6734 * postgresExplainForeignScan.
6735 */
6736 fpinfo->relation_name = psprintf("Aggregate on (%s)",
6737 ofpinfo->relation_name);
6738
6739 return true;
6740 }
6741
6742 /*
6743 * postgresGetForeignUpperPaths
6744 * Add paths for post-join operations like aggregation, grouping etc. if
6745 * corresponding operations are safe to push down.
6746 */
6747 static void
6748 postgresGetForeignUpperPaths(PlannerInfo *root, UpperRelationKind stage,
6749 RelOptInfo *input_rel, RelOptInfo *output_rel,
6750 void *extra)
6751 {
6752 PgFdwRelationInfo *fpinfo;
6753
6754 /*
6755 * If input rel is not safe to pushdown, then simply return as we cannot
6756 * perform any post-join operations on the foreign server.
6757 */
6758 if (!input_rel->fdw_private ||
6759 !((PgFdwRelationInfo *) input_rel->fdw_private)->pushdown_safe)
6760 return;
6761
6762 /* Ignore stages we don't support; and skip any duplicate calls. */
6763 if ((stage != UPPERREL_GROUP_AGG &&
6764 stage != UPPERREL_ORDERED &&
6765 stage != UPPERREL_FINAL) ||
6766 output_rel->fdw_private)
6767 return;
6768
6769 fpinfo = (PgFdwRelationInfo *) palloc0(sizeof(PgFdwRelationInfo));
6770 fpinfo->pushdown_safe = false;
6771 fpinfo->stage = stage;
6772 output_rel->fdw_private = fpinfo;
6773
6774 switch (stage)
6775 {
6776 case UPPERREL_GROUP_AGG:
6777 add_foreign_grouping_paths(root, input_rel, output_rel,
6778 (GroupPathExtraData *) extra);
6779 break;
6780 case UPPERREL_ORDERED:
6781 add_foreign_ordered_paths(root, input_rel, output_rel);
6782 break;
6783 case UPPERREL_FINAL:
6784 add_foreign_final_paths(root, input_rel, output_rel,
6785 (FinalPathExtraData *) extra);
6786 break;
6787 default:
6788 elog(ERROR, "unexpected upper relation: %d", (int) stage);
6789 break;
6790 }
6791 }
6792
6793 /*
6794 * add_foreign_grouping_paths
6795 * Add foreign path for grouping and/or aggregation.
6796 *
6797 * Given input_rel represents the underlying scan. The paths are added to the
6798 * given grouped_rel.
6799 */
6800 static void
6801 add_foreign_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
6802 RelOptInfo *grouped_rel,
6803 GroupPathExtraData *extra)
6804 {
6805 Query *parse = root->parse;
6806 PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6807 PgFdwRelationInfo *fpinfo = grouped_rel->fdw_private;
6808 ForeignPath *grouppath;
6809 double rows;
6810 int width;
6811 int disabled_nodes;
6812 Cost startup_cost;
6813 Cost total_cost;
6814
6815 /* Nothing to be done, if there is no grouping or aggregation required. */
6816 if (!parse->groupClause && !parse->groupingSets && !parse->hasAggs &&
6817 !root->hasHavingQual)
6818 return;
6819
6820 Assert(extra->patype == PARTITIONWISE_AGGREGATE_NONE ||
6821 extra->patype == PARTITIONWISE_AGGREGATE_FULL);
6822
6823 /* save the input_rel as outerrel in fpinfo */
6824 fpinfo->outerrel = input_rel;
6825
6826 /*
6827 * Copy foreign table, foreign server, user mapping, FDW options etc.
6828 * details from the input relation's fpinfo.
6829 */
6830 fpinfo->table = ifpinfo->table;
6831 fpinfo->server = ifpinfo->server;
6832 fpinfo->user = ifpinfo->user;
6833 merge_fdw_options(fpinfo, ifpinfo, NULL);
6834
6835 /*
6836 * Assess if it is safe to push down aggregation and grouping.
6837 *
6838 * Use HAVING qual from extra. In case of child partition, it will have
6839 * translated Vars.
6840 */
6841 if (!foreign_grouping_ok(root, grouped_rel, extra->havingQual))
6842 return;
6843
6844 /*
6845 * Compute the selectivity and cost of the local_conds, so we don't have
6846 * to do it over again for each path. (Currently we create just a single
6847 * path here, but in future it would be possible that we build more paths
6848 * such as pre-sorted paths as in postgresGetForeignPaths and
6849 * postgresGetForeignJoinPaths.) The best we can do for these conditions
6850 * is to estimate selectivity on the basis of local statistics.
6851 */
6852 fpinfo->local_conds_sel = clauselist_selectivity(root,
6853 fpinfo->local_conds,
6854 0,
6855 JOIN_INNER,
6856 NULL);
6857
6858 cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
6859
6860 /* Estimate the cost of push down */
6861 estimate_path_cost_size(root, grouped_rel, NIL, NIL, NULL,
6862 &rows, &width, &disabled_nodes,
6863 &startup_cost, &total_cost);
6864
6865 /* Now update this information in the fpinfo */
6866 fpinfo->rows = rows;
6867 fpinfo->width = width;
6868 fpinfo->disabled_nodes = disabled_nodes;
6869 fpinfo->startup_cost = startup_cost;
6870 fpinfo->total_cost = total_cost;
6871
6872 /* Create and add foreign path to the grouping relation. */
6873 grouppath = create_foreign_upper_path(root,
6874 grouped_rel,
6875 grouped_rel->reltarget,
6876 rows,
6877 disabled_nodes,
6878 startup_cost,
6879 total_cost,
6880 NIL, /* no pathkeys */
6881 NULL,
6882 NIL, /* no fdw_restrictinfo list */
6883 NIL); /* no fdw_private */
6884
6885 /* Add generated path into grouped_rel by add_path(). */
6886 add_path(grouped_rel, (Path *) grouppath);
6887 }
6888
6889 /*
6890 * add_foreign_ordered_paths
6891 * Add foreign paths for performing the final sort remotely.
6892 *
6893 * Given input_rel contains the source-data Paths. The paths are added to the
6894 * given ordered_rel.
6895 */
6896 static void
6897 add_foreign_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel,
6898 RelOptInfo *ordered_rel)
6899 {
6900 Query *parse = root->parse;
6901 PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6902 PgFdwRelationInfo *fpinfo = ordered_rel->fdw_private;
6903 PgFdwPathExtraData *fpextra;
6904 double rows;
6905 int width;
6906 int disabled_nodes;
6907 Cost startup_cost;
6908 Cost total_cost;
6909 List *fdw_private;
6910 ForeignPath *ordered_path;
6911 ListCell *lc;
6912
6913 /* Shouldn't get here unless the query has ORDER BY */
6914 Assert(parse->sortClause);
6915
6916 /* We don't support cases where there are any SRFs in the targetlist */
6917 if (parse->hasTargetSRFs)
6918 return;
6919
6920 /* Save the input_rel as outerrel in fpinfo */
6921 fpinfo->outerrel = input_rel;
6922
6923 /*
6924 * Copy foreign table, foreign server, user mapping, FDW options etc.
6925 * details from the input relation's fpinfo.
6926 */
6927 fpinfo->table = ifpinfo->table;
6928 fpinfo->server = ifpinfo->server;
6929 fpinfo->user = ifpinfo->user;
6930 merge_fdw_options(fpinfo, ifpinfo, NULL);
6931
6932 /*
6933 * If the input_rel is a base or join relation, we would already have
6934 * considered pushing down the final sort to the remote server when
6935 * creating pre-sorted foreign paths for that relation, because the
6936 * query_pathkeys is set to the root->sort_pathkeys in that case (see
6937 * standard_qp_callback()).
6938 */
6939 if (input_rel->reloptkind == RELOPT_BASEREL ||
6940 input_rel->reloptkind == RELOPT_JOINREL)
6941 {
6942 Assert(root->query_pathkeys == root->sort_pathkeys);
6943
6944 /* Safe to push down if the query_pathkeys is safe to push down */
6945 fpinfo->pushdown_safe = ifpinfo->qp_is_pushdown_safe;
6946
6947 return;
6948 }
6949
6950 /* The input_rel should be a grouping relation */
6951 Assert(input_rel->reloptkind == RELOPT_UPPER_REL &&
6952 ifpinfo->stage == UPPERREL_GROUP_AGG);
6953
6954 /*
6955 * We try to create a path below by extending a simple foreign path for
6956 * the underlying grouping relation to perform the final sort remotely,
6957 * which is stored into the fdw_private list of the resulting path.
6958 */
6959
6960 /* Assess if it is safe to push down the final sort */
6961 foreach(lc, root->sort_pathkeys)
6962 {
6963 PathKey *pathkey = (PathKey *) lfirst(lc);
6964 EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
6965
6966 /*
6967 * is_foreign_expr would detect volatile expressions as well, but
6968 * checking ec_has_volatile here saves some cycles.
6969 */
6970 if (pathkey_ec->ec_has_volatile)
6971 return;
6972
6973 /*
6974 * Can't push down the sort if pathkey's opfamily is not shippable.
6975 */
6976 if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId,
6977 fpinfo))
6978 return;
6979
6980 /*
6981 * The EC must contain a shippable EM that is computed in input_rel's
6982 * reltarget, else we can't push down the sort.
6983 */
6984 if (find_em_for_rel_target(root,
6985 pathkey_ec,
6986 input_rel) == NULL)
6987 return;
6988 }
6989
6990 /* Safe to push down */
6991 fpinfo->pushdown_safe = true;
6992
6993 /* Construct PgFdwPathExtraData */
6994 fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
6995 fpextra->target = root->upper_targets[UPPERREL_ORDERED];
6996 fpextra->has_final_sort = true;
6997
6998 /* Estimate the costs of performing the final sort remotely */
6999 estimate_path_cost_size(root, input_rel, NIL, root->sort_pathkeys, fpextra,
7000 &rows, &width, &disabled_nodes,
7001 &startup_cost, &total_cost);
7002
7003 /*
7004 * Build the fdw_private list that will be used by postgresGetForeignPlan.
7005 * Items in the list must match order in enum FdwPathPrivateIndex.
7006 */
7007 fdw_private = list_make2(makeBoolean(true), makeBoolean(false));
7008
7009 /* Create foreign ordering path */
7010 ordered_path = create_foreign_upper_path(root,
7011 input_rel,
7012 root->upper_targets[UPPERREL_ORDERED],
7013 rows,
7014 disabled_nodes,
7015 startup_cost,
7016 total_cost,
7017 root->sort_pathkeys,
7018 NULL, /* no extra plan */
7019 NIL, /* no fdw_restrictinfo
7020 * list */
7021 fdw_private);
7022
7023 /* and add it to the ordered_rel */
7024 add_path(ordered_rel, (Path *) ordered_path);
7025 }
7026
7027 /*
7028 * add_foreign_final_paths
7029 * Add foreign paths for performing the final processing remotely.
7030 *
7031 * Given input_rel contains the source-data Paths. The paths are added to the
7032 * given final_rel.
7033 */
7034 static void
7035 add_foreign_final_paths(PlannerInfo *root, RelOptInfo *input_rel,
7036 RelOptInfo *final_rel,
7037 FinalPathExtraData *extra)
7038 {
7039 Query *parse = root->parse;
7040 PgFdwRelationInfo *ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
7041 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) final_rel->fdw_private;
7042 bool has_final_sort = false;
7043 List *pathkeys = NIL;
7044 PgFdwPathExtraData *fpextra;
7045 bool save_use_remote_estimate = false;
7046 double rows;
7047 int width;
7048 int disabled_nodes;
7049 Cost startup_cost;
7050 Cost total_cost;
7051 List *fdw_private;
7052 ForeignPath *final_path;
7053
7054 /*
7055 * Currently, we only support this for SELECT commands
7056 */
7057 if (parse->commandType != CMD_SELECT)
7058 return;
7059
7060 /*
7061 * No work if there is no FOR UPDATE/SHARE clause and if there is no need
7062 * to add a LIMIT node
7063 */
7064 if (!parse->rowMarks && !extra->limit_needed)
7065 return;
7066
7067 /* We don't support cases where there are any SRFs in the targetlist */
7068 if (parse->hasTargetSRFs)
7069 return;
7070
7071 /* Save the input_rel as outerrel in fpinfo */
7072 fpinfo->outerrel = input_rel;
7073
7074 /*
7075 * Copy foreign table, foreign server, user mapping, FDW options etc.
7076 * details from the input relation's fpinfo.
7077 */
7078 fpinfo->table = ifpinfo->table;
7079 fpinfo->server = ifpinfo->server;
7080 fpinfo->user = ifpinfo->user;
7081 merge_fdw_options(fpinfo, ifpinfo, NULL);
7082
7083 /*
7084 * If there is no need to add a LIMIT node, there might be a ForeignPath
7085 * in the input_rel's pathlist that implements all behavior of the query.
7086 * Note: we would already have accounted for the query's FOR UPDATE/SHARE
7087 * (if any) before we get here.
7088 */
7089 if (!extra->limit_needed)
7090 {
7091 ListCell *lc;
7092
7093 Assert(parse->rowMarks);
7094
7095 /*
7096 * Grouping and aggregation are not supported with FOR UPDATE/SHARE,
7097 * so the input_rel should be a base, join, or ordered relation; and
7098 * if it's an ordered relation, its input relation should be a base or
7099 * join relation.
7100 */
7101 Assert(input_rel->reloptkind == RELOPT_BASEREL ||
7102 input_rel->reloptkind == RELOPT_JOINREL ||
7103 (input_rel->reloptkind == RELOPT_UPPER_REL &&
7104 ifpinfo->stage == UPPERREL_ORDERED &&
7105 (ifpinfo->outerrel->reloptkind == RELOPT_BASEREL ||
7106 ifpinfo->outerrel->reloptkind == RELOPT_JOINREL)));
7107
7108 foreach(lc, input_rel->pathlist)
7109 {
7110 Path *path = (Path *) lfirst(lc);
7111
7112 /*
7113 * apply_scanjoin_target_to_paths() uses create_projection_path()
7114 * to adjust each of its input paths if needed, whereas
7115 * create_ordered_paths() uses apply_projection_to_path() to do
7116 * that. So the former might have put a ProjectionPath on top of
7117 * the ForeignPath; look through ProjectionPath and see if the
7118 * path underneath it is ForeignPath.
7119 */
7120 if (IsA(path, ForeignPath) ||
7121 (IsA(path, ProjectionPath) &&
7122 IsA(((ProjectionPath *) path)->subpath, ForeignPath)))
7123 {
7124 /*
7125 * Create foreign final path; this gets rid of a
7126 * no-longer-needed outer plan (if any), which makes the
7127 * EXPLAIN output look cleaner
7128 */
7129 final_path = create_foreign_upper_path(root,
7130 path->parent,
7131 path->pathtarget,
7132 path->rows,
7133 path->disabled_nodes,
7134 path->startup_cost,
7135 path->total_cost,
7136 path->pathkeys,
7137 NULL, /* no extra plan */
7138 NIL, /* no fdw_restrictinfo
7139 * list */
7140 NIL); /* no fdw_private */
7141
7142 /* and add it to the final_rel */
7143 add_path(final_rel, (Path *) final_path);
7144
7145 /* Safe to push down */
7146 fpinfo->pushdown_safe = true;
7147
7148 return;
7149 }
7150 }
7151
7152 /*
7153 * If we get here it means no ForeignPaths; since we would already
7154 * have considered pushing down all operations for the query to the
7155 * remote server, give up on it.
7156 */
7157 return;
7158 }
7159
7160 Assert(extra->limit_needed);
7161
7162 /*
7163 * If the input_rel is an ordered relation, replace the input_rel with its
7164 * input relation
7165 */
7166 if (input_rel->reloptkind == RELOPT_UPPER_REL &&
7167 ifpinfo->stage == UPPERREL_ORDERED)
7168 {
7169 input_rel = ifpinfo->outerrel;
7170 ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
7171 has_final_sort = true;
7172 pathkeys = root->sort_pathkeys;
7173 }
7174
7175 /* The input_rel should be a base, join, or grouping relation */
7176 Assert(input_rel->reloptkind == RELOPT_BASEREL ||
7177 input_rel->reloptkind == RELOPT_JOINREL ||
7178 (input_rel->reloptkind == RELOPT_UPPER_REL &&
7179 ifpinfo->stage == UPPERREL_GROUP_AGG));
7180
7181 /*
7182 * We try to create a path below by extending a simple foreign path for
7183 * the underlying base, join, or grouping relation to perform the final
7184 * sort (if has_final_sort) and the LIMIT restriction remotely, which is
7185 * stored into the fdw_private list of the resulting path. (We
7186 * re-estimate the costs of sorting the underlying relation, if
7187 * has_final_sort.)
7188 */
7189
7190 /*
7191 * Assess if it is safe to push down the LIMIT and OFFSET to the remote
7192 * server
7193 */
7194
7195 /*
7196 * If the underlying relation has any local conditions, the LIMIT/OFFSET
7197 * cannot be pushed down.
7198 */
7199 if (ifpinfo->local_conds)
7200 return;
7201
7202 /*
7203 * If the query has FETCH FIRST .. WITH TIES, 1) it must have ORDER BY as
7204 * well, which is used to determine which additional rows tie for the last
7205 * place in the result set, and 2) ORDER BY must already have been
7206 * determined to be safe to push down before we get here. So in that case
7207 * the FETCH clause is safe to push down with ORDER BY if the remote
7208 * server is v13 or later, but if not, the remote query will fail entirely
7209 * for lack of support for it. Since we do not currently have a way to do
7210 * a remote-version check (without accessing the remote server), disable
7211 * pushing the FETCH clause for now.
7212 */
7213 if (parse->limitOption == LIMIT_OPTION_WITH_TIES)
7214 return;
7215
7216 /*
7217 * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are
7218 * not safe to remote.
7219 */
7220 if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) ||
7221 !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount))
7222 return;
7223
7224 /* Safe to push down */
7225 fpinfo->pushdown_safe = true;
7226
7227 /* Construct PgFdwPathExtraData */
7228 fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
7229 fpextra->target = root->upper_targets[UPPERREL_FINAL];
7230 fpextra->has_final_sort = has_final_sort;
7231 fpextra->has_limit = extra->limit_needed;
7232 fpextra->limit_tuples = extra->limit_tuples;
7233 fpextra->count_est = extra->count_est;
7234 fpextra->offset_est = extra->offset_est;
7235
7236 /*
7237 * Estimate the costs of performing the final sort and the LIMIT
7238 * restriction remotely. If has_final_sort is false, we wouldn't need to
7239 * execute EXPLAIN anymore if use_remote_estimate, since the costs can be
7240 * roughly estimated using the costs we already have for the underlying
7241 * relation, in the same way as when use_remote_estimate is false. Since
7242 * it's pretty expensive to execute EXPLAIN, force use_remote_estimate to
7243 * false in that case.
7244 */
7245 if (!fpextra->has_final_sort)
7246 {
7247 save_use_remote_estimate = ifpinfo->use_remote_estimate;
7248 ifpinfo->use_remote_estimate = false;
7249 }
7250 estimate_path_cost_size(root, input_rel, NIL, pathkeys, fpextra,
7251 &rows, &width, &disabled_nodes,
7252 &startup_cost, &total_cost);
7253 if (!fpextra->has_final_sort)
7254 ifpinfo->use_remote_estimate = save_use_remote_estimate;
7255
7256 /*
7257 * Build the fdw_private list that will be used by postgresGetForeignPlan.
7258 * Items in the list must match order in enum FdwPathPrivateIndex.
7259 */
7260 fdw_private = list_make2(makeBoolean(has_final_sort),
7261 makeBoolean(extra->limit_needed));
7262
7263 /*
7264 * Create foreign final path; this gets rid of a no-longer-needed outer
7265 * plan (if any), which makes the EXPLAIN output look cleaner
7266 */
7267 final_path = create_foreign_upper_path(root,
7268 input_rel,
7269 root->upper_targets[UPPERREL_FINAL],
7270 rows,
7271 disabled_nodes,
7272 startup_cost,
7273 total_cost,
7274 pathkeys,
7275 NULL, /* no extra plan */
7276 NIL, /* no fdw_restrictinfo list */
7277 fdw_private);
7278
7279 /* and add it to the final_rel */
7280 add_path(final_rel, (Path *) final_path);
7281 }
7282
7283 /*
7284 * postgresIsForeignPathAsyncCapable
7285 * Check whether a given ForeignPath node is async-capable.
7286 */
7287 static bool
7288 postgresIsForeignPathAsyncCapable(ForeignPath *path)
7289 {
7290 RelOptInfo *rel = ((Path *) path)->parent;
7291 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
7292
7293 return fpinfo->async_capable;
7294 }
7295
7296 /*
7297 * postgresForeignAsyncRequest
7298 * Asynchronously request next tuple from a foreign PostgreSQL table.
7299 */
7300 static void
7301 postgresForeignAsyncRequest(AsyncRequest *areq)
7302 {
7303 produce_tuple_asynchronously(areq, true);
7304 }
7305
7306 /*
7307 * postgresForeignAsyncConfigureWait
7308 * Configure a file descriptor event for which we wish to wait.
7309 */
7310 static void
7311 postgresForeignAsyncConfigureWait(AsyncRequest *areq)
7312 {
7313 ForeignScanState *node = (ForeignScanState *) areq->requestee;
7314 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7315 AsyncRequest *pendingAreq = fsstate->conn_state->pendingAreq;
7316 AppendState *requestor = (AppendState *) areq->requestor;
7317 WaitEventSet *set = requestor->as_eventset;
7318
7319 /* This should not be called unless callback_pending */
7320 Assert(areq->callback_pending);
7321
7322 /*
7323 * If process_pending_request() has been invoked on the given request
7324 * before we get here, we might have some tuples already; in which case
7325 * complete the request
7326 */
7327 if (fsstate->next_tuple < fsstate->num_tuples)
7328 {
7329 complete_pending_request(areq);
7330 if (areq->request_complete)
7331 return;
7332 Assert(areq->callback_pending);
7333 }
7334
7335 /* We must have run out of tuples */
7336 Assert(fsstate->next_tuple >= fsstate->num_tuples);
7337
7338 /* The core code would have registered postmaster death event */
7339 Assert(GetNumRegisteredWaitEvents(set) >= 1);
7340
7341 /* Begin an asynchronous data fetch if not already done */
7342 if (!pendingAreq)
7343 fetch_more_data_begin(areq);
7344 else if (pendingAreq->requestor != areq->requestor)
7345 {
7346 /*
7347 * This is the case when the in-process request was made by another
7348 * Append. Note that it might be useless to process the request made
7349 * by that Append, because the query might not need tuples from that
7350 * Append anymore; so we avoid processing it to begin a fetch for the
7351 * given request if possible. If there are any child subplans of the
7352 * same parent that are ready for new requests, skip the given
7353 * request. Likewise, if there are any configured events other than
7354 * the postmaster death event, skip it. Otherwise, process the
7355 * in-process request, then begin a fetch to configure the event
7356 * below, because we might otherwise end up with no configured events
7357 * other than the postmaster death event.
7358 */
7359 if (!bms_is_empty(requestor->as_needrequest))
7360 return;
7361 if (GetNumRegisteredWaitEvents(set) > 1)
7362 return;
7363 process_pending_request(pendingAreq);
7364 fetch_more_data_begin(areq);
7365 }
7366 else if (pendingAreq->requestee != areq->requestee)
7367 {
7368 /*
7369 * This is the case when the in-process request was made by the same
7370 * parent but for a different child. Since we configure only the
7371 * event for the request made for that child, skip the given request.
7372 */
7373 return;
7374 }
7375 else
7376 Assert(pendingAreq == areq);
7377
7378 AddWaitEventToSet(set, WL_SOCKET_READABLE, PQsocket(fsstate->conn),
7379 NULL, areq);
7380 }
7381
7382 /*
7383 * postgresForeignAsyncNotify
7384 * Fetch some more tuples from a file descriptor that becomes ready,
7385 * requesting next tuple.
7386 */
7387 static void
7388 postgresForeignAsyncNotify(AsyncRequest *areq)
7389 {
7390 ForeignScanState *node = (ForeignScanState *) areq->requestee;
7391 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7392
7393 /* The core code would have initialized the callback_pending flag */
7394 Assert(!areq->callback_pending);
7395
7396 /*
7397 * If process_pending_request() has been invoked on the given request
7398 * before we get here, we might have some tuples already; in which case
7399 * produce the next tuple
7400 */
7401 if (fsstate->next_tuple < fsstate->num_tuples)
7402 {
7403 produce_tuple_asynchronously(areq, true);
7404 return;
7405 }
7406
7407 /* We must have run out of tuples */
7408 Assert(fsstate->next_tuple >= fsstate->num_tuples);
7409
7410 /* The request should be currently in-process */
7411 Assert(fsstate->conn_state->pendingAreq == areq);
7412
7413 /* On error, report the original query, not the FETCH. */
7414 if (!PQconsumeInput(fsstate->conn))
7415 pgfdw_report_error(ERROR, NULL, fsstate->conn, false, fsstate->query);
7416
7417 fetch_more_data(node);
7418
7419 produce_tuple_asynchronously(areq, true);
7420 }
7421
7422 /*
7423 * Asynchronously produce next tuple from a foreign PostgreSQL table.
7424 */
7425 static void
7426 produce_tuple_asynchronously(AsyncRequest *areq, bool fetch)
7427 {
7428 ForeignScanState *node = (ForeignScanState *) areq->requestee;
7429 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7430 AsyncRequest *pendingAreq = fsstate->conn_state->pendingAreq;
7431 TupleTableSlot *result;
7432
7433 /* This should not be called if the request is currently in-process */
7434 Assert(areq != pendingAreq);
7435
7436 /* Fetch some more tuples, if we've run out */
7437 if (fsstate->next_tuple >= fsstate->num_tuples)
7438 {
7439 /* No point in another fetch if we already detected EOF, though */
7440 if (!fsstate->eof_reached)
7441 {
7442 /* Mark the request as pending for a callback */
7443 ExecAsyncRequestPending(areq);
7444 /* Begin another fetch if requested and if no pending request */
7445 if (fetch && !pendingAreq)
7446 fetch_more_data_begin(areq);
7447 }
7448 else
7449 {
7450 /* There's nothing more to do; just return a NULL pointer */
7451 result = NULL;
7452 /* Mark the request as complete */
7453 ExecAsyncRequestDone(areq, result);
7454 }
7455 return;
7456 }
7457
7458 /* Get a tuple from the ForeignScan node */
7459 result = areq->requestee->ExecProcNodeReal(areq->requestee);
7460 if (!TupIsNull(result))
7461 {
7462 /* Mark the request as complete */
7463 ExecAsyncRequestDone(areq, result);
7464 return;
7465 }
7466
7467 /* We must have run out of tuples */
7468 Assert(fsstate->next_tuple >= fsstate->num_tuples);
7469
7470 /* Fetch some more tuples, if we've not detected EOF yet */
7471 if (!fsstate->eof_reached)
7472 {
7473 /* Mark the request as pending for a callback */
7474 ExecAsyncRequestPending(areq);
7475 /* Begin another fetch if requested and if no pending request */
7476 if (fetch && !pendingAreq)
7477 fetch_more_data_begin(areq);
7478 }
7479 else
7480 {
7481 /* There's nothing more to do; just return a NULL pointer */
7482 result = NULL;
7483 /* Mark the request as complete */
7484 ExecAsyncRequestDone(areq, result);
7485 }
7486 }
7487
7488 /*
7489 * Begin an asynchronous data fetch.
7490 *
7491 * Note: this function assumes there is no currently-in-progress asynchronous
7492 * data fetch.
7493 *
7494 * Note: fetch_more_data must be called to fetch the result.
7495 */
7496 static void
7497 fetch_more_data_begin(AsyncRequest *areq)
7498 {
7499 ForeignScanState *node = (ForeignScanState *) areq->requestee;
7500 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7501 char sql[64];
7502
7503 Assert(!fsstate->conn_state->pendingAreq);
7504
7505 /* Create the cursor synchronously. */
7506 if (!fsstate->cursor_exists)
7507 create_cursor(node);
7508
7509 /* We will send this query, but not wait for the response. */
7510 snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
7511 fsstate->fetch_size, fsstate->cursor_number);
7512
7513 if (!PQsendQuery(fsstate->conn, sql))
7514 pgfdw_report_error(ERROR, NULL, fsstate->conn, false, fsstate->query);
7515
7516 /* Remember that the request is in process */
7517 fsstate->conn_state->pendingAreq = areq;
7518 }
7519
7520 /*
7521 * Process a pending asynchronous request.
7522 */
7523 void
7524 process_pending_request(AsyncRequest *areq)
7525 {
7526 ForeignScanState *node = (ForeignScanState *) areq->requestee;
7527 PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7528
7529 /* The request would have been pending for a callback */
7530 Assert(areq->callback_pending);
7531
7532 /* The request should be currently in-process */
7533 Assert(fsstate->conn_state->pendingAreq == areq);
7534
7535 fetch_more_data(node);
7536
7537 /*
7538 * If we didn't get any tuples, must be end of data; complete the request
7539 * now. Otherwise, we postpone completing the request until we are called
7540 * from postgresForeignAsyncConfigureWait()/postgresForeignAsyncNotify().
7541 */
7542 if (fsstate->next_tuple >= fsstate->num_tuples)
7543 {
7544 /* Unlike AsyncNotify, we unset callback_pending ourselves */
7545 areq->callback_pending = false;
7546 /* Mark the request as complete */
7547 ExecAsyncRequestDone(areq, NULL);
7548 /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
7549 ExecAsyncResponse(areq);
7550 }
7551 }
7552
7553 /*
7554 * Complete a pending asynchronous request.
7555 */
7556 static void
7557 complete_pending_request(AsyncRequest *areq)
7558 {
7559 /* The request would have been pending for a callback */
7560 Assert(areq->callback_pending);
7561
7562 /* Unlike AsyncNotify, we unset callback_pending ourselves */
7563 areq->callback_pending = false;
7564
7565 /* We begin a fetch afterwards if necessary; don't fetch */
7566 produce_tuple_asynchronously(areq, false);
7567
7568 /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
7569 ExecAsyncResponse(areq);
7570
7571 /* Also, we do instrumentation ourselves, if required */
7572 if (areq->requestee->instrument)
7573 InstrUpdateTupleCount(areq->requestee->instrument,
7574 TupIsNull(areq->result) ? 0.0 : 1.0);
7575 }
7576
7577 /*
7578 * Create a tuple from the specified row of the PGresult.
7579 *
7580 * rel is the local representation of the foreign table, attinmeta is
7581 * conversion data for the rel's tupdesc, and retrieved_attrs is an
7582 * integer list of the table column numbers present in the PGresult.
7583 * fsstate is the ForeignScan plan node's execution state.
7584 * temp_context is a working context that can be reset after each tuple.
7585 *
7586 * Note: either rel or fsstate, but not both, can be NULL. rel is NULL
7587 * if we're processing a remote join, while fsstate is NULL in a non-query
7588 * context such as ANALYZE, or if we're processing a non-scan query node.
7589 */
7590 static HeapTuple
7591 make_tuple_from_result_row(PGresult *res,
7592 int row,
7593 Relation rel,
7594 AttInMetadata *attinmeta,
7595 List *retrieved_attrs,
7596 ForeignScanState *fsstate,
7597 MemoryContext temp_context)
7598 {
7599 HeapTuple tuple;
7600 TupleDesc tupdesc;
7601 Datum *values;
7602 bool *nulls;
7603 ItemPointer ctid = NULL;
7604 ConversionLocation errpos;
7605 ErrorContextCallback errcallback;
7606 MemoryContext oldcontext;
7607 ListCell *lc;
7608 int j;
7609
7610 Assert(row < PQntuples(res));
7611
7612 /*
7613 * Do the following work in a temp context that we reset after each tuple.
7614 * This cleans up not only the data we have direct access to, but any
7615 * cruft the I/O functions might leak.
7616 */
7617 oldcontext = MemoryContextSwitchTo(temp_context);
7618
7619 /*
7620 * Get the tuple descriptor for the row. Use the rel's tupdesc if rel is
7621 * provided, otherwise look to the scan node's ScanTupleSlot.
7622 */
7623 if (rel)
7624 tupdesc = RelationGetDescr(rel);
7625 else
7626 {
7627 Assert(fsstate);
7628 tupdesc = fsstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
7629 }
7630
7631 values = (Datum *) palloc0(tupdesc->natts * sizeof(Datum));
7632 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
7633 /* Initialize to nulls for any columns not present in result */
7634 memset(nulls, true, tupdesc->natts * sizeof(bool));
7635
7636 /*
7637 * Set up and install callback to report where conversion error occurs.
7638 */
7639 errpos.cur_attno = 0;
7640 errpos.rel = rel;
7641 errpos.fsstate = fsstate;
7642 errcallback.callback = conversion_error_callback;
7643 errcallback.arg = &errpos;
7644 errcallback.previous = error_context_stack;
7645 error_context_stack = &errcallback;
7646
7647 /*
7648 * i indexes columns in the relation, j indexes columns in the PGresult.
7649 */
7650 j = 0;
7651 foreach(lc, retrieved_attrs)
7652 {
7653 int i = lfirst_int(lc);
7654 char *valstr;
7655
7656 /* fetch next column's textual value */
7657 if (PQgetisnull(res, row, j))
7658 valstr = NULL;
7659 else
7660 valstr = PQgetvalue(res, row, j);
7661
7662 /*
7663 * convert value to internal representation
7664 *
7665 * Note: we ignore system columns other than ctid and oid in result
7666 */
7667 errpos.cur_attno = i;
7668 if (i > 0)
7669 {
7670 /* ordinary column */
7671 Assert(i <= tupdesc->natts);
7672 nulls[i - 1] = (valstr == NULL);
7673 /* Apply the input function even to nulls, to support domains */
7674 values[i - 1] = InputFunctionCall(&attinmeta->attinfuncs[i - 1],
7675 valstr,
7676 attinmeta->attioparams[i - 1],
7677 attinmeta->atttypmods[i - 1]);
7678 }
7679 else if (i == SelfItemPointerAttributeNumber)
7680 {
7681 /* ctid */
7682 if (valstr != NULL)
7683 {
7684 Datum datum;
7685
7686 datum = DirectFunctionCall1(tidin, CStringGetDatum(valstr));
7687 ctid = (ItemPointer) DatumGetPointer(datum);
7688 }
7689 }
7690 errpos.cur_attno = 0;
7691
7692 j++;
7693 }
7694
7695 /* Uninstall error context callback. */
7696 error_context_stack = errcallback.previous;
7697
7698 /*
7699 * Check we got the expected number of columns. Note: j == 0 and
7700 * PQnfields == 1 is expected, since deparse emits a NULL if no columns.
7701 */
7702 if (j > 0 && j != PQnfields(res))
7703 elog(ERROR, "remote query result does not match the foreign table");
7704
7705 /*
7706 * Build the result tuple in caller's memory context.
7707 */
7708 MemoryContextSwitchTo(oldcontext);
7709
7710 tuple = heap_form_tuple(tupdesc, values, nulls);
7711
7712 /*
7713 * If we have a CTID to return, install it in both t_self and t_ctid.
7714 * t_self is the normal place, but if the tuple is converted to a
7715 * composite Datum, t_self will be lost; setting t_ctid allows CTID to be
7716 * preserved during EvalPlanQual re-evaluations (see ROW_MARK_COPY code).
7717 */
7718 if (ctid)
7719 tuple->t_self = tuple->t_data->t_ctid = *ctid;
7720
7721 /*
7722 * Stomp on the xmin, xmax, and cmin fields from the tuple created by
7723 * heap_form_tuple. heap_form_tuple actually creates the tuple with
7724 * DatumTupleFields, not HeapTupleFields, but the executor expects
7725 * HeapTupleFields and will happily extract system columns on that
7726 * assumption. If we don't do this then, for example, the tuple length
7727 * ends up in the xmin field, which isn't what we want.
7728 */
7729 HeapTupleHeaderSetXmax(tuple->t_data, InvalidTransactionId);
7730 HeapTupleHeaderSetXmin(tuple->t_data, InvalidTransactionId);
7731 HeapTupleHeaderSetCmin(tuple->t_data, InvalidTransactionId);
7732
7733 /* Clean up */
7734 MemoryContextReset(temp_context);
7735
7736 return tuple;
7737 }
7738
7739 /*
7740 * Callback function which is called when error occurs during column value
7741 * conversion. Print names of column and relation.
7742 *
7743 * Note that this function mustn't do any catalog lookups, since we are in
7744 * an already-failed transaction. Fortunately, we can get the needed info
7745 * from the relation or the query's rangetable instead.
7746 */
7747 static void
7748 conversion_error_callback(void *arg)
7749 {
7750 ConversionLocation *errpos = (ConversionLocation *) arg;
7751 Relation rel = errpos->rel;
7752 ForeignScanState *fsstate = errpos->fsstate;
7753 const char *attname = NULL;
7754 const char *relname = NULL;
7755 bool is_wholerow = false;
7756
7757 /*
7758 * If we're in a scan node, always use aliases from the rangetable, for
7759 * consistency between the simple-relation and remote-join cases. Look at
7760 * the relation's tupdesc only if we're not in a scan node.
7761 */
7762 if (fsstate)
7763 {
7764 /* ForeignScan case */
7765 ForeignScan *fsplan = castNode(ForeignScan, fsstate->ss.ps.plan);
7766 int varno = 0;
7767 AttrNumber colno = 0;
7768
7769 if (fsplan->scan.scanrelid > 0)
7770 {
7771 /* error occurred in a scan against a foreign table */
7772 varno = fsplan->scan.scanrelid;
7773 colno = errpos->cur_attno;
7774 }
7775 else
7776 {
7777 /* error occurred in a scan against a foreign join */
7778 TargetEntry *tle;
7779
7780 tle = list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
7781 errpos->cur_attno - 1);
7782
7783 /*
7784 * Target list can have Vars and expressions. For Vars, we can
7785 * get some information, however for expressions we can't. Thus
7786 * for expressions, just show generic context message.
7787 */
7788 if (IsA(tle->expr, Var))
7789 {
7790 Var *var = (Var *) tle->expr;
7791
7792 varno = var->varno;
7793 colno = var->varattno;
7794 }
7795 }
7796
7797 if (varno > 0)
7798 {
7799 EState *estate = fsstate->ss.ps.state;
7800 RangeTblEntry *rte = exec_rt_fetch(varno, estate);
7801
7802 relname = rte->eref->aliasname;
7803
7804 if (colno == 0)
7805 is_wholerow = true;
7806 else if (colno > 0 && colno <= list_length(rte->eref->colnames))
7807 attname = strVal(list_nth(rte->eref->colnames, colno - 1));
7808 else if (colno == SelfItemPointerAttributeNumber)
7809 attname = "ctid";
7810 }
7811 }
7812 else if (rel)
7813 {
7814 /* Non-ForeignScan case (we should always have a rel here) */
7815 TupleDesc tupdesc = RelationGetDescr(rel);
7816
7817 relname = RelationGetRelationName(rel);
7818 if (errpos->cur_attno > 0 && errpos->cur_attno <= tupdesc->natts)
7819 {
7820 Form_pg_attribute attr = TupleDescAttr(tupdesc,
7821 errpos->cur_attno - 1);
7822
7823 attname = NameStr(attr->attname);
7824 }
7825 else if (errpos->cur_attno == SelfItemPointerAttributeNumber)
7826 attname = "ctid";
7827 }
7828
7829 if (relname && is_wholerow)
7830 errcontext("whole-row reference to foreign table \"%s\"", relname);
7831 else if (relname && attname)
7832 errcontext("column \"%s\" of foreign table \"%s\"", attname, relname);
7833 else
7834 errcontext("processing expression at position %d in select list",
7835 errpos->cur_attno);
7836 }
7837
7838 /*
7839 * Given an EquivalenceClass and a foreign relation, find an EC member
7840 * that can be used to sort the relation remotely according to a pathkey
7841 * using this EC.
7842 *
7843 * If there is more than one suitable candidate, return an arbitrary
7844 * one of them. If there is none, return NULL.
7845 *
7846 * This checks that the EC member expression uses only Vars from the given
7847 * rel and is shippable. Caller must separately verify that the pathkey's
7848 * ordering operator is shippable.
7849 */
7850 EquivalenceMember *
7851 find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
7852 {
7853 PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
7854 EquivalenceMemberIterator it;
7855 EquivalenceMember *em;
7856
7857 setup_eclass_member_iterator(&it, ec, rel->relids);
7858 while ((em = eclass_member_iterator_next(&it)) != NULL)
7859 {
7860 /*
7861 * Note we require !bms_is_empty, else we'd accept constant
7862 * expressions which are not suitable for the purpose.
7863 */
7864 if (bms_is_subset(em->em_relids, rel->relids) &&
7865 !bms_is_empty(em->em_relids) &&
7866 bms_is_empty(bms_intersect(em->em_relids, fpinfo->hidden_subquery_rels)) &&
7867 is_foreign_expr(root, rel, em->em_expr))
7868 return em;
7869 }
7870
7871 return NULL;
7872 }
7873
7874 /*
7875 * Find an EquivalenceClass member that is to be computed as a sort column
7876 * in the given rel's reltarget, and is shippable.
7877 *
7878 * If there is more than one suitable candidate, return an arbitrary
7879 * one of them. If there is none, return NULL.
7880 *
7881 * This checks that the EC member expression uses only Vars from the given
7882 * rel and is shippable. Caller must separately verify that the pathkey's
7883 * ordering operator is shippable.
7884 */
7885 EquivalenceMember *
7886 find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec,
7887 RelOptInfo *rel)
7888 {
7889 PathTarget *target = rel->reltarget;
7890 ListCell *lc1;
7891 int i;
7892
7893 i = 0;
7894 foreach(lc1, target->exprs)
7895 {
7896 Expr *expr = (Expr *) lfirst(lc1);
7897 Index sgref = get_pathtarget_sortgroupref(target, i);
7898 ListCell *lc2;
7899
7900 /* Ignore non-sort expressions */
7901 if (sgref == 0 ||
7902 get_sortgroupref_clause_noerr(sgref,
7903 root->parse->sortClause) == NULL)
7904 {
7905 i++;
7906 continue;
7907 }
7908
7909 /* We ignore binary-compatible relabeling on both ends */
7910 while (expr && IsA(expr, RelabelType))
7911 expr = ((RelabelType *) expr)->arg;
7912
7913 /*
7914 * Locate an EquivalenceClass member matching this expr, if any.
7915 * Ignore child members.
7916 */
7917 foreach(lc2, ec->ec_members)
7918 {
7919 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
7920 Expr *em_expr;
7921
7922 /* Don't match constants */
7923 if (em->em_is_const)
7924 continue;
7925
7926 /* Child members should not exist in ec_members */
7927 Assert(!em->em_is_child);
7928
7929 /* Match if same expression (after stripping relabel) */
7930 em_expr = em->em_expr;
7931 while (em_expr && IsA(em_expr, RelabelType))
7932 em_expr = ((RelabelType *) em_expr)->arg;
7933
7934 if (!equal(em_expr, expr))
7935 continue;
7936
7937 /* Check that expression (including relabels!) is shippable */
7938 if (is_foreign_expr(root, rel, em->em_expr))
7939 return em;
7940 }
7941
7942 i++;
7943 }
7944
7945 return NULL;
7946 }
7947
7948 /*
7949 * Determine batch size for a given foreign table. The option specified for
7950 * a table has precedence.
7951 */
7952 static int
7953 get_batch_size_option(Relation rel)
7954 {
7955 Oid foreigntableid = RelationGetRelid(rel);
7956 ForeignTable *table;
7957 ForeignServer *server;
7958 List *options;
7959 ListCell *lc;
7960
7961 /* we use 1 by default, which means "no batching" */
7962 int batch_size = 1;
7963
7964 /*
7965 * Load options for table and server. We append server options after table
7966 * options, because table options take precedence.
7967 */
7968 table = GetForeignTable(foreigntableid);
7969 server = GetForeignServer(table->serverid);
7970
7971 options = NIL;
7972 options = list_concat(options, table->options);
7973 options = list_concat(options, server->options);
7974
7975 /* See if either table or server specifies batch_size. */
7976 foreach(lc, options)
7977 {
7978 DefElem *def = (DefElem *) lfirst(lc);
7979
7980 if (strcmp(def->defname, "batch_size") == 0)
7981 {
7982 (void) parse_int(defGetString(def), &batch_size, 0, NULL);
7983 break;
7984 }
7985 }
7986
7987 return batch_size;
7988 }