PostgreSQL Source Code  git master
postgres_fdw.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * postgres_fdw.c
4  * Foreign-data wrapper for remote PostgreSQL servers
5  *
6  * Portions Copyright (c) 2012-2022, 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_class.h"
21 #include "catalog/pg_opfamily.h"
22 #include "commands/defrem.h"
23 #include "commands/explain.h"
24 #include "commands/vacuum.h"
25 #include "executor/execAsync.h"
26 #include "foreign/fdwapi.h"
27 #include "funcapi.h"
28 #include "miscadmin.h"
29 #include "nodes/makefuncs.h"
30 #include "nodes/nodeFuncs.h"
31 #include "optimizer/appendinfo.h"
32 #include "optimizer/clauses.h"
33 #include "optimizer/cost.h"
34 #include "optimizer/optimizer.h"
35 #include "optimizer/pathnode.h"
36 #include "optimizer/paths.h"
37 #include "optimizer/planmain.h"
38 #include "optimizer/prep.h"
39 #include "optimizer/restrictinfo.h"
40 #include "optimizer/tlist.h"
41 #include "parser/parsetree.h"
42 #include "postgres_fdw.h"
43 #include "storage/latch.h"
44 #include "utils/builtins.h"
45 #include "utils/float.h"
46 #include "utils/guc.h"
47 #include "utils/lsyscache.h"
48 #include "utils/memutils.h"
49 #include "utils/rel.h"
50 #include "utils/sampling.h"
51 #include "utils/selfuncs.h"
52 
54 
55 /* Default CPU cost to start up a foreign query. */
56 #define DEFAULT_FDW_STARTUP_COST 100.0
57 
58 /* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
59 #define DEFAULT_FDW_TUPLE_COST 0.01
60 
61 /* If no remote estimates, assume a sort costs 20% extra */
62 #define DEFAULT_FDW_SORT_MULTIPLIER 1.2
63 
64 /*
65  * Indexes of FDW-private information stored in fdw_private lists.
66  *
67  * These items are indexed with the enum FdwScanPrivateIndex, so an item
68  * can be fetched with list_nth(). For example, to get the SELECT statement:
69  * sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
70  */
72 {
73  /* SQL statement to execute remotely (as a String node) */
75  /* Integer list of attribute numbers retrieved by the SELECT */
77  /* Integer representing the desired fetch_size */
79 
80  /*
81  * String describing join i.e. names of relations being joined and types
82  * of join, added when the scan is join
83  */
85 };
86 
87 /*
88  * Similarly, this enum describes what's kept in the fdw_private list for
89  * a ModifyTable node referencing a postgres_fdw foreign table. We store:
90  *
91  * 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server
92  * 2) Integer list of target attribute numbers for INSERT/UPDATE
93  * (NIL for a DELETE)
94  * 3) Length till the end of VALUES clause for INSERT
95  * (-1 for a DELETE/UPDATE)
96  * 4) Boolean flag showing if the remote query has a RETURNING clause
97  * 5) Integer list of attribute numbers retrieved by RETURNING, if any
98  */
100 {
101  /* SQL statement to execute remotely (as a String node) */
103  /* Integer list of target attribute numbers for INSERT/UPDATE */
105  /* Length till the end of VALUES clause (as an Integer node) */
107  /* has-returning flag (as a Boolean node) */
109  /* Integer list of attribute numbers retrieved by RETURNING */
111 };
112 
113 /*
114  * Similarly, this enum describes what's kept in the fdw_private list for
115  * a ForeignScan node that modifies a foreign table directly. We store:
116  *
117  * 1) UPDATE/DELETE statement text to be sent to the remote server
118  * 2) Boolean flag showing if the remote query has a RETURNING clause
119  * 3) Integer list of attribute numbers retrieved by RETURNING, if any
120  * 4) Boolean flag showing if we set the command es_processed
121  */
123 {
124  /* SQL statement to execute remotely (as a String node) */
126  /* has-returning flag (as a Boolean node) */
128  /* Integer list of attribute numbers retrieved by RETURNING */
130  /* set-processed flag (as a Boolean node) */
132 };
133 
134 /*
135  * Execution state of a foreign scan using postgres_fdw.
136  */
137 typedef struct PgFdwScanState
138 {
139  Relation rel; /* relcache entry for the foreign table. NULL
140  * for a foreign join scan. */
141  TupleDesc tupdesc; /* tuple descriptor of scan */
142  AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
143 
144  /* extracted fdw_private data */
145  char *query; /* text of SELECT command */
146  List *retrieved_attrs; /* list of retrieved attribute numbers */
147 
148  /* for remote query execution */
149  PGconn *conn; /* connection for the scan */
150  PgFdwConnState *conn_state; /* extra per-connection state */
151  unsigned int cursor_number; /* quasi-unique ID for my cursor */
152  bool cursor_exists; /* have we created the cursor? */
153  int numParams; /* number of parameters passed to query */
154  FmgrInfo *param_flinfo; /* output conversion functions for them */
155  List *param_exprs; /* executable expressions for param values */
156  const char **param_values; /* textual values of query parameters */
157 
158  /* for storing result tuples */
159  HeapTuple *tuples; /* array of currently-retrieved tuples */
160  int num_tuples; /* # of tuples in array */
161  int next_tuple; /* index of next one to return */
162 
163  /* batch-level state, for optimizing rewinds and avoiding useless fetch */
164  int fetch_ct_2; /* Min(# of fetches done, 2) */
165  bool eof_reached; /* true if last fetch reached EOF */
166 
167  /* for asynchronous execution */
168  bool async_capable; /* engage asynchronous-capable logic? */
169 
170  /* working memory contexts */
171  MemoryContext batch_cxt; /* context holding current batch of tuples */
172  MemoryContext temp_cxt; /* context for per-tuple temporary data */
173 
174  int fetch_size; /* number of tuples per fetch */
176 
177 /*
178  * Execution state of a foreign insert/update/delete operation.
179  */
180 typedef struct PgFdwModifyState
181 {
182  Relation rel; /* relcache entry for the foreign table */
183  AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
184 
185  /* for remote query execution */
186  PGconn *conn; /* connection for the scan */
187  PgFdwConnState *conn_state; /* extra per-connection state */
188  char *p_name; /* name of prepared statement, if created */
189 
190  /* extracted fdw_private data */
191  char *query; /* text of INSERT/UPDATE/DELETE command */
192  char *orig_query; /* original text of INSERT command */
193  List *target_attrs; /* list of target attribute numbers */
194  int values_end; /* length up to the end of VALUES */
195  int batch_size; /* value of FDW option "batch_size" */
196  bool has_returning; /* is there a RETURNING clause? */
197  List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
198 
199  /* info about parameters for prepared statement */
200  AttrNumber ctidAttno; /* attnum of input resjunk ctid column */
201  int p_nums; /* number of parameters to transmit */
202  FmgrInfo *p_flinfo; /* output conversion functions for them */
203 
204  /* batch operation stuff */
205  int num_slots; /* number of slots to insert */
206 
207  /* working memory context */
208  MemoryContext temp_cxt; /* context for per-tuple temporary data */
209 
210  /* for update row movement if subplan result rel */
211  struct PgFdwModifyState *aux_fmstate; /* foreign-insert state, if
212  * created */
214 
215 /*
216  * Execution state of a foreign scan that modifies a foreign table directly.
217  */
219 {
220  Relation rel; /* relcache entry for the foreign table */
221  AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
222 
223  /* extracted fdw_private data */
224  char *query; /* text of UPDATE/DELETE command */
225  bool has_returning; /* is there a RETURNING clause? */
226  List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
227  bool set_processed; /* do we set the command es_processed? */
228 
229  /* for remote query execution */
230  PGconn *conn; /* connection for the update */
231  PgFdwConnState *conn_state; /* extra per-connection state */
232  int numParams; /* number of parameters passed to query */
233  FmgrInfo *param_flinfo; /* output conversion functions for them */
234  List *param_exprs; /* executable expressions for param values */
235  const char **param_values; /* textual values of query parameters */
236 
237  /* for storing result tuples */
238  PGresult *result; /* result for query */
239  int num_tuples; /* # of result tuples */
240  int next_tuple; /* index of next one to return */
241  Relation resultRel; /* relcache entry for the target relation */
242  AttrNumber *attnoMap; /* array of attnums of input user columns */
243  AttrNumber ctidAttno; /* attnum of input ctid column */
244  AttrNumber oidAttno; /* attnum of input oid column */
245  bool hasSystemCols; /* are there system columns of resultRel? */
246 
247  /* working memory context */
248  MemoryContext temp_cxt; /* context for per-tuple temporary data */
250 
251 /*
252  * Workspace for analyzing a foreign table.
253  */
254 typedef struct PgFdwAnalyzeState
255 {
256  Relation rel; /* relcache entry for the foreign table */
257  AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
258  List *retrieved_attrs; /* attr numbers retrieved by query */
259 
260  /* collected sample rows */
261  HeapTuple *rows; /* array of size targrows */
262  int targrows; /* target # of sample rows */
263  int numrows; /* # of sample rows collected */
264 
265  /* for random sampling */
266  double samplerows; /* # of rows fetched */
267  double rowstoskip; /* # of rows to skip before next sample */
268  ReservoirStateData rstate; /* state for reservoir sampling */
269 
270  /* working memory contexts */
271  MemoryContext anl_cxt; /* context for per-analyze lifespan data */
272  MemoryContext temp_cxt; /* context for per-tuple temporary data */
274 
275 /*
276  * This enum describes what's kept in the fdw_private list for a ForeignPath.
277  * We store:
278  *
279  * 1) Boolean flag showing if the remote query has the final sort
280  * 2) Boolean flag showing if the remote query has the LIMIT clause
281  */
283 {
284  /* has-final-sort flag (as a Boolean node) */
286  /* has-limit flag (as a Boolean node) */
288 };
289 
290 /* Struct for extra information passed to estimate_path_cost_size() */
291 typedef struct
292 {
295  bool has_limit;
296  double limit_tuples;
297  int64 count_est;
298  int64 offset_est;
300 
301 /*
302  * Identify the attribute where data conversion fails.
303  */
304 typedef struct ConversionLocation
305 {
306  AttrNumber cur_attno; /* attribute number being processed, or 0 */
307  Relation rel; /* foreign table being processed, or NULL */
308  ForeignScanState *fsstate; /* plan node being processed, or NULL */
310 
311 /* Callback argument for ec_member_matches_foreign */
312 typedef struct
313 {
314  Expr *current; /* current expr, or NULL if not yet found */
315  List *already_used; /* expressions already dealt with */
317 
318 /*
319  * SQL functions
320  */
322 
323 /*
324  * FDW callback routines
325  */
326 static void postgresGetForeignRelSize(PlannerInfo *root,
327  RelOptInfo *baserel,
328  Oid foreigntableid);
329 static void postgresGetForeignPaths(PlannerInfo *root,
330  RelOptInfo *baserel,
331  Oid foreigntableid);
333  RelOptInfo *foreignrel,
334  Oid foreigntableid,
335  ForeignPath *best_path,
336  List *tlist,
337  List *scan_clauses,
338  Plan *outer_plan);
339 static void postgresBeginForeignScan(ForeignScanState *node, int eflags);
342 static void postgresEndForeignScan(ForeignScanState *node);
344  Index rtindex,
345  RangeTblEntry *target_rte,
346  Relation target_relation);
348  ModifyTable *plan,
349  Index resultRelation,
350  int subplan_index);
351 static void postgresBeginForeignModify(ModifyTableState *mtstate,
352  ResultRelInfo *resultRelInfo,
353  List *fdw_private,
354  int subplan_index,
355  int eflags);
357  ResultRelInfo *resultRelInfo,
358  TupleTableSlot *slot,
359  TupleTableSlot *planSlot);
361  ResultRelInfo *resultRelInfo,
362  TupleTableSlot **slots,
363  TupleTableSlot **planSlots,
364  int *numSlots);
365 static int postgresGetForeignModifyBatchSize(ResultRelInfo *resultRelInfo);
367  ResultRelInfo *resultRelInfo,
368  TupleTableSlot *slot,
369  TupleTableSlot *planSlot);
371  ResultRelInfo *resultRelInfo,
372  TupleTableSlot *slot,
373  TupleTableSlot *planSlot);
374 static void postgresEndForeignModify(EState *estate,
375  ResultRelInfo *resultRelInfo);
376 static void postgresBeginForeignInsert(ModifyTableState *mtstate,
377  ResultRelInfo *resultRelInfo);
378 static void postgresEndForeignInsert(EState *estate,
379  ResultRelInfo *resultRelInfo);
381 static bool postgresPlanDirectModify(PlannerInfo *root,
382  ModifyTable *plan,
383  Index resultRelation,
384  int subplan_index);
385 static void postgresBeginDirectModify(ForeignScanState *node, int eflags);
387 static void postgresEndDirectModify(ForeignScanState *node);
389  ExplainState *es);
391  ResultRelInfo *rinfo,
392  List *fdw_private,
393  int subplan_index,
394  ExplainState *es);
396  ExplainState *es);
397 static void postgresExecForeignTruncate(List *rels,
398  DropBehavior behavior,
399  bool restart_seqs);
400 static bool postgresAnalyzeForeignTable(Relation relation,
401  AcquireSampleRowsFunc *func,
402  BlockNumber *totalpages);
404  Oid serverOid);
405 static void postgresGetForeignJoinPaths(PlannerInfo *root,
406  RelOptInfo *joinrel,
407  RelOptInfo *outerrel,
408  RelOptInfo *innerrel,
409  JoinType jointype,
410  JoinPathExtraData *extra);
412  TupleTableSlot *slot);
413 static void postgresGetForeignUpperPaths(PlannerInfo *root,
414  UpperRelationKind stage,
415  RelOptInfo *input_rel,
416  RelOptInfo *output_rel,
417  void *extra);
419 static void postgresForeignAsyncRequest(AsyncRequest *areq);
421 static void postgresForeignAsyncNotify(AsyncRequest *areq);
422 
423 /*
424  * Helper functions
425  */
426 static void estimate_path_cost_size(PlannerInfo *root,
427  RelOptInfo *foreignrel,
428  List *param_join_conds,
429  List *pathkeys,
430  PgFdwPathExtraData *fpextra,
431  double *p_rows, int *p_width,
432  Cost *p_startup_cost, Cost *p_total_cost);
433 static void get_remote_estimate(const char *sql,
434  PGconn *conn,
435  double *rows,
436  int *width,
437  Cost *startup_cost,
438  Cost *total_cost);
440  List *pathkeys,
441  double retrieved_rows,
442  double width,
443  double limit_tuples,
444  Cost *p_startup_cost,
445  Cost *p_run_cost);
446 static bool ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
448  void *arg);
449 static void create_cursor(ForeignScanState *node);
450 static void fetch_more_data(ForeignScanState *node);
451 static void close_cursor(PGconn *conn, unsigned int cursor_number,
452  PgFdwConnState *conn_state);
454  RangeTblEntry *rte,
455  ResultRelInfo *resultRelInfo,
456  CmdType operation,
457  Plan *subplan,
458  char *query,
459  List *target_attrs,
460  int len,
461  bool has_returning,
462  List *retrieved_attrs);
464  ResultRelInfo *resultRelInfo,
465  CmdType operation,
466  TupleTableSlot **slots,
467  TupleTableSlot **planSlots,
468  int *numSlots);
469 static void prepare_foreign_modify(PgFdwModifyState *fmstate);
470 static const char **convert_prep_stmt_params(PgFdwModifyState *fmstate,
471  ItemPointer tupleid,
472  TupleTableSlot **slots,
473  int numSlots);
474 static void store_returning_result(PgFdwModifyState *fmstate,
475  TupleTableSlot *slot, PGresult *res);
476 static void finish_foreign_modify(PgFdwModifyState *fmstate);
477 static void deallocate_query(PgFdwModifyState *fmstate);
478 static List *build_remote_returning(Index rtindex, Relation rel,
479  List *returningList);
480 static void rebuild_fdw_scan_tlist(ForeignScan *fscan, List *tlist);
481 static void execute_dml_stmt(ForeignScanState *node);
483 static void init_returning_filter(PgFdwDirectModifyState *dmstate,
484  List *fdw_scan_tlist,
485  Index rtindex);
487  ResultRelInfo *resultRelInfo,
488  TupleTableSlot *slot,
489  EState *estate);
490 static void prepare_query_params(PlanState *node,
491  List *fdw_exprs,
492  int numParams,
493  FmgrInfo **param_flinfo,
494  List **param_exprs,
495  const char ***param_values);
496 static void process_query_params(ExprContext *econtext,
497  FmgrInfo *param_flinfo,
498  List *param_exprs,
499  const char **param_values);
500 static int postgresAcquireSampleRowsFunc(Relation relation, int elevel,
501  HeapTuple *rows, int targrows,
502  double *totalrows,
503  double *totaldeadrows);
504 static void analyze_row_processor(PGresult *res, int row,
505  PgFdwAnalyzeState *astate);
506 static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch);
507 static void fetch_more_data_begin(AsyncRequest *areq);
508 static void complete_pending_request(AsyncRequest *areq);
510  int row,
511  Relation rel,
512  AttInMetadata *attinmeta,
513  List *retrieved_attrs,
514  ForeignScanState *fsstate,
515  MemoryContext temp_context);
516 static void conversion_error_callback(void *arg);
517 static bool foreign_join_ok(PlannerInfo *root, RelOptInfo *joinrel,
518  JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel,
519  JoinPathExtraData *extra);
520 static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel,
521  Node *havingQual);
523  RelOptInfo *rel);
526  Path *epq_path);
527 static void add_foreign_grouping_paths(PlannerInfo *root,
528  RelOptInfo *input_rel,
529  RelOptInfo *grouped_rel,
530  GroupPathExtraData *extra);
531 static void add_foreign_ordered_paths(PlannerInfo *root,
532  RelOptInfo *input_rel,
533  RelOptInfo *ordered_rel);
534 static void add_foreign_final_paths(PlannerInfo *root,
535  RelOptInfo *input_rel,
536  RelOptInfo *final_rel,
537  FinalPathExtraData *extra);
538 static void apply_server_options(PgFdwRelationInfo *fpinfo);
539 static void apply_table_options(PgFdwRelationInfo *fpinfo);
540 static void merge_fdw_options(PgFdwRelationInfo *fpinfo,
541  const PgFdwRelationInfo *fpinfo_o,
542  const PgFdwRelationInfo *fpinfo_i);
543 static int get_batch_size_option(Relation rel);
544 
545 
546 /*
547  * Foreign-data wrapper handler function: return a struct with pointers
548  * to my callback routines.
549  */
550 Datum
552 {
553  FdwRoutine *routine = makeNode(FdwRoutine);
554 
555  /* Functions for scanning foreign tables */
563 
564  /* Functions for updating foreign tables */
581 
582  /* Function for EvalPlanQual rechecks */
584  /* Support functions for EXPLAIN */
588 
589  /* Support function for TRUNCATE */
591 
592  /* Support functions for ANALYZE */
594 
595  /* Support functions for IMPORT FOREIGN SCHEMA */
597 
598  /* Support functions for join push-down */
600 
601  /* Support functions for upper relation push-down */
603 
604  /* Support functions for asynchronous execution */
609 
610  PG_RETURN_POINTER(routine);
611 }
612 
613 /*
614  * postgresGetForeignRelSize
615  * Estimate # of rows and width of the result of the scan
616  *
617  * We should consider the effect of all baserestrictinfo clauses here, but
618  * not any join clauses.
619  */
620 static void
622  RelOptInfo *baserel,
623  Oid foreigntableid)
624 {
625  PgFdwRelationInfo *fpinfo;
626  ListCell *lc;
627  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
628 
629  /*
630  * We use PgFdwRelationInfo to pass various information to subsequent
631  * functions.
632  */
633  fpinfo = (PgFdwRelationInfo *) palloc0(sizeof(PgFdwRelationInfo));
634  baserel->fdw_private = (void *) fpinfo;
635 
636  /* Base foreign tables need to be pushed down always. */
637  fpinfo->pushdown_safe = true;
638 
639  /* Look up foreign-table catalog info. */
640  fpinfo->table = GetForeignTable(foreigntableid);
641  fpinfo->server = GetForeignServer(fpinfo->table->serverid);
642 
643  /*
644  * Extract user-settable option values. Note that per-table settings of
645  * use_remote_estimate, fetch_size and async_capable override per-server
646  * settings of them, respectively.
647  */
648  fpinfo->use_remote_estimate = false;
651  fpinfo->shippable_extensions = NIL;
652  fpinfo->fetch_size = 100;
653  fpinfo->async_capable = false;
654 
655  apply_server_options(fpinfo);
656  apply_table_options(fpinfo);
657 
658  /*
659  * If the table or the server is configured to use remote estimates,
660  * identify which user to do remote access as during planning. This
661  * should match what ExecCheckRTEPerms() does. If we fail due to lack of
662  * permissions, the query would have failed at runtime anyway.
663  */
664  if (fpinfo->use_remote_estimate)
665  {
666  Oid userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
667 
668  fpinfo->user = GetUserMapping(userid, fpinfo->server->serverid);
669  }
670  else
671  fpinfo->user = NULL;
672 
673  /*
674  * Identify which baserestrictinfo clauses can be sent to the remote
675  * server and which can't.
676  */
677  classifyConditions(root, baserel, baserel->baserestrictinfo,
678  &fpinfo->remote_conds, &fpinfo->local_conds);
679 
680  /*
681  * Identify which attributes will need to be retrieved from the remote
682  * server. These include all attrs needed for joins or final output, plus
683  * all attrs used in the local_conds. (Note: if we end up using a
684  * parameterized scan, it's possible that some of the join clauses will be
685  * sent to the remote and thus we wouldn't really need to retrieve the
686  * columns used in them. Doesn't seem worth detecting that case though.)
687  */
688  fpinfo->attrs_used = NULL;
689  pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
690  &fpinfo->attrs_used);
691  foreach(lc, fpinfo->local_conds)
692  {
693  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
694 
695  pull_varattnos((Node *) rinfo->clause, baserel->relid,
696  &fpinfo->attrs_used);
697  }
698 
699  /*
700  * Compute the selectivity and cost of the local_conds, so we don't have
701  * to do it over again for each path. The best we can do for these
702  * conditions is to estimate selectivity on the basis of local statistics.
703  */
705  fpinfo->local_conds,
706  baserel->relid,
707  JOIN_INNER,
708  NULL);
709 
710  cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
711 
712  /*
713  * Set # of retrieved rows and cached relation costs to some negative
714  * value, so that we can detect when they are set to some sensible values,
715  * during one (usually the first) of the calls to estimate_path_cost_size.
716  */
717  fpinfo->retrieved_rows = -1;
718  fpinfo->rel_startup_cost = -1;
719  fpinfo->rel_total_cost = -1;
720 
721  /*
722  * If the table or the server is configured to use remote estimates,
723  * connect to the foreign server and execute EXPLAIN to estimate the
724  * number of rows selected by the restriction clauses, as well as the
725  * average row width. Otherwise, estimate using whatever statistics we
726  * have locally, in a way similar to ordinary tables.
727  */
728  if (fpinfo->use_remote_estimate)
729  {
730  /*
731  * Get cost/size estimates with help of remote server. Save the
732  * values in fpinfo so we don't need to do it again to generate the
733  * basic foreign path.
734  */
735  estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
736  &fpinfo->rows, &fpinfo->width,
737  &fpinfo->startup_cost, &fpinfo->total_cost);
738 
739  /* Report estimated baserel size to planner. */
740  baserel->rows = fpinfo->rows;
741  baserel->reltarget->width = fpinfo->width;
742  }
743  else
744  {
745  /*
746  * If the foreign table has never been ANALYZEd, it will have
747  * reltuples < 0, meaning "unknown". We can't do much if we're not
748  * allowed to consult the remote server, but we can use a hack similar
749  * to plancat.c's treatment of empty relations: use a minimum size
750  * estimate of 10 pages, and divide by the column-datatype-based width
751  * estimate to get the corresponding number of tuples.
752  */
753  if (baserel->tuples < 0)
754  {
755  baserel->pages = 10;
756  baserel->tuples =
757  (10 * BLCKSZ) / (baserel->reltarget->width +
759  }
760 
761  /* Estimate baserel size as best we can with local statistics. */
762  set_baserel_size_estimates(root, baserel);
763 
764  /* Fill in basically-bogus cost estimates for use later. */
765  estimate_path_cost_size(root, baserel, NIL, NIL, NULL,
766  &fpinfo->rows, &fpinfo->width,
767  &fpinfo->startup_cost, &fpinfo->total_cost);
768  }
769 
770  /*
771  * fpinfo->relation_name gets the numeric rangetable index of the foreign
772  * table RTE. (If this query gets EXPLAIN'd, we'll convert that to a
773  * human-readable string at that time.)
774  */
775  fpinfo->relation_name = psprintf("%u", baserel->relid);
776 
777  /* No outer and inner relations. */
778  fpinfo->make_outerrel_subquery = false;
779  fpinfo->make_innerrel_subquery = false;
780  fpinfo->lower_subquery_rels = NULL;
781  /* Set the relation index. */
782  fpinfo->relation_index = baserel->relid;
783 }
784 
785 /*
786  * get_useful_ecs_for_relation
787  * Determine which EquivalenceClasses might be involved in useful
788  * orderings of this relation.
789  *
790  * This function is in some respects a mirror image of the core function
791  * pathkeys_useful_for_merging: for a regular table, we know what indexes
792  * we have and want to test whether any of them are useful. For a foreign
793  * table, we don't know what indexes are present on the remote side but
794  * want to speculate about which ones we'd like to use if they existed.
795  *
796  * This function returns a list of potentially-useful equivalence classes,
797  * but it does not guarantee that an EquivalenceMember exists which contains
798  * Vars only from the given relation. For example, given ft1 JOIN t1 ON
799  * ft1.x + t1.x = 0, this function will say that the equivalence class
800  * containing ft1.x + t1.x is potentially useful. Supposing ft1 is remote and
801  * t1 is local (or on a different server), it will turn out that no useful
802  * ORDER BY clause can be generated. It's not our job to figure that out
803  * here; we're only interested in identifying relevant ECs.
804  */
805 static List *
807 {
808  List *useful_eclass_list = NIL;
809  ListCell *lc;
810  Relids relids;
811 
812  /*
813  * First, consider whether any active EC is potentially useful for a merge
814  * join against this relation.
815  */
816  if (rel->has_eclass_joins)
817  {
818  foreach(lc, root->eq_classes)
819  {
820  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc);
821 
822  if (eclass_useful_for_merging(root, cur_ec, rel))
823  useful_eclass_list = lappend(useful_eclass_list, cur_ec);
824  }
825  }
826 
827  /*
828  * Next, consider whether there are any non-EC derivable join clauses that
829  * are merge-joinable. If the joininfo list is empty, we can exit
830  * quickly.
831  */
832  if (rel->joininfo == NIL)
833  return useful_eclass_list;
834 
835  /* If this is a child rel, we must use the topmost parent rel to search. */
836  if (IS_OTHER_REL(rel))
837  {
839  relids = rel->top_parent_relids;
840  }
841  else
842  relids = rel->relids;
843 
844  /* Check each join clause in turn. */
845  foreach(lc, rel->joininfo)
846  {
847  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
848 
849  /* Consider only mergejoinable clauses */
850  if (restrictinfo->mergeopfamilies == NIL)
851  continue;
852 
853  /* Make sure we've got canonical ECs. */
854  update_mergeclause_eclasses(root, restrictinfo);
855 
856  /*
857  * restrictinfo->mergeopfamilies != NIL is sufficient to guarantee
858  * that left_ec and right_ec will be initialized, per comments in
859  * distribute_qual_to_rels.
860  *
861  * We want to identify which side of this merge-joinable clause
862  * contains columns from the relation produced by this RelOptInfo. We
863  * test for overlap, not containment, because there could be extra
864  * relations on either side. For example, suppose we've got something
865  * like ((A JOIN B ON A.x = B.x) JOIN C ON A.y = C.y) LEFT JOIN D ON
866  * A.y = D.y. The input rel might be the joinrel between A and B, and
867  * we'll consider the join clause A.y = D.y. relids contains a
868  * relation not involved in the join class (B) and the equivalence
869  * class for the left-hand side of the clause contains a relation not
870  * involved in the input rel (C). Despite the fact that we have only
871  * overlap and not containment in either direction, A.y is potentially
872  * useful as a sort column.
873  *
874  * Note that it's even possible that relids overlaps neither side of
875  * the join clause. For example, consider A LEFT JOIN B ON A.x = B.x
876  * AND A.x = 1. The clause A.x = 1 will appear in B's joininfo list,
877  * but overlaps neither side of B. In that case, we just skip this
878  * join clause, since it doesn't suggest a useful sort order for this
879  * relation.
880  */
881  if (bms_overlap(relids, restrictinfo->right_ec->ec_relids))
882  useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
883  restrictinfo->right_ec);
884  else if (bms_overlap(relids, restrictinfo->left_ec->ec_relids))
885  useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
886  restrictinfo->left_ec);
887  }
888 
889  return useful_eclass_list;
890 }
891 
892 /*
893  * get_useful_pathkeys_for_relation
894  * Determine which orderings of a relation might be useful.
895  *
896  * Getting data in sorted order can be useful either because the requested
897  * order matches the final output ordering for the overall query we're
898  * planning, or because it enables an efficient merge join. Here, we try
899  * to figure out which pathkeys to consider.
900  */
901 static List *
903 {
904  List *useful_pathkeys_list = NIL;
905  List *useful_eclass_list;
907  EquivalenceClass *query_ec = NULL;
908  ListCell *lc;
909 
910  /*
911  * Pushing the query_pathkeys to the remote server is always worth
912  * considering, because it might let us avoid a local sort.
913  */
914  fpinfo->qp_is_pushdown_safe = false;
915  if (root->query_pathkeys)
916  {
917  bool query_pathkeys_ok = true;
918 
919  foreach(lc, root->query_pathkeys)
920  {
921  PathKey *pathkey = (PathKey *) lfirst(lc);
922 
923  /*
924  * The planner and executor don't have any clever strategy for
925  * taking data sorted by a prefix of the query's pathkeys and
926  * getting it to be sorted by all of those pathkeys. We'll just
927  * end up resorting the entire data set. So, unless we can push
928  * down all of the query pathkeys, forget it.
929  */
930  if (!is_foreign_pathkey(root, rel, pathkey))
931  {
932  query_pathkeys_ok = false;
933  break;
934  }
935  }
936 
937  if (query_pathkeys_ok)
938  {
939  useful_pathkeys_list = list_make1(list_copy(root->query_pathkeys));
940  fpinfo->qp_is_pushdown_safe = true;
941  }
942  }
943 
944  /*
945  * Even if we're not using remote estimates, having the remote side do the
946  * sort generally won't be any worse than doing it locally, and it might
947  * be much better if the remote side can generate data in the right order
948  * without needing a sort at all. However, what we're going to do next is
949  * try to generate pathkeys that seem promising for possible merge joins,
950  * and that's more speculative. A wrong choice might hurt quite a bit, so
951  * bail out if we can't use remote estimates.
952  */
953  if (!fpinfo->use_remote_estimate)
954  return useful_pathkeys_list;
955 
956  /* Get the list of interesting EquivalenceClasses. */
957  useful_eclass_list = get_useful_ecs_for_relation(root, rel);
958 
959  /* Extract unique EC for query, if any, so we don't consider it again. */
960  if (list_length(root->query_pathkeys) == 1)
961  {
962  PathKey *query_pathkey = linitial(root->query_pathkeys);
963 
964  query_ec = query_pathkey->pk_eclass;
965  }
966 
967  /*
968  * As a heuristic, the only pathkeys we consider here are those of length
969  * one. It's surely possible to consider more, but since each one we
970  * choose to consider will generate a round-trip to the remote side, we
971  * need to be a bit cautious here. It would sure be nice to have a local
972  * cache of information about remote index definitions...
973  */
974  foreach(lc, useful_eclass_list)
975  {
976  EquivalenceClass *cur_ec = lfirst(lc);
977  PathKey *pathkey;
978 
979  /* If redundant with what we did above, skip it. */
980  if (cur_ec == query_ec)
981  continue;
982 
983  /* Can't push down the sort if the EC's opfamily is not shippable. */
985  OperatorFamilyRelationId, fpinfo))
986  continue;
987 
988  /* If no pushable expression for this rel, skip it. */
989  if (find_em_for_rel(root, cur_ec, rel) == NULL)
990  continue;
991 
992  /* Looks like we can generate a pathkey, so let's do it. */
993  pathkey = make_canonical_pathkey(root, cur_ec,
994  linitial_oid(cur_ec->ec_opfamilies),
996  false);
997  useful_pathkeys_list = lappend(useful_pathkeys_list,
998  list_make1(pathkey));
999  }
1000 
1001  return useful_pathkeys_list;
1002 }
1003 
1004 /*
1005  * postgresGetForeignPaths
1006  * Create possible scan paths for a scan on the foreign table
1007  */
1008 static void
1010  RelOptInfo *baserel,
1011  Oid foreigntableid)
1012 {
1013  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
1014  ForeignPath *path;
1015  List *ppi_list;
1016  ListCell *lc;
1017 
1018  /*
1019  * Create simplest ForeignScan path node and add it to baserel. This path
1020  * corresponds to SeqScan path of regular tables (though depending on what
1021  * baserestrict conditions we were able to send to remote, there might
1022  * actually be an indexscan happening there). We already did all the work
1023  * to estimate cost and size of this path.
1024  *
1025  * Although this path uses no join clauses, it could still have required
1026  * parameterization due to LATERAL refs in its tlist.
1027  */
1028  path = create_foreignscan_path(root, baserel,
1029  NULL, /* default pathtarget */
1030  fpinfo->rows,
1031  fpinfo->startup_cost,
1032  fpinfo->total_cost,
1033  NIL, /* no pathkeys */
1034  baserel->lateral_relids,
1035  NULL, /* no extra plan */
1036  NIL); /* no fdw_private list */
1037  add_path(baserel, (Path *) path);
1038 
1039  /* Add paths with pathkeys */
1040  add_paths_with_pathkeys_for_rel(root, baserel, NULL);
1041 
1042  /*
1043  * If we're not using remote estimates, stop here. We have no way to
1044  * estimate whether any join clauses would be worth sending across, so
1045  * don't bother building parameterized paths.
1046  */
1047  if (!fpinfo->use_remote_estimate)
1048  return;
1049 
1050  /*
1051  * Thumb through all join clauses for the rel to identify which outer
1052  * relations could supply one or more safe-to-send-to-remote join clauses.
1053  * We'll build a parameterized path for each such outer relation.
1054  *
1055  * It's convenient to manage this by representing each candidate outer
1056  * relation by the ParamPathInfo node for it. We can then use the
1057  * ppi_clauses list in the ParamPathInfo node directly as a list of the
1058  * interesting join clauses for that rel. This takes care of the
1059  * possibility that there are multiple safe join clauses for such a rel,
1060  * and also ensures that we account for unsafe join clauses that we'll
1061  * still have to enforce locally (since the parameterized-path machinery
1062  * insists that we handle all movable clauses).
1063  */
1064  ppi_list = NIL;
1065  foreach(lc, baserel->joininfo)
1066  {
1067  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1068  Relids required_outer;
1069  ParamPathInfo *param_info;
1070 
1071  /* Check if clause can be moved to this rel */
1072  if (!join_clause_is_movable_to(rinfo, baserel))
1073  continue;
1074 
1075  /* See if it is safe to send to remote */
1076  if (!is_foreign_expr(root, baserel, rinfo->clause))
1077  continue;
1078 
1079  /* Calculate required outer rels for the resulting path */
1080  required_outer = bms_union(rinfo->clause_relids,
1081  baserel->lateral_relids);
1082  /* We do not want the foreign rel itself listed in required_outer */
1083  required_outer = bms_del_member(required_outer, baserel->relid);
1084 
1085  /*
1086  * required_outer probably can't be empty here, but if it were, we
1087  * couldn't make a parameterized path.
1088  */
1089  if (bms_is_empty(required_outer))
1090  continue;
1091 
1092  /* Get the ParamPathInfo */
1093  param_info = get_baserel_parampathinfo(root, baserel,
1094  required_outer);
1095  Assert(param_info != NULL);
1096 
1097  /*
1098  * Add it to list unless we already have it. Testing pointer equality
1099  * is OK since get_baserel_parampathinfo won't make duplicates.
1100  */
1101  ppi_list = list_append_unique_ptr(ppi_list, param_info);
1102  }
1103 
1104  /*
1105  * The above scan examined only "generic" join clauses, not those that
1106  * were absorbed into EquivalenceClauses. See if we can make anything out
1107  * of EquivalenceClauses.
1108  */
1109  if (baserel->has_eclass_joins)
1110  {
1111  /*
1112  * We repeatedly scan the eclass list looking for column references
1113  * (or expressions) belonging to the foreign rel. Each time we find
1114  * one, we generate a list of equivalence joinclauses for it, and then
1115  * see if any are safe to send to the remote. Repeat till there are
1116  * no more candidate EC members.
1117  */
1119 
1120  arg.already_used = NIL;
1121  for (;;)
1122  {
1123  List *clauses;
1124 
1125  /* Make clauses, skipping any that join to lateral_referencers */
1126  arg.current = NULL;
1128  baserel,
1130  (void *) &arg,
1131  baserel->lateral_referencers);
1132 
1133  /* Done if there are no more expressions in the foreign rel */
1134  if (arg.current == NULL)
1135  {
1136  Assert(clauses == NIL);
1137  break;
1138  }
1139 
1140  /* Scan the extracted join clauses */
1141  foreach(lc, clauses)
1142  {
1143  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1144  Relids required_outer;
1145  ParamPathInfo *param_info;
1146 
1147  /* Check if clause can be moved to this rel */
1148  if (!join_clause_is_movable_to(rinfo, baserel))
1149  continue;
1150 
1151  /* See if it is safe to send to remote */
1152  if (!is_foreign_expr(root, baserel, rinfo->clause))
1153  continue;
1154 
1155  /* Calculate required outer rels for the resulting path */
1156  required_outer = bms_union(rinfo->clause_relids,
1157  baserel->lateral_relids);
1158  required_outer = bms_del_member(required_outer, baserel->relid);
1159  if (bms_is_empty(required_outer))
1160  continue;
1161 
1162  /* Get the ParamPathInfo */
1163  param_info = get_baserel_parampathinfo(root, baserel,
1164  required_outer);
1165  Assert(param_info != NULL);
1166 
1167  /* Add it to list unless we already have it */
1168  ppi_list = list_append_unique_ptr(ppi_list, param_info);
1169  }
1170 
1171  /* Try again, now ignoring the expression we found this time */
1172  arg.already_used = lappend(arg.already_used, arg.current);
1173  }
1174  }
1175 
1176  /*
1177  * Now build a path for each useful outer relation.
1178  */
1179  foreach(lc, ppi_list)
1180  {
1181  ParamPathInfo *param_info = (ParamPathInfo *) lfirst(lc);
1182  double rows;
1183  int width;
1184  Cost startup_cost;
1185  Cost total_cost;
1186 
1187  /* Get a cost estimate from the remote */
1188  estimate_path_cost_size(root, baserel,
1189  param_info->ppi_clauses, NIL, NULL,
1190  &rows, &width,
1191  &startup_cost, &total_cost);
1192 
1193  /*
1194  * ppi_rows currently won't get looked at by anything, but still we
1195  * may as well ensure that it matches our idea of the rowcount.
1196  */
1197  param_info->ppi_rows = rows;
1198 
1199  /* Make the path */
1200  path = create_foreignscan_path(root, baserel,
1201  NULL, /* default pathtarget */
1202  rows,
1203  startup_cost,
1204  total_cost,
1205  NIL, /* no pathkeys */
1206  param_info->ppi_req_outer,
1207  NULL,
1208  NIL); /* no fdw_private list */
1209  add_path(baserel, (Path *) path);
1210  }
1211 }
1212 
1213 /*
1214  * postgresGetForeignPlan
1215  * Create ForeignScan plan node which implements selected best path
1216  */
1217 static ForeignScan *
1219  RelOptInfo *foreignrel,
1220  Oid foreigntableid,
1221  ForeignPath *best_path,
1222  List *tlist,
1223  List *scan_clauses,
1224  Plan *outer_plan)
1225 {
1226  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1227  Index scan_relid;
1228  List *fdw_private;
1229  List *remote_exprs = NIL;
1230  List *local_exprs = NIL;
1231  List *params_list = NIL;
1232  List *fdw_scan_tlist = NIL;
1233  List *fdw_recheck_quals = NIL;
1234  List *retrieved_attrs;
1235  StringInfoData sql;
1236  bool has_final_sort = false;
1237  bool has_limit = false;
1238  ListCell *lc;
1239 
1240  /*
1241  * Get FDW private data created by postgresGetForeignUpperPaths(), if any.
1242  */
1243  if (best_path->fdw_private)
1244  {
1245  has_final_sort = boolVal(list_nth(best_path->fdw_private,
1247  has_limit = boolVal(list_nth(best_path->fdw_private,
1249  }
1250 
1251  if (IS_SIMPLE_REL(foreignrel))
1252  {
1253  /*
1254  * For base relations, set scan_relid as the relid of the relation.
1255  */
1256  scan_relid = foreignrel->relid;
1257 
1258  /*
1259  * In a base-relation scan, we must apply the given scan_clauses.
1260  *
1261  * Separate the scan_clauses into those that can be executed remotely
1262  * and those that can't. baserestrictinfo clauses that were
1263  * previously determined to be safe or unsafe by classifyConditions
1264  * are found in fpinfo->remote_conds and fpinfo->local_conds. Anything
1265  * else in the scan_clauses list will be a join clause, which we have
1266  * to check for remote-safety.
1267  *
1268  * Note: the join clauses we see here should be the exact same ones
1269  * previously examined by postgresGetForeignPaths. Possibly it'd be
1270  * worth passing forward the classification work done then, rather
1271  * than repeating it here.
1272  *
1273  * This code must match "extract_actual_clauses(scan_clauses, false)"
1274  * except for the additional decision about remote versus local
1275  * execution.
1276  */
1277  foreach(lc, scan_clauses)
1278  {
1279  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1280 
1281  /* Ignore any pseudoconstants, they're dealt with elsewhere */
1282  if (rinfo->pseudoconstant)
1283  continue;
1284 
1285  if (list_member_ptr(fpinfo->remote_conds, rinfo))
1286  remote_exprs = lappend(remote_exprs, rinfo->clause);
1287  else if (list_member_ptr(fpinfo->local_conds, rinfo))
1288  local_exprs = lappend(local_exprs, rinfo->clause);
1289  else if (is_foreign_expr(root, foreignrel, rinfo->clause))
1290  remote_exprs = lappend(remote_exprs, rinfo->clause);
1291  else
1292  local_exprs = lappend(local_exprs, rinfo->clause);
1293  }
1294 
1295  /*
1296  * For a base-relation scan, we have to support EPQ recheck, which
1297  * should recheck all the remote quals.
1298  */
1299  fdw_recheck_quals = remote_exprs;
1300  }
1301  else
1302  {
1303  /*
1304  * Join relation or upper relation - set scan_relid to 0.
1305  */
1306  scan_relid = 0;
1307 
1308  /*
1309  * For a join rel, baserestrictinfo is NIL and we are not considering
1310  * parameterization right now, so there should be no scan_clauses for
1311  * a joinrel or an upper rel either.
1312  */
1313  Assert(!scan_clauses);
1314 
1315  /*
1316  * Instead we get the conditions to apply from the fdw_private
1317  * structure.
1318  */
1319  remote_exprs = extract_actual_clauses(fpinfo->remote_conds, false);
1320  local_exprs = extract_actual_clauses(fpinfo->local_conds, false);
1321 
1322  /*
1323  * We leave fdw_recheck_quals empty in this case, since we never need
1324  * to apply EPQ recheck clauses. In the case of a joinrel, EPQ
1325  * recheck is handled elsewhere --- see postgresGetForeignJoinPaths().
1326  * If we're planning an upperrel (ie, remote grouping or aggregation)
1327  * then there's no EPQ to do because SELECT FOR UPDATE wouldn't be
1328  * allowed, and indeed we *can't* put the remote clauses into
1329  * fdw_recheck_quals because the unaggregated Vars won't be available
1330  * locally.
1331  */
1332 
1333  /* Build the list of columns to be fetched from the foreign server. */
1334  fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
1335 
1336  /*
1337  * Ensure that the outer plan produces a tuple whose descriptor
1338  * matches our scan tuple slot. Also, remove the local conditions
1339  * from outer plan's quals, lest they be evaluated twice, once by the
1340  * local plan and once by the scan.
1341  */
1342  if (outer_plan)
1343  {
1344  ListCell *lc;
1345 
1346  /*
1347  * Right now, we only consider grouping and aggregation beyond
1348  * joins. Queries involving aggregates or grouping do not require
1349  * EPQ mechanism, hence should not have an outer plan here.
1350  */
1351  Assert(!IS_UPPER_REL(foreignrel));
1352 
1353  /*
1354  * First, update the plan's qual list if possible. In some cases
1355  * the quals might be enforced below the topmost plan level, in
1356  * which case we'll fail to remove them; it's not worth working
1357  * harder than this.
1358  */
1359  foreach(lc, local_exprs)
1360  {
1361  Node *qual = lfirst(lc);
1362 
1363  outer_plan->qual = list_delete(outer_plan->qual, qual);
1364 
1365  /*
1366  * For an inner join the local conditions of foreign scan plan
1367  * can be part of the joinquals as well. (They might also be
1368  * in the mergequals or hashquals, but we can't touch those
1369  * without breaking the plan.)
1370  */
1371  if (IsA(outer_plan, NestLoop) ||
1372  IsA(outer_plan, MergeJoin) ||
1373  IsA(outer_plan, HashJoin))
1374  {
1375  Join *join_plan = (Join *) outer_plan;
1376 
1377  if (join_plan->jointype == JOIN_INNER)
1378  join_plan->joinqual = list_delete(join_plan->joinqual,
1379  qual);
1380  }
1381  }
1382 
1383  /*
1384  * Now fix the subplan's tlist --- this might result in inserting
1385  * a Result node atop the plan tree.
1386  */
1387  outer_plan = change_plan_targetlist(outer_plan, fdw_scan_tlist,
1388  best_path->path.parallel_safe);
1389  }
1390  }
1391 
1392  /*
1393  * Build the query string to be sent for execution, and identify
1394  * expressions to be sent as parameters.
1395  */
1396  initStringInfo(&sql);
1397  deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
1398  remote_exprs, best_path->path.pathkeys,
1399  has_final_sort, has_limit, false,
1400  &retrieved_attrs, &params_list);
1401 
1402  /* Remember remote_exprs for possible use by postgresPlanDirectModify */
1403  fpinfo->final_remote_exprs = remote_exprs;
1404 
1405  /*
1406  * Build the fdw_private list that will be available to the executor.
1407  * Items in the list must match order in enum FdwScanPrivateIndex.
1408  */
1409  fdw_private = list_make3(makeString(sql.data),
1410  retrieved_attrs,
1411  makeInteger(fpinfo->fetch_size));
1412  if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
1413  fdw_private = lappend(fdw_private,
1414  makeString(fpinfo->relation_name));
1415 
1416  /*
1417  * Create the ForeignScan node for the given relation.
1418  *
1419  * Note that the remote parameter expressions are stored in the fdw_exprs
1420  * field of the finished plan node; we can't keep them in private state
1421  * because then they wouldn't be subject to later planner processing.
1422  */
1423  return make_foreignscan(tlist,
1424  local_exprs,
1425  scan_relid,
1426  params_list,
1427  fdw_private,
1428  fdw_scan_tlist,
1429  fdw_recheck_quals,
1430  outer_plan);
1431 }
1432 
1433 /*
1434  * Construct a tuple descriptor for the scan tuples handled by a foreign join.
1435  */
1436 static TupleDesc
1438 {
1439  ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1440  EState *estate = node->ss.ps.state;
1441  TupleDesc tupdesc;
1442 
1443  /*
1444  * The core code has already set up a scan tuple slot based on
1445  * fsplan->fdw_scan_tlist, and this slot's tupdesc is mostly good enough,
1446  * but there's one case where it isn't. If we have any whole-row row
1447  * identifier Vars, they may have vartype RECORD, and we need to replace
1448  * that with the associated table's actual composite type. This ensures
1449  * that when we read those ROW() expression values from the remote server,
1450  * we can convert them to a composite type the local server knows.
1451  */
1453  for (int i = 0; i < tupdesc->natts; i++)
1454  {
1455  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1456  Var *var;
1457  RangeTblEntry *rte;
1458  Oid reltype;
1459 
1460  /* Nothing to do if it's not a generic RECORD attribute */
1461  if (att->atttypid != RECORDOID || att->atttypmod >= 0)
1462  continue;
1463 
1464  /*
1465  * If we can't identify the referenced table, do nothing. This'll
1466  * likely lead to failure later, but perhaps we can muddle through.
1467  */
1468  var = (Var *) list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
1469  i)->expr;
1470  if (!IsA(var, Var) || var->varattno != 0)
1471  continue;
1472  rte = list_nth(estate->es_range_table, var->varno - 1);
1473  if (rte->rtekind != RTE_RELATION)
1474  continue;
1475  reltype = get_rel_type_id(rte->relid);
1476  if (!OidIsValid(reltype))
1477  continue;
1478  att->atttypid = reltype;
1479  /* shouldn't need to change anything else */
1480  }
1481  return tupdesc;
1482 }
1483 
1484 /*
1485  * postgresBeginForeignScan
1486  * Initiate an executor scan of a foreign PostgreSQL table.
1487  */
1488 static void
1490 {
1491  ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1492  EState *estate = node->ss.ps.state;
1493  PgFdwScanState *fsstate;
1494  RangeTblEntry *rte;
1495  Oid userid;
1496  ForeignTable *table;
1497  UserMapping *user;
1498  int rtindex;
1499  int numParams;
1500 
1501  /*
1502  * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
1503  */
1504  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
1505  return;
1506 
1507  /*
1508  * We'll save private state in node->fdw_state.
1509  */
1510  fsstate = (PgFdwScanState *) palloc0(sizeof(PgFdwScanState));
1511  node->fdw_state = (void *) fsstate;
1512 
1513  /*
1514  * Identify which user to do the remote access as. This should match what
1515  * ExecCheckRTEPerms() does. In case of a join or aggregate, use the
1516  * lowest-numbered member RTE as a representative; we would get the same
1517  * result from any.
1518  */
1519  if (fsplan->scan.scanrelid > 0)
1520  rtindex = fsplan->scan.scanrelid;
1521  else
1522  rtindex = bms_next_member(fsplan->fs_relids, -1);
1523  rte = exec_rt_fetch(rtindex, estate);
1524  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
1525 
1526  /* Get info about foreign table. */
1527  table = GetForeignTable(rte->relid);
1528  user = GetUserMapping(userid, table->serverid);
1529 
1530  /*
1531  * Get connection to the foreign server. Connection manager will
1532  * establish new connection if necessary.
1533  */
1534  fsstate->conn = GetConnection(user, false, &fsstate->conn_state);
1535 
1536  /* Assign a unique ID for my cursor */
1537  fsstate->cursor_number = GetCursorNumber(fsstate->conn);
1538  fsstate->cursor_exists = false;
1539 
1540  /* Get private info created by planner functions. */
1541  fsstate->query = strVal(list_nth(fsplan->fdw_private,
1543  fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
1545  fsstate->fetch_size = intVal(list_nth(fsplan->fdw_private,
1547 
1548  /* Create contexts for batches of tuples and per-tuple temp workspace. */
1549  fsstate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt,
1550  "postgres_fdw tuple data",
1552  fsstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
1553  "postgres_fdw temporary data",
1555 
1556  /*
1557  * Get info we'll need for converting data fetched from the foreign server
1558  * into local representation and error reporting during that process.
1559  */
1560  if (fsplan->scan.scanrelid > 0)
1561  {
1562  fsstate->rel = node->ss.ss_currentRelation;
1563  fsstate->tupdesc = RelationGetDescr(fsstate->rel);
1564  }
1565  else
1566  {
1567  fsstate->rel = NULL;
1568  fsstate->tupdesc = get_tupdesc_for_join_scan_tuples(node);
1569  }
1570 
1571  fsstate->attinmeta = TupleDescGetAttInMetadata(fsstate->tupdesc);
1572 
1573  /*
1574  * Prepare for processing of parameters used in remote query, if any.
1575  */
1576  numParams = list_length(fsplan->fdw_exprs);
1577  fsstate->numParams = numParams;
1578  if (numParams > 0)
1580  fsplan->fdw_exprs,
1581  numParams,
1582  &fsstate->param_flinfo,
1583  &fsstate->param_exprs,
1584  &fsstate->param_values);
1585 
1586  /* Set the async-capable flag */
1587  fsstate->async_capable = node->ss.ps.async_capable;
1588 }
1589 
1590 /*
1591  * postgresIterateForeignScan
1592  * Retrieve next row from the result set, or clear tuple slot to indicate
1593  * EOF.
1594  */
1595 static TupleTableSlot *
1597 {
1598  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1599  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
1600 
1601  /*
1602  * In sync mode, if this is the first call after Begin or ReScan, we need
1603  * to create the cursor on the remote side. In async mode, we would have
1604  * already created the cursor before we get here, even if this is the
1605  * first call after Begin or ReScan.
1606  */
1607  if (!fsstate->cursor_exists)
1608  create_cursor(node);
1609 
1610  /*
1611  * Get some more tuples, if we've run out.
1612  */
1613  if (fsstate->next_tuple >= fsstate->num_tuples)
1614  {
1615  /* In async mode, just clear tuple slot. */
1616  if (fsstate->async_capable)
1617  return ExecClearTuple(slot);
1618  /* No point in another fetch if we already detected EOF, though. */
1619  if (!fsstate->eof_reached)
1620  fetch_more_data(node);
1621  /* If we didn't get any tuples, must be end of data. */
1622  if (fsstate->next_tuple >= fsstate->num_tuples)
1623  return ExecClearTuple(slot);
1624  }
1625 
1626  /*
1627  * Return the next tuple.
1628  */
1629  ExecStoreHeapTuple(fsstate->tuples[fsstate->next_tuple++],
1630  slot,
1631  false);
1632 
1633  return slot;
1634 }
1635 
1636 /*
1637  * postgresReScanForeignScan
1638  * Restart the scan.
1639  */
1640 static void
1642 {
1643  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1644  char sql[64];
1645  PGresult *res;
1646 
1647  /* If we haven't created the cursor yet, nothing to do. */
1648  if (!fsstate->cursor_exists)
1649  return;
1650 
1651  /*
1652  * If the node is async-capable, and an asynchronous fetch for it has been
1653  * begun, the asynchronous fetch might not have yet completed. Check if
1654  * the node is async-capable, and an asynchronous fetch for it is still in
1655  * progress; if so, complete the asynchronous fetch before restarting the
1656  * scan.
1657  */
1658  if (fsstate->async_capable &&
1659  fsstate->conn_state->pendingAreq &&
1660  fsstate->conn_state->pendingAreq->requestee == (PlanState *) node)
1661  fetch_more_data(node);
1662 
1663  /*
1664  * If any internal parameters affecting this node have changed, we'd
1665  * better destroy and recreate the cursor. Otherwise, rewinding it should
1666  * be good enough. If we've only fetched zero or one batch, we needn't
1667  * even rewind the cursor, just rescan what we have.
1668  */
1669  if (node->ss.ps.chgParam != NULL)
1670  {
1671  fsstate->cursor_exists = false;
1672  snprintf(sql, sizeof(sql), "CLOSE c%u",
1673  fsstate->cursor_number);
1674  }
1675  else if (fsstate->fetch_ct_2 > 1)
1676  {
1677  snprintf(sql, sizeof(sql), "MOVE BACKWARD ALL IN c%u",
1678  fsstate->cursor_number);
1679  }
1680  else
1681  {
1682  /* Easy: just rescan what we already have in memory, if anything */
1683  fsstate->next_tuple = 0;
1684  return;
1685  }
1686 
1687  /*
1688  * We don't use a PG_TRY block here, so be careful not to throw error
1689  * without releasing the PGresult.
1690  */
1691  res = pgfdw_exec_query(fsstate->conn, sql, fsstate->conn_state);
1693  pgfdw_report_error(ERROR, res, fsstate->conn, true, sql);
1694  PQclear(res);
1695 
1696  /* Now force a fresh FETCH. */
1697  fsstate->tuples = NULL;
1698  fsstate->num_tuples = 0;
1699  fsstate->next_tuple = 0;
1700  fsstate->fetch_ct_2 = 0;
1701  fsstate->eof_reached = false;
1702 }
1703 
1704 /*
1705  * postgresEndForeignScan
1706  * Finish scanning foreign table and dispose objects used for this scan
1707  */
1708 static void
1710 {
1711  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
1712 
1713  /* if fsstate is NULL, we are in EXPLAIN; nothing to do */
1714  if (fsstate == NULL)
1715  return;
1716 
1717  /* Close the cursor if open, to prevent accumulation of cursors */
1718  if (fsstate->cursor_exists)
1719  close_cursor(fsstate->conn, fsstate->cursor_number,
1720  fsstate->conn_state);
1721 
1722  /* Release remote connection */
1723  ReleaseConnection(fsstate->conn);
1724  fsstate->conn = NULL;
1725 
1726  /* MemoryContexts will be deleted automatically. */
1727 }
1728 
1729 /*
1730  * postgresAddForeignUpdateTargets
1731  * Add resjunk column(s) needed for update/delete on a foreign table
1732  */
1733 static void
1735  Index rtindex,
1736  RangeTblEntry *target_rte,
1737  Relation target_relation)
1738 {
1739  Var *var;
1740 
1741  /*
1742  * In postgres_fdw, what we need is the ctid, same as for a regular table.
1743  */
1744 
1745  /* Make a Var representing the desired value */
1746  var = makeVar(rtindex,
1748  TIDOID,
1749  -1,
1750  InvalidOid,
1751  0);
1752 
1753  /* Register it as a row-identity column needed by this target rel */
1754  add_row_identity_var(root, var, rtindex, "ctid");
1755 }
1756 
1757 /*
1758  * postgresPlanForeignModify
1759  * Plan an insert/update/delete operation on a foreign table
1760  */
1761 static List *
1763  ModifyTable *plan,
1764  Index resultRelation,
1765  int subplan_index)
1766 {
1767  CmdType operation = plan->operation;
1768  RangeTblEntry *rte = planner_rt_fetch(resultRelation, root);
1769  Relation rel;
1770  StringInfoData sql;
1771  List *targetAttrs = NIL;
1772  List *withCheckOptionList = NIL;
1773  List *returningList = NIL;
1774  List *retrieved_attrs = NIL;
1775  bool doNothing = false;
1776  int values_end_len = -1;
1777 
1778  initStringInfo(&sql);
1779 
1780  /*
1781  * Core code already has some lock on each rel being planned, so we can
1782  * use NoLock here.
1783  */
1784  rel = table_open(rte->relid, NoLock);
1785 
1786  /*
1787  * In an INSERT, we transmit all columns that are defined in the foreign
1788  * table. In an UPDATE, if there are BEFORE ROW UPDATE triggers on the
1789  * foreign table, we transmit all columns like INSERT; else we transmit
1790  * only columns that were explicitly targets of the UPDATE, so as to avoid
1791  * unnecessary data transmission. (We can't do that for INSERT since we
1792  * would miss sending default values for columns not listed in the source
1793  * statement, and for UPDATE if there are BEFORE ROW UPDATE triggers since
1794  * those triggers might change values for non-target columns, in which
1795  * case we would miss sending changed values for those columns.)
1796  */
1797  if (operation == CMD_INSERT ||
1798  (operation == CMD_UPDATE &&
1799  rel->trigdesc &&
1801  {
1802  TupleDesc tupdesc = RelationGetDescr(rel);
1803  int attnum;
1804 
1805  for (attnum = 1; attnum <= tupdesc->natts; attnum++)
1806  {
1807  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
1808 
1809  if (!attr->attisdropped)
1810  targetAttrs = lappend_int(targetAttrs, attnum);
1811  }
1812  }
1813  else if (operation == CMD_UPDATE)
1814  {
1815  int col;
1816  Bitmapset *allUpdatedCols = bms_union(rte->updatedCols, rte->extraUpdatedCols);
1817 
1818  col = -1;
1819  while ((col = bms_next_member(allUpdatedCols, col)) >= 0)
1820  {
1821  /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
1823 
1824  if (attno <= InvalidAttrNumber) /* shouldn't happen */
1825  elog(ERROR, "system-column update is not supported");
1826  targetAttrs = lappend_int(targetAttrs, attno);
1827  }
1828  }
1829 
1830  /*
1831  * Extract the relevant WITH CHECK OPTION list if any.
1832  */
1833  if (plan->withCheckOptionLists)
1834  withCheckOptionList = (List *) list_nth(plan->withCheckOptionLists,
1835  subplan_index);
1836 
1837  /*
1838  * Extract the relevant RETURNING list if any.
1839  */
1840  if (plan->returningLists)
1841  returningList = (List *) list_nth(plan->returningLists, subplan_index);
1842 
1843  /*
1844  * ON CONFLICT DO UPDATE and DO NOTHING case with inference specification
1845  * should have already been rejected in the optimizer, as presently there
1846  * is no way to recognize an arbiter index on a foreign table. Only DO
1847  * NOTHING is supported without an inference specification.
1848  */
1849  if (plan->onConflictAction == ONCONFLICT_NOTHING)
1850  doNothing = true;
1851  else if (plan->onConflictAction != ONCONFLICT_NONE)
1852  elog(ERROR, "unexpected ON CONFLICT specification: %d",
1853  (int) plan->onConflictAction);
1854 
1855  /*
1856  * Construct the SQL command string.
1857  */
1858  switch (operation)
1859  {
1860  case CMD_INSERT:
1861  deparseInsertSql(&sql, rte, resultRelation, rel,
1862  targetAttrs, doNothing,
1863  withCheckOptionList, returningList,
1864  &retrieved_attrs, &values_end_len);
1865  break;
1866  case CMD_UPDATE:
1867  deparseUpdateSql(&sql, rte, resultRelation, rel,
1868  targetAttrs,
1869  withCheckOptionList, returningList,
1870  &retrieved_attrs);
1871  break;
1872  case CMD_DELETE:
1873  deparseDeleteSql(&sql, rte, resultRelation, rel,
1874  returningList,
1875  &retrieved_attrs);
1876  break;
1877  default:
1878  elog(ERROR, "unexpected operation: %d", (int) operation);
1879  break;
1880  }
1881 
1882  table_close(rel, NoLock);
1883 
1884  /*
1885  * Build the fdw_private list that will be available to the executor.
1886  * Items in the list must match enum FdwModifyPrivateIndex, above.
1887  */
1888  return list_make5(makeString(sql.data),
1889  targetAttrs,
1890  makeInteger(values_end_len),
1891  makeBoolean((retrieved_attrs != NIL)),
1892  retrieved_attrs);
1893 }
1894 
1895 /*
1896  * postgresBeginForeignModify
1897  * Begin an insert/update/delete operation on a foreign table
1898  */
1899 static void
1901  ResultRelInfo *resultRelInfo,
1902  List *fdw_private,
1903  int subplan_index,
1904  int eflags)
1905 {
1906  PgFdwModifyState *fmstate;
1907  char *query;
1908  List *target_attrs;
1909  bool has_returning;
1910  int values_end_len;
1911  List *retrieved_attrs;
1912  RangeTblEntry *rte;
1913 
1914  /*
1915  * Do nothing in EXPLAIN (no ANALYZE) case. resultRelInfo->ri_FdwState
1916  * stays NULL.
1917  */
1918  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
1919  return;
1920 
1921  /* Deconstruct fdw_private data. */
1922  query = strVal(list_nth(fdw_private,
1924  target_attrs = (List *) list_nth(fdw_private,
1926  values_end_len = intVal(list_nth(fdw_private,
1928  has_returning = boolVal(list_nth(fdw_private,
1930  retrieved_attrs = (List *) list_nth(fdw_private,
1932 
1933  /* Find RTE. */
1934  rte = exec_rt_fetch(resultRelInfo->ri_RangeTableIndex,
1935  mtstate->ps.state);
1936 
1937  /* Construct an execution state. */
1938  fmstate = create_foreign_modify(mtstate->ps.state,
1939  rte,
1940  resultRelInfo,
1941  mtstate->operation,
1942  outerPlanState(mtstate)->plan,
1943  query,
1944  target_attrs,
1945  values_end_len,
1946  has_returning,
1947  retrieved_attrs);
1948 
1949  resultRelInfo->ri_FdwState = fmstate;
1950 }
1951 
1952 /*
1953  * postgresExecForeignInsert
1954  * Insert one row into a foreign table
1955  */
1956 static TupleTableSlot *
1958  ResultRelInfo *resultRelInfo,
1959  TupleTableSlot *slot,
1960  TupleTableSlot *planSlot)
1961 {
1962  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
1963  TupleTableSlot **rslot;
1964  int numSlots = 1;
1965 
1966  /*
1967  * If the fmstate has aux_fmstate set, use the aux_fmstate (see
1968  * postgresBeginForeignInsert())
1969  */
1970  if (fmstate->aux_fmstate)
1971  resultRelInfo->ri_FdwState = fmstate->aux_fmstate;
1972  rslot = execute_foreign_modify(estate, resultRelInfo, CMD_INSERT,
1973  &slot, &planSlot, &numSlots);
1974  /* Revert that change */
1975  if (fmstate->aux_fmstate)
1976  resultRelInfo->ri_FdwState = fmstate;
1977 
1978  return rslot ? *rslot : NULL;
1979 }
1980 
1981 /*
1982  * postgresExecForeignBatchInsert
1983  * Insert multiple rows into a foreign table
1984  */
1985 static TupleTableSlot **
1987  ResultRelInfo *resultRelInfo,
1988  TupleTableSlot **slots,
1989  TupleTableSlot **planSlots,
1990  int *numSlots)
1991 {
1992  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
1993  TupleTableSlot **rslot;
1994 
1995  /*
1996  * If the fmstate has aux_fmstate set, use the aux_fmstate (see
1997  * postgresBeginForeignInsert())
1998  */
1999  if (fmstate->aux_fmstate)
2000  resultRelInfo->ri_FdwState = fmstate->aux_fmstate;
2001  rslot = execute_foreign_modify(estate, resultRelInfo, CMD_INSERT,
2002  slots, planSlots, numSlots);
2003  /* Revert that change */
2004  if (fmstate->aux_fmstate)
2005  resultRelInfo->ri_FdwState = fmstate;
2006 
2007  return rslot;
2008 }
2009 
2010 /*
2011  * postgresGetForeignModifyBatchSize
2012  * Determine the maximum number of tuples that can be inserted in bulk
2013  *
2014  * Returns the batch size specified for server or table. When batching is not
2015  * allowed (e.g. for tables with BEFORE/AFTER ROW triggers or with RETURNING
2016  * clause), returns 1.
2017  */
2018 static int
2020 {
2021  int batch_size;
2022  PgFdwModifyState *fmstate = resultRelInfo->ri_FdwState ?
2023  (PgFdwModifyState *) resultRelInfo->ri_FdwState :
2024  NULL;
2025 
2026  /* should be called only once */
2027  Assert(resultRelInfo->ri_BatchSize == 0);
2028 
2029  /*
2030  * Should never get called when the insert is being performed as part of a
2031  * row movement operation.
2032  */
2033  Assert(fmstate == NULL || fmstate->aux_fmstate == NULL);
2034 
2035  /*
2036  * In EXPLAIN without ANALYZE, ri_FdwState is NULL, so we have to lookup
2037  * the option directly in server/table options. Otherwise just use the
2038  * value we determined earlier.
2039  */
2040  if (fmstate)
2041  batch_size = fmstate->batch_size;
2042  else
2043  batch_size = get_batch_size_option(resultRelInfo->ri_RelationDesc);
2044 
2045  /*
2046  * Disable batching when we have to use RETURNING or there are any
2047  * BEFORE/AFTER ROW INSERT triggers on the foreign table.
2048  *
2049  * When there are any BEFORE ROW INSERT triggers on the table, we can't
2050  * support it, because such triggers might query the table we're inserting
2051  * into and act differently if the tuples that have already been processed
2052  * and prepared for insertion are not there.
2053  */
2054  if (resultRelInfo->ri_projectReturning != NULL ||
2055  (resultRelInfo->ri_TrigDesc &&
2056  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
2057  resultRelInfo->ri_TrigDesc->trig_insert_after_row)))
2058  return 1;
2059 
2060  /*
2061  * Otherwise use the batch size specified for server/table. The number of
2062  * parameters in a batch is limited to 65535 (uint16), so make sure we
2063  * don't exceed this limit by using the maximum batch_size possible.
2064  */
2065  if (fmstate && fmstate->p_nums > 0)
2066  batch_size = Min(batch_size, PQ_QUERY_PARAM_MAX_LIMIT / fmstate->p_nums);
2067 
2068  return batch_size;
2069 }
2070 
2071 /*
2072  * postgresExecForeignUpdate
2073  * Update one row in a foreign table
2074  */
2075 static TupleTableSlot *
2077  ResultRelInfo *resultRelInfo,
2078  TupleTableSlot *slot,
2079  TupleTableSlot *planSlot)
2080 {
2081  TupleTableSlot **rslot;
2082  int numSlots = 1;
2083 
2084  rslot = execute_foreign_modify(estate, resultRelInfo, CMD_UPDATE,
2085  &slot, &planSlot, &numSlots);
2086 
2087  return rslot ? rslot[0] : NULL;
2088 }
2089 
2090 /*
2091  * postgresExecForeignDelete
2092  * Delete one row from a foreign table
2093  */
2094 static TupleTableSlot *
2096  ResultRelInfo *resultRelInfo,
2097  TupleTableSlot *slot,
2098  TupleTableSlot *planSlot)
2099 {
2100  TupleTableSlot **rslot;
2101  int numSlots = 1;
2102 
2103  rslot = execute_foreign_modify(estate, resultRelInfo, CMD_DELETE,
2104  &slot, &planSlot, &numSlots);
2105 
2106  return rslot ? rslot[0] : NULL;
2107 }
2108 
2109 /*
2110  * postgresEndForeignModify
2111  * Finish an insert/update/delete operation on a foreign table
2112  */
2113 static void
2115  ResultRelInfo *resultRelInfo)
2116 {
2117  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2118 
2119  /* If fmstate is NULL, we are in EXPLAIN; nothing to do */
2120  if (fmstate == NULL)
2121  return;
2122 
2123  /* Destroy the execution state */
2124  finish_foreign_modify(fmstate);
2125 }
2126 
2127 /*
2128  * postgresBeginForeignInsert
2129  * Begin an insert operation on a foreign table
2130  */
2131 static void
2133  ResultRelInfo *resultRelInfo)
2134 {
2135  PgFdwModifyState *fmstate;
2136  ModifyTable *plan = castNode(ModifyTable, mtstate->ps.plan);
2137  EState *estate = mtstate->ps.state;
2138  Index resultRelation;
2139  Relation rel = resultRelInfo->ri_RelationDesc;
2140  RangeTblEntry *rte;
2141  TupleDesc tupdesc = RelationGetDescr(rel);
2142  int attnum;
2143  int values_end_len;
2144  StringInfoData sql;
2145  List *targetAttrs = NIL;
2146  List *retrieved_attrs = NIL;
2147  bool doNothing = false;
2148 
2149  /*
2150  * If the foreign table we are about to insert routed rows into is also an
2151  * UPDATE subplan result rel that will be updated later, proceeding with
2152  * the INSERT will result in the later UPDATE incorrectly modifying those
2153  * routed rows, so prevent the INSERT --- it would be nice if we could
2154  * handle this case; but for now, throw an error for safety.
2155  */
2156  if (plan && plan->operation == CMD_UPDATE &&
2157  (resultRelInfo->ri_usesFdwDirectModify ||
2158  resultRelInfo->ri_FdwState))
2159  ereport(ERROR,
2160  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2161  errmsg("cannot route tuples into foreign table to be updated \"%s\"",
2162  RelationGetRelationName(rel))));
2163 
2164  initStringInfo(&sql);
2165 
2166  /* We transmit all columns that are defined in the foreign table. */
2167  for (attnum = 1; attnum <= tupdesc->natts; attnum++)
2168  {
2169  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2170 
2171  if (!attr->attisdropped)
2172  targetAttrs = lappend_int(targetAttrs, attnum);
2173  }
2174 
2175  /* Check if we add the ON CONFLICT clause to the remote query. */
2176  if (plan)
2177  {
2178  OnConflictAction onConflictAction = plan->onConflictAction;
2179 
2180  /* We only support DO NOTHING without an inference specification. */
2181  if (onConflictAction == ONCONFLICT_NOTHING)
2182  doNothing = true;
2183  else if (onConflictAction != ONCONFLICT_NONE)
2184  elog(ERROR, "unexpected ON CONFLICT specification: %d",
2185  (int) onConflictAction);
2186  }
2187 
2188  /*
2189  * If the foreign table is a partition that doesn't have a corresponding
2190  * RTE entry, we need to create a new RTE describing the foreign table for
2191  * use by deparseInsertSql and create_foreign_modify() below, after first
2192  * copying the parent's RTE and modifying some fields to describe the
2193  * foreign partition to work on. However, if this is invoked by UPDATE,
2194  * the existing RTE may already correspond to this partition if it is one
2195  * of the UPDATE subplan target rels; in that case, we can just use the
2196  * existing RTE as-is.
2197  */
2198  if (resultRelInfo->ri_RangeTableIndex == 0)
2199  {
2200  ResultRelInfo *rootResultRelInfo = resultRelInfo->ri_RootResultRelInfo;
2201 
2202  rte = exec_rt_fetch(rootResultRelInfo->ri_RangeTableIndex, estate);
2203  rte = copyObject(rte);
2204  rte->relid = RelationGetRelid(rel);
2205  rte->relkind = RELKIND_FOREIGN_TABLE;
2206 
2207  /*
2208  * For UPDATE, we must use the RT index of the first subplan target
2209  * rel's RTE, because the core code would have built expressions for
2210  * the partition, such as RETURNING, using that RT index as varno of
2211  * Vars contained in those expressions.
2212  */
2213  if (plan && plan->operation == CMD_UPDATE &&
2214  rootResultRelInfo->ri_RangeTableIndex == plan->rootRelation)
2215  resultRelation = mtstate->resultRelInfo[0].ri_RangeTableIndex;
2216  else
2217  resultRelation = rootResultRelInfo->ri_RangeTableIndex;
2218  }
2219  else
2220  {
2221  resultRelation = resultRelInfo->ri_RangeTableIndex;
2222  rte = exec_rt_fetch(resultRelation, estate);
2223  }
2224 
2225  /* Construct the SQL command string. */
2226  deparseInsertSql(&sql, rte, resultRelation, rel, targetAttrs, doNothing,
2227  resultRelInfo->ri_WithCheckOptions,
2228  resultRelInfo->ri_returningList,
2229  &retrieved_attrs, &values_end_len);
2230 
2231  /* Construct an execution state. */
2232  fmstate = create_foreign_modify(mtstate->ps.state,
2233  rte,
2234  resultRelInfo,
2235  CMD_INSERT,
2236  NULL,
2237  sql.data,
2238  targetAttrs,
2239  values_end_len,
2240  retrieved_attrs != NIL,
2241  retrieved_attrs);
2242 
2243  /*
2244  * If the given resultRelInfo already has PgFdwModifyState set, it means
2245  * the foreign table is an UPDATE subplan result rel; in which case, store
2246  * the resulting state into the aux_fmstate of the PgFdwModifyState.
2247  */
2248  if (resultRelInfo->ri_FdwState)
2249  {
2250  Assert(plan && plan->operation == CMD_UPDATE);
2251  Assert(resultRelInfo->ri_usesFdwDirectModify == false);
2252  ((PgFdwModifyState *) resultRelInfo->ri_FdwState)->aux_fmstate = fmstate;
2253  }
2254  else
2255  resultRelInfo->ri_FdwState = fmstate;
2256 }
2257 
2258 /*
2259  * postgresEndForeignInsert
2260  * Finish an insert operation on a foreign table
2261  */
2262 static void
2264  ResultRelInfo *resultRelInfo)
2265 {
2266  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
2267 
2268  Assert(fmstate != NULL);
2269 
2270  /*
2271  * If the fmstate has aux_fmstate set, get the aux_fmstate (see
2272  * postgresBeginForeignInsert())
2273  */
2274  if (fmstate->aux_fmstate)
2275  fmstate = fmstate->aux_fmstate;
2276 
2277  /* Destroy the execution state */
2278  finish_foreign_modify(fmstate);
2279 }
2280 
2281 /*
2282  * postgresIsForeignRelUpdatable
2283  * Determine whether a foreign table supports INSERT, UPDATE and/or
2284  * DELETE.
2285  */
2286 static int
2288 {
2289  bool updatable;
2290  ForeignTable *table;
2291  ForeignServer *server;
2292  ListCell *lc;
2293 
2294  /*
2295  * By default, all postgres_fdw foreign tables are assumed updatable. This
2296  * can be overridden by a per-server setting, which in turn can be
2297  * overridden by a per-table setting.
2298  */
2299  updatable = true;
2300 
2301  table = GetForeignTable(RelationGetRelid(rel));
2302  server = GetForeignServer(table->serverid);
2303 
2304  foreach(lc, server->options)
2305  {
2306  DefElem *def = (DefElem *) lfirst(lc);
2307 
2308  if (strcmp(def->defname, "updatable") == 0)
2309  updatable = defGetBoolean(def);
2310  }
2311  foreach(lc, table->options)
2312  {
2313  DefElem *def = (DefElem *) lfirst(lc);
2314 
2315  if (strcmp(def->defname, "updatable") == 0)
2316  updatable = defGetBoolean(def);
2317  }
2318 
2319  /*
2320  * Currently "updatable" means support for INSERT, UPDATE and DELETE.
2321  */
2322  return updatable ?
2323  (1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE) : 0;
2324 }
2325 
2326 /*
2327  * postgresRecheckForeignScan
2328  * Execute a local join execution plan for a foreign join
2329  */
2330 static bool
2332 {
2333  Index scanrelid = ((Scan *) node->ss.ps.plan)->scanrelid;
2335  TupleTableSlot *result;
2336 
2337  /* For base foreign relations, it suffices to set fdw_recheck_quals */
2338  if (scanrelid > 0)
2339  return true;
2340 
2341  Assert(outerPlan != NULL);
2342 
2343  /* Execute a local join execution plan */
2344  result = ExecProcNode(outerPlan);
2345  if (TupIsNull(result))
2346  return false;
2347 
2348  /* Store result in the given slot */
2349  ExecCopySlot(slot, result);
2350 
2351  return true;
2352 }
2353 
2354 /*
2355  * find_modifytable_subplan
2356  * Helper routine for postgresPlanDirectModify to find the
2357  * ModifyTable subplan node that scans the specified RTI.
2358  *
2359  * Returns NULL if the subplan couldn't be identified. That's not a fatal
2360  * error condition, we just abandon trying to do the update directly.
2361  */
2362 static ForeignScan *
2364  ModifyTable *plan,
2365  Index rtindex,
2366  int subplan_index)
2367 {
2368  Plan *subplan = outerPlan(plan);
2369 
2370  /*
2371  * The cases we support are (1) the desired ForeignScan is the immediate
2372  * child of ModifyTable, or (2) it is the subplan_index'th child of an
2373  * Append node that is the immediate child of ModifyTable. There is no
2374  * point in looking further down, as that would mean that local joins are
2375  * involved, so we can't do the update directly.
2376  *
2377  * There could be a Result atop the Append too, acting to compute the
2378  * UPDATE targetlist values. We ignore that here; the tlist will be
2379  * checked by our caller.
2380  *
2381  * In principle we could examine all the children of the Append, but it's
2382  * currently unlikely that the core planner would generate such a plan
2383  * with the children out-of-order. Moreover, such a search risks costing
2384  * O(N^2) time when there are a lot of children.
2385  */
2386  if (IsA(subplan, Append))
2387  {
2388  Append *appendplan = (Append *) subplan;
2389 
2390  if (subplan_index < list_length(appendplan->appendplans))
2391  subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2392  }
2393  else if (IsA(subplan, Result) &&
2394  outerPlan(subplan) != NULL &&
2395  IsA(outerPlan(subplan), Append))
2396  {
2397  Append *appendplan = (Append *) outerPlan(subplan);
2398 
2399  if (subplan_index < list_length(appendplan->appendplans))
2400  subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2401  }
2402 
2403  /* Now, have we got a ForeignScan on the desired rel? */
2404  if (IsA(subplan, ForeignScan))
2405  {
2406  ForeignScan *fscan = (ForeignScan *) subplan;
2407 
2408  if (bms_is_member(rtindex, fscan->fs_relids))
2409  return fscan;
2410  }
2411 
2412  return NULL;
2413 }
2414 
2415 /*
2416  * postgresPlanDirectModify
2417  * Consider a direct foreign table modification
2418  *
2419  * Decide whether it is safe to modify a foreign table directly, and if so,
2420  * rewrite subplan accordingly.
2421  */
2422 static bool
2424  ModifyTable *plan,
2425  Index resultRelation,
2426  int subplan_index)
2427 {
2428  CmdType operation = plan->operation;
2429  RelOptInfo *foreignrel;
2430  RangeTblEntry *rte;
2431  PgFdwRelationInfo *fpinfo;
2432  Relation rel;
2433  StringInfoData sql;
2434  ForeignScan *fscan;
2435  List *processed_tlist = NIL;
2436  List *targetAttrs = NIL;
2437  List *remote_exprs;
2438  List *params_list = NIL;
2439  List *returningList = NIL;
2440  List *retrieved_attrs = NIL;
2441 
2442  /*
2443  * Decide whether it is safe to modify a foreign table directly.
2444  */
2445 
2446  /*
2447  * The table modification must be an UPDATE or DELETE.
2448  */
2449  if (operation != CMD_UPDATE && operation != CMD_DELETE)
2450  return false;
2451 
2452  /*
2453  * Try to locate the ForeignScan subplan that's scanning resultRelation.
2454  */
2455  fscan = find_modifytable_subplan(root, plan, resultRelation, subplan_index);
2456  if (!fscan)
2457  return false;
2458 
2459  /*
2460  * It's unsafe to modify a foreign table directly if there are any quals
2461  * that should be evaluated locally.
2462  */
2463  if (fscan->scan.plan.qual != NIL)
2464  return false;
2465 
2466  /* Safe to fetch data about the target foreign rel */
2467  if (fscan->scan.scanrelid == 0)
2468  {
2469  foreignrel = find_join_rel(root, fscan->fs_relids);
2470  /* We should have a rel for this foreign join. */
2471  Assert(foreignrel);
2472  }
2473  else
2474  foreignrel = root->simple_rel_array[resultRelation];
2475  rte = root->simple_rte_array[resultRelation];
2476  fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
2477 
2478  /*
2479  * It's unsafe to update a foreign table directly, if any expressions to
2480  * assign to the target columns are unsafe to evaluate remotely.
2481  */
2482  if (operation == CMD_UPDATE)
2483  {
2484  ListCell *lc,
2485  *lc2;
2486 
2487  /*
2488  * The expressions of concern are the first N columns of the processed
2489  * targetlist, where N is the length of the rel's update_colnos.
2490  */
2491  get_translated_update_targetlist(root, resultRelation,
2492  &processed_tlist, &targetAttrs);
2493  forboth(lc, processed_tlist, lc2, targetAttrs)
2494  {
2495  TargetEntry *tle = lfirst_node(TargetEntry, lc);
2496  AttrNumber attno = lfirst_int(lc2);
2497 
2498  /* update's new-value expressions shouldn't be resjunk */
2499  Assert(!tle->resjunk);
2500 
2501  if (attno <= InvalidAttrNumber) /* shouldn't happen */
2502  elog(ERROR, "system-column update is not supported");
2503 
2504  if (!is_foreign_expr(root, foreignrel, (Expr *) tle->expr))
2505  return false;
2506  }
2507  }
2508 
2509  /*
2510  * Ok, rewrite subplan so as to modify the foreign table directly.
2511  */
2512  initStringInfo(&sql);
2513 
2514  /*
2515  * Core code already has some lock on each rel being planned, so we can
2516  * use NoLock here.
2517  */
2518  rel = table_open(rte->relid, NoLock);
2519 
2520  /*
2521  * Recall the qual clauses that must be evaluated remotely. (These are
2522  * bare clauses not RestrictInfos, but deparse.c's appendConditions()
2523  * doesn't care.)
2524  */
2525  remote_exprs = fpinfo->final_remote_exprs;
2526 
2527  /*
2528  * Extract the relevant RETURNING list if any.
2529  */
2530  if (plan->returningLists)
2531  {
2532  returningList = (List *) list_nth(plan->returningLists, subplan_index);
2533 
2534  /*
2535  * When performing an UPDATE/DELETE .. RETURNING on a join directly,
2536  * we fetch from the foreign server any Vars specified in RETURNING
2537  * that refer not only to the target relation but to non-target
2538  * relations. So we'll deparse them into the RETURNING clause of the
2539  * remote query; use a targetlist consisting of them instead, which
2540  * will be adjusted to be new fdw_scan_tlist of the foreign-scan plan
2541  * node below.
2542  */
2543  if (fscan->scan.scanrelid == 0)
2544  returningList = build_remote_returning(resultRelation, rel,
2545  returningList);
2546  }
2547 
2548  /*
2549  * Construct the SQL command string.
2550  */
2551  switch (operation)
2552  {
2553  case CMD_UPDATE:
2554  deparseDirectUpdateSql(&sql, root, resultRelation, rel,
2555  foreignrel,
2556  processed_tlist,
2557  targetAttrs,
2558  remote_exprs, &params_list,
2559  returningList, &retrieved_attrs);
2560  break;
2561  case CMD_DELETE:
2562  deparseDirectDeleteSql(&sql, root, resultRelation, rel,
2563  foreignrel,
2564  remote_exprs, &params_list,
2565  returningList, &retrieved_attrs);
2566  break;
2567  default:
2568  elog(ERROR, "unexpected operation: %d", (int) operation);
2569  break;
2570  }
2571 
2572  /*
2573  * Update the operation and target relation info.
2574  */
2575  fscan->operation = operation;
2576  fscan->resultRelation = resultRelation;
2577 
2578  /*
2579  * Update the fdw_exprs list that will be available to the executor.
2580  */
2581  fscan->fdw_exprs = params_list;
2582 
2583  /*
2584  * Update the fdw_private list that will be available to the executor.
2585  * Items in the list must match enum FdwDirectModifyPrivateIndex, above.
2586  */
2587  fscan->fdw_private = list_make4(makeString(sql.data),
2588  makeBoolean((retrieved_attrs != NIL)),
2589  retrieved_attrs,
2590  makeBoolean(plan->canSetTag));
2591 
2592  /*
2593  * Update the foreign-join-related fields.
2594  */
2595  if (fscan->scan.scanrelid == 0)
2596  {
2597  /* No need for the outer subplan. */
2598  fscan->scan.plan.lefttree = NULL;
2599 
2600  /* Build new fdw_scan_tlist if UPDATE/DELETE .. RETURNING. */
2601  if (returningList)
2602  rebuild_fdw_scan_tlist(fscan, returningList);
2603  }
2604 
2605  /*
2606  * Finally, unset the async-capable flag if it is set, as we currently
2607  * don't support asynchronous execution of direct modifications.
2608  */
2609  if (fscan->scan.plan.async_capable)
2610  fscan->scan.plan.async_capable = false;
2611 
2612  table_close(rel, NoLock);
2613  return true;
2614 }
2615 
2616 /*
2617  * postgresBeginDirectModify
2618  * Prepare a direct foreign table modification
2619  */
2620 static void
2622 {
2623  ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
2624  EState *estate = node->ss.ps.state;
2625  PgFdwDirectModifyState *dmstate;
2626  Index rtindex;
2627  RangeTblEntry *rte;
2628  Oid userid;
2629  ForeignTable *table;
2630  UserMapping *user;
2631  int numParams;
2632 
2633  /*
2634  * Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
2635  */
2636  if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
2637  return;
2638 
2639  /*
2640  * We'll save private state in node->fdw_state.
2641  */
2642  dmstate = (PgFdwDirectModifyState *) palloc0(sizeof(PgFdwDirectModifyState));
2643  node->fdw_state = (void *) dmstate;
2644 
2645  /*
2646  * Identify which user to do the remote access as. This should match what
2647  * ExecCheckRTEPerms() does.
2648  */
2649  rtindex = node->resultRelInfo->ri_RangeTableIndex;
2650  rte = exec_rt_fetch(rtindex, estate);
2651  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
2652 
2653  /* Get info about foreign table. */
2654  if (fsplan->scan.scanrelid == 0)
2655  dmstate->rel = ExecOpenScanRelation(estate, rtindex, eflags);
2656  else
2657  dmstate->rel = node->ss.ss_currentRelation;
2658  table = GetForeignTable(RelationGetRelid(dmstate->rel));
2659  user = GetUserMapping(userid, table->serverid);
2660 
2661  /*
2662  * Get connection to the foreign server. Connection manager will
2663  * establish new connection if necessary.
2664  */
2665  dmstate->conn = GetConnection(user, false, &dmstate->conn_state);
2666 
2667  /* Update the foreign-join-related fields. */
2668  if (fsplan->scan.scanrelid == 0)
2669  {
2670  /* Save info about foreign table. */
2671  dmstate->resultRel = dmstate->rel;
2672 
2673  /*
2674  * Set dmstate->rel to NULL to teach get_returning_data() and
2675  * make_tuple_from_result_row() that columns fetched from the remote
2676  * server are described by fdw_scan_tlist of the foreign-scan plan
2677  * node, not the tuple descriptor for the target relation.
2678  */
2679  dmstate->rel = NULL;
2680  }
2681 
2682  /* Initialize state variable */
2683  dmstate->num_tuples = -1; /* -1 means not set yet */
2684 
2685  /* Get private info created by planner functions. */
2686  dmstate->query = strVal(list_nth(fsplan->fdw_private,
2688  dmstate->has_returning = boolVal(list_nth(fsplan->fdw_private,
2690  dmstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
2692  dmstate->set_processed = boolVal(list_nth(fsplan->fdw_private,
2694 
2695  /* Create context for per-tuple temp workspace. */
2696  dmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
2697  "postgres_fdw temporary data",
2699 
2700  /* Prepare for input conversion of RETURNING results. */
2701  if (dmstate->has_returning)
2702  {
2703  TupleDesc tupdesc;
2704 
2705  if (fsplan->scan.scanrelid == 0)
2706  tupdesc = get_tupdesc_for_join_scan_tuples(node);
2707  else
2708  tupdesc = RelationGetDescr(dmstate->rel);
2709 
2710  dmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2711 
2712  /*
2713  * When performing an UPDATE/DELETE .. RETURNING on a join directly,
2714  * initialize a filter to extract an updated/deleted tuple from a scan
2715  * tuple.
2716  */
2717  if (fsplan->scan.scanrelid == 0)
2718  init_returning_filter(dmstate, fsplan->fdw_scan_tlist, rtindex);
2719  }
2720 
2721  /*
2722  * Prepare for processing of parameters used in remote query, if any.
2723  */
2724  numParams = list_length(fsplan->fdw_exprs);
2725  dmstate->numParams = numParams;
2726  if (numParams > 0)
2728  fsplan->fdw_exprs,
2729  numParams,
2730  &dmstate->param_flinfo,
2731  &dmstate->param_exprs,
2732  &dmstate->param_values);
2733 }
2734 
2735 /*
2736  * postgresIterateDirectModify
2737  * Execute a direct foreign table modification
2738  */
2739 static TupleTableSlot *
2741 {
2743  EState *estate = node->ss.ps.state;
2744  ResultRelInfo *resultRelInfo = node->resultRelInfo;
2745 
2746  /*
2747  * If this is the first call after Begin, execute the statement.
2748  */
2749  if (dmstate->num_tuples == -1)
2750  execute_dml_stmt(node);
2751 
2752  /*
2753  * If the local query doesn't specify RETURNING, just clear tuple slot.
2754  */
2755  if (!resultRelInfo->ri_projectReturning)
2756  {
2757  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
2758  Instrumentation *instr = node->ss.ps.instrument;
2759 
2760  Assert(!dmstate->has_returning);
2761 
2762  /* Increment the command es_processed count if necessary. */
2763  if (dmstate->set_processed)
2764  estate->es_processed += dmstate->num_tuples;
2765 
2766  /* Increment the tuple count for EXPLAIN ANALYZE if necessary. */
2767  if (instr)
2768  instr->tuplecount += dmstate->num_tuples;
2769 
2770  return ExecClearTuple(slot);
2771  }
2772 
2773  /*
2774  * Get the next RETURNING tuple.
2775  */
2776  return get_returning_data(node);
2777 }
2778 
2779 /*
2780  * postgresEndDirectModify
2781  * Finish a direct foreign table modification
2782  */
2783 static void
2785 {
2787 
2788  /* if dmstate is NULL, we are in EXPLAIN; nothing to do */
2789  if (dmstate == NULL)
2790  return;
2791 
2792  /* Release PGresult */
2793  PQclear(dmstate->result);
2794 
2795  /* Release remote connection */
2796  ReleaseConnection(dmstate->conn);
2797  dmstate->conn = NULL;
2798 
2799  /* MemoryContext will be deleted automatically. */
2800 }
2801 
2802 /*
2803  * postgresExplainForeignScan
2804  * Produce extra output for EXPLAIN of a ForeignScan on a foreign table
2805  */
2806 static void
2808 {
2809  ForeignScan *plan = castNode(ForeignScan, node->ss.ps.plan);
2810  List *fdw_private = plan->fdw_private;
2811 
2812  /*
2813  * Identify foreign scans that are really joins or upper relations. The
2814  * input looks something like "(1) LEFT JOIN (2)", and we must replace the
2815  * digit string(s), which are RT indexes, with the correct relation names.
2816  * We do that here, not when the plan is created, because we can't know
2817  * what aliases ruleutils.c will assign at plan creation time.
2818  */
2819  if (list_length(fdw_private) > FdwScanPrivateRelations)
2820  {
2821  StringInfo relations;
2822  char *rawrelations;
2823  char *ptr;
2824  int minrti,
2825  rtoffset;
2826 
2827  rawrelations = strVal(list_nth(fdw_private, FdwScanPrivateRelations));
2828 
2829  /*
2830  * A difficulty with using a string representation of RT indexes is
2831  * that setrefs.c won't update the string when flattening the
2832  * rangetable. To find out what rtoffset was applied, identify the
2833  * minimum RT index appearing in the string and compare it to the
2834  * minimum member of plan->fs_relids. (We expect all the relids in
2835  * the join will have been offset by the same amount; the Asserts
2836  * below should catch it if that ever changes.)
2837  */
2838  minrti = INT_MAX;
2839  ptr = rawrelations;
2840  while (*ptr)
2841  {
2842  if (isdigit((unsigned char) *ptr))
2843  {
2844  int rti = strtol(ptr, &ptr, 10);
2845 
2846  if (rti < minrti)
2847  minrti = rti;
2848  }
2849  else
2850  ptr++;
2851  }
2852  rtoffset = bms_next_member(plan->fs_relids, -1) - minrti;
2853 
2854  /* Now we can translate the string */
2855  relations = makeStringInfo();
2856  ptr = rawrelations;
2857  while (*ptr)
2858  {
2859  if (isdigit((unsigned char) *ptr))
2860  {
2861  int rti = strtol(ptr, &ptr, 10);
2862  RangeTblEntry *rte;
2863  char *relname;
2864  char *refname;
2865 
2866  rti += rtoffset;
2867  Assert(bms_is_member(rti, plan->fs_relids));
2868  rte = rt_fetch(rti, es->rtable);
2869  Assert(rte->rtekind == RTE_RELATION);
2870  /* This logic should agree with explain.c's ExplainTargetRel */
2871  relname = get_rel_name(rte->relid);
2872  if (es->verbose)
2873  {
2874  char *namespace;
2875 
2876  namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid));
2877  appendStringInfo(relations, "%s.%s",
2878  quote_identifier(namespace),
2880  }
2881  else
2882  appendStringInfoString(relations,
2884  refname = (char *) list_nth(es->rtable_names, rti - 1);
2885  if (refname == NULL)
2886  refname = rte->eref->aliasname;
2887  if (strcmp(refname, relname) != 0)
2888  appendStringInfo(relations, " %s",
2889  quote_identifier(refname));
2890  }
2891  else
2892  appendStringInfoChar(relations, *ptr++);
2893  }
2894  ExplainPropertyText("Relations", relations->data, es);
2895  }
2896 
2897  /*
2898  * Add remote query, when VERBOSE option is specified.
2899  */
2900  if (es->verbose)
2901  {
2902  char *sql;
2903 
2904  sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
2905  ExplainPropertyText("Remote SQL", sql, es);
2906  }
2907 }
2908 
2909 /*
2910  * postgresExplainForeignModify
2911  * Produce extra output for EXPLAIN of a ModifyTable on a foreign table
2912  */
2913 static void
2915  ResultRelInfo *rinfo,
2916  List *fdw_private,
2917  int subplan_index,
2918  ExplainState *es)
2919 {
2920  if (es->verbose)
2921  {
2922  char *sql = strVal(list_nth(fdw_private,
2924 
2925  ExplainPropertyText("Remote SQL", sql, es);
2926 
2927  /*
2928  * For INSERT we should always have batch size >= 1, but UPDATE and
2929  * DELETE don't support batching so don't show the property.
2930  */
2931  if (rinfo->ri_BatchSize > 0)
2932  ExplainPropertyInteger("Batch Size", NULL, rinfo->ri_BatchSize, es);
2933  }
2934 }
2935 
2936 /*
2937  * postgresExplainDirectModify
2938  * Produce extra output for EXPLAIN of a ForeignScan that modifies a
2939  * foreign table directly
2940  */
2941 static void
2943 {
2944  List *fdw_private;
2945  char *sql;
2946 
2947  if (es->verbose)
2948  {
2949  fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
2950  sql = strVal(list_nth(fdw_private, FdwDirectModifyPrivateUpdateSql));
2951  ExplainPropertyText("Remote SQL", sql, es);
2952  }
2953 }
2954 
2955 /*
2956  * postgresExecForeignTruncate
2957  * Truncate one or more foreign tables
2958  */
2959 static void
2961  DropBehavior behavior,
2962  bool restart_seqs)
2963 {
2964  Oid serverid = InvalidOid;
2965  UserMapping *user = NULL;
2966  PGconn *conn = NULL;
2967  StringInfoData sql;
2968  ListCell *lc;
2969  bool server_truncatable = true;
2970 
2971  /*
2972  * By default, all postgres_fdw foreign tables are assumed truncatable.
2973  * This can be overridden by a per-server setting, which in turn can be
2974  * overridden by a per-table setting.
2975  */
2976  foreach(lc, rels)
2977  {
2978  ForeignServer *server = NULL;
2979  Relation rel = lfirst(lc);
2981  ListCell *cell;
2982  bool truncatable;
2983 
2984  /*
2985  * First time through, determine whether the foreign server allows
2986  * truncates. Since all specified foreign tables are assumed to belong
2987  * to the same foreign server, this result can be used for other
2988  * foreign tables.
2989  */
2990  if (!OidIsValid(serverid))
2991  {
2992  serverid = table->serverid;
2993  server = GetForeignServer(serverid);
2994 
2995  foreach(cell, server->options)
2996  {
2997  DefElem *defel = (DefElem *) lfirst(cell);
2998 
2999  if (strcmp(defel->defname, "truncatable") == 0)
3000  {
3001  server_truncatable = defGetBoolean(defel);
3002  break;
3003  }
3004  }
3005  }
3006 
3007  /*
3008  * Confirm that all specified foreign tables belong to the same
3009  * foreign server.
3010  */
3011  Assert(table->serverid == serverid);
3012 
3013  /* Determine whether this foreign table allows truncations */
3014  truncatable = server_truncatable;
3015  foreach(cell, table->options)
3016  {
3017  DefElem *defel = (DefElem *) lfirst(cell);
3018 
3019  if (strcmp(defel->defname, "truncatable") == 0)
3020  {
3021  truncatable = defGetBoolean(defel);
3022  break;
3023  }
3024  }
3025 
3026  if (!truncatable)
3027  ereport(ERROR,
3028  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3029  errmsg("foreign table \"%s\" does not allow truncates",
3030  RelationGetRelationName(rel))));
3031  }
3032  Assert(OidIsValid(serverid));
3033 
3034  /*
3035  * Get connection to the foreign server. Connection manager will
3036  * establish new connection if necessary.
3037  */
3038  user = GetUserMapping(GetUserId(), serverid);
3039  conn = GetConnection(user, false, NULL);
3040 
3041  /* Construct the TRUNCATE command string */
3042  initStringInfo(&sql);
3043  deparseTruncateSql(&sql, rels, behavior, restart_seqs);
3044 
3045  /* Issue the TRUNCATE command to remote server */
3046  do_sql_command(conn, sql.data);
3047 
3048  pfree(sql.data);
3049 }
3050 
3051 /*
3052  * estimate_path_cost_size
3053  * Get cost and size estimates for a foreign scan on given foreign relation
3054  * either a base relation or a join between foreign relations or an upper
3055  * relation containing foreign relations.
3056  *
3057  * param_join_conds are the parameterization clauses with outer relations.
3058  * pathkeys specify the expected sort order if any for given path being costed.
3059  * fpextra specifies additional post-scan/join-processing steps such as the
3060  * final sort and the LIMIT restriction.
3061  *
3062  * The function returns the cost and size estimates in p_rows, p_width,
3063  * p_startup_cost and p_total_cost variables.
3064  */
3065 static void
3067  RelOptInfo *foreignrel,
3068  List *param_join_conds,
3069  List *pathkeys,
3070  PgFdwPathExtraData *fpextra,
3071  double *p_rows, int *p_width,
3072  Cost *p_startup_cost, Cost *p_total_cost)
3073 {
3074  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
3075  double rows;
3076  double retrieved_rows;
3077  int width;
3078  Cost startup_cost;
3079  Cost total_cost;
3080 
3081  /* Make sure the core code has set up the relation's reltarget */
3082  Assert(foreignrel->reltarget);
3083 
3084  /*
3085  * If the table or the server is configured to use remote estimates,
3086  * connect to the foreign server and execute EXPLAIN to estimate the
3087  * number of rows selected by the restriction+join clauses. Otherwise,
3088  * estimate rows using whatever statistics we have locally, in a way
3089  * similar to ordinary tables.
3090  */
3091  if (fpinfo->use_remote_estimate)
3092  {
3093  List *remote_param_join_conds;
3094  List *local_param_join_conds;
3095  StringInfoData sql;
3096  PGconn *conn;
3097  Selectivity local_sel;
3098  QualCost local_cost;
3099  List *fdw_scan_tlist = NIL;
3100  List *remote_conds;
3101 
3102  /* Required only to be passed to deparseSelectStmtForRel */
3103  List *retrieved_attrs;
3104 
3105  /*
3106  * param_join_conds might contain both clauses that are safe to send
3107  * across, and clauses that aren't.
3108  */
3109  classifyConditions(root, foreignrel, param_join_conds,
3110  &remote_param_join_conds, &local_param_join_conds);
3111 
3112  /* Build the list of columns to be fetched from the foreign server. */
3113  if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
3114  fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
3115  else
3116  fdw_scan_tlist = NIL;
3117 
3118  /*
3119  * The complete list of remote conditions includes everything from
3120  * baserestrictinfo plus any extra join_conds relevant to this
3121  * particular path.
3122  */
3123  remote_conds = list_concat(remote_param_join_conds,
3124  fpinfo->remote_conds);
3125 
3126  /*
3127  * Construct EXPLAIN query including the desired SELECT, FROM, and
3128  * WHERE clauses. Params and other-relation Vars are replaced by dummy
3129  * values, so don't request params_list.
3130  */
3131  initStringInfo(&sql);
3132  appendStringInfoString(&sql, "EXPLAIN ");
3133  deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
3134  remote_conds, pathkeys,
3135  fpextra ? fpextra->has_final_sort : false,
3136  fpextra ? fpextra->has_limit : false,
3137  false, &retrieved_attrs, NULL);
3138 
3139  /* Get the remote estimate */
3140  conn = GetConnection(fpinfo->user, false, NULL);
3141  get_remote_estimate(sql.data, conn, &rows, &width,
3142  &startup_cost, &total_cost);
3144 
3145  retrieved_rows = rows;
3146 
3147  /* Factor in the selectivity of the locally-checked quals */
3148  local_sel = clauselist_selectivity(root,
3149  local_param_join_conds,
3150  foreignrel->relid,
3151  JOIN_INNER,
3152  NULL);
3153  local_sel *= fpinfo->local_conds_sel;
3154 
3155  rows = clamp_row_est(rows * local_sel);
3156 
3157  /* Add in the eval cost of the locally-checked quals */
3158  startup_cost += fpinfo->local_conds_cost.startup;
3159  total_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3160  cost_qual_eval(&local_cost, local_param_join_conds, root);
3161  startup_cost += local_cost.startup;
3162  total_cost += local_cost.per_tuple * retrieved_rows;
3163 
3164  /*
3165  * Add in tlist eval cost for each output row. In case of an
3166  * aggregate, some of the tlist expressions such as grouping
3167  * expressions will be evaluated remotely, so adjust the costs.
3168  */
3169  startup_cost += foreignrel->reltarget->cost.startup;
3170  total_cost += foreignrel->reltarget->cost.startup;
3171  total_cost += foreignrel->reltarget->cost.per_tuple * rows;
3172  if (IS_UPPER_REL(foreignrel))
3173  {
3174  QualCost tlist_cost;
3175 
3176  cost_qual_eval(&tlist_cost, fdw_scan_tlist, root);
3177  startup_cost -= tlist_cost.startup;
3178  total_cost -= tlist_cost.startup;
3179  total_cost -= tlist_cost.per_tuple * rows;
3180  }
3181  }
3182  else
3183  {
3184  Cost run_cost = 0;
3185 
3186  /*
3187  * We don't support join conditions in this mode (hence, no
3188  * parameterized paths can be made).
3189  */
3190  Assert(param_join_conds == NIL);
3191 
3192  /*
3193  * We will come here again and again with different set of pathkeys or
3194  * additional post-scan/join-processing steps that caller wants to
3195  * cost. We don't need to calculate the cost/size estimates for the
3196  * underlying scan, join, or grouping each time. Instead, use those
3197  * estimates if we have cached them already.
3198  */
3199  if (fpinfo->rel_startup_cost >= 0 && fpinfo->rel_total_cost >= 0)
3200  {
3201  Assert(fpinfo->retrieved_rows >= 0);
3202 
3203  rows = fpinfo->rows;
3204  retrieved_rows = fpinfo->retrieved_rows;
3205  width = fpinfo->width;
3206  startup_cost = fpinfo->rel_startup_cost;
3207  run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
3208 
3209  /*
3210  * If we estimate the costs of a foreign scan or a foreign join
3211  * with additional post-scan/join-processing steps, the scan or
3212  * join costs obtained from the cache wouldn't yet contain the
3213  * eval costs for the final scan/join target, which would've been
3214  * updated by apply_scanjoin_target_to_paths(); add the eval costs
3215  * now.
3216  */
3217  if (fpextra && !IS_UPPER_REL(foreignrel))
3218  {
3219  /* Shouldn't get here unless we have LIMIT */
3220  Assert(fpextra->has_limit);
3221  Assert(foreignrel->reloptkind == RELOPT_BASEREL ||
3222  foreignrel->reloptkind == RELOPT_JOINREL);
3223  startup_cost += foreignrel->reltarget->cost.startup;
3224  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3225  }
3226  }
3227  else if (IS_JOIN_REL(foreignrel))
3228  {
3229  PgFdwRelationInfo *fpinfo_i;
3230  PgFdwRelationInfo *fpinfo_o;
3231  QualCost join_cost;
3232  QualCost remote_conds_cost;
3233  double nrows;
3234 
3235  /* Use rows/width estimates made by the core code. */
3236  rows = foreignrel->rows;
3237  width = foreignrel->reltarget->width;
3238 
3239  /* For join we expect inner and outer relations set */
3240  Assert(fpinfo->innerrel && fpinfo->outerrel);
3241 
3242  fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private;
3243  fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
3244 
3245  /* Estimate of number of rows in cross product */
3246  nrows = fpinfo_i->rows * fpinfo_o->rows;
3247 
3248  /*
3249  * Back into an estimate of the number of retrieved rows. Just in
3250  * case this is nuts, clamp to at most nrows.
3251  */
3252  retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3253  retrieved_rows = Min(retrieved_rows, nrows);
3254 
3255  /*
3256  * The cost of foreign join is estimated as cost of generating
3257  * rows for the joining relations + cost for applying quals on the
3258  * rows.
3259  */
3260 
3261  /*
3262  * Calculate the cost of clauses pushed down to the foreign server
3263  */
3264  cost_qual_eval(&remote_conds_cost, fpinfo->remote_conds, root);
3265  /* Calculate the cost of applying join clauses */
3266  cost_qual_eval(&join_cost, fpinfo->joinclauses, root);
3267 
3268  /*
3269  * Startup cost includes startup cost of joining relations and the
3270  * startup cost for join and other clauses. We do not include the
3271  * startup cost specific to join strategy (e.g. setting up hash
3272  * tables) since we do not know what strategy the foreign server
3273  * is going to use.
3274  */
3275  startup_cost = fpinfo_i->rel_startup_cost + fpinfo_o->rel_startup_cost;
3276  startup_cost += join_cost.startup;
3277  startup_cost += remote_conds_cost.startup;
3278  startup_cost += fpinfo->local_conds_cost.startup;
3279 
3280  /*
3281  * Run time cost includes:
3282  *
3283  * 1. Run time cost (total_cost - startup_cost) of relations being
3284  * joined
3285  *
3286  * 2. Run time cost of applying join clauses on the cross product
3287  * of the joining relations.
3288  *
3289  * 3. Run time cost of applying pushed down other clauses on the
3290  * result of join
3291  *
3292  * 4. Run time cost of applying nonpushable other clauses locally
3293  * on the result fetched from the foreign server.
3294  */
3295  run_cost = fpinfo_i->rel_total_cost - fpinfo_i->rel_startup_cost;
3296  run_cost += fpinfo_o->rel_total_cost - fpinfo_o->rel_startup_cost;
3297  run_cost += nrows * join_cost.per_tuple;
3298  nrows = clamp_row_est(nrows * fpinfo->joinclause_sel);
3299  run_cost += nrows * remote_conds_cost.per_tuple;
3300  run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3301 
3302  /* Add in tlist eval cost for each output row */
3303  startup_cost += foreignrel->reltarget->cost.startup;
3304  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3305  }
3306  else if (IS_UPPER_REL(foreignrel))
3307  {
3308  RelOptInfo *outerrel = fpinfo->outerrel;
3309  PgFdwRelationInfo *ofpinfo;
3310  AggClauseCosts aggcosts;
3311  double input_rows;
3312  int numGroupCols;
3313  double numGroups = 1;
3314 
3315  /* The upper relation should have its outer relation set */
3316  Assert(outerrel);
3317  /* and that outer relation should have its reltarget set */
3318  Assert(outerrel->reltarget);
3319 
3320  /*
3321  * This cost model is mixture of costing done for sorted and
3322  * hashed aggregates in cost_agg(). We are not sure which
3323  * strategy will be considered at remote side, thus for
3324  * simplicity, we put all startup related costs in startup_cost
3325  * and all finalization and run cost are added in total_cost.
3326  */
3327 
3328  ofpinfo = (PgFdwRelationInfo *) outerrel->fdw_private;
3329 
3330  /* Get rows from input rel */
3331  input_rows = ofpinfo->rows;
3332 
3333  /* Collect statistics about aggregates for estimating costs. */
3334  MemSet(&aggcosts, 0, sizeof(AggClauseCosts));
3335  if (root->parse->hasAggs)
3336  {
3337  get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &aggcosts);
3338  }
3339 
3340  /* Get number of grouping columns and possible number of groups */
3341  numGroupCols = list_length(root->parse->groupClause);
3342  numGroups = estimate_num_groups(root,
3344  fpinfo->grouped_tlist),
3345  input_rows, NULL, NULL);
3346 
3347  /*
3348  * Get the retrieved_rows and rows estimates. If there are HAVING
3349  * quals, account for their selectivity.
3350  */
3351  if (root->parse->havingQual)
3352  {
3353  /* Factor in the selectivity of the remotely-checked quals */
3354  retrieved_rows =
3355  clamp_row_est(numGroups *
3357  fpinfo->remote_conds,
3358  0,
3359  JOIN_INNER,
3360  NULL));
3361  /* Factor in the selectivity of the locally-checked quals */
3362  rows = clamp_row_est(retrieved_rows * fpinfo->local_conds_sel);
3363  }
3364  else
3365  {
3366  rows = retrieved_rows = numGroups;
3367  }
3368 
3369  /* Use width estimate made by the core code. */
3370  width = foreignrel->reltarget->width;
3371 
3372  /*-----
3373  * Startup cost includes:
3374  * 1. Startup cost for underneath input relation, adjusted for
3375  * tlist replacement by apply_scanjoin_target_to_paths()
3376  * 2. Cost of performing aggregation, per cost_agg()
3377  *-----
3378  */
3379  startup_cost = ofpinfo->rel_startup_cost;
3380  startup_cost += outerrel->reltarget->cost.startup;
3381  startup_cost += aggcosts.transCost.startup;
3382  startup_cost += aggcosts.transCost.per_tuple * input_rows;
3383  startup_cost += aggcosts.finalCost.startup;
3384  startup_cost += (cpu_operator_cost * numGroupCols) * input_rows;
3385 
3386  /*-----
3387  * Run time cost includes:
3388  * 1. Run time cost of underneath input relation, adjusted for
3389  * tlist replacement by apply_scanjoin_target_to_paths()
3390  * 2. Run time cost of performing aggregation, per cost_agg()
3391  *-----
3392  */
3393  run_cost = ofpinfo->rel_total_cost - ofpinfo->rel_startup_cost;
3394  run_cost += outerrel->reltarget->cost.per_tuple * input_rows;
3395  run_cost += aggcosts.finalCost.per_tuple * numGroups;
3396  run_cost += cpu_tuple_cost * numGroups;
3397 
3398  /* Account for the eval cost of HAVING quals, if any */
3399  if (root->parse->havingQual)
3400  {
3401  QualCost remote_cost;
3402 
3403  /* Add in the eval cost of the remotely-checked quals */
3404  cost_qual_eval(&remote_cost, fpinfo->remote_conds, root);
3405  startup_cost += remote_cost.startup;
3406  run_cost += remote_cost.per_tuple * numGroups;
3407  /* Add in the eval cost of the locally-checked quals */
3408  startup_cost += fpinfo->local_conds_cost.startup;
3409  run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3410  }
3411 
3412  /* Add in tlist eval cost for each output row */
3413  startup_cost += foreignrel->reltarget->cost.startup;
3414  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3415  }
3416  else
3417  {
3418  Cost cpu_per_tuple;
3419 
3420  /* Use rows/width estimates made by set_baserel_size_estimates. */
3421  rows = foreignrel->rows;
3422  width = foreignrel->reltarget->width;
3423 
3424  /*
3425  * Back into an estimate of the number of retrieved rows. Just in
3426  * case this is nuts, clamp to at most foreignrel->tuples.
3427  */
3428  retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3429  retrieved_rows = Min(retrieved_rows, foreignrel->tuples);
3430 
3431  /*
3432  * Cost as though this were a seqscan, which is pessimistic. We
3433  * effectively imagine the local_conds are being evaluated
3434  * remotely, too.
3435  */
3436  startup_cost = 0;
3437  run_cost = 0;
3438  run_cost += seq_page_cost * foreignrel->pages;
3439 
3440  startup_cost += foreignrel->baserestrictcost.startup;
3441  cpu_per_tuple = cpu_tuple_cost + foreignrel->baserestrictcost.per_tuple;
3442  run_cost += cpu_per_tuple * foreignrel->tuples;
3443 
3444  /* Add in tlist eval cost for each output row */
3445  startup_cost += foreignrel->reltarget->cost.startup;
3446  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3447  }
3448 
3449  /*
3450  * Without remote estimates, we have no real way to estimate the cost
3451  * of generating sorted output. It could be free if the query plan
3452  * the remote side would have chosen generates properly-sorted output
3453  * anyway, but in most cases it will cost something. Estimate a value
3454  * high enough that we won't pick the sorted path when the ordering
3455  * isn't locally useful, but low enough that we'll err on the side of
3456  * pushing down the ORDER BY clause when it's useful to do so.
3457  */
3458  if (pathkeys != NIL)
3459  {
3460  if (IS_UPPER_REL(foreignrel))
3461  {
3462  Assert(foreignrel->reloptkind == RELOPT_UPPER_REL &&
3463  fpinfo->stage == UPPERREL_GROUP_AGG);
3464  adjust_foreign_grouping_path_cost(root, pathkeys,
3465  retrieved_rows, width,
3466  fpextra->limit_tuples,
3467  &startup_cost, &run_cost);
3468  }
3469  else
3470  {
3471  startup_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3472  run_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3473  }
3474  }
3475 
3476  total_cost = startup_cost + run_cost;
3477 
3478  /* Adjust the cost estimates if we have LIMIT */
3479  if (fpextra && fpextra->has_limit)
3480  {
3481  adjust_limit_rows_costs(&rows, &startup_cost, &total_cost,
3482  fpextra->offset_est, fpextra->count_est);
3483  retrieved_rows = rows;
3484  }
3485  }
3486 
3487  /*
3488  * If this includes the final sort step, the given target, which will be
3489  * applied to the resulting path, might have different expressions from
3490  * the foreignrel's reltarget (see make_sort_input_target()); adjust tlist
3491  * eval costs.
3492  */
3493  if (fpextra && fpextra->has_final_sort &&
3494  fpextra->target != foreignrel->reltarget)
3495  {
3496  QualCost oldcost = foreignrel->reltarget->cost;
3497  QualCost newcost = fpextra->target->cost;
3498 
3499  startup_cost += newcost.startup - oldcost.startup;
3500  total_cost += newcost.startup - oldcost.startup;
3501  total_cost += (newcost.per_tuple - oldcost.per_tuple) * rows;
3502  }
3503 
3504  /*
3505  * Cache the retrieved rows and cost estimates for scans, joins, or
3506  * groupings without any parameterization, pathkeys, or additional
3507  * post-scan/join-processing steps, before adding the costs for
3508  * transferring data from the foreign server. These estimates are useful
3509  * for costing remote joins involving this relation or costing other
3510  * remote operations on this relation such as remote sorts and remote
3511  * LIMIT restrictions, when the costs can not be obtained from the foreign
3512  * server. This function will be called at least once for every foreign
3513  * relation without any parameterization, pathkeys, or additional
3514  * post-scan/join-processing steps.
3515  */
3516  if (pathkeys == NIL && param_join_conds == NIL && fpextra == NULL)
3517  {
3518  fpinfo->retrieved_rows = retrieved_rows;
3519  fpinfo->rel_startup_cost = startup_cost;
3520  fpinfo->rel_total_cost = total_cost;
3521  }
3522 
3523  /*
3524  * Add some additional cost factors to account for connection overhead
3525  * (fdw_startup_cost), transferring data across the network
3526  * (fdw_tuple_cost per retrieved row), and local manipulation of the data
3527  * (cpu_tuple_cost per retrieved row).
3528  */
3529  startup_cost += fpinfo->fdw_startup_cost;
3530  total_cost += fpinfo->fdw_startup_cost;
3531  total_cost += fpinfo->fdw_tuple_cost * retrieved_rows;
3532  total_cost += cpu_tuple_cost * retrieved_rows;
3533 
3534  /*
3535  * If we have LIMIT, we should prefer performing the restriction remotely
3536  * rather than locally, as the former avoids extra row fetches from the
3537  * remote that the latter might cause. But since the core code doesn't
3538  * account for such fetches when estimating the costs of the local
3539  * restriction (see create_limit_path()), there would be no difference
3540  * between the costs of the local restriction and the costs of the remote
3541  * restriction estimated above if we don't use remote estimates (except
3542  * for the case where the foreignrel is a grouping relation, the given
3543  * pathkeys is not NIL, and the effects of a bounded sort for that rel is
3544  * accounted for in costing the remote restriction). Tweak the costs of
3545  * the remote restriction to ensure we'll prefer it if LIMIT is a useful
3546  * one.
3547  */
3548  if (!fpinfo->use_remote_estimate &&
3549  fpextra && fpextra->has_limit &&
3550  fpextra->limit_tuples > 0 &&
3551  fpextra->limit_tuples < fpinfo->rows)
3552  {
3553  Assert(fpinfo->rows > 0);
3554  total_cost -= (total_cost - startup_cost) * 0.05 *
3555  (fpinfo->rows - fpextra->limit_tuples) / fpinfo->rows;
3556  }
3557 
3558  /* Return results. */
3559  *p_rows = rows;
3560  *p_width = width;
3561  *p_startup_cost = startup_cost;
3562  *p_total_cost = total_cost;
3563 }
3564 
3565 /*
3566  * Estimate costs of executing a SQL statement remotely.
3567  * The given "sql" must be an EXPLAIN command.
3568  */
3569 static void
3570 get_remote_estimate(const char *sql, PGconn *conn,
3571  double *rows, int *width,
3572  Cost *startup_cost, Cost *total_cost)
3573 {
3574  PGresult *volatile res = NULL;
3575 
3576  /* PGresult must be released before leaving this function. */
3577  PG_TRY();
3578  {
3579  char *line;
3580  char *p;
3581  int n;
3582 
3583  /*
3584  * Execute EXPLAIN remotely.
3585  */
3586  res = pgfdw_exec_query(conn, sql, NULL);
3588  pgfdw_report_error(ERROR, res, conn, false, sql);
3589 
3590  /*
3591  * Extract cost numbers for topmost plan node. Note we search for a
3592  * left paren from the end of the line to avoid being confused by
3593  * other uses of parentheses.
3594  */
3595  line = PQgetvalue(res, 0, 0);
3596  p = strrchr(line, '(');
3597  if (p == NULL)
3598  elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3599  n = sscanf(p, "(cost=%lf..%lf rows=%lf width=%d)",
3600  startup_cost, total_cost, rows, width);
3601  if (n != 4)
3602  elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3603  }
3604  PG_FINALLY();
3605  {
3606  PQclear(res);
3607  }
3608  PG_END_TRY();
3609 }
3610 
3611 /*
3612  * Adjust the cost estimates of a foreign grouping path to include the cost of
3613  * generating properly-sorted output.
3614  */
3615 static void
3617  List *pathkeys,
3618  double retrieved_rows,
3619  double width,
3620  double limit_tuples,
3621  Cost *p_startup_cost,
3622  Cost *p_run_cost)
3623 {
3624  /*
3625  * If the GROUP BY clause isn't sort-able, the plan chosen by the remote
3626  * side is unlikely to generate properly-sorted output, so it would need
3627  * an explicit sort; adjust the given costs with cost_sort(). Likewise,
3628  * if the GROUP BY clause is sort-able but isn't a superset of the given
3629  * pathkeys, adjust the costs with that function. Otherwise, adjust the
3630  * costs by applying the same heuristic as for the scan or join case.
3631  */
3632  if (!grouping_is_sortable(root->parse->groupClause) ||
3633  !pathkeys_contained_in(pathkeys, root->group_pathkeys))
3634  {
3635  Path sort_path; /* dummy for result of cost_sort */
3636 
3637  cost_sort(&sort_path,
3638  root,
3639  pathkeys,
3640  *p_startup_cost + *p_run_cost,
3641  retrieved_rows,
3642  width,
3643  0.0,
3644  work_mem,
3645  limit_tuples);
3646 
3647  *p_startup_cost = sort_path.startup_cost;
3648  *p_run_cost = sort_path.total_cost - sort_path.startup_cost;
3649  }
3650  else
3651  {
3652  /*
3653  * The default extra cost seems too large for foreign-grouping cases;
3654  * add 1/4th of that default.
3655  */
3656  double sort_multiplier = 1.0 + (DEFAULT_FDW_SORT_MULTIPLIER
3657  - 1.0) * 0.25;
3658 
3659  *p_startup_cost *= sort_multiplier;
3660  *p_run_cost *= sort_multiplier;
3661  }
3662 }
3663 
3664 /*
3665  * Detect whether we want to process an EquivalenceClass member.
3666  *
3667  * This is a callback for use by generate_implied_equalities_for_column.
3668  */
3669 static bool
3672  void *arg)
3673 {
3675  Expr *expr = em->em_expr;
3676 
3677  /*
3678  * If we've identified what we're processing in the current scan, we only
3679  * want to match that expression.
3680  */
3681  if (state->current != NULL)
3682  return equal(expr, state->current);
3683 
3684  /*
3685  * Otherwise, ignore anything we've already processed.
3686  */
3687  if (list_member(state->already_used, expr))
3688  return false;
3689 
3690  /* This is the new target to process. */
3691  state->current = expr;
3692  return true;
3693 }
3694 
3695 /*
3696  * Create cursor for node's query with current parameter values.
3697  */
3698 static void
3700 {
3701  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3702  ExprContext *econtext = node->ss.ps.ps_ExprContext;
3703  int numParams = fsstate->numParams;
3704  const char **values = fsstate->param_values;
3705  PGconn *conn = fsstate->conn;
3707  PGresult *res;
3708 
3709  /* First, process a pending asynchronous request, if any. */
3710  if (fsstate->conn_state->pendingAreq)
3712 
3713  /*
3714  * Construct array of query parameter values in text format. We do the
3715  * conversions in the short-lived per-tuple context, so as not to cause a
3716  * memory leak over repeated scans.
3717  */
3718  if (numParams > 0)
3719  {
3720  MemoryContext oldcontext;
3721 
3722  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3723 
3724  process_query_params(econtext,
3725  fsstate->param_flinfo,
3726  fsstate->param_exprs,
3727  values);
3728 
3729  MemoryContextSwitchTo(oldcontext);
3730  }
3731 
3732  /* Construct the DECLARE CURSOR command */
3733  initStringInfo(&buf);
3734  appendStringInfo(&buf, "DECLARE c%u CURSOR FOR\n%s",
3735  fsstate->cursor_number, fsstate->query);
3736 
3737  /*
3738  * Notice that we pass NULL for paramTypes, thus forcing the remote server
3739  * to infer types for all parameters. Since we explicitly cast every
3740  * parameter (see deparse.c), the "inference" is trivial and will produce
3741  * the desired result. This allows us to avoid assuming that the remote
3742  * server has the same OIDs we do for the parameters' types.
3743  */
3744  if (!PQsendQueryParams(conn, buf.data, numParams,
3745  NULL, values, NULL, NULL, 0))
3746  pgfdw_report_error(ERROR, NULL, conn, false, buf.data);
3747 
3748  /*
3749  * Get the result, and check for success.
3750  *
3751  * We don't use a PG_TRY block here, so be careful not to throw error
3752  * without releasing the PGresult.
3753  */
3754  res = pgfdw_get_result(conn, buf.data);
3756  pgfdw_report_error(ERROR, res, conn, true, fsstate->query);
3757  PQclear(res);
3758 
3759  /* Mark the cursor as created, and show no tuples have been retrieved */
3760  fsstate->cursor_exists = true;
3761  fsstate->tuples = NULL;
3762  fsstate->num_tuples = 0;
3763  fsstate->next_tuple = 0;
3764  fsstate->fetch_ct_2 = 0;
3765  fsstate->eof_reached = false;
3766 
3767  /* Clean up */
3768  pfree(buf.data);
3769 }
3770 
3771 /*
3772  * Fetch some more rows from the node's cursor.
3773  */
3774 static void
3776 {
3777  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3778  PGresult *volatile res = NULL;
3779  MemoryContext oldcontext;
3780 
3781  /*
3782  * We'll store the tuples in the batch_cxt. First, flush the previous
3783  * batch.
3784  */
3785  fsstate->tuples = NULL;
3786  MemoryContextReset(fsstate->batch_cxt);
3787  oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
3788 
3789  /* PGresult must be released before leaving this function. */
3790  PG_TRY();
3791  {
3792  PGconn *conn = fsstate->conn;
3793  int numrows;
3794  int i;
3795 
3796  if (fsstate->async_capable)
3797  {
3798  Assert(fsstate->conn_state->pendingAreq);
3799 
3800  /*
3801  * The query was already sent by an earlier call to
3802  * fetch_more_data_begin. So now we just fetch the result.
3803  */
3804  res = pgfdw_get_result(conn, fsstate->query);
3805  /* On error, report the original query, not the FETCH. */
3807  pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3808 
3809  /* Reset per-connection state */
3810  fsstate->conn_state->pendingAreq = NULL;
3811  }
3812  else
3813  {
3814  char sql[64];
3815 
3816  /* This is a regular synchronous fetch. */
3817  snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
3818  fsstate->fetch_size, fsstate->cursor_number);
3819 
3820  res = pgfdw_exec_query(conn, sql, fsstate->conn_state);
3821  /* On error, report the original query, not the FETCH. */
3823  pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3824  }
3825 
3826  /* Convert the data into HeapTuples */
3827  numrows = PQntuples(res);
3828  fsstate->tuples = (HeapTuple *) palloc0(numrows * sizeof(HeapTuple));
3829  fsstate->num_tuples = numrows;
3830  fsstate->next_tuple = 0;
3831 
3832  for (i = 0; i < numrows; i++)
3833  {
3834  Assert(IsA(node->ss.ps.plan, ForeignScan));
3835 
3836  fsstate->tuples[i] =
3838  fsstate->rel,
3839  fsstate->attinmeta,
3840  fsstate->retrieved_attrs,
3841  node,
3842  fsstate->temp_cxt);
3843  }
3844 
3845  /* Update fetch_ct_2 */
3846  if (fsstate->fetch_ct_2 < 2)
3847  fsstate->fetch_ct_2++;
3848 
3849  /* Must be EOF if we didn't get as many tuples as we asked for. */
3850  fsstate->eof_reached = (numrows < fsstate->fetch_size);
3851  }
3852  PG_FINALLY();
3853  {
3854  PQclear(res);
3855  }
3856  PG_END_TRY();
3857 
3858  MemoryContextSwitchTo(oldcontext);
3859 }
3860 
3861 /*
3862  * Force assorted GUC parameters to settings that ensure that we'll output
3863  * data values in a form that is unambiguous to the remote server.
3864  *
3865  * This is rather expensive and annoying to do once per row, but there's
3866  * little choice if we want to be sure values are transmitted accurately;
3867  * we can't leave the settings in place between rows for fear of affecting
3868  * user-visible computations.
3869  *
3870  * We use the equivalent of a function SET option to allow the settings to
3871  * persist only until the caller calls reset_transmission_modes(). If an
3872  * error is thrown in between, guc.c will take care of undoing the settings.
3873  *
3874  * The return value is the nestlevel that must be passed to
3875  * reset_transmission_modes() to undo things.
3876  */
3877 int
3879 {
3880  int nestlevel = NewGUCNestLevel();
3881 
3882  /*
3883  * The values set here should match what pg_dump does. See also
3884  * configure_remote_session in connection.c.
3885  */
3886  if (DateStyle != USE_ISO_DATES)
3887  (void) set_config_option("datestyle", "ISO",
3889  GUC_ACTION_SAVE, true, 0, false);
3891  (void) set_config_option("intervalstyle", "postgres",
3893  GUC_ACTION_SAVE, true, 0, false);
3894  if (extra_float_digits < 3)
3895  (void) set_config_option("extra_float_digits", "3",
3897  GUC_ACTION_SAVE, true, 0, false);
3898 
3899  return nestlevel;
3900 }
3901 
3902 /*
3903  * Undo the effects of set_transmission_modes().
3904  */
3905 void
3907 {
3908  AtEOXact_GUC(true, nestlevel);
3909 }
3910 
3911 /*
3912  * Utility routine to close a cursor.
3913  */
3914 static void
3916  PgFdwConnState *conn_state)
3917 {
3918  char sql[64];
3919  PGresult *res;
3920 
3921  snprintf(sql, sizeof(sql), "CLOSE c%u", cursor_number);
3922 
3923  /*
3924  * We don't use a PG_TRY block here, so be careful not to throw error
3925  * without releasing the PGresult.
3926  */
3927  res = pgfdw_exec_query(conn, sql, conn_state);
3929  pgfdw_report_error(ERROR, res, conn, true, sql);
3930  PQclear(res);
3931 }
3932 
3933 /*
3934  * create_foreign_modify
3935  * Construct an execution state of a foreign insert/update/delete
3936  * operation
3937  */
3938 static PgFdwModifyState *
3940  RangeTblEntry *rte,
3941  ResultRelInfo *resultRelInfo,
3942  CmdType operation,
3943  Plan *subplan,
3944  char *query,
3945  List *target_attrs,
3946  int values_end,
3947  bool has_returning,
3948  List *retrieved_attrs)
3949 {
3950  PgFdwModifyState *fmstate;
3951  Relation rel = resultRelInfo->ri_RelationDesc;
3952  TupleDesc tupdesc = RelationGetDescr(rel);
3953  Oid userid;
3954  ForeignTable *table;
3955  UserMapping *user;
3956  AttrNumber n_params;
3957  Oid typefnoid;
3958  bool isvarlena;
3959  ListCell *lc;
3960 
3961  /* Begin constructing PgFdwModifyState. */
3962  fmstate = (PgFdwModifyState *) palloc0(sizeof(PgFdwModifyState));
3963  fmstate->rel = rel;
3964 
3965  /*
3966  * Identify which user to do the remote access as. This should match what
3967  * ExecCheckRTEPerms() does.
3968  */
3969  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
3970 
3971  /* Get info about foreign table. */
3972  table = GetForeignTable(RelationGetRelid(rel));
3973  user = GetUserMapping(userid, table->serverid);
3974 
3975  /* Open connection; report that we'll create a prepared statement. */
3976  fmstate->conn = GetConnection(user, true, &fmstate->conn_state);
3977  fmstate->p_name = NULL; /* prepared statement not made yet */
3978 
3979  /* Set up remote query information. */
3980  fmstate->query = query;
3981  if (operation == CMD_INSERT)
3982  {
3983  fmstate->query = pstrdup(fmstate->query);
3984  fmstate->orig_query = pstrdup(fmstate->query);
3985  }
3986  fmstate->target_attrs = target_attrs;
3987  fmstate->values_end = values_end;
3988  fmstate->has_returning = has_returning;
3989  fmstate->retrieved_attrs = retrieved_attrs;
3990 
3991  /* Create context for per-tuple temp workspace. */
3992  fmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
3993  "postgres_fdw temporary data",
3995 
3996  /* Prepare for input conversion of RETURNING results. */
3997  if (fmstate->has_returning)
3998  fmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
3999 
4000  /* Prepare for output conversion of parameters used in prepared stmt. */
4001  n_params = list_length(fmstate->target_attrs) + 1;
4002  fmstate->p_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * n_params);
4003  fmstate->p_nums = 0;
4004 
4005  if (operation == CMD_UPDATE || operation == CMD_DELETE)
4006  {
4007  Assert(subplan != NULL);
4008 
4009  /* Find the ctid resjunk column in the subplan's result */
4011  "ctid");
4012  if (!AttributeNumberIsValid(fmstate->ctidAttno))
4013  elog(ERROR, "could not find junk ctid column");
4014 
4015  /* First transmittable parameter will be ctid */
4016  getTypeOutputInfo(TIDOID, &typefnoid, &isvarlena);
4017  fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4018  fmstate->p_nums++;
4019  }
4020 
4021  if (operation == CMD_INSERT || operation == CMD_UPDATE)
4022  {
4023  /* Set up for remaining transmittable parameters */
4024  foreach(lc, fmstate->target_attrs)
4025  {
4026  int attnum = lfirst_int(lc);
4027  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4028 
4029  Assert(!attr->attisdropped);
4030 
4031  /* Ignore generated columns; they are set to DEFAULT */
4032  if (attr->attgenerated)
4033  continue;
4034  getTypeOutputInfo(attr->atttypid, &typefnoid, &isvarlena);
4035  fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4036  fmstate->p_nums++;
4037  }
4038  }
4039 
4040  Assert(fmstate->p_nums <= n_params);
4041 
4042  /* Set batch_size from foreign server/table options. */
4043  if (operation == CMD_INSERT)
4044  fmstate->batch_size = get_batch_size_option(rel);
4045 
4046  fmstate->num_slots = 1;
4047 
4048  /* Initialize auxiliary state */
4049  fmstate->aux_fmstate = NULL;
4050 
4051  return fmstate;
4052 }
4053 
4054 /*
4055  * execute_foreign_modify
4056  * Perform foreign-table modification as required, and fetch RETURNING
4057  * result if any. (This is the shared guts of postgresExecForeignInsert,
4058  * postgresExecForeignBatchInsert, postgresExecForeignUpdate, and
4059  * postgresExecForeignDelete.)
4060  */
4061 static TupleTableSlot **
4063  ResultRelInfo *resultRelInfo,
4064  CmdType operation,
4065  TupleTableSlot **slots,
4066  TupleTableSlot **planSlots,
4067  int *numSlots)
4068 {
4069  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
4070  ItemPointer ctid = NULL;
4071  const char **p_values;
4072  PGresult *res;
4073  int n_rows;
4074  StringInfoData sql;
4075 
4076  /* The operation should be INSERT, UPDATE, or DELETE */
4077  Assert(operation == CMD_INSERT ||
4078  operation == CMD_UPDATE ||
4079  operation == CMD_DELETE);
4080 
4081  /* First, process a pending asynchronous request, if any. */
4082  if (fmstate->conn_state->pendingAreq)
4084 
4085  /*
4086  * If the existing query was deparsed and prepared for a different number
4087  * of rows, rebuild it for the proper number.
4088  */
4089  if (operation == CMD_INSERT && fmstate->num_slots != *numSlots)
4090  {
4091  /* Destroy the prepared statement created previously */
4092  if (fmstate->p_name)
4093  deallocate_query(fmstate);
4094 
4095  /* Build INSERT string with numSlots records in its VALUES clause. */
4096  initStringInfo(&sql);
4097  rebuildInsertSql(&sql, fmstate->rel,
4098  fmstate->orig_query, fmstate->target_attrs,
4099  fmstate->values_end, fmstate->p_nums,
4100  *numSlots - 1);
4101  pfree(fmstate->query);
4102  fmstate->query = sql.data;
4103  fmstate->num_slots = *numSlots;
4104  }
4105 
4106  /* Set up the prepared statement on the remote server, if we didn't yet */
4107  if (!fmstate->p_name)
4108  prepare_foreign_modify(fmstate);
4109 
4110  /*
4111  * For UPDATE/DELETE, get the ctid that was passed up as a resjunk column
4112  */
4113  if (operation == CMD_UPDATE || operation == CMD_DELETE)
4114  {
4115  Datum datum;
4116  bool isNull;
4117 
4118  datum = ExecGetJunkAttribute(planSlots[0],
4119  fmstate->ctidAttno,
4120  &isNull);
4121  /* shouldn't ever get a null result... */
4122  if (isNull)
4123  elog(ERROR, "ctid is NULL");
4124  ctid = (ItemPointer) DatumGetPointer(datum);
4125  }
4126 
4127  /* Convert parameters needed by prepared statement to text form */
4128  p_values = convert_prep_stmt_params(fmstate, ctid, slots, *numSlots);
4129 
4130  /*
4131  * Execute the prepared statement.
4132  */
4133  if (!PQsendQueryPrepared(fmstate->conn,
4134  fmstate->p_name,
4135  fmstate->p_nums * (*numSlots),
4136  p_values,
4137  NULL,
4138  NULL,
4139  0))
4140  pgfdw_report_error(ERROR, NULL, fmstate->conn, false, fmstate->query);
4141 
4142  /*
4143  * Get the result, and check for success.
4144  *
4145  * We don't use a PG_TRY block here, so be careful not to throw error
4146  * without releasing the PGresult.
4147  */
4148  res = pgfdw_get_result(fmstate->conn, fmstate->query);
4149  if (PQresultStatus(res) !=
4151  pgfdw_report_error(ERROR, res, fmstate->conn, true, fmstate->query);
4152 
4153  /* Check number of rows affected, and fetch RETURNING tuple if any */
4154  if (fmstate->has_returning)
4155  {
4156  Assert(*numSlots == 1);
4157  n_rows = PQntuples(res);
4158  if (n_rows > 0)
4159  store_returning_result(fmstate, slots[0], res);
4160  }
4161  else
4162  n_rows = atoi(PQcmdTuples(res));
4163 
4164  /* And clean up */
4165  PQclear(res);
4166 
4167  MemoryContextReset(fmstate->temp_cxt);
4168 
4169  *numSlots = n_rows;
4170 
4171  /*
4172  * Return NULL if nothing was inserted/updated/deleted on the remote end
4173  */
4174  return (n_rows > 0) ? slots : NULL;
4175 }
4176 
4177 /*
4178  * prepare_foreign_modify
4179  * Establish a prepared statement for execution of INSERT/UPDATE/DELETE
4180  */
4181 static void
4183 {
4184  char prep_name[NAMEDATALEN];
4185  char *p_name;
4186  PGresult *res;
4187 
4188  /*
4189  * The caller would already have processed a pending asynchronous request
4190  * if any, so no need to do it here.
4191  */
4192 
4193  /* Construct name we'll use for the prepared statement. */
4194  snprintf(prep_name, sizeof(prep_name), "pgsql_fdw_prep_%u",
4195  GetPrepStmtNumber(fmstate->conn));
4196  p_name = pstrdup(prep_name);
4197 
4198  /*
4199  * We intentionally do not specify parameter types here, but leave the
4200  * remote server to derive them by default. This avoids possible problems
4201  * with the remote server using different type OIDs than we do. All of
4202  * the prepared statements we use in this module are simple enough that
4203  * the remote server will make the right choices.
4204  */
4205  if (!PQsendPrepare(fmstate->conn,
4206  p_name,
4207  fmstate->query,
4208  0,
4209  NULL))
4210  pgfdw_report_error(ERROR, NULL, fmstate->conn, false, fmstate->query);
4211 
4212  /*
4213  * Get the result, and check for success.
4214  *
4215  * We don't use a PG_TRY block here, so be careful not to throw error
4216  * without releasing the PGresult.
4217  */
4218  res = pgfdw_get_result(fmstate->conn, fmstate->query);
4220  pgfdw_report_error(ERROR, res, fmstate->conn, true, fmstate->query);
4221  PQclear(res);
4222 
4223  /* This action shows that the prepare has been done. */
4224  fmstate->p_name = p_name;
4225 }
4226 
4227 /*
4228  * convert_prep_stmt_params
4229  * Create array of text strings representing parameter values
4230  *
4231  * tupleid is ctid to send, or NULL if none
4232  * slot is slot to get remaining parameters from, or NULL if none
4233  *
4234  * Data is constructed in temp_cxt; caller should reset that after use.
4235  */
4236 static const char **
4238  ItemPointer tupleid,
4239  TupleTableSlot **slots,
4240  int numSlots)
4241 {
4242  const char **p_values;
4243  int i;
4244  int j;
4245  int pindex = 0;
4246  MemoryContext oldcontext;
4247 
4248  oldcontext = MemoryContextSwitchTo(fmstate->temp_cxt);
4249 
4250  p_values = (const char **) palloc(sizeof(char *) * fmstate->p_nums * numSlots);
4251 
4252  /* ctid is provided only for UPDATE/DELETE, which don't allow batching */
4253  Assert(!(tupleid != NULL && numSlots > 1));
4254 
4255  /* 1st parameter should be ctid, if it's in use */
4256  if (tupleid != NULL)
4257  {
4258  Assert(numSlots == 1);
4259  /* don't need set_transmission_modes for TID output */
4260  p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[pindex],
4261  PointerGetDatum(tupleid));
4262  pindex++;
4263  }
4264 
4265  /* get following parameters from slots */
4266  if (slots != NULL && fmstate->target_attrs != NIL)
4267  {
4268  TupleDesc tupdesc = RelationGetDescr(fmstate->rel);
4269  int nestlevel;
4270  ListCell *lc;
4271 
4272  nestlevel = set_transmission_modes();
4273 
4274  for (i = 0; i < numSlots; i++)
4275  {
4276  j = (tupleid != NULL) ? 1 : 0;
4277  foreach(lc, fmstate->target_attrs)
4278  {
4279  int attnum = lfirst_int(lc);
4280  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4281  Datum value;
4282  bool isnull;
4283 
4284  /* Ignore generated columns; they are set to DEFAULT */
4285  if (attr->attgenerated)
4286  continue;
4287  value = slot_getattr(slots[i], attnum, &isnull);
4288  if (isnull)
4289  p_values[pindex] = NULL;
4290  else
4291  p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[j],
4292  value);
4293  pindex++;
4294  j++;
4295  }
4296  }
4297 
4298  reset_transmission_modes(nestlevel);
4299  }
4300 
4301  Assert(pindex == fmstate->p_nums * numSlots);
4302 
4303  MemoryContextSwitchTo(oldcontext);
4304 
4305  return p_values;
4306 }
4307 
4308 /*
4309  * store_returning_result
4310  * Store the result of a RETURNING clause
4311  *
4312  * On error, be sure to release the PGresult on the way out. Callers do not
4313  * have PG_TRY blocks to ensure this happens.
4314  */
4315 static void
4317  TupleTableSlot *slot, PGresult *res)
4318 {
4319  PG_TRY();
4320  {
4321  HeapTuple newtup;
4322 
4323  newtup = make_tuple_from_result_row(res, 0,
4324  fmstate->rel,
4325  fmstate->attinmeta,
4326  fmstate->retrieved_attrs,
4327  NULL,
4328  fmstate->temp_cxt);
4329 
4330  /*
4331  * The returning slot will not necessarily be suitable to store
4332  * heaptuples directly, so allow for conversion.
4333  */
4334  ExecForceStoreHeapTuple(newtup, slot, true);
4335  }
4336  PG_CATCH();
4337  {
4338  PQclear(res);
4339  PG_RE_THROW();
4340  }
4341  PG_END_TRY();
4342 }
4343 
4344 /*
4345  * finish_foreign_modify
4346  * Release resources for a foreign insert/update/delete operation
4347  */
4348 static void
4350 {
4351  Assert(fmstate != NULL);
4352 
4353  /* If we created a prepared statement, destroy it */
4354  deallocate_query(fmstate);
4355 
4356  /* Release remote connection */
4357  ReleaseConnection(fmstate->conn);
4358  fmstate->conn = NULL;
4359 }
4360 
4361 /*
4362  * deallocate_query
4363  * Deallocate a prepared statement for a foreign insert/update/delete
4364  * operation
4365  */
4366 static void
4368 {
4369  char sql[64];
4370  PGresult *res;
4371 
4372  /* do nothing if the query is not allocated */
4373  if (!fmstate->p_name)
4374  return;
4375 
4376  snprintf(sql, sizeof(sql), "DEALLOCATE %s", fmstate->p_name);
4377 
4378  /*
4379  * We don't use a PG_TRY block here, so be careful not to throw error
4380  * without releasing the PGresult.
4381  */
4382  res = pgfdw_exec_query(fmstate->conn, sql, fmstate->conn_state);
4384  pgfdw_report_error(ERROR, res, fmstate->conn, true, sql);
4385  PQclear(res);
4386  pfree(fmstate->p_name);
4387  fmstate->p_name = NULL;
4388 }
4389 
4390 /*
4391  * build_remote_returning
4392  * Build a RETURNING targetlist of a remote query for performing an
4393  * UPDATE/DELETE .. RETURNING on a join directly
4394  */
4395 static List *
4396 build_remote_returning(Index rtindex, Relation rel, List *returningList)
4397 {
4398  bool have_wholerow = false;
4399  List *tlist = NIL;
4400  List *vars;
4401  ListCell *lc;
4402 
4403  Assert(returningList);
4404 
4405  vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS);
4406 
4407  /*
4408  * If there's a whole-row reference to the target relation, then we'll
4409  * need all the columns of the relation.
4410  */
4411  foreach(lc, vars)
4412  {
4413  Var *var = (Var *) lfirst(lc);
4414 
4415  if (IsA(var, Var) &&
4416  var->varno == rtindex &&
4417  var->varattno == InvalidAttrNumber)
4418  {
4419  have_wholerow = true;
4420  break;
4421  }
4422  }
4423 
4424  if (have_wholerow)
4425  {
4426  TupleDesc tupdesc = RelationGetDescr(rel);
4427  int i;
4428 
4429  for (i = 1; i <= tupdesc->natts; i++)
4430  {
4431  Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
4432  Var *var;
4433 
4434  /* Ignore dropped attributes. */
4435  if (attr->attisdropped)
4436  continue;
4437 
4438  var = makeVar(rtindex,
4439  i,
4440  attr->atttypid,
4441  attr->atttypmod,
4442  attr->attcollation,
4443  0);
4444 
4445  tlist = lappend(tlist,
4446  makeTargetEntry((Expr *) var,
4447  list_length(tlist) + 1,
4448  NULL,
4449  false));
4450  }
4451  }
4452 
4453  /* Now add any remaining columns to tlist. */
4454  foreach(lc, vars)
4455  {
4456  Var *var = (Var *) lfirst(lc);
4457 
4458  /*
4459  * No need for whole-row references to the target relation. We don't
4460  * need system columns other than ctid and oid either, since those are
4461  * set locally.
4462  */
4463  if (IsA(var, Var) &&
4464  var->varno == rtindex &&
4465  var->varattno <= InvalidAttrNumber &&
4467  continue; /* don't need it */
4468 
4469  if (tlist_member((Expr *) var, tlist))
4470  continue; /* already got it */
4471 
4472  tlist = lappend(tlist,
4473  makeTargetEntry((Expr *) var,
4474  list_length(tlist) + 1,
4475  NULL,
4476  false));
4477  }
4478 
4479  list_free(vars);
4480 
4481  return tlist;
4482 }
4483 
4484 /*
4485  * rebuild_fdw_scan_tlist
4486  * Build new fdw_scan_tlist of given foreign-scan plan node from given
4487  * tlist
4488  *
4489  * There might be columns that the fdw_scan_tlist of the given foreign-scan
4490  * plan node contains that the given tlist doesn't. The fdw_scan_tlist would
4491  * have contained resjunk columns such as 'ctid' of the target relation and
4492  * 'wholerow' of non-target relations, but the tlist might not contain them,
4493  * for example. So, adjust the tlist so it contains all the columns specified
4494  * in the fdw_scan_tlist; else setrefs.c will get confused.
4495  */
4496 static void
4498 {
4499  List *new_tlist = tlist;
4500  List *old_tlist = fscan->fdw_scan_tlist;
4501  ListCell *lc;
4502 
4503  foreach(lc, old_tlist)
4504  {
4505  TargetEntry *tle = (TargetEntry *) lfirst(lc);
4506 
4507  if (tlist_member(tle->expr, new_tlist))
4508  continue; /* already got it */
4509 
4510  new_tlist = lappend(new_tlist,
4511  makeTargetEntry(tle->expr,
4512  list_length(new_tlist) + 1,
4513  NULL,
4514  false));
4515  }
4516  fscan->fdw_scan_tlist = new_tlist;
4517 }
4518 
4519 /*
4520  * Execute a direct UPDATE/DELETE statement.
4521  */
4522 static void
4524 {
4526  ExprContext *econtext = node->ss.ps.ps_ExprContext;
4527  int numParams = dmstate->numParams;
4528  const char **values = dmstate->param_values;
4529 
4530  /* First, process a pending asynchronous request, if any. */
4531  if (dmstate->conn_state->pendingAreq)
4533 
4534  /*
4535  * Construct array of query parameter values in text format.
4536  */
4537  if (numParams > 0)
4538  process_query_params(econtext,
4539  dmstate->param_flinfo,
4540  dmstate->param_exprs,
4541  values);
4542 
4543  /*
4544  * Notice that we pass NULL for paramTypes, thus forcing the remote server
4545  * to infer types for all parameters. Since we explicitly cast every
4546  * parameter (see deparse.c), the "inference" is trivial and will produce
4547  * the desired result. This allows us to avoid assuming that the remote
4548  * server has the same OIDs we do for the parameters' types.
4549  */
4550  if (!PQsendQueryParams(dmstate->conn, dmstate->query, numParams,
4551  NULL, values, NULL, NULL, 0))
4552  pgfdw_report_error(ERROR, NULL, dmstate->conn, false, dmstate->query);
4553 
4554  /*
4555  * Get the result, and check for success.
4556  *
4557  * We don't use a PG_TRY block here, so be careful not to throw error
4558  * without releasing the PGresult.
4559  */
4560  dmstate->result = pgfdw_get_result(dmstate->conn, dmstate->query);
4561  if (PQresultStatus(dmstate->result) !=
4563  pgfdw_report_error(ERROR, dmstate->result, dmstate->conn, true,
4564  dmstate->query);
4565 
4566  /* Get the number of rows affected. */
4567  if (dmstate->has_returning)
4568  dmstate->num_tuples = PQntuples(dmstate->result);
4569  else
4570  dmstate->num_tuples = atoi(PQcmdTuples(dmstate->result));
4571 }
4572 
4573 /*
4574  * Get the result of a RETURNING clause.
4575  */
4576 static TupleTableSlot *
4578 {
4580  EState *estate = node->ss.ps.state;
4581  ResultRelInfo *resultRelInfo = node->resultRelInfo;
4582  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
4583  TupleTableSlot *resultSlot;
4584 
4585  Assert(resultRelInfo->ri_projectReturning);
4586 
4587  /* If we didn't get any tuples, must be end of data. */
4588  if (dmstate->next_tuple >= dmstate->num_tuples)
4589  return ExecClearTuple(slot);
4590 
4591  /* Increment the command es_processed count if necessary. */
4592  if (dmstate->set_processed)
4593  estate->es_processed += 1;
4594 
4595  /*
4596  * Store a RETURNING tuple. If has_returning is false, just emit a dummy
4597  * tuple. (has_returning is false when the local query is of the form
4598  * "UPDATE/DELETE .. RETURNING 1" for example.)
4599  */
4600  if (!dmstate->has_returning)
4601  {
4602  ExecStoreAllNullTuple(slot);
4603  resultSlot = slot;
4604  }
4605  else
4606  {
4607  /*
4608  * On error, be sure to release the PGresult on the way out. Callers
4609  * do not have PG_TRY blocks to ensure this happens.
4610  */
4611  PG_TRY();
4612  {
4613  HeapTuple newtup;
4614 
4615  newtup = make_tuple_from_result_row(dmstate->result,
4616  dmstate->next_tuple,
4617  dmstate->rel,
4618  dmstate->attinmeta,
4619  dmstate->retrieved_attrs,
4620  node,
4621  dmstate->temp_cxt);
4622  ExecStoreHeapTuple(newtup, slot, false);
4623  }
4624  PG_CATCH();
4625  {
4626  PQclear(dmstate->result);
4627  PG_RE_THROW();
4628  }
4629  PG_END_TRY();
4630 
4631  /* Get the updated/deleted tuple. */
4632  if (dmstate->rel)
4633  resultSlot = slot;
4634  else
4635  resultSlot = apply_returning_filter(dmstate, resultRelInfo, slot, estate);
4636  }
4637  dmstate->next_tuple++;
4638 
4639  /* Make slot available for evaluation of the local query RETURNING list. */
4640  resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple =
4641  resultSlot;
4642 
4643  return slot;
4644 }
4645 
4646 /*
4647  * Initialize a filter to extract an updated/deleted tuple from a scan tuple.
4648  */
4649 static void
4651  List *fdw_scan_tlist,
4652  Index rtindex)
4653 {
4654  TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4655  ListCell *lc;
4656  int i;
4657 
4658  /*
4659  * Calculate the mapping between the fdw_scan_tlist's entries and the
4660  * result tuple's attributes.
4661  *
4662  * The "map" is an array of indexes of the result tuple's attributes in
4663  * fdw_scan_tlist, i.e., one entry for every attribute of the result
4664  * tuple. We store zero for any attributes that don't have the
4665  * corresponding entries in that list, marking that a NULL is needed in
4666  * the result tuple.
4667  *
4668  * Also get the indexes of the entries for ctid and oid if any.
4669  */
4670  dmstate->attnoMap = (AttrNumber *)
4671  palloc0(resultTupType->natts * sizeof(AttrNumber));
4672 
4673  dmstate->ctidAttno = dmstate->oidAttno = 0;
4674 
4675  i = 1;
4676  dmstate->hasSystemCols = false;
4677  foreach(lc, fdw_scan_tlist)
4678  {
4679  TargetEntry *tle = (TargetEntry *) lfirst(lc);
4680  Var *var = (Var *) tle->expr;
4681 
4682  Assert(IsA(var, Var));
4683 
4684  /*
4685  * If the Var is a column of the target relation to be retrieved from
4686  * the foreign server, get the index of the entry.
4687  */
4688  if (var->varno == rtindex &&
4689  list_member_int(dmstate->retrieved_attrs, i))
4690  {
4691  int attrno = var->varattno;
4692 
4693  if (attrno < 0)
4694  {
4695  /*
4696  * We don't retrieve system columns other than ctid and oid.
4697  */
4698  if (attrno == SelfItemPointerAttributeNumber)
4699  dmstate->ctidAttno = i;
4700  else
4701  Assert(false);
4702  dmstate->hasSystemCols = true;
4703  }
4704  else
4705  {
4706  /*
4707  * We don't retrieve whole-row references to the target
4708  * relation either.
4709  */
4710  Assert(attrno > 0);
4711 
4712  dmstate->attnoMap[attrno - 1] = i;
4713  }
4714  }
4715  i++;
4716  }
4717 }
4718 
4719 /*
4720  * Extract and return an updated/deleted tuple from a scan tuple.
4721  */
4722 static TupleTableSlot *
4724  ResultRelInfo *resultRelInfo,
4725  TupleTableSlot *slot,
4726  EState *estate)
4727 {
4728  TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4729  TupleTableSlot *resultSlot;
4730  Datum *values;
4731  bool *isnull;
4732  Datum *old_values;
4733  bool *old_isnull;
4734  int i;
4735 
4736  /*
4737  * Use the return tuple slot as a place to store the result tuple.
4738  */
4739  resultSlot = ExecGetReturningSlot(estate, resultRelInfo);
4740 
4741  /*
4742  * Extract all the values of the scan tuple.
4743  */
4744  slot_getallattrs(slot);
4745  old_values = slot->tts_values;
4746  old_isnull = slot->tts_isnull;
4747 
4748  /*
4749  * Prepare to build the result tuple.
4750  */
4751  ExecClearTuple(resultSlot);
4752  values = resultSlot->tts_values;
4753  isnull = resultSlot->tts_isnull;
4754 
4755  /*
4756  * Transpose data into proper fields of the result tuple.
4757  */
4758  for (i = 0; i < resultTupType->natts; i++)
4759  {
4760  int j = dmstate->attnoMap[i];
4761 
4762  if (j == 0)
4763  {
4764  values[i] = (Datum) 0;
4765  isnull[i] = true;
4766  }
4767  else
4768  {
4769  values[i] = old_values[j - 1];
4770  isnull[i] = old_isnull[j - 1];
4771  }
4772  }
4773 
4774  /*
4775  * Build the virtual tuple.
4776  */
4777  ExecStoreVirtualTuple(resultSlot);
4778 
4779  /*
4780  * If we have any system columns to return, materialize a heap tuple in
4781  * the slot from column values set above and install system columns in
4782  * that tuple.
4783  */
4784  if (dmstate->hasSystemCols)
4785  {
4786  HeapTuple resultTup = ExecFetchSlotHeapTuple(resultSlot, true, NULL);
4787 
4788  /* ctid */
4789  if (dmstate->ctidAttno)
4790  {
4791  ItemPointer ctid = NULL;
4792 
4793  ctid = (ItemPointer) DatumGetPointer(old_values[dmstate->ctidAttno - 1]);
4794  resultTup->t_self = *ctid;
4795  }
4796 
4797  /*
4798  * And remaining columns
4799  *
4800  * Note: since we currently don't allow the target relation to appear
4801  * on the nullable side of an outer join, any system columns wouldn't
4802  * go to NULL.
4803  *
4804  * Note: no need to care about tableoid here because it will be
4805  * initialized in ExecProcessReturning().
4806  */
4810  }
4811 
4812  /*
4813  * And return the result tuple.
4814  */
4815  return resultSlot;
4816 }
4817 
4818 /*
4819  * Prepare for processing of parameters used in remote query.
4820  */
4821 static void
4823  List *fdw_exprs,
4824  int numParams,
4825  FmgrInfo **param_flinfo,
4826  List **param_exprs,
4827  const char ***param_values)
4828 {
4829  int i;
4830  ListCell *lc;
4831 
4832  Assert(numParams > 0);
4833 
4834  /* Prepare for output conversion of parameters used in remote query. */
4835  *param_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * numParams);
4836 
4837  i = 0;
4838  foreach(lc, fdw_exprs)
4839  {
4840  Node *param_expr = (Node *) lfirst(lc);
4841  Oid typefnoid;
4842  bool isvarlena;
4843 
4844  getTypeOutputInfo(exprType(param_expr), &typefnoid, &isvarlena);
4845  fmgr_info(typefnoid, &(*param_flinfo)[i]);
4846  i++;
4847  }
4848 
4849  /*
4850  * Prepare remote-parameter expressions for evaluation. (Note: in
4851  * practice, we expect that all these expressions will be just Params, so
4852  * we could possibly do something more efficient than using the full
4853  * expression-eval machinery for this. But probably there would be little
4854  * benefit, and it'd require postgres_fdw to know more than is desirable
4855  * about Param evaluation.)
4856  */
4857  *param_exprs = ExecInitExprList(fdw_exprs, node);
4858 
4859  /* Allocate buffer for text form of query parameters. */
4860  *param_values = (const char **) palloc0(numParams * sizeof(char *));
4861 }
4862 
4863 /*
4864  * Construct array of query parameter values in text format.
4865  */
4866 static void
4868  FmgrInfo *param_flinfo,
4869  List *param_exprs,
4870  const char **param_values)
4871 {
4872  int nestlevel;
4873  int i;
4874  ListCell *lc;
4875 
4876  nestlevel = set_transmission_modes();
4877 
4878  i = 0;
4879  foreach(lc, param_exprs)
4880  {
4881  ExprState *expr_state = (ExprState *) lfirst(lc);
4882  Datum expr_value;
4883  bool isNull;
4884 
4885  /* Evaluate the parameter expression */
4886  expr_value = ExecEvalExpr(expr_state, econtext, &isNull);
4887 
4888  /*
4889  * Get string representation of each parameter value by invoking
4890  * type-specific output function, unless the value is null.
4891  */
4892  if (isNull)
4893  param_values[i] = NULL;
4894  else
4895  param_values[i] = OutputFunctionCall(&param_flinfo[i], expr_value);
4896 
4897  i++;
4898  }
4899 
4900  reset_transmission_modes(nestlevel);
4901 }
4902 
4903 /*
4904  * postgresAnalyzeForeignTable
4905  * Test whether analyzing this foreign table is supported
4906  */
4907 static bool
4909  AcquireSampleRowsFunc *func,
4910  BlockNumber *totalpages)
4911 {
4912  ForeignTable *table;
4913  UserMapping *user;
4914  PGconn *conn;
4915  StringInfoData sql;
4916  PGresult *volatile res = NULL;
4917 
4918  /* Return the row-analysis function pointer */
4920 
4921  /*
4922  * Now we have to get the number of pages. It's annoying that the ANALYZE
4923  * API requires us to return that now, because it forces some duplication
4924  * of effort between this routine and postgresAcquireSampleRowsFunc. But
4925  * it's probably not worth redefining that API at this point.
4926  */
4927 
4928  /*
4929  * Get the connection to use. We do the remote access as the table's
4930  * owner, even if the ANALYZE was started by some other user.
4931  */
4932  table = GetForeignTable(RelationGetRelid(relation));
4933  user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
4934  conn = GetConnection(user, false, NULL);
4935 
4936  /*
4937  * Construct command to get page count for relation.
4938  */
4939  initStringInfo(&sql);
4940  deparseAnalyzeSizeSql(&sql, relation);
4941 
4942  /* In what follows, do not risk leaking any PGresults. */
4943  PG_TRY();
4944  {
4945  res = pgfdw_exec_query(conn, sql.data, NULL);
4947  pgfdw_report_error(ERROR, res, conn, false, sql.data);
4948 
4949  if (PQntuples(res) != 1 || PQnfields(res) != 1)
4950  elog(ERROR, "unexpected result from deparseAnalyzeSizeSql query");
4951  *totalpages = strtoul(PQgetvalue(res, 0, 0), NULL, 10);
4952  }
4953  PG_FINALLY();
4954  {
4955  PQclear(res);
4956  }
4957  PG_END_TRY();
4958 
4960 
4961  return true;
4962 }
4963 
4964 /*
4965  * Acquire a random sample of rows from foreign table managed by postgres_fdw.
4966  *
4967  * We fetch the whole table from the remote side and pick out some sample rows.
4968  *
4969  * Selected rows are returned in the caller-allocated array rows[],
4970  * which must have at least targrows entries.
4971  * The actual number of rows selected is returned as the function result.
4972  * We also count the total number of rows in the table and return it into
4973  * *totalrows. Note that *totaldeadrows is always set to 0.
4974  *
4975  * Note that the returned list of rows is not always in order by physical
4976  * position in the table. Therefore, correlation estimates derived later
4977  * may be meaningless, but it's OK because we don't use the estimates
4978  * currently (the planner only pays attention to correlation for indexscans).
4979  */
4980 static int
4982  HeapTuple *rows, int targrows,
4983  double *totalrows,
4984  double *totaldeadrows)
4985 {
4986  PgFdwAnalyzeState astate;
4987  ForeignTable *table;
4988  ForeignServer *server;
4989  UserMapping *user;
4990  PGconn *conn;
4991  unsigned int cursor_number;
4992  StringInfoData sql;
4993  PGresult *volatile res = NULL;
4994 
4995  /* Initialize workspace state */
4996  astate.rel = relation;
4998 
4999  astate.rows = rows;
5000  astate.targrows = targrows;
5001  astate.numrows = 0;
5002  astate.samplerows = 0;
5003  astate.rowstoskip = -1; /* -1 means not set yet */
5004  reservoir_init_selection_state(&astate.rstate, targrows);
5005 
5006  /* Remember ANALYZE context, and create a per-tuple temp context */
5007  astate.anl_cxt = CurrentMemoryContext;
5009  "postgres_fdw temporary data",
5011 
5012  /*
5013  * Get the connection to use. We do the remote access as the table's
5014  * owner, even if the ANALYZE was started by some other user.
5015  */
5016  table = GetForeignTable(RelationGetRelid(relation));
5017  server = GetForeignServer(table->serverid);
5018  user = GetUserMapping(relation->rd_rel->relowner, table->serverid);
5019  conn = GetConnection(user, false, NULL);
5020 
5021  /*
5022  * Construct cursor that retrieves whole rows from remote.
5023  */
5025  initStringInfo(&sql);
5026  appendStringInfo(&sql, "DECLARE c%u CURSOR FOR ", cursor_number);
5027  deparseAnalyzeSql(&sql, relation, &astate.retrieved_attrs);
5028 
5029  /* In what follows, do not risk leaking any PGresults. */
5030  PG_TRY();
5031  {
5032  char fetch_sql[64];
5033  int fetch_size;
5034  ListCell *lc;
5035 
5036  res = pgfdw_exec_query(conn, sql.data, NULL);
5038  pgfdw_report_error(ERROR, res, conn, false, sql.data);
5039  PQclear(res);
5040  res = NULL;
5041 
5042  /*
5043  * Determine the fetch size. The default is arbitrary, but shouldn't
5044  * be enormous.
5045  */
5046  fetch_size = 100;
5047  foreach(lc, server->options)
5048  {
5049  DefElem *def = (DefElem *) lfirst(lc);
5050 
5051  if (strcmp(def->defname, "fetch_size") == 0)
5052  {
5053  (void) parse_int(defGetString(def), &fetch_size, 0, NULL);
5054  break;
5055  }
5056  }
5057  foreach(lc, table->options)
5058  {
5059  DefElem *def = (DefElem *) lfirst(lc);
5060 
5061  if (strcmp(def->defname, "fetch_size") == 0)
5062  {
5063  (void) parse_int(defGetString(def), &fetch_size, 0, NULL);
5064  break;
5065  }
5066  }
5067 
5068  /* Construct command to fetch rows from remote. */
5069  snprintf(fetch_sql, sizeof(fetch_sql), "FETCH %d FROM c%u",
5071 
5072  /* Retrieve and process rows a batch at a time. */
5073  for (;;)
5074  {
5075  int numrows;
5076  int i;
5077 
5078  /* Allow users to cancel long query */
5080 
5081  /*
5082  * XXX possible future improvement: if rowstoskip is large, we
5083  * could issue a MOVE rather than physically fetching the rows,
5084  * then just adjust rowstoskip and samplerows appropriately.
5085  */
5086 
5087  /* Fetch some rows */
5088  res = pgfdw_exec_query(conn, fetch_sql, NULL);
5089  /* On error, report the original query, not the FETCH. */
5091  pgfdw_report_error(ERROR, res, conn, false, sql.data);
5092 
5093  /* Process whatever we got. */
5094  numrows = PQntuples(res);
5095  for (i = 0; i < numrows; i++)
5096  analyze_row_processor(res, i, &astate);
5097 
5098  PQclear(res);
5099  res = NULL;
5100 
5101  /* Must be EOF if we didn't get all the rows requested. */
5102  if (numrows < fetch_size)
5103  break;
5104  }
5105 
5106  /* Close the cursor, just to be tidy. */
5108  }
5109  PG_CATCH();
5110  {
5111  PQclear(res);
5112  PG_RE_THROW();
5113  }
5114  PG_END_TRY();
5115 
5117 
5118  /* We assume that we have no dead tuple. */
5119  *totaldeadrows = 0.0;
5120 
5121  /* We've retrieved all living tuples from foreign server. */
5122  *totalrows = astate.samplerows;
5123 
5124  /*
5125  * Emit some interesting relation info
5126  */
5127  ereport(elevel,
5128  (errmsg("\"%s\": table contains %.0f rows, %d rows in sample",
5129  RelationGetRelationName(relation),
5130  astate.samplerows, astate.numrows)));
5131 
5132  return astate.numrows;
5133 }
5134 
5135 /*
5136  * Collect sample rows from the result of query.
5137  * - Use all tuples in sample until target # of samples are collected.
5138  * - Subsequently, replace already-sampled tuples randomly.
5139  */
5140 static void
5142 {
5143  int targrows = astate->targrows;
5144  int pos; /* array index to store tuple in */
5145  MemoryContext oldcontext;
5146 
5147  /* Always increment sample row counter. */
5148  astate->samplerows += 1;
5149 
5150  /*
5151  * Determine the slot where this sample row should be stored. Set pos to
5152  * negative value to indicate the row should be skipped.
5153  */
5154  if (astate->numrows < targrows)
5155  {
5156  /* First targrows rows are always included into the sample */
5157  pos = astate->numrows++;
5158  }
5159  else
5160  {
5161  /*
5162  * Now we start replacing tuples in the sample until we reach the end
5163  * of the relation. Same algorithm as in acquire_sample_rows in
5164  * analyze.c; see Jeff Vitter's paper.
5165  */
5166  if (astate->rowstoskip < 0)
5167  astate->rowstoskip = reservoir_get_next_S(&astate->rstate, astate->samplerows, targrows);
5168 
5169  if (astate->rowstoskip <= 0)
5170  {
5171  /* Choose a random reservoir element to replace. */
5172  pos = (int) (targrows * sampler_random_fract(&astate->rstate.randstate));
5173  Assert(pos >= 0 && pos < targrows);
5174  heap_freetuple(astate->rows[pos]);
5175  }
5176  else
5177  {
5178  /* Skip this tuple. */
5179  pos = -1;
5180  }
5181 
5182  astate->rowstoskip -= 1;
5183  }
5184 
5185  if (pos >= 0)
5186  {
5187  /*
5188  * Create sample tuple from current result row, and store it in the
5189  * position determined above. The tuple has to be created in anl_cxt.
5190  */
5191  oldcontext = MemoryContextSwitchTo(astate->anl_cxt);
5192 
5193  astate->rows[pos] = make_tuple_from_result_row(res, row,
5194  astate->rel,
5195  astate->attinmeta,
5196  astate->retrieved_attrs,
5197  NULL,
5198  astate->temp_cxt);
5199 
5200  MemoryContextSwitchTo(oldcontext);
5201  }
5202 }
5203 
5204 /*
5205  * Import a foreign schema
5206  */
5207 static List *
5209 {
5210  List *commands = NIL;
5211  bool import_collate = true;
5212  bool import_default = false;
5213  bool import_generated = true;
5214  bool import_not_null = true;
5215  ForeignServer *server;
5216  UserMapping *mapping;
5217  PGconn *conn;
5219  PGresult *volatile res = NULL;
5220  int numrows,
5221  i;
5222  ListCell *lc;
5223 
5224  /* Parse statement options */
5225  foreach(lc, stmt->options)
5226  {
5227  DefElem *def = (DefElem *) lfirst(lc);
5228 
5229  if (strcmp(def->defname, "import_collate") == 0)
5230  import_collate = defGetBoolean(def);
5231  else if (strcmp(def->defname, "import_default") == 0)
5232  import_default = defGetBoolean(def);
5233  else if (strcmp(def->defname, "import_generated") == 0)
5234  import_generated = defGetBoolean(def);
5235  else if (strcmp(def->defname, "import_not_null") == 0)
5236  import_not_null = defGetBoolean(def);
5237  else
5238  ereport(ERROR,
5239  (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
5240  errmsg("invalid option \"%s\"", def->defname)));
5241  }
5242 
5243  /*
5244  * Get connection to the foreign server. Connection manager will
5245  * establish new connection if necessary.
5246  */
5247  server = GetForeignServer(serverOid);
5248  mapping = GetUserMapping(GetUserId(), server->serverid);
5249  conn = GetConnection(mapping, false, NULL);
5250 
5251  /* Don't attempt to import collation if remote server hasn't got it */
5252  if (PQserverVersion(conn) < 90100)
5253  import_collate = false;
5254 
5255  /* Create workspace for strings */
5256  initStringInfo(&buf);
5257 
5258  /* In what follows, do not risk leaking any PGresults. */
5259  PG_TRY();
5260  {
5261  /* Check that the schema really exists */
5262  appendStringInfoString(&buf, "SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ");
5264 
5265  res = pgfdw_exec_query(conn, buf.data, NULL);
5267  pgfdw_report_error(ERROR, res, conn, false, buf.data);
5268 
5269  if (PQntuples(res) != 1)
5270  ereport(ERROR,
5271  (errcode(ERRCODE_FDW_SCHEMA_NOT_FOUND),
5272  errmsg("schema \"%s\" is not present on foreign server \"%s\"",
5273  stmt->remote_schema, server->servername)));
5274 
5275  PQclear(res);
5276  res = NULL;
5277  resetStringInfo(&buf);
5278 
5279  /*
5280  * Fetch all table data from this schema, possibly restricted by
5281  * EXCEPT or LIMIT TO. (We don't actually need to pay any attention
5282  * to EXCEPT/LIMIT TO here, because the core code will filter the
5283  * statements we return according to those lists anyway. But it
5284  * should save a few cycles to not process excluded tables in the
5285  * first place.)
5286  *
5287  * Import table data for partitions only when they are explicitly
5288  * specified in LIMIT TO clause. Otherwise ignore them and only
5289  * include the definitions of the root partitioned tables to allow
5290  * access to the complete remote data set locally in the schema
5291  * imported.
5292  *
5293  * Note: because we run the connection with search_path restricted to
5294  * pg_catalog, the format_type() and pg_get_expr() outputs will always
5295  * include a schema name for types/functions in other schemas, which
5296  * is what we want.
5297  */
5299  "SELECT relname, "
5300  " attname, "
5301  " format_type(atttypid, atttypmod), "
5302  " attnotnull, "
5303  " pg_get_expr(adbin, adrelid), ");
5304 
5305  /* Generated columns are supported since Postgres 12 */
5306  if (PQserverVersion(conn) >= 120000)
5308  " attgenerated, ");
5309  else
5311  " NULL, ");
5312 
5313  if (import_collate)
5315  " collname, "
5316  " collnsp.nspname ");
5317  else
5319  " NULL, NULL ");
5320 
5322  "FROM pg_class c "
5323  " JOIN pg_namespace n ON "
5324  " relnamespace = n.oid "
5325  " LEFT JOIN pg_attribute a ON "
5326  " attrelid = c.oid AND attnum > 0 "
5327  " AND NOT attisdropped "
5328  " LEFT JOIN pg_attrdef ad ON "
5329  " adrelid = c.oid AND adnum = attnum ");
5330 
5331  if (import_collate)
5333  " LEFT JOIN pg_collation coll ON "
5334  " coll.oid = attcollation "
5335  " LEFT JOIN pg_namespace collnsp ON "
5336  " collnsp.oid = collnamespace ");
5337 
5339  "WHERE c.relkind IN ("
5340  CppAsString2(RELKIND_RELATION) ","
5341  CppAsString2(RELKIND_VIEW) ","
5342  CppAsString2(RELKIND_FOREIGN_TABLE) ","
5343  CppAsString2(RELKIND_MATVIEW) ","
5344  CppAsString2(RELKIND_PARTITIONED_TABLE) ") "
5345  " AND n.nspname = ");
5347 
5348  /* Partitions are supported since Postgres 10 */
5349  if (PQserverVersion(conn) >= 100000 &&
5351  appendStringInfoString(&buf, " AND NOT c.relispartition ");
5352 
5353  /* Apply restrictions for LIMIT TO and EXCEPT */
5354  if (stmt->list_type == FDW_IMPORT_SCHEMA_LIMIT_TO ||
5356  {
5357  bool first_item = true;
5358 
5359  appendStringInfoString(&buf, " AND c.relname ");
5360  if (stmt->list_type == FDW_IMPORT_SCHEMA_EXCEPT)
5361  appendStringInfoString(&buf, "NOT ");
5362  appendStringInfoString(&buf, "IN (");
5363 
5364  /* Append list of table names within IN clause */
5365  foreach(lc, stmt->table_list)
5366  {
5367  RangeVar *rv = (RangeVar *) lfirst(lc);
5368 
5369  if (first_item)
5370  first_item = false;
5371  else
5372  appendStringInfoString(&buf, ", ");
5374  }
5375  appendStringInfoChar(&buf, ')');
5376  }
5377 
5378  /* Append ORDER BY at the end of query to ensure output ordering */
5379  appendStringInfoString(&buf, " ORDER BY c.relname, a.attnum");
5380 
5381  /* Fetch the data */
5382  res = pgfdw_exec_query(conn, buf.data, NULL);
5384  pgfdw_report_error(ERROR, res, conn, false, buf.data);
5385 
5386  /* Process results */
5387  numrows = PQntuples(res);
5388  /* note: incrementation of i happens in inner loop's while() test */
5389  for (i = 0; i < numrows;)
5390  {
5391  char *tablename = PQgetvalue(res, i, 0);
5392  bool first_item = true;
5393 
5394  resetStringInfo(&buf);
5395  appendStringInfo(&buf, "CREATE FOREIGN TABLE %s (\n",
5396  quote_identifier(tablename));
5397 
5398  /* Scan all rows for this table */
5399  do
5400  {
5401  char *attname;
5402  char *typename;
5403  char *attnotnull;
5404  char *attgenerated;
5405  char *attdefault;
5406  char *collname;
5407  char *collnamespace;
5408 
5409  /* If table has no columns, we'll see nulls here */
5410  if (PQgetisnull(res, i, 1))
5411  continue;
5412 
5413  attname = PQgetvalue(res, i, 1);
5414  typename = PQgetvalue(res, i, 2);
5415  attnotnull = PQgetvalue(res, i, 3);
5416  attdefault = PQgetisnull(res, i, 4) ? (char *) NULL :
5417  PQgetvalue(res, i, 4);
5418  attgenerated = PQgetisnull(res, i, 5) ? (char *) NULL :
5419  PQgetvalue(res, i, 5);
5420  collname = PQgetisnull(res, i, 6) ? (char *) NULL :
5421  PQgetvalue(res, i, 6);
5422  collnamespace = PQgetisnull(res, i, 7) ? (char *) NULL :
5423  PQgetvalue(res, i, 7);
5424 
5425  if (first_item)
5426  first_item = false;
5427  else
5428  appendStringInfoString(&buf, ",\n");
5429 
5430  /* Print column name and type */
5431  appendStringInfo(&buf, " %s %s",
5433  typename);
5434 
5435  /*
5436  * Add column_name option so that renaming the foreign table's
5437  * column doesn't break the association to the underlying
5438  * column.
5439  */
5440  appendStringInfoString(&buf, " OPTIONS (column_name ");
5442  appendStringInfoChar(&buf, ')');
5443 
5444  /* Add COLLATE if needed */
5445  if (import_collate && collname != NULL && collnamespace != NULL)
5446  appendStringInfo(&buf, " COLLATE %s.%s",
5447  quote_identifier(collnamespace),
5448  quote_identifier(collname));
5449 
5450  /* Add DEFAULT if needed */
5451  if (import_default && attdefault != NULL &&
5452  (!attgenerated || !attgenerated[0]))
5453  appendStringInfo(&buf, " DEFAULT %s", attdefault);
5454 
5455  /* Add GENERATED if needed */
5456  if (import_generated && attgenerated != NULL &&
5457  attgenerated[0] == ATTRIBUTE_GENERATED_STORED)
5458  {
5459  Assert(attdefault != NULL);
5461  " GENERATED ALWAYS AS (%s) STORED",
5462  attdefault);
5463  }
5464 
5465  /* Add NOT NULL if needed */
5466  if (import_not_null && attnotnull[0] == 't')
5467  appendStringInfoString(&buf, " NOT NULL");
5468  }
5469  while (++i < numrows &&
5470  strcmp(PQgetvalue(res, i, 0), tablename) == 0);
5471 
5472  /*
5473  * Add server name and table-level options. We specify remote
5474  * schema and table name as options (the latter to ensure that
5475  * renaming the foreign table doesn't break the association).
5476  */
5477  appendStringInfo(&buf, "\n) SERVER %s\nOPTIONS (",
5478  quote_identifier(server->servername));
5479 
5480  appendStringInfoString(&buf, "schema_name ");
5482  appendStringInfoString(&buf, ", table_name ");
5483  deparseStringLiteral(&buf, tablename);
5484 
5485  appendStringInfoString(&buf, ");");
5486 
5487  commands = lappend(commands, pstrdup(buf.data));
5488  }
5489  }
5490&