LCOV - code coverage report
Current view: top level - contrib/postgres_fdw - postgres_fdw.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 93.5 % 2526 2363
Test Date: 2026-08-15 05:15:43 Functions: 100.0 % 105 105
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 79.4 % 1643 1305

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

Generated by: LCOV version 2.0-1