LCOV - code coverage report
Current view: top level - contrib/postgres_fdw - postgres_fdw.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 1723 1847 93.3 %
Date: 2020-11-27 11:06:40 Functions: 70 71 98.6 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13