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