PostgreSQL Source Code  git master
postgres_fdw.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "catalog/pg_class.h"
#include "catalog/pg_opfamily.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "executor/execAsync.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/appendinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/inherit.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "postgres_fdw.h"
#include "storage/latch.h"
#include "utils/builtins.h"
#include "utils/float.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
Include dependency graph for postgres_fdw.c:

Go to the source code of this file.

Data Structures

struct  PgFdwScanState
 
struct  PgFdwModifyState
 
struct  PgFdwDirectModifyState
 
struct  PgFdwAnalyzeState
 
struct  PgFdwPathExtraData
 
struct  ConversionLocation
 
struct  ec_member_foreign_arg
 

Macros

#define DEFAULT_FDW_STARTUP_COST   100.0
 
#define DEFAULT_FDW_TUPLE_COST   0.2
 
#define DEFAULT_FDW_SORT_MULTIPLIER   1.2
 

Typedefs

typedef struct PgFdwScanState PgFdwScanState
 
typedef struct PgFdwModifyState PgFdwModifyState
 
typedef struct PgFdwDirectModifyState PgFdwDirectModifyState
 
typedef struct PgFdwAnalyzeState PgFdwAnalyzeState
 
typedef struct ConversionLocation ConversionLocation
 

Enumerations

enum  FdwScanPrivateIndex { FdwScanPrivateSelectSql , FdwScanPrivateRetrievedAttrs , FdwScanPrivateFetchSize , FdwScanPrivateRelations }
 
enum  FdwModifyPrivateIndex {
  FdwModifyPrivateUpdateSql , FdwModifyPrivateTargetAttnums , FdwModifyPrivateLen , FdwModifyPrivateHasReturning ,
  FdwModifyPrivateRetrievedAttrs
}
 
enum  FdwDirectModifyPrivateIndex { FdwDirectModifyPrivateUpdateSql , FdwDirectModifyPrivateHasReturning , FdwDirectModifyPrivateRetrievedAttrs , FdwDirectModifyPrivateSetProcessed }
 
enum  FdwPathPrivateIndex { FdwPathPrivateHasFinalSort , FdwPathPrivateHasLimit }
 

Functions

 PG_FUNCTION_INFO_V1 (postgres_fdw_handler)
 
static void postgresGetForeignRelSize (PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
 
static void postgresGetForeignPaths (PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
 
static ForeignScanpostgresGetForeignPlan (PlannerInfo *root, RelOptInfo *foreignrel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
 
static void postgresBeginForeignScan (ForeignScanState *node, int eflags)
 
static TupleTableSlotpostgresIterateForeignScan (ForeignScanState *node)
 
static void postgresReScanForeignScan (ForeignScanState *node)
 
static void postgresEndForeignScan (ForeignScanState *node)
 
static void postgresAddForeignUpdateTargets (PlannerInfo *root, Index rtindex, RangeTblEntry *target_rte, Relation target_relation)
 
static ListpostgresPlanForeignModify (PlannerInfo *root, ModifyTable *plan, Index resultRelation, int subplan_index)
 
static void postgresBeginForeignModify (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, List *fdw_private, int subplan_index, int eflags)
 
static TupleTableSlotpostgresExecForeignInsert (EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *planSlot)
 
static TupleTableSlot ** postgresExecForeignBatchInsert (EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot **slots, TupleTableSlot **planSlots, int *numSlots)
 
static int postgresGetForeignModifyBatchSize (ResultRelInfo *resultRelInfo)
 
static TupleTableSlotpostgresExecForeignUpdate (EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *planSlot)
 
static TupleTableSlotpostgresExecForeignDelete (EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *planSlot)
 
static void postgresEndForeignModify (EState *estate, ResultRelInfo *resultRelInfo)
 
static void postgresBeginForeignInsert (ModifyTableState *mtstate, ResultRelInfo *resultRelInfo)
 
static void postgresEndForeignInsert (EState *estate, ResultRelInfo *resultRelInfo)
 
static int postgresIsForeignRelUpdatable (Relation rel)
 
static bool postgresPlanDirectModify (PlannerInfo *root, ModifyTable *plan, Index resultRelation, int subplan_index)
 
static void postgresBeginDirectModify (ForeignScanState *node, int eflags)
 
static TupleTableSlotpostgresIterateDirectModify (ForeignScanState *node)
 
static void postgresEndDirectModify (ForeignScanState *node)
 
static void postgresExplainForeignScan (ForeignScanState *node, ExplainState *es)
 
static void postgresExplainForeignModify (ModifyTableState *mtstate, ResultRelInfo *rinfo, List *fdw_private, int subplan_index, ExplainState *es)
 
static void postgresExplainDirectModify (ForeignScanState *node, ExplainState *es)
 
static void postgresExecForeignTruncate (List *rels, DropBehavior behavior, bool restart_seqs)
 
static bool postgresAnalyzeForeignTable (Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages)
 
static ListpostgresImportForeignSchema (ImportForeignSchemaStmt *stmt, Oid serverOid)
 
static void postgresGetForeignJoinPaths (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra)
 
static bool postgresRecheckForeignScan (ForeignScanState *node, TupleTableSlot *slot)
 
static void postgresGetForeignUpperPaths (PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel, RelOptInfo *output_rel, void *extra)
 
static bool postgresIsForeignPathAsyncCapable (ForeignPath *path)
 
static void postgresForeignAsyncRequest (AsyncRequest *areq)
 
static void postgresForeignAsyncConfigureWait (AsyncRequest *areq)
 
static void postgresForeignAsyncNotify (AsyncRequest *areq)
 
static void estimate_path_cost_size (PlannerInfo *root, RelOptInfo *foreignrel, List *param_join_conds, List *pathkeys, PgFdwPathExtraData *fpextra, double *p_rows, int *p_width, Cost *p_startup_cost, Cost *p_total_cost)
 
static void get_remote_estimate (const char *sql, PGconn *conn, double *rows, int *width, Cost *startup_cost, Cost *total_cost)
 
static void adjust_foreign_grouping_path_cost (PlannerInfo *root, List *pathkeys, double retrieved_rows, double width, double limit_tuples, Cost *p_startup_cost, Cost *p_run_cost)
 
static bool ec_member_matches_foreign (PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, EquivalenceMember *em, void *arg)
 
static void create_cursor (ForeignScanState *node)
 
static void fetch_more_data (ForeignScanState *node)
 
static void close_cursor (PGconn *conn, unsigned int cursor_number, PgFdwConnState *conn_state)
 
static PgFdwModifyStatecreate_foreign_modify (EState *estate, RangeTblEntry *rte, ResultRelInfo *resultRelInfo, CmdType operation, Plan *subplan, char *query, List *target_attrs, int values_end, bool has_returning, List *retrieved_attrs)
 
static TupleTableSlot ** execute_foreign_modify (EState *estate, ResultRelInfo *resultRelInfo, CmdType operation, TupleTableSlot **slots, TupleTableSlot **planSlots, int *numSlots)
 
static void prepare_foreign_modify (PgFdwModifyState *fmstate)
 
static const char ** convert_prep_stmt_params (PgFdwModifyState *fmstate, ItemPointer tupleid, TupleTableSlot **slots, int numSlots)
 
static void store_returning_result (PgFdwModifyState *fmstate, TupleTableSlot *slot, PGresult *res)
 
static void finish_foreign_modify (PgFdwModifyState *fmstate)
 
static void deallocate_query (PgFdwModifyState *fmstate)
 
static Listbuild_remote_returning (Index rtindex, Relation rel, List *returningList)
 
static void rebuild_fdw_scan_tlist (ForeignScan *fscan, List *tlist)
 
static void execute_dml_stmt (ForeignScanState *node)
 
static TupleTableSlotget_returning_data (ForeignScanState *node)
 
static void init_returning_filter (PgFdwDirectModifyState *dmstate, List *fdw_scan_tlist, Index rtindex)
 
static TupleTableSlotapply_returning_filter (PgFdwDirectModifyState *dmstate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
 
static void prepare_query_params (PlanState *node, List *fdw_exprs, int numParams, FmgrInfo **param_flinfo, List **param_exprs, const char ***param_values)
 
static void process_query_params (ExprContext *econtext, FmgrInfo *param_flinfo, List *param_exprs, const char **param_values)
 
static int postgresAcquireSampleRowsFunc (Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
 
static void analyze_row_processor (PGresult *res, int row, PgFdwAnalyzeState *astate)
 
static void produce_tuple_asynchronously (AsyncRequest *areq, bool fetch)
 
static void fetch_more_data_begin (AsyncRequest *areq)
 
static void complete_pending_request (AsyncRequest *areq)
 
static HeapTuple make_tuple_from_result_row (PGresult *res, int row, Relation rel, AttInMetadata *attinmeta, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context)
 
static void conversion_error_callback (void *arg)
 
static bool foreign_join_ok (PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinPathExtraData *extra)
 
static bool foreign_grouping_ok (PlannerInfo *root, RelOptInfo *grouped_rel, Node *havingQual)
 
static Listget_useful_pathkeys_for_relation (PlannerInfo *root, RelOptInfo *rel)
 
static Listget_useful_ecs_for_relation (PlannerInfo *root, RelOptInfo *rel)
 
static void add_paths_with_pathkeys_for_rel (PlannerInfo *root, RelOptInfo *rel, Path *epq_path, List *restrictlist)
 
static void add_foreign_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, GroupPathExtraData *extra)
 
static void add_foreign_ordered_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *ordered_rel)
 
static void add_foreign_final_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_rel, FinalPathExtraData *extra)
 
static void apply_server_options (PgFdwRelationInfo *fpinfo)
 
static void apply_table_options (PgFdwRelationInfo *fpinfo)
 
static void merge_fdw_options (PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_i)
 
static int get_batch_size_option (Relation rel)
 
Datum postgres_fdw_handler (PG_FUNCTION_ARGS)
 
static TupleDesc get_tupdesc_for_join_scan_tuples (ForeignScanState *node)
 
static ForeignScanfind_modifytable_subplan (PlannerInfo *root, ModifyTable *plan, Index rtindex, int subplan_index)
 
int set_transmission_modes (void)
 
void reset_transmission_modes (int nestlevel)
 
static double postgresGetAnalyzeInfoForForeignTable (Relation relation, bool *can_tablesample)
 
static bool semijoin_target_ok (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel)
 
void process_pending_request (AsyncRequest *areq)
 
EquivalenceMemberfind_em_for_rel (PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
 
EquivalenceMemberfind_em_for_rel_target (PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
 

Variables

 PG_MODULE_MAGIC
 

Macro Definition Documentation

◆ DEFAULT_FDW_SORT_MULTIPLIER

#define DEFAULT_FDW_SORT_MULTIPLIER   1.2

Definition at line 63 of file postgres_fdw.c.

◆ DEFAULT_FDW_STARTUP_COST

#define DEFAULT_FDW_STARTUP_COST   100.0

Definition at line 57 of file postgres_fdw.c.

◆ DEFAULT_FDW_TUPLE_COST

#define DEFAULT_FDW_TUPLE_COST   0.2

Definition at line 60 of file postgres_fdw.c.

Typedef Documentation

◆ ConversionLocation

◆ PgFdwAnalyzeState

◆ PgFdwDirectModifyState

◆ PgFdwModifyState

◆ PgFdwScanState

Enumeration Type Documentation

◆ FdwDirectModifyPrivateIndex

Enumerator
FdwDirectModifyPrivateUpdateSql 
FdwDirectModifyPrivateHasReturning 
FdwDirectModifyPrivateRetrievedAttrs 
FdwDirectModifyPrivateSetProcessed 

Definition at line 123 of file postgres_fdw.c.

124 {
125  /* SQL statement to execute remotely (as a String node) */
127  /* has-returning flag (as a Boolean node) */
129  /* Integer list of attribute numbers retrieved by RETURNING */
131  /* set-processed flag (as a Boolean node) */
133 };
@ FdwDirectModifyPrivateSetProcessed
Definition: postgres_fdw.c:132
@ FdwDirectModifyPrivateHasReturning
Definition: postgres_fdw.c:128
@ FdwDirectModifyPrivateRetrievedAttrs
Definition: postgres_fdw.c:130
@ FdwDirectModifyPrivateUpdateSql
Definition: postgres_fdw.c:126

◆ FdwModifyPrivateIndex

Enumerator
FdwModifyPrivateUpdateSql 
FdwModifyPrivateTargetAttnums 
FdwModifyPrivateLen 
FdwModifyPrivateHasReturning 
FdwModifyPrivateRetrievedAttrs 

Definition at line 100 of file postgres_fdw.c.

101 {
102  /* SQL statement to execute remotely (as a String node) */
104  /* Integer list of target attribute numbers for INSERT/UPDATE */
106  /* Length till the end of VALUES clause (as an Integer node) */
108  /* has-returning flag (as a Boolean node) */
110  /* Integer list of attribute numbers retrieved by RETURNING */
112 };
@ FdwModifyPrivateLen
Definition: postgres_fdw.c:107
@ FdwModifyPrivateUpdateSql
Definition: postgres_fdw.c:103
@ FdwModifyPrivateTargetAttnums
Definition: postgres_fdw.c:105
@ FdwModifyPrivateRetrievedAttrs
Definition: postgres_fdw.c:111
@ FdwModifyPrivateHasReturning
Definition: postgres_fdw.c:109

◆ FdwPathPrivateIndex

Enumerator
FdwPathPrivateHasFinalSort 
FdwPathPrivateHasLimit 

Definition at line 283 of file postgres_fdw.c.

284 {
285  /* has-final-sort flag (as a Boolean node) */
287  /* has-limit flag (as a Boolean node) */
289 };
@ FdwPathPrivateHasLimit
Definition: postgres_fdw.c:288
@ FdwPathPrivateHasFinalSort
Definition: postgres_fdw.c:286

◆ FdwScanPrivateIndex

Enumerator
FdwScanPrivateSelectSql 
FdwScanPrivateRetrievedAttrs 
FdwScanPrivateFetchSize 
FdwScanPrivateRelations 

Definition at line 72 of file postgres_fdw.c.

73 {
74  /* SQL statement to execute remotely (as a String node) */
76  /* Integer list of attribute numbers retrieved by the SELECT */
78  /* Integer representing the desired fetch_size */
80 
81  /*
82  * String describing join i.e. names of relations being joined and types
83  * of join, added when the scan is join
84  */
86 };
@ FdwScanPrivateRetrievedAttrs
Definition: postgres_fdw.c:77
@ FdwScanPrivateSelectSql
Definition: postgres_fdw.c:75
@ FdwScanPrivateFetchSize
Definition: postgres_fdw.c:79
@ FdwScanPrivateRelations
Definition: postgres_fdw.c:85

Function Documentation

◆ add_foreign_final_paths()

static void add_foreign_final_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo final_rel,
FinalPathExtraData extra 
)
static

Definition at line 6978 of file postgres_fdw.c.

6981 {
6982  Query *parse = root->parse;
6983  PgFdwRelationInfo *ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
6984  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) final_rel->fdw_private;
6985  bool has_final_sort = false;
6986  List *pathkeys = NIL;
6987  PgFdwPathExtraData *fpextra;
6988  bool save_use_remote_estimate = false;
6989  double rows;
6990  int width;
6991  Cost startup_cost;
6992  Cost total_cost;
6993  List *fdw_private;
6994  ForeignPath *final_path;
6995 
6996  /*
6997  * Currently, we only support this for SELECT commands
6998  */
6999  if (parse->commandType != CMD_SELECT)
7000  return;
7001 
7002  /*
7003  * No work if there is no FOR UPDATE/SHARE clause and if there is no need
7004  * to add a LIMIT node
7005  */
7006  if (!parse->rowMarks && !extra->limit_needed)
7007  return;
7008 
7009  /* We don't support cases where there are any SRFs in the targetlist */
7010  if (parse->hasTargetSRFs)
7011  return;
7012 
7013  /* Save the input_rel as outerrel in fpinfo */
7014  fpinfo->outerrel = input_rel;
7015 
7016  /*
7017  * Copy foreign table, foreign server, user mapping, FDW options etc.
7018  * details from the input relation's fpinfo.
7019  */
7020  fpinfo->table = ifpinfo->table;
7021  fpinfo->server = ifpinfo->server;
7022  fpinfo->user = ifpinfo->user;
7023  merge_fdw_options(fpinfo, ifpinfo, NULL);
7024 
7025  /*
7026  * If there is no need to add a LIMIT node, there might be a ForeignPath
7027  * in the input_rel's pathlist that implements all behavior of the query.
7028  * Note: we would already have accounted for the query's FOR UPDATE/SHARE
7029  * (if any) before we get here.
7030  */
7031  if (!extra->limit_needed)
7032  {
7033  ListCell *lc;
7034 
7035  Assert(parse->rowMarks);
7036 
7037  /*
7038  * Grouping and aggregation are not supported with FOR UPDATE/SHARE,
7039  * so the input_rel should be a base, join, or ordered relation; and
7040  * if it's an ordered relation, its input relation should be a base or
7041  * join relation.
7042  */
7043  Assert(input_rel->reloptkind == RELOPT_BASEREL ||
7044  input_rel->reloptkind == RELOPT_JOINREL ||
7045  (input_rel->reloptkind == RELOPT_UPPER_REL &&
7046  ifpinfo->stage == UPPERREL_ORDERED &&
7047  (ifpinfo->outerrel->reloptkind == RELOPT_BASEREL ||
7048  ifpinfo->outerrel->reloptkind == RELOPT_JOINREL)));
7049 
7050  foreach(lc, input_rel->pathlist)
7051  {
7052  Path *path = (Path *) lfirst(lc);
7053 
7054  /*
7055  * apply_scanjoin_target_to_paths() uses create_projection_path()
7056  * to adjust each of its input paths if needed, whereas
7057  * create_ordered_paths() uses apply_projection_to_path() to do
7058  * that. So the former might have put a ProjectionPath on top of
7059  * the ForeignPath; look through ProjectionPath and see if the
7060  * path underneath it is ForeignPath.
7061  */
7062  if (IsA(path, ForeignPath) ||
7063  (IsA(path, ProjectionPath) &&
7064  IsA(((ProjectionPath *) path)->subpath, ForeignPath)))
7065  {
7066  /*
7067  * Create foreign final path; this gets rid of a
7068  * no-longer-needed outer plan (if any), which makes the
7069  * EXPLAIN output look cleaner
7070  */
7071  final_path = create_foreign_upper_path(root,
7072  path->parent,
7073  path->pathtarget,
7074  path->rows,
7075  path->startup_cost,
7076  path->total_cost,
7077  path->pathkeys,
7078  NULL, /* no extra plan */
7079  NIL, /* no fdw_restrictinfo
7080  * list */
7081  NIL); /* no fdw_private */
7082 
7083  /* and add it to the final_rel */
7084  add_path(final_rel, (Path *) final_path);
7085 
7086  /* Safe to push down */
7087  fpinfo->pushdown_safe = true;
7088 
7089  return;
7090  }
7091  }
7092 
7093  /*
7094  * If we get here it means no ForeignPaths; since we would already
7095  * have considered pushing down all operations for the query to the
7096  * remote server, give up on it.
7097  */
7098  return;
7099  }
7100 
7101  Assert(extra->limit_needed);
7102 
7103  /*
7104  * If the input_rel is an ordered relation, replace the input_rel with its
7105  * input relation
7106  */
7107  if (input_rel->reloptkind == RELOPT_UPPER_REL &&
7108  ifpinfo->stage == UPPERREL_ORDERED)
7109  {
7110  input_rel = ifpinfo->outerrel;
7111  ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
7112  has_final_sort = true;
7113  pathkeys = root->sort_pathkeys;
7114  }
7115 
7116  /* The input_rel should be a base, join, or grouping relation */
7117  Assert(input_rel->reloptkind == RELOPT_BASEREL ||
7118  input_rel->reloptkind == RELOPT_JOINREL ||
7119  (input_rel->reloptkind == RELOPT_UPPER_REL &&
7120  ifpinfo->stage == UPPERREL_GROUP_AGG));
7121 
7122  /*
7123  * We try to create a path below by extending a simple foreign path for
7124  * the underlying base, join, or grouping relation to perform the final
7125  * sort (if has_final_sort) and the LIMIT restriction remotely, which is
7126  * stored into the fdw_private list of the resulting path. (We
7127  * re-estimate the costs of sorting the underlying relation, if
7128  * has_final_sort.)
7129  */
7130 
7131  /*
7132  * Assess if it is safe to push down the LIMIT and OFFSET to the remote
7133  * server
7134  */
7135 
7136  /*
7137  * If the underlying relation has any local conditions, the LIMIT/OFFSET
7138  * cannot be pushed down.
7139  */
7140  if (ifpinfo->local_conds)
7141  return;
7142 
7143  /*
7144  * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are
7145  * not safe to remote.
7146  */
7147  if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) ||
7148  !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount))
7149  return;
7150 
7151  /* Safe to push down */
7152  fpinfo->pushdown_safe = true;
7153 
7154  /* Construct PgFdwPathExtraData */
7155  fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
7156  fpextra->target = root->upper_targets[UPPERREL_FINAL];
7157  fpextra->has_final_sort = has_final_sort;
7158  fpextra->has_limit = extra->limit_needed;
7159  fpextra->limit_tuples = extra->limit_tuples;
7160  fpextra->count_est = extra->count_est;
7161  fpextra->offset_est = extra->offset_est;
7162 
7163  /*
7164  * Estimate the costs of performing the final sort and the LIMIT
7165  * restriction remotely. If has_final_sort is false, we wouldn't need to
7166  * execute EXPLAIN anymore if use_remote_estimate, since the costs can be
7167  * roughly estimated using the costs we already have for the underlying
7168  * relation, in the same way as when use_remote_estimate is false. Since
7169  * it's pretty expensive to execute EXPLAIN, force use_remote_estimate to
7170  * false in that case.
7171  */
7172  if (!fpextra->has_final_sort)
7173  {
7174  save_use_remote_estimate = ifpinfo->use_remote_estimate;
7175  ifpinfo->use_remote_estimate = false;
7176  }
7177  estimate_path_cost_size(root, input_rel, NIL, pathkeys, fpextra,
7178  &rows, &width, &startup_cost, &total_cost);
7179  if (!fpextra->has_final_sort)
7180  ifpinfo->use_remote_estimate = save_use_remote_estimate;
7181 
7182  /*
7183  * Build the fdw_private list that will be used by postgresGetForeignPlan.
7184  * Items in the list must match order in enum FdwPathPrivateIndex.
7185  */
7186  fdw_private = list_make2(makeBoolean(has_final_sort),
7187  makeBoolean(extra->limit_needed));
7188 
7189  /*
7190  * Create foreign final path; this gets rid of a no-longer-needed outer
7191  * plan (if any), which makes the EXPLAIN output look cleaner
7192  */
7193  final_path = create_foreign_upper_path(root,
7194  input_rel,
7195  root->upper_targets[UPPERREL_FINAL],
7196  rows,
7197  startup_cost,
7198  total_cost,
7199  pathkeys,
7200  NULL, /* no extra plan */
7201  NIL, /* no fdw_restrictinfo list */
7202  fdw_private);
7203 
7204  /* and add it to the final_rel */
7205  add_path(final_rel, (Path *) final_path);
7206 }
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:244
Assert(fmt[strlen(fmt) - 1] !='\n')
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void * palloc0(Size size)
Definition: mcxt.c:1257
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
double Cost
Definition: nodes.h:262
@ CMD_SELECT
Definition: nodes.h:276
ForeignPath * create_foreign_upper_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, double rows, Cost startup_cost, Cost total_cost, List *pathkeys, Path *fdw_outerpath, List *fdw_restrictinfo, List *fdw_private)
Definition: pathnode.c:2324
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
@ UPPERREL_GROUP_AGG
Definition: pathnodes.h:74
@ UPPERREL_FINAL
Definition: pathnodes.h:79
@ UPPERREL_ORDERED
Definition: pathnodes.h:78
@ RELOPT_BASEREL
Definition: pathnodes.h:812
@ RELOPT_UPPER_REL
Definition: pathnodes.h:816
@ RELOPT_JOINREL
Definition: pathnodes.h:813
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define list_make2(x1, x2)
Definition: pg_list.h:214
static void estimate_path_cost_size(PlannerInfo *root, RelOptInfo *foreignrel, List *param_join_conds, List *pathkeys, PgFdwPathExtraData *fpextra, double *p_rows, int *p_width, Cost *p_startup_cost, Cost *p_total_cost)
static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_i)
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:715
Cardinality limit_tuples
Definition: pathnodes.h:3275
Definition: pg_list.h:54
List * pathkeys
Definition: pathnodes.h:1633
Cardinality rows
Definition: pathnodes.h:1628
Cost startup_cost
Definition: pathnodes.h:1629
Cost total_cost
Definition: pathnodes.h:1630
PathTarget * target
Definition: postgres_fdw.c:294
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
ForeignTable * table
Definition: postgres_fdw.h:85
UserMapping * user
Definition: postgres_fdw.h:87
ForeignServer * server
Definition: postgres_fdw.h:86
UpperRelationKind stage
Definition: postgres_fdw.h:109
List * sort_pathkeys
Definition: pathnodes.h:399
Query * parse
Definition: pathnodes.h:199
List * pathlist
Definition: pathnodes.h:883
RelOptKind reloptkind
Definition: pathnodes.h:850
Boolean * makeBoolean(bool val)
Definition: value.c:49

References add_path(), Assert(), CMD_SELECT, PgFdwPathExtraData::count_est, FinalPathExtraData::count_est, create_foreign_upper_path(), estimate_path_cost_size(), PgFdwPathExtraData::has_final_sort, PgFdwPathExtraData::has_limit, is_foreign_expr(), IsA, lfirst, FinalPathExtraData::limit_needed, PgFdwPathExtraData::limit_tuples, FinalPathExtraData::limit_tuples, list_make2, PgFdwRelationInfo::local_conds, makeBoolean(), merge_fdw_options(), NIL, PgFdwPathExtraData::offset_est, FinalPathExtraData::offset_est, PgFdwRelationInfo::outerrel, palloc0(), parse(), PlannerInfo::parse, Path::pathkeys, RelOptInfo::pathlist, RELOPT_BASEREL, RELOPT_JOINREL, RELOPT_UPPER_REL, RelOptInfo::reloptkind, Path::rows, PgFdwRelationInfo::server, PlannerInfo::sort_pathkeys, PgFdwRelationInfo::stage, Path::startup_cost, subpath(), PgFdwRelationInfo::table, PgFdwPathExtraData::target, Path::total_cost, UPPERREL_FINAL, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, PgFdwRelationInfo::use_remote_estimate, and PgFdwRelationInfo::user.

Referenced by postgresGetForeignUpperPaths().

◆ add_foreign_grouping_paths()

static void add_foreign_grouping_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
GroupPathExtraData extra 
)
static

Definition at line 6751 of file postgres_fdw.c.

6754 {
6755  Query *parse = root->parse;
6756  PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6757  PgFdwRelationInfo *fpinfo = grouped_rel->fdw_private;
6758  ForeignPath *grouppath;
6759  double rows;
6760  int width;
6761  Cost startup_cost;
6762  Cost total_cost;
6763 
6764  /* Nothing to be done, if there is no grouping or aggregation required. */
6765  if (!parse->groupClause && !parse->groupingSets && !parse->hasAggs &&
6766  !root->hasHavingQual)
6767  return;
6768 
6771 
6772  /* save the input_rel as outerrel in fpinfo */
6773  fpinfo->outerrel = input_rel;
6774 
6775  /*
6776  * Copy foreign table, foreign server, user mapping, FDW options etc.
6777  * details from the input relation's fpinfo.
6778  */
6779  fpinfo->table = ifpinfo->table;
6780  fpinfo->server = ifpinfo->server;
6781  fpinfo->user = ifpinfo->user;
6782  merge_fdw_options(fpinfo, ifpinfo, NULL);
6783 
6784  /*
6785  * Assess if it is safe to push down aggregation and grouping.
6786  *
6787  * Use HAVING qual from extra. In case of child partition, it will have
6788  * translated Vars.
6789  */
6790  if (!foreign_grouping_ok(root, grouped_rel, extra->havingQual))
6791  return;
6792 
6793  /*
6794  * Compute the selectivity and cost of the local_conds, so we don't have
6795  * to do it over again for each path. (Currently we create just a single
6796  * path here, but in future it would be possible that we build more paths
6797  * such as pre-sorted paths as in postgresGetForeignPaths and
6798  * postgresGetForeignJoinPaths.) The best we can do for these conditions
6799  * is to estimate selectivity on the basis of local statistics.
6800  */
6801  fpinfo->local_conds_sel = clauselist_selectivity(root,
6802  fpinfo->local_conds,
6803  0,
6804  JOIN_INNER,
6805  NULL);
6806 
6807  cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
6808 
6809  /* Estimate the cost of push down */
6810  estimate_path_cost_size(root, grouped_rel, NIL, NIL, NULL,
6811  &rows, &width, &startup_cost, &total_cost);
6812 
6813  /* Now update this information in the fpinfo */
6814  fpinfo->rows = rows;
6815  fpinfo->width = width;
6816  fpinfo->startup_cost = startup_cost;
6817  fpinfo->total_cost = total_cost;
6818 
6819  /* Create and add foreign path to the grouping relation. */
6820  grouppath = create_foreign_upper_path(root,
6821  grouped_rel,
6822  grouped_rel->reltarget,
6823  rows,
6824  startup_cost,
6825  total_cost,
6826  NIL, /* no pathkeys */
6827  NULL,
6828  NIL, /* no fdw_restrictinfo list */
6829  NIL); /* no fdw_private */
6830 
6831  /* Add generated path into grouped_rel by add_path(). */
6832  add_path(grouped_rel, (Path *) grouppath);
6833 }
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4612
@ JOIN_INNER
Definition: nodes.h:304
@ PARTITIONWISE_AGGREGATE_FULL
Definition: pathnodes.h:3230
@ PARTITIONWISE_AGGREGATE_NONE
Definition: pathnodes.h:3229
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, Node *havingQual)
PartitionwiseAggregateType patype
Definition: pathnodes.h:3259
Selectivity local_conds_sel
Definition: postgres_fdw.h:57
QualCost local_conds_cost
Definition: postgres_fdw.h:56
bool hasHavingQual
Definition: pathnodes.h:493
struct PathTarget * reltarget
Definition: pathnodes.h:878

References add_path(), Assert(), clauselist_selectivity(), cost_qual_eval(), create_foreign_upper_path(), estimate_path_cost_size(), foreign_grouping_ok(), PlannerInfo::hasHavingQual, GroupPathExtraData::havingQual, JOIN_INNER, PgFdwRelationInfo::local_conds, PgFdwRelationInfo::local_conds_cost, PgFdwRelationInfo::local_conds_sel, merge_fdw_options(), NIL, PgFdwRelationInfo::outerrel, parse(), PlannerInfo::parse, PARTITIONWISE_AGGREGATE_FULL, PARTITIONWISE_AGGREGATE_NONE, GroupPathExtraData::patype, RelOptInfo::reltarget, PgFdwRelationInfo::rows, PgFdwRelationInfo::server, PgFdwRelationInfo::startup_cost, PgFdwRelationInfo::table, PgFdwRelationInfo::total_cost, PgFdwRelationInfo::user, and PgFdwRelationInfo::width.

Referenced by postgresGetForeignUpperPaths().

◆ add_foreign_ordered_paths()

static void add_foreign_ordered_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo ordered_rel 
)
static

Definition at line 6843 of file postgres_fdw.c.

6845 {
6846  Query *parse = root->parse;
6847  PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6848  PgFdwRelationInfo *fpinfo = ordered_rel->fdw_private;
6849  PgFdwPathExtraData *fpextra;
6850  double rows;
6851  int width;
6852  Cost startup_cost;
6853  Cost total_cost;
6854  List *fdw_private;
6855  ForeignPath *ordered_path;
6856  ListCell *lc;
6857 
6858  /* Shouldn't get here unless the query has ORDER BY */
6859  Assert(parse->sortClause);
6860 
6861  /* We don't support cases where there are any SRFs in the targetlist */
6862  if (parse->hasTargetSRFs)
6863  return;
6864 
6865  /* Save the input_rel as outerrel in fpinfo */
6866  fpinfo->outerrel = input_rel;
6867 
6868  /*
6869  * Copy foreign table, foreign server, user mapping, FDW options etc.
6870  * details from the input relation's fpinfo.
6871  */
6872  fpinfo->table = ifpinfo->table;
6873  fpinfo->server = ifpinfo->server;
6874  fpinfo->user = ifpinfo->user;
6875  merge_fdw_options(fpinfo, ifpinfo, NULL);
6876 
6877  /*
6878  * If the input_rel is a base or join relation, we would already have
6879  * considered pushing down the final sort to the remote server when
6880  * creating pre-sorted foreign paths for that relation, because the
6881  * query_pathkeys is set to the root->sort_pathkeys in that case (see
6882  * standard_qp_callback()).
6883  */
6884  if (input_rel->reloptkind == RELOPT_BASEREL ||
6885  input_rel->reloptkind == RELOPT_JOINREL)
6886  {
6887  Assert(root->query_pathkeys == root->sort_pathkeys);
6888 
6889  /* Safe to push down if the query_pathkeys is safe to push down */
6890  fpinfo->pushdown_safe = ifpinfo->qp_is_pushdown_safe;
6891 
6892  return;
6893  }
6894 
6895  /* The input_rel should be a grouping relation */
6896  Assert(input_rel->reloptkind == RELOPT_UPPER_REL &&
6897  ifpinfo->stage == UPPERREL_GROUP_AGG);
6898 
6899  /*
6900  * We try to create a path below by extending a simple foreign path for
6901  * the underlying grouping relation to perform the final sort remotely,
6902  * which is stored into the fdw_private list of the resulting path.
6903  */
6904 
6905  /* Assess if it is safe to push down the final sort */
6906  foreach(lc, root->sort_pathkeys)
6907  {
6908  PathKey *pathkey = (PathKey *) lfirst(lc);
6909  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
6910 
6911  /*
6912  * is_foreign_expr would detect volatile expressions as well, but
6913  * checking ec_has_volatile here saves some cycles.
6914  */
6915  if (pathkey_ec->ec_has_volatile)
6916  return;
6917 
6918  /*
6919  * Can't push down the sort if pathkey's opfamily is not shippable.
6920  */
6921  if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId,
6922  fpinfo))
6923  return;
6924 
6925  /*
6926  * The EC must contain a shippable EM that is computed in input_rel's
6927  * reltarget, else we can't push down the sort.
6928  */
6929  if (find_em_for_rel_target(root,
6930  pathkey_ec,
6931  input_rel) == NULL)
6932  return;
6933  }
6934 
6935  /* Safe to push down */
6936  fpinfo->pushdown_safe = true;
6937 
6938  /* Construct PgFdwPathExtraData */
6939  fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
6940  fpextra->target = root->upper_targets[UPPERREL_ORDERED];
6941  fpextra->has_final_sort = true;
6942 
6943  /* Estimate the costs of performing the final sort remotely */
6944  estimate_path_cost_size(root, input_rel, NIL, root->sort_pathkeys, fpextra,
6945  &rows, &width, &startup_cost, &total_cost);
6946 
6947  /*
6948  * Build the fdw_private list that will be used by postgresGetForeignPlan.
6949  * Items in the list must match order in enum FdwPathPrivateIndex.
6950  */
6951  fdw_private = list_make2(makeBoolean(true), makeBoolean(false));
6952 
6953  /* Create foreign ordering path */
6954  ordered_path = create_foreign_upper_path(root,
6955  input_rel,
6956  root->upper_targets[UPPERREL_ORDERED],
6957  rows,
6958  startup_cost,
6959  total_cost,
6960  root->sort_pathkeys,
6961  NULL, /* no extra plan */
6962  NIL, /* no fdw_restrictinfo
6963  * list */
6964  fdw_private);
6965 
6966  /* and add it to the ordered_rel */
6967  add_path(ordered_rel, (Path *) ordered_path);
6968 }
EquivalenceMember * find_em_for_rel_target(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
bool is_shippable(Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo)
Definition: shippable.c:162
Oid pk_opfamily
Definition: pathnodes.h:1454
List * query_pathkeys
Definition: pathnodes.h:382

References add_path(), Assert(), create_foreign_upper_path(), EquivalenceClass::ec_has_volatile, estimate_path_cost_size(), find_em_for_rel_target(), PgFdwPathExtraData::has_final_sort, is_shippable(), lfirst, list_make2, makeBoolean(), merge_fdw_options(), NIL, PgFdwRelationInfo::outerrel, palloc0(), parse(), PlannerInfo::parse, PathKey::pk_opfamily, PgFdwRelationInfo::pushdown_safe, PgFdwRelationInfo::qp_is_pushdown_safe, PlannerInfo::query_pathkeys, RELOPT_BASEREL, RELOPT_JOINREL, RELOPT_UPPER_REL, RelOptInfo::reloptkind, PgFdwRelationInfo::server, PlannerInfo::sort_pathkeys, PgFdwRelationInfo::stage, PgFdwRelationInfo::table, PgFdwPathExtraData::target, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, and PgFdwRelationInfo::user.

Referenced by postgresGetForeignUpperPaths().

◆ add_paths_with_pathkeys_for_rel()

static void add_paths_with_pathkeys_for_rel ( PlannerInfo root,
RelOptInfo rel,
Path epq_path,
List restrictlist 
)
static

Definition at line 6078 of file postgres_fdw.c.

6080 {
6081  List *useful_pathkeys_list = NIL; /* List of all pathkeys */
6082  ListCell *lc;
6083 
6084  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel);
6085 
6086  /*
6087  * Before creating sorted paths, arrange for the passed-in EPQ path, if
6088  * any, to return columns needed by the parent ForeignScan node so that
6089  * they will propagate up through Sort nodes injected below, if necessary.
6090  */
6091  if (epq_path != NULL && useful_pathkeys_list != NIL)
6092  {
6093  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
6094  PathTarget *target = copy_pathtarget(epq_path->pathtarget);
6095 
6096  /* Include columns required for evaluating PHVs in the tlist. */
6098  pull_var_clause((Node *) target->exprs,
6100 
6101  /* Include columns required for evaluating the local conditions. */
6102  foreach(lc, fpinfo->local_conds)
6103  {
6104  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
6105 
6107  pull_var_clause((Node *) rinfo->clause,
6109  }
6110 
6111  /*
6112  * If we have added any new columns, adjust the tlist of the EPQ path.
6113  *
6114  * Note: the plan created using this path will only be used to execute
6115  * EPQ checks, where accuracy of the plan cost and width estimates
6116  * would not be important, so we do not do set_pathtarget_cost_width()
6117  * for the new pathtarget here. See also postgresGetForeignPlan().
6118  */
6119  if (list_length(target->exprs) > list_length(epq_path->pathtarget->exprs))
6120  {
6121  /* The EPQ path is a join path, so it is projection-capable. */
6123 
6124  /*
6125  * Use create_projection_path() here, so as to avoid modifying it
6126  * in place.
6127  */
6128  epq_path = (Path *) create_projection_path(root,
6129  rel,
6130  epq_path,
6131  target);
6132  }
6133  }
6134 
6135  /* Create one path for each set of pathkeys we found above. */
6136  foreach(lc, useful_pathkeys_list)
6137  {
6138  double rows;
6139  int width;
6140  Cost startup_cost;
6141  Cost total_cost;
6142  List *useful_pathkeys = lfirst(lc);
6143  Path *sorted_epq_path;
6144 
6145  estimate_path_cost_size(root, rel, NIL, useful_pathkeys, NULL,
6146  &rows, &width, &startup_cost, &total_cost);
6147 
6148  /*
6149  * The EPQ path must be at least as well sorted as the path itself, in
6150  * case it gets used as input to a mergejoin.
6151  */
6152  sorted_epq_path = epq_path;
6153  if (sorted_epq_path != NULL &&
6154  !pathkeys_contained_in(useful_pathkeys,
6155  sorted_epq_path->pathkeys))
6156  sorted_epq_path = (Path *)
6157  create_sort_path(root,
6158  rel,
6159  sorted_epq_path,
6160  useful_pathkeys,
6161  -1.0);
6162 
6163  if (IS_SIMPLE_REL(rel))
6164  add_path(rel, (Path *)
6165  create_foreignscan_path(root, rel,
6166  NULL,
6167  rows,
6168  startup_cost,
6169  total_cost,
6170  useful_pathkeys,
6171  rel->lateral_relids,
6172  sorted_epq_path,
6173  NIL, /* no fdw_restrictinfo
6174  * list */
6175  NIL));
6176  else
6177  add_path(rel, (Path *)
6178  create_foreign_join_path(root, rel,
6179  NULL,
6180  rows,
6181  startup_cost,
6182  total_cost,
6183  useful_pathkeys,
6184  rel->lateral_relids,
6185  sorted_epq_path,
6186  restrictlist,
6187  NIL));
6188  }
6189 }
bool is_projection_capable_path(Path *path)
Definition: createplan.c:7177
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:190
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:340
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2959
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2644
ForeignPath * create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, double rows, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer, Path *fdw_outerpath, List *fdw_restrictinfo, List *fdw_private)
Definition: pathnode.c:2226
ForeignPath * create_foreign_join_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, double rows, Cost startup_cost, Cost total_cost, List *pathkeys, Relids required_outer, Path *fdw_outerpath, List *fdw_restrictinfo, List *fdw_private)
Definition: pathnode.c:2272
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:824
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
Definition: postgres_fdw.c:904
Definition: nodes.h:129
Relids lateral_relids
Definition: pathnodes.h:898
Expr * clause
Definition: pathnodes.h:2529
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:657
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:752
List * pull_var_clause(Node *node, int flags)
Definition: var.c:607

References add_new_columns_to_pathtarget(), add_path(), Assert(), RestrictInfo::clause, copy_pathtarget(), create_foreign_join_path(), create_foreignscan_path(), create_projection_path(), create_sort_path(), estimate_path_cost_size(), get_useful_pathkeys_for_relation(), is_projection_capable_path(), IS_SIMPLE_REL, RelOptInfo::lateral_relids, lfirst, lfirst_node, list_length(), PgFdwRelationInfo::local_conds, NIL, Path::pathkeys, pathkeys_contained_in(), pull_var_clause(), and PVC_RECURSE_PLACEHOLDERS.

Referenced by postgresGetForeignJoinPaths(), and postgresGetForeignPaths().

◆ adjust_foreign_grouping_path_cost()

static void adjust_foreign_grouping_path_cost ( PlannerInfo root,
List pathkeys,
double  retrieved_rows,
double  width,
double  limit_tuples,
Cost p_startup_cost,
Cost p_run_cost 
)
static

Definition at line 3625 of file postgres_fdw.c.

3632 {
3633  /*
3634  * If the GROUP BY clause isn't sort-able, the plan chosen by the remote
3635  * side is unlikely to generate properly-sorted output, so it would need
3636  * an explicit sort; adjust the given costs with cost_sort(). Likewise,
3637  * if the GROUP BY clause is sort-able but isn't a superset of the given
3638  * pathkeys, adjust the costs with that function. Otherwise, adjust the
3639  * costs by applying the same heuristic as for the scan or join case.
3640  */
3642  !pathkeys_contained_in(pathkeys, root->group_pathkeys))
3643  {
3644  Path sort_path; /* dummy for result of cost_sort */
3645 
3646  cost_sort(&sort_path,
3647  root,
3648  pathkeys,
3649  *p_startup_cost + *p_run_cost,
3650  retrieved_rows,
3651  width,
3652  0.0,
3653  work_mem,
3654  limit_tuples);
3655 
3656  *p_startup_cost = sort_path.startup_cost;
3657  *p_run_cost = sort_path.total_cost - sort_path.startup_cost;
3658  }
3659  else
3660  {
3661  /*
3662  * The default extra cost seems too large for foreign-grouping cases;
3663  * add 1/4th of that default.
3664  */
3665  double sort_multiplier = 1.0 + (DEFAULT_FDW_SORT_MULTIPLIER
3666  - 1.0) * 0.25;
3667 
3668  *p_startup_cost *= sort_multiplier;
3669  *p_run_cost *= sort_multiplier;
3670  }
3671 }
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:2096
int work_mem
Definition: globals.c:127
#define DEFAULT_FDW_SORT_MULTIPLIER
Definition: postgres_fdw.c:63
List * group_pathkeys
Definition: pathnodes.h:385
List * processed_groupClause
Definition: pathnodes.h:430
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:540

References cost_sort(), DEFAULT_FDW_SORT_MULTIPLIER, PlannerInfo::group_pathkeys, grouping_is_sortable(), pathkeys_contained_in(), PlannerInfo::processed_groupClause, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by estimate_path_cost_size().

◆ analyze_row_processor()

static void analyze_row_processor ( PGresult res,
int  row,
PgFdwAnalyzeState astate 
)
static

Definition at line 5368 of file postgres_fdw.c.

5369 {
5370  int targrows = astate->targrows;
5371  int pos; /* array index to store tuple in */
5372  MemoryContext oldcontext;
5373 
5374  /* Always increment sample row counter. */
5375  astate->samplerows += 1;
5376 
5377  /*
5378  * Determine the slot where this sample row should be stored. Set pos to
5379  * negative value to indicate the row should be skipped.
5380  */
5381  if (astate->numrows < targrows)
5382  {
5383  /* First targrows rows are always included into the sample */
5384  pos = astate->numrows++;
5385  }
5386  else
5387  {
5388  /*
5389  * Now we start replacing tuples in the sample until we reach the end
5390  * of the relation. Same algorithm as in acquire_sample_rows in
5391  * analyze.c; see Jeff Vitter's paper.
5392  */
5393  if (astate->rowstoskip < 0)
5394  astate->rowstoskip = reservoir_get_next_S(&astate->rstate, astate->samplerows, targrows);
5395 
5396  if (astate->rowstoskip <= 0)
5397  {
5398  /* Choose a random reservoir element to replace. */
5399  pos = (int) (targrows * sampler_random_fract(&astate->rstate.randstate));
5400  Assert(pos >= 0 && pos < targrows);
5401  heap_freetuple(astate->rows[pos]);
5402  }
5403  else
5404  {
5405  /* Skip this tuple. */
5406  pos = -1;
5407  }
5408 
5409  astate->rowstoskip -= 1;
5410  }
5411 
5412  if (pos >= 0)
5413  {
5414  /*
5415  * Create sample tuple from current result row, and store it in the
5416  * position determined above. The tuple has to be created in anl_cxt.
5417  */
5418  oldcontext = MemoryContextSwitchTo(astate->anl_cxt);
5419 
5420  astate->rows[pos] = make_tuple_from_result_row(res, row,
5421  astate->rel,
5422  astate->attinmeta,
5423  astate->retrieved_attrs,
5424  NULL,
5425  astate->temp_cxt);
5426 
5427  MemoryContextSwitchTo(oldcontext);
5428  }
5429 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static HeapTuple make_tuple_from_result_row(PGresult *res, int row, Relation rel, AttInMetadata *attinmeta, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context)
double sampler_random_fract(pg_prng_state *randstate)
Definition: sampling.c:241
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:147
ReservoirStateData rstate
Definition: postgres_fdw.c:269
AttInMetadata * attinmeta
Definition: postgres_fdw.c:258
MemoryContext anl_cxt
Definition: postgres_fdw.c:272
HeapTuple * rows
Definition: postgres_fdw.c:262
MemoryContext temp_cxt
Definition: postgres_fdw.c:273
pg_prng_state randstate
Definition: sampling.h:49

References PgFdwAnalyzeState::anl_cxt, Assert(), PgFdwAnalyzeState::attinmeta, heap_freetuple(), make_tuple_from_result_row(), MemoryContextSwitchTo(), PgFdwAnalyzeState::numrows, ReservoirStateData::randstate, PgFdwAnalyzeState::rel, res, reservoir_get_next_S(), PgFdwAnalyzeState::retrieved_attrs, PgFdwAnalyzeState::rows, PgFdwAnalyzeState::rowstoskip, PgFdwAnalyzeState::rstate, sampler_random_fract(), PgFdwAnalyzeState::samplerows, PgFdwAnalyzeState::targrows, and PgFdwAnalyzeState::temp_cxt.

Referenced by postgresAcquireSampleRowsFunc().

◆ apply_returning_filter()

static TupleTableSlot * apply_returning_filter ( PgFdwDirectModifyState dmstate,
ResultRelInfo resultRelInfo,
TupleTableSlot slot,
EState estate 
)
static

Definition at line 4737 of file postgres_fdw.c.

4741 {
4742  TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4743  TupleTableSlot *resultSlot;
4744  Datum *values;
4745  bool *isnull;
4746  Datum *old_values;
4747  bool *old_isnull;
4748  int i;
4749 
4750  /*
4751  * Use the return tuple slot as a place to store the result tuple.
4752  */
4753  resultSlot = ExecGetReturningSlot(estate, resultRelInfo);
4754 
4755  /*
4756  * Extract all the values of the scan tuple.
4757  */
4758  slot_getallattrs(slot);
4759  old_values = slot->tts_values;
4760  old_isnull = slot->tts_isnull;
4761 
4762  /*
4763  * Prepare to build the result tuple.
4764  */
4765  ExecClearTuple(resultSlot);
4766  values = resultSlot->tts_values;
4767  isnull = resultSlot->tts_isnull;
4768 
4769  /*
4770  * Transpose data into proper fields of the result tuple.
4771  */
4772  for (i = 0; i < resultTupType->natts; i++)
4773  {
4774  int j = dmstate->attnoMap[i];
4775 
4776  if (j == 0)
4777  {
4778  values[i] = (Datum) 0;
4779  isnull[i] = true;
4780  }
4781  else
4782  {
4783  values[i] = old_values[j - 1];
4784  isnull[i] = old_isnull[j - 1];
4785  }
4786  }
4787 
4788  /*
4789  * Build the virtual tuple.
4790  */
4791  ExecStoreVirtualTuple(resultSlot);
4792 
4793  /*
4794  * If we have any system columns to return, materialize a heap tuple in
4795  * the slot from column values set above and install system columns in
4796  * that tuple.
4797  */
4798  if (dmstate->hasSystemCols)
4799  {
4800  HeapTuple resultTup = ExecFetchSlotHeapTuple(resultSlot, true, NULL);
4801 
4802  /* ctid */
4803  if (dmstate->ctidAttno)
4804  {
4805  ItemPointer ctid = NULL;
4806 
4807  ctid = (ItemPointer) DatumGetPointer(old_values[dmstate->ctidAttno - 1]);
4808  resultTup->t_self = *ctid;
4809  }
4810 
4811  /*
4812  * And remaining columns
4813  *
4814  * Note: since we currently don't allow the target relation to appear
4815  * on the nullable side of an outer join, any system columns wouldn't
4816  * go to NULL.
4817  *
4818  * Note: no need to care about tableoid here because it will be
4819  * initialized in ExecProcessReturning().
4820  */
4824  }
4825 
4826  /*
4827  * And return the result tuple.
4828  */
4829  return resultSlot;
4830 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1553
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1645
TupleTableSlot * ExecGetReturningSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1187
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:315
#define HeapTupleHeaderSetXmax(tup, xid)
Definition: htup_details.h:376
#define HeapTupleHeaderSetCmin(tup, cid)
Definition: htup_details.h:393
int j
Definition: isn.c:74
int i
Definition: isn.c:73
ItemPointerData * ItemPointer
Definition: itemptr.h:49
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
#define RelationGetDescr(relation)
Definition: rel.h:530
ItemPointerData t_self
Definition: htup.h:65
HeapTupleHeader t_data
Definition: htup.h:68
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
#define InvalidTransactionId
Definition: transam.h:31
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:432
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:361

References PgFdwDirectModifyState::attnoMap, PgFdwDirectModifyState::ctidAttno, DatumGetPointer(), ExecClearTuple(), ExecFetchSlotHeapTuple(), ExecGetReturningSlot(), ExecStoreVirtualTuple(), PgFdwDirectModifyState::hasSystemCols, HeapTupleHeaderSetCmin, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXmin, i, InvalidTransactionId, j, TupleDescData::natts, RelationGetDescr, PgFdwDirectModifyState::resultRel, slot_getallattrs(), HeapTupleData::t_data, HeapTupleData::t_self, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, and values.

Referenced by get_returning_data().

◆ apply_server_options()

static void apply_server_options ( PgFdwRelationInfo fpinfo)
static

Definition at line 6197 of file postgres_fdw.c.

6198 {
6199  ListCell *lc;
6200 
6201  foreach(lc, fpinfo->server->options)
6202  {
6203  DefElem *def = (DefElem *) lfirst(lc);
6204 
6205  if (strcmp(def->defname, "use_remote_estimate") == 0)
6206  fpinfo->use_remote_estimate = defGetBoolean(def);
6207  else if (strcmp(def->defname, "fdw_startup_cost") == 0)
6208  (void) parse_real(defGetString(def), &fpinfo->fdw_startup_cost, 0,
6209  NULL);
6210  else if (strcmp(def->defname, "fdw_tuple_cost") == 0)
6211  (void) parse_real(defGetString(def), &fpinfo->fdw_tuple_cost, 0,
6212  NULL);
6213  else if (strcmp(def->defname, "extensions") == 0)
6214  fpinfo->shippable_extensions =
6215  ExtractExtensionList(defGetString(def), false);
6216  else if (strcmp(def->defname, "fetch_size") == 0)
6217  (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
6218  else if (strcmp(def->defname, "async_capable") == 0)
6219  fpinfo->async_capable = defGetBoolean(def);
6220  }
6221 }
List * ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
Definition: option.c:445
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition: guc.c:2854
bool parse_real(const char *value, double *result, int flags, const char **hintmsg)
Definition: guc.c:2944
char * defname
Definition: parsenodes.h:802
List * options
Definition: foreign.h:42
List * shippable_extensions
Definition: postgres_fdw.h:81

References PgFdwRelationInfo::async_capable, defGetBoolean(), defGetString(), DefElem::defname, ExtractExtensionList(), PgFdwRelationInfo::fdw_startup_cost, PgFdwRelationInfo::fdw_tuple_cost, PgFdwRelationInfo::fetch_size, lfirst, ForeignServer::options, parse_int(), parse_real(), PgFdwRelationInfo::server, PgFdwRelationInfo::shippable_extensions, and PgFdwRelationInfo::use_remote_estimate.

Referenced by postgresGetForeignRelSize().

◆ apply_table_options()

static void apply_table_options ( PgFdwRelationInfo fpinfo)
static

Definition at line 6229 of file postgres_fdw.c.

6230 {
6231  ListCell *lc;
6232 
6233  foreach(lc, fpinfo->table->options)
6234  {
6235  DefElem *def = (DefElem *) lfirst(lc);
6236 
6237  if (strcmp(def->defname, "use_remote_estimate") == 0)
6238  fpinfo->use_remote_estimate = defGetBoolean(def);
6239  else if (strcmp(def->defname, "fetch_size") == 0)
6240  (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
6241  else if (strcmp(def->defname, "async_capable") == 0)
6242  fpinfo->async_capable = defGetBoolean(def);
6243  }
6244 }
List * options
Definition: foreign.h:57

References PgFdwRelationInfo::async_capable, defGetBoolean(), defGetString(), DefElem::defname, PgFdwRelationInfo::fetch_size, lfirst, ForeignTable::options, parse_int(), PgFdwRelationInfo::table, and PgFdwRelationInfo::use_remote_estimate.

Referenced by postgresGetForeignRelSize().

◆ build_remote_returning()

static List * build_remote_returning ( Index  rtindex,
Relation  rel,
List returningList 
)
static

Definition at line 4410 of file postgres_fdw.c.

4411 {
4412  bool have_wholerow = false;
4413  List *tlist = NIL;
4414  List *vars;
4415  ListCell *lc;
4416 
4417  Assert(returningList);
4418 
4419  vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS);
4420 
4421  /*
4422  * If there's a whole-row reference to the target relation, then we'll
4423  * need all the columns of the relation.
4424  */
4425  foreach(lc, vars)
4426  {
4427  Var *var = (Var *) lfirst(lc);
4428 
4429  if (IsA(var, Var) &&
4430  var->varno == rtindex &&
4431  var->varattno == InvalidAttrNumber)
4432  {
4433  have_wholerow = true;
4434  break;
4435  }
4436  }
4437 
4438  if (have_wholerow)
4439  {
4440  TupleDesc tupdesc = RelationGetDescr(rel);
4441  int i;
4442 
4443  for (i = 1; i <= tupdesc->natts; i++)
4444  {
4445  Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
4446  Var *var;
4447 
4448  /* Ignore dropped attributes. */
4449  if (attr->attisdropped)
4450  continue;
4451 
4452  var = makeVar(rtindex,
4453  i,
4454  attr->atttypid,
4455  attr->atttypmod,
4456  attr->attcollation,
4457  0);
4458 
4459  tlist = lappend(tlist,
4460  makeTargetEntry((Expr *) var,
4461  list_length(tlist) + 1,
4462  NULL,
4463  false));
4464  }
4465  }
4466 
4467  /* Now add any remaining columns to tlist. */
4468  foreach(lc, vars)
4469  {
4470  Var *var = (Var *) lfirst(lc);
4471 
4472  /*
4473  * No need for whole-row references to the target relation. We don't
4474  * need system columns other than ctid and oid either, since those are
4475  * set locally.
4476  */
4477  if (IsA(var, Var) &&
4478  var->varno == rtindex &&
4479  var->varattno <= InvalidAttrNumber &&
4481  continue; /* don't need it */
4482 
4483  if (tlist_member((Expr *) var, tlist))
4484  continue; /* already got it */
4485 
4486  tlist = lappend(tlist,
4487  makeTargetEntry((Expr *) var,
4488  list_length(tlist) + 1,
4489  NULL,
4490  false));
4491  }
4492 
4493  list_free(vars);
4494 
4495  return tlist;
4496 }
#define InvalidAttrNumber
Definition: attnum.h:23
List * lappend(List *list, void *datum)
Definition: list.c:338
void list_free(List *list)
Definition: list.c:1545
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:241
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:189
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
Definition: primnodes.h:234
AttrNumber varattno
Definition: primnodes.h:246
int varno
Definition: primnodes.h:241
Definition: regcomp.c:281
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition: tlist.c:79
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References Assert(), i, InvalidAttrNumber, IsA, lappend(), lfirst, list_free(), list_length(), makeTargetEntry(), makeVar(), TupleDescData::natts, NIL, pull_var_clause(), PVC_INCLUDE_PLACEHOLDERS, RelationGetDescr, SelfItemPointerAttributeNumber, tlist_member(), TupleDescAttr, Var::varattno, and Var::varno.

Referenced by postgresPlanDirectModify().

◆ close_cursor()

static void close_cursor ( PGconn conn,
unsigned int  cursor_number,
PgFdwConnState conn_state 
)
static

Definition at line 3932 of file postgres_fdw.c.

3934 {
3935  char sql[64];
3936  PGresult *res;
3937 
3938  snprintf(sql, sizeof(sql), "CLOSE c%u", cursor_number);
3939 
3940  /*
3941  * We don't use a PG_TRY block here, so be careful not to throw error
3942  * without releasing the PGresult.
3943  */
3944  res = pgfdw_exec_query(conn, sql, conn_state);
3946  pgfdw_report_error(ERROR, res, conn, true, sql);
3947  PQclear(res);
3948 }
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:924
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:827
static unsigned int cursor_number
Definition: connection.c:80
#define ERROR
Definition: elog.h:39
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3352
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
#define snprintf
Definition: port.h:238
PGconn * conn
Definition: streamutil.c:54

References conn, cursor_number, ERROR, pgfdw_exec_query(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear(), PQresultStatus(), res, and snprintf.

Referenced by postgresAcquireSampleRowsFunc(), and postgresEndForeignScan().

◆ complete_pending_request()

static void complete_pending_request ( AsyncRequest areq)
static

Definition at line 7480 of file postgres_fdw.c.

7481 {
7482  /* The request would have been pending for a callback */
7483  Assert(areq->callback_pending);
7484 
7485  /* Unlike AsyncNotify, we unset callback_pending ourselves */
7486  areq->callback_pending = false;
7487 
7488  /* We begin a fetch afterwards if necessary; don't fetch */
7489  produce_tuple_asynchronously(areq, false);
7490 
7491  /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
7492  ExecAsyncResponse(areq);
7493 
7494  /* Also, we do instrumentation ourselves, if required */
7495  if (areq->requestee->instrument)
7497  TupIsNull(areq->result) ? 0.0 : 1.0);
7498 }
void ExecAsyncResponse(AsyncRequest *areq)
Definition: execAsync.c:117
void InstrUpdateTupleCount(Instrumentation *instr, double nTuples)
Definition: instrument.c:132
static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch)
TupleTableSlot * result
Definition: execnodes.h:599
bool callback_pending
Definition: execnodes.h:597
struct PlanState * requestee
Definition: execnodes.h:595
Instrumentation * instrument
Definition: execnodes.h:1046
#define TupIsNull(slot)
Definition: tuptable.h:299

References Assert(), AsyncRequest::callback_pending, ExecAsyncResponse(), PlanState::instrument, InstrUpdateTupleCount(), produce_tuple_asynchronously(), AsyncRequest::requestee, AsyncRequest::result, and TupIsNull.

Referenced by postgresForeignAsyncConfigureWait().

◆ conversion_error_callback()

static void conversion_error_callback ( void *  arg)
static

Definition at line 7671 of file postgres_fdw.c.

7672 {
7674  Relation rel = errpos->rel;
7675  ForeignScanState *fsstate = errpos->fsstate;
7676  const char *attname = NULL;
7677  const char *relname = NULL;
7678  bool is_wholerow = false;
7679 
7680  /*
7681  * If we're in a scan node, always use aliases from the rangetable, for
7682  * consistency between the simple-relation and remote-join cases. Look at
7683  * the relation's tupdesc only if we're not in a scan node.
7684  */
7685  if (fsstate)
7686  {
7687  /* ForeignScan case */
7688  ForeignScan *fsplan = castNode(ForeignScan, fsstate->ss.ps.plan);
7689  int varno = 0;
7690  AttrNumber colno = 0;
7691 
7692  if (fsplan->scan.scanrelid > 0)
7693  {
7694  /* error occurred in a scan against a foreign table */
7695  varno = fsplan->scan.scanrelid;
7696  colno = errpos->cur_attno;
7697  }
7698  else
7699  {
7700  /* error occurred in a scan against a foreign join */
7701  TargetEntry *tle;
7702 
7703  tle = list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
7704  errpos->cur_attno - 1);
7705 
7706  /*
7707  * Target list can have Vars and expressions. For Vars, we can
7708  * get some information, however for expressions we can't. Thus
7709  * for expressions, just show generic context message.
7710  */
7711  if (IsA(tle->expr, Var))
7712  {
7713  Var *var = (Var *) tle->expr;
7714 
7715  varno = var->varno;
7716  colno = var->varattno;
7717  }
7718  }
7719 
7720  if (varno > 0)
7721  {
7722  EState *estate = fsstate->ss.ps.state;
7723  RangeTblEntry *rte = exec_rt_fetch(varno, estate);
7724 
7725  relname = rte->eref->aliasname;
7726 
7727  if (colno == 0)
7728  is_wholerow = true;
7729  else if (colno > 0 && colno <= list_length(rte->eref->colnames))
7730  attname = strVal(list_nth(rte->eref->colnames, colno - 1));
7731  else if (colno == SelfItemPointerAttributeNumber)
7732  attname = "ctid";
7733  }
7734  }
7735  else if (rel)
7736  {
7737  /* Non-ForeignScan case (we should always have a rel here) */
7738  TupleDesc tupdesc = RelationGetDescr(rel);
7739 
7741  if (errpos->cur_attno > 0 && errpos->cur_attno <= tupdesc->natts)
7742  {
7743  Form_pg_attribute attr = TupleDescAttr(tupdesc,
7744  errpos->cur_attno - 1);
7745 
7746  attname = NameStr(attr->attname);
7747  }
7748  else if (errpos->cur_attno == SelfItemPointerAttributeNumber)
7749  attname = "ctid";
7750  }
7751 
7752  if (relname && is_wholerow)
7753  errcontext("whole-row reference to foreign table \"%s\"", relname);
7754  else if (relname && attname)
7755  errcontext("column \"%s\" of foreign table \"%s\"", attname, relname);
7756  else
7757  errcontext("processing expression at position %d in select list",
7758  errpos->cur_attno);
7759 }
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:735
#define errcontext
Definition: elog.h:196
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:586
#define castNode(_type_, nodeptr)
Definition: nodes.h:197
NameData attname
Definition: pg_attribute.h:41
void * arg
NameData relname
Definition: pg_class.h:38
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
#define RelationGetRelationName(relation)
Definition: rel.h:538
char * aliasname
Definition: primnodes.h:50
List * colnames
Definition: primnodes.h:51
AttrNumber cur_attno
Definition: postgres_fdw.c:307
ForeignScanState * fsstate
Definition: postgres_fdw.c:309
ScanState ss
Definition: execnodes.h:1953
List * fdw_scan_tlist
Definition: plannodes.h:715
Plan * plan
Definition: execnodes.h:1036
EState * state
Definition: execnodes.h:1038
Alias * eref
Definition: parsenodes.h:1192
PlanState ps
Definition: execnodes.h:1473
Index scanrelid
Definition: plannodes.h:387
Expr * expr
Definition: primnodes.h:1922
#define strVal(v)
Definition: value.h:82

References Alias::aliasname, arg, attname, castNode, Alias::colnames, ConversionLocation::cur_attno, RangeTblEntry::eref, errcontext, exec_rt_fetch(), TargetEntry::expr, ForeignScan::fdw_scan_tlist, ConversionLocation::fsstate, IsA, list_length(), list_nth(), list_nth_node, NameStr, TupleDescData::natts, PlanState::plan, ScanState::ps, ConversionLocation::rel, RelationGetDescr, RelationGetRelationName, relname, ForeignScan::scan, Scan::scanrelid, SelfItemPointerAttributeNumber, ForeignScanState::ss, PlanState::state, strVal, TupleDescAttr, Var::varattno, and Var::varno.

Referenced by make_tuple_from_result_row().

◆ convert_prep_stmt_params()

static const char ** convert_prep_stmt_params ( PgFdwModifyState fmstate,
ItemPointer  tupleid,
TupleTableSlot **  slots,
int  numSlots 
)
static

Definition at line 4251 of file postgres_fdw.c.

4255 {
4256  const char **p_values;
4257  int i;
4258  int j;
4259  int pindex = 0;
4260  MemoryContext oldcontext;
4261 
4262  oldcontext = MemoryContextSwitchTo(fmstate->temp_cxt);
4263 
4264  p_values = (const char **) palloc(sizeof(char *) * fmstate->p_nums * numSlots);
4265 
4266  /* ctid is provided only for UPDATE/DELETE, which don't allow batching */
4267  Assert(!(tupleid != NULL && numSlots > 1));
4268 
4269  /* 1st parameter should be ctid, if it's in use */
4270  if (tupleid != NULL)
4271  {
4272  Assert(numSlots == 1);
4273  /* don't need set_transmission_modes for TID output */
4274  p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[pindex],
4275  PointerGetDatum(tupleid));
4276  pindex++;
4277  }
4278 
4279  /* get following parameters from slots */
4280  if (slots != NULL && fmstate->target_attrs != NIL)
4281  {
4282  TupleDesc tupdesc = RelationGetDescr(fmstate->rel);
4283  int nestlevel;
4284  ListCell *lc;
4285 
4286  nestlevel = set_transmission_modes();
4287 
4288  for (i = 0; i < numSlots; i++)
4289  {
4290  j = (tupleid != NULL) ? 1 : 0;
4291  foreach(lc, fmstate->target_attrs)
4292  {
4293  int attnum = lfirst_int(lc);
4294  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4295  Datum value;
4296  bool isnull;
4297 
4298  /* Ignore generated columns; they are set to DEFAULT */
4299  if (attr->attgenerated)
4300  continue;
4301  value = slot_getattr(slots[i], attnum, &isnull);
4302  if (isnull)
4303  p_values[pindex] = NULL;
4304  else
4305  p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[j],
4306  value);
4307  pindex++;
4308  j++;
4309  }
4310  }
4311 
4312  reset_transmission_modes(nestlevel);
4313  }
4314 
4315  Assert(pindex == fmstate->p_nums * numSlots);
4316 
4317  MemoryContextSwitchTo(oldcontext);
4318 
4319  return p_values;
4320 }
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1666
static struct @148 value
void * palloc(Size size)
Definition: mcxt.c:1226
int16 attnum
Definition: pg_attribute.h:74
#define lfirst_int(lc)
Definition: pg_list.h:173
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
void reset_transmission_modes(int nestlevel)
int set_transmission_modes(void)
MemoryContext temp_cxt
Definition: postgres_fdw.c:209
FmgrInfo * p_flinfo
Definition: postgres_fdw.c:203
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:388

References Assert(), attnum, i, j, lfirst_int, MemoryContextSwitchTo(), NIL, OutputFunctionCall(), PgFdwModifyState::p_flinfo, PgFdwModifyState::p_nums, palloc(), PointerGetDatum(), PgFdwModifyState::rel, RelationGetDescr, reset_transmission_modes(), set_transmission_modes(), slot_getattr(), PgFdwModifyState::target_attrs, PgFdwModifyState::temp_cxt, TupleDescAttr, and value.

Referenced by execute_foreign_modify().

◆ create_cursor()

static void create_cursor ( ForeignScanState node)
static

Definition at line 3708 of file postgres_fdw.c.

3709 {
3710  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3711  ExprContext *econtext = node->ss.ps.ps_ExprContext;
3712  int numParams = fsstate->numParams;
3713  const char **values = fsstate->param_values;
3714  PGconn *conn = fsstate->conn;
3716  PGresult *res;
3717 
3718  /* First, process a pending asynchronous request, if any. */
3719  if (fsstate->conn_state->pendingAreq)
3721 
3722  /*
3723  * Construct array of query parameter values in text format. We do the
3724  * conversions in the short-lived per-tuple context, so as not to cause a
3725  * memory leak over repeated scans.
3726  */
3727  if (numParams > 0)
3728  {
3729  MemoryContext oldcontext;
3730 
3731  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3732 
3733  process_query_params(econtext,
3734  fsstate->param_flinfo,
3735  fsstate->param_exprs,
3736  values);
3737 
3738  MemoryContextSwitchTo(oldcontext);
3739  }
3740 
3741  /* Construct the DECLARE CURSOR command */
3742  initStringInfo(&buf);
3743  appendStringInfo(&buf, "DECLARE c%u CURSOR FOR\n%s",
3744  fsstate->cursor_number, fsstate->query);
3745 
3746  /*
3747  * Notice that we pass NULL for paramTypes, thus forcing the remote server
3748  * to infer types for all parameters. Since we explicitly cast every
3749  * parameter (see deparse.c), the "inference" is trivial and will produce
3750  * the desired result. This allows us to avoid assuming that the remote
3751  * server has the same OIDs we do for the parameters' types.
3752  */
3753  if (!PQsendQueryParams(conn, buf.data, numParams,
3754  NULL, values, NULL, NULL, 0))
3755  pgfdw_report_error(ERROR, NULL, conn, false, buf.data);
3756 
3757  /*
3758  * Get the result, and check for success.
3759  *
3760  * We don't use a PG_TRY block here, so be careful not to throw error
3761  * without releasing the PGresult.
3762  */
3763  res = pgfdw_get_result(conn, buf.data);
3765  pgfdw_report_error(ERROR, res, conn, true, fsstate->query);
3766  PQclear(res);
3767 
3768  /* Mark the cursor as created, and show no tuples have been retrieved */
3769  fsstate->cursor_exists = true;
3770  fsstate->tuples = NULL;
3771  fsstate->num_tuples = 0;
3772  fsstate->next_tuple = 0;
3773  fsstate->fetch_ct_2 = 0;
3774  fsstate->eof_reached = false;
3775 
3776  /* Clean up */
3777  pfree(buf.data);
3778 }
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:855
int PQsendQueryParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1498
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void pfree(void *pointer)
Definition: mcxt.c:1456
static char * buf
Definition: pg_test_fsync.c:73
void process_pending_request(AsyncRequest *areq)
static void process_query_params(ExprContext *econtext, FmgrInfo *param_flinfo, List *param_exprs, const char **param_values)
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:138
FmgrInfo * param_flinfo
Definition: postgres_fdw.c:155
const char ** param_values
Definition: postgres_fdw.c:157
unsigned int cursor_number
Definition: postgres_fdw.c:152
List * param_exprs
Definition: postgres_fdw.c:156
PgFdwConnState * conn_state
Definition: postgres_fdw.c:151
HeapTuple * tuples
Definition: postgres_fdw.c:160
ExprContext * ps_ExprContext
Definition: execnodes.h:1075

References appendStringInfo(), buf, PgFdwScanState::conn, conn, PgFdwScanState::conn_state, PgFdwScanState::cursor_exists, PgFdwScanState::cursor_number, PgFdwScanState::eof_reached, ERROR, ForeignScanState::fdw_state, PgFdwScanState::fetch_ct_2, if(), initStringInfo(), MemoryContextSwitchTo(), PgFdwScanState::next_tuple, PgFdwScanState::num_tuples, PgFdwScanState::numParams, PgFdwScanState::param_exprs, PgFdwScanState::param_flinfo, PgFdwScanState::param_values, PgFdwConnState::pendingAreq, pfree(), pgfdw_get_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear(), PQresultStatus(), PQsendQueryParams(), process_pending_request(), process_query_params(), ScanState::ps, PlanState::ps_ExprContext, PgFdwScanState::query, res, ForeignScanState::ss, PgFdwScanState::tuples, and values.

Referenced by fetch_more_data_begin(), and postgresIterateForeignScan().

◆ create_foreign_modify()

static PgFdwModifyState * create_foreign_modify ( EState estate,
RangeTblEntry rte,
ResultRelInfo resultRelInfo,
CmdType  operation,
Plan subplan,
char *  query,
List target_attrs,
int  values_end,
bool  has_returning,
List retrieved_attrs 
)
static

Definition at line 3956 of file postgres_fdw.c.

3966 {
3967  PgFdwModifyState *fmstate;
3968  Relation rel = resultRelInfo->ri_RelationDesc;
3969  TupleDesc tupdesc = RelationGetDescr(rel);
3970  Oid userid;
3971  ForeignTable *table;
3972  UserMapping *user;
3973  AttrNumber n_params;
3974  Oid typefnoid;
3975  bool isvarlena;
3976  ListCell *lc;
3977 
3978  /* Begin constructing PgFdwModifyState. */
3979  fmstate = (PgFdwModifyState *) palloc0(sizeof(PgFdwModifyState));
3980  fmstate->rel = rel;
3981 
3982  /* Identify which user to do the remote access as. */
3983  userid = ExecGetResultRelCheckAsUser(resultRelInfo, estate);
3984 
3985  /* Get info about foreign table. */
3986  table = GetForeignTable(RelationGetRelid(rel));
3987  user = GetUserMapping(userid, table->serverid);
3988 
3989  /* Open connection; report that we'll create a prepared statement. */
3990  fmstate->conn = GetConnection(user, true, &fmstate->conn_state);
3991  fmstate->p_name = NULL; /* prepared statement not made yet */
3992 
3993  /* Set up remote query information. */
3994  fmstate->query = query;
3995  if (operation == CMD_INSERT)
3996  {
3997  fmstate->query = pstrdup(fmstate->query);
3998  fmstate->orig_query = pstrdup(fmstate->query);
3999  }
4000  fmstate->target_attrs = target_attrs;
4001  fmstate->values_end = values_end;
4002  fmstate->has_returning = has_returning;
4003  fmstate->retrieved_attrs = retrieved_attrs;
4004 
4005  /* Create context for per-tuple temp workspace. */
4006  fmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
4007  "postgres_fdw temporary data",
4009 
4010  /* Prepare for input conversion of RETURNING results. */
4011  if (fmstate->has_returning)
4012  fmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
4013 
4014  /* Prepare for output conversion of parameters used in prepared stmt. */
4015  n_params = list_length(fmstate->target_attrs) + 1;
4016  fmstate->p_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * n_params);
4017  fmstate->p_nums = 0;
4018 
4019  if (operation == CMD_UPDATE || operation == CMD_DELETE)
4020  {
4021  Assert(subplan != NULL);
4022 
4023  /* Find the ctid resjunk column in the subplan's result */
4025  "ctid");
4026  if (!AttributeNumberIsValid(fmstate->ctidAttno))
4027  elog(ERROR, "could not find junk ctid column");
4028 
4029  /* First transmittable parameter will be ctid */
4030  getTypeOutputInfo(TIDOID, &typefnoid, &isvarlena);
4031  fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4032  fmstate->p_nums++;
4033  }
4034 
4035  if (operation == CMD_INSERT || operation == CMD_UPDATE)
4036  {
4037  /* Set up for remaining transmittable parameters */
4038  foreach(lc, fmstate->target_attrs)
4039  {
4040  int attnum = lfirst_int(lc);
4041  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4042 
4043  Assert(!attr->attisdropped);
4044 
4045  /* Ignore generated columns; they are set to DEFAULT */
4046  if (attr->attgenerated)
4047  continue;
4048  getTypeOutputInfo(attr->atttypid, &typefnoid, &isvarlena);
4049  fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4050  fmstate->p_nums++;
4051  }
4052  }
4053 
4054  Assert(fmstate->p_nums <= n_params);
4055 
4056  /* Set batch_size from foreign server/table options. */
4057  if (operation == CMD_INSERT)
4058  fmstate->batch_size = get_batch_size_option(rel);
4059 
4060  fmstate->num_slots = 1;
4061 
4062  /* Initialize auxiliary state */
4063  fmstate->aux_fmstate = NULL;
4064 
4065  return fmstate;
4066 }
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:177
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2087
Oid ExecGetResultRelCheckAsUser(ResultRelInfo *relInfo, EState *estate)
Definition: execUtils.c:1400
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:254
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:200
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2889
char * pstrdup(const char *in)
Definition: mcxt.c:1644
#define AllocSetContextCreate
Definition: memutils.h:126
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:160
@ CMD_INSERT
Definition: nodes.h:278
@ CMD_DELETE
Definition: nodes.h:279
@ CMD_UPDATE
Definition: nodes.h:277
static char * user
Definition: pg_regress.c:120
unsigned int Oid
Definition: postgres_ext.h:31
static int get_batch_size_option(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:504
MemoryContext es_query_cxt
Definition: execnodes.h:658
Definition: fmgr.h:57
Oid serverid
Definition: foreign.h:56
AttInMetadata * attinmeta
Definition: postgres_fdw.c:184
PgFdwConnState * conn_state
Definition: postgres_fdw.c:188
AttrNumber ctidAttno
Definition: postgres_fdw.c:201
struct PgFdwModifyState * aux_fmstate
Definition: postgres_fdw.c:212
List * retrieved_attrs
Definition: postgres_fdw.c:198
List * targetlist
Definition: plannodes.h:152
Relation ri_RelationDesc
Definition: execnodes.h:449

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert(), PgFdwModifyState::attinmeta, attnum, AttributeNumberIsValid, PgFdwModifyState::aux_fmstate, PgFdwModifyState::batch_size, CMD_DELETE, CMD_INSERT, CMD_UPDATE, PgFdwModifyState::conn, PgFdwModifyState::conn_state, PgFdwModifyState::ctidAttno, elog(), ERROR, EState::es_query_cxt, ExecFindJunkAttributeInTlist(), ExecGetResultRelCheckAsUser(), fmgr_info(), get_batch_size_option(), GetConnection(), GetForeignTable(), getTypeOutputInfo(), GetUserMapping(), PgFdwModifyState::has_returning, lfirst_int, list_length(), PgFdwModifyState::num_slots, PgFdwModifyState::orig_query, PgFdwModifyState::p_flinfo, PgFdwModifyState::p_name, PgFdwModifyState::p_nums, palloc0(), pstrdup(), PgFdwModifyState::query, PgFdwModifyState::rel, RelationGetDescr, RelationGetRelid, PgFdwModifyState::retrieved_attrs, ResultRelInfo::ri_RelationDesc, ForeignTable::serverid, PgFdwModifyState::target_attrs, Plan::targetlist, PgFdwModifyState::temp_cxt, TupleDescAttr, TupleDescGetAttInMetadata(), user, and PgFdwModifyState::values_end.

Referenced by postgresBeginForeignInsert(), and postgresBeginForeignModify().

◆ deallocate_query()

static void deallocate_query ( PgFdwModifyState fmstate)
static

Definition at line 4381 of file postgres_fdw.c.

4382 {
4383  char sql[64];
4384  PGresult *res;
4385 
4386  /* do nothing if the query is not allocated */
4387  if (!fmstate->p_name)
4388  return;
4389 
4390  snprintf(sql, sizeof(sql), "DEALLOCATE %s", fmstate->p_name);
4391 
4392  /*
4393  * We don't use a PG_TRY block here, so be careful not to throw error
4394  * without releasing the PGresult.
4395  */
4396  res = pgfdw_exec_query(fmstate->conn, sql, fmstate->conn_state);
4398  pgfdw_report_error(ERROR, res, fmstate->conn, true, sql);
4399  PQclear(res);
4400  pfree(fmstate->p_name);
4401  fmstate->p_name = NULL;
4402 }

References PgFdwModifyState::conn, PgFdwModifyState::conn_state, ERROR, PgFdwModifyState::p_name, pfree(), pgfdw_exec_query(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear(), PQresultStatus(), res, and snprintf.

Referenced by execute_foreign_modify(), and finish_foreign_modify().

◆ ec_member_matches_foreign()

static bool ec_member_matches_foreign ( PlannerInfo root,
RelOptInfo rel,
EquivalenceClass ec,
EquivalenceMember em,
void *  arg 
)
static

Definition at line 3679 of file postgres_fdw.c.

3682 {
3684  Expr *expr = em->em_expr;
3685 
3686  /*
3687  * If we've identified what we're processing in the current scan, we only
3688  * want to match that expression.
3689  */
3690  if (state->current != NULL)
3691  return equal(expr, state->current);
3692 
3693  /*
3694  * Otherwise, ignore anything we've already processed.
3695  */
3696  if (list_member(state->already_used, expr))
3697  return false;
3698 
3699  /* This is the new target to process. */
3700  state->current = expr;
3701  return true;
3702 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
bool list_member(const List *list, const void *datum)
Definition: list.c:660
Definition: regguts.h:323

References arg, EquivalenceMember::em_expr, equal(), and list_member().

Referenced by postgresGetForeignPaths().

◆ estimate_path_cost_size()

static void estimate_path_cost_size ( PlannerInfo root,
RelOptInfo foreignrel,
List param_join_conds,
List pathkeys,
PgFdwPathExtraData fpextra,
double *  p_rows,
int *  p_width,
Cost p_startup_cost,
Cost p_total_cost 
)
static

Definition at line 3075 of file postgres_fdw.c.

3082 {
3083  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
3084  double rows;
3085  double retrieved_rows;
3086  int width;
3087  Cost startup_cost;
3088  Cost total_cost;
3089 
3090  /* Make sure the core code has set up the relation's reltarget */
3091  Assert(foreignrel->reltarget);
3092 
3093  /*
3094  * If the table or the server is configured to use remote estimates,
3095  * connect to the foreign server and execute EXPLAIN to estimate the
3096  * number of rows selected by the restriction+join clauses. Otherwise,
3097  * estimate rows using whatever statistics we have locally, in a way
3098  * similar to ordinary tables.
3099  */
3100  if (fpinfo->use_remote_estimate)
3101  {
3102  List *remote_param_join_conds;
3103  List *local_param_join_conds;
3104  StringInfoData sql;
3105  PGconn *conn;
3106  Selectivity local_sel;
3107  QualCost local_cost;
3108  List *fdw_scan_tlist = NIL;
3109  List *remote_conds;
3110 
3111  /* Required only to be passed to deparseSelectStmtForRel */
3112  List *retrieved_attrs;
3113 
3114  /*
3115  * param_join_conds might contain both clauses that are safe to send
3116  * across, and clauses that aren't.
3117  */
3118  classifyConditions(root, foreignrel, param_join_conds,
3119  &remote_param_join_conds, &local_param_join_conds);
3120 
3121  /* Build the list of columns to be fetched from the foreign server. */
3122  if (IS_JOIN_REL(foreignrel) || IS_UPPER_REL(foreignrel))
3123  fdw_scan_tlist = build_tlist_to_deparse(foreignrel);
3124  else
3125  fdw_scan_tlist = NIL;
3126 
3127  /*
3128  * The complete list of remote conditions includes everything from
3129  * baserestrictinfo plus any extra join_conds relevant to this
3130  * particular path.
3131  */
3132  remote_conds = list_concat(remote_param_join_conds,
3133  fpinfo->remote_conds);
3134 
3135  /*
3136  * Construct EXPLAIN query including the desired SELECT, FROM, and
3137  * WHERE clauses. Params and other-relation Vars are replaced by dummy
3138  * values, so don't request params_list.
3139  */
3140  initStringInfo(&sql);
3141  appendStringInfoString(&sql, "EXPLAIN ");
3142  deparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
3143  remote_conds, pathkeys,
3144  fpextra ? fpextra->has_final_sort : false,
3145  fpextra ? fpextra->has_limit : false,
3146  false, &retrieved_attrs, NULL);
3147 
3148  /* Get the remote estimate */
3149  conn = GetConnection(fpinfo->user, false, NULL);
3150  get_remote_estimate(sql.data, conn, &rows, &width,
3151  &startup_cost, &total_cost);
3153 
3154  retrieved_rows = rows;
3155 
3156  /* Factor in the selectivity of the locally-checked quals */
3157  local_sel = clauselist_selectivity(root,
3158  local_param_join_conds,
3159  foreignrel->relid,
3160  JOIN_INNER,
3161  NULL);
3162  local_sel *= fpinfo->local_conds_sel;
3163 
3164  rows = clamp_row_est(rows * local_sel);
3165 
3166  /* Add in the eval cost of the locally-checked quals */
3167  startup_cost += fpinfo->local_conds_cost.startup;
3168  total_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3169  cost_qual_eval(&local_cost, local_param_join_conds, root);
3170  startup_cost += local_cost.startup;
3171  total_cost += local_cost.per_tuple * retrieved_rows;
3172 
3173  /*
3174  * Add in tlist eval cost for each output row. In case of an
3175  * aggregate, some of the tlist expressions such as grouping
3176  * expressions will be evaluated remotely, so adjust the costs.
3177  */
3178  startup_cost += foreignrel->reltarget->cost.startup;
3179  total_cost += foreignrel->reltarget->cost.startup;
3180  total_cost += foreignrel->reltarget->cost.per_tuple * rows;
3181  if (IS_UPPER_REL(foreignrel))
3182  {
3183  QualCost tlist_cost;
3184 
3185  cost_qual_eval(&tlist_cost, fdw_scan_tlist, root);
3186  startup_cost -= tlist_cost.startup;
3187  total_cost -= tlist_cost.startup;
3188  total_cost -= tlist_cost.per_tuple * rows;
3189  }
3190  }
3191  else
3192  {
3193  Cost run_cost = 0;
3194 
3195  /*
3196  * We don't support join conditions in this mode (hence, no
3197  * parameterized paths can be made).
3198  */
3199  Assert(param_join_conds == NIL);
3200 
3201  /*
3202  * We will come here again and again with different set of pathkeys or
3203  * additional post-scan/join-processing steps that caller wants to
3204  * cost. We don't need to calculate the cost/size estimates for the
3205  * underlying scan, join, or grouping each time. Instead, use those
3206  * estimates if we have cached them already.
3207  */
3208  if (fpinfo->rel_startup_cost >= 0 && fpinfo->rel_total_cost >= 0)
3209  {
3210  Assert(fpinfo->retrieved_rows >= 0);
3211 
3212  rows = fpinfo->rows;
3213  retrieved_rows = fpinfo->retrieved_rows;
3214  width = fpinfo->width;
3215  startup_cost = fpinfo->rel_startup_cost;
3216  run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
3217 
3218  /*
3219  * If we estimate the costs of a foreign scan or a foreign join
3220  * with additional post-scan/join-processing steps, the scan or
3221  * join costs obtained from the cache wouldn't yet contain the
3222  * eval costs for the final scan/join target, which would've been
3223  * updated by apply_scanjoin_target_to_paths(); add the eval costs
3224  * now.
3225  */
3226  if (fpextra && !IS_UPPER_REL(foreignrel))
3227  {
3228  /* Shouldn't get here unless we have LIMIT */
3229  Assert(fpextra->has_limit);
3230  Assert(foreignrel->reloptkind == RELOPT_BASEREL ||
3231  foreignrel->reloptkind == RELOPT_JOINREL);
3232  startup_cost += foreignrel->reltarget->cost.startup;
3233  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3234  }
3235  }
3236  else if (IS_JOIN_REL(foreignrel))
3237  {
3238  PgFdwRelationInfo *fpinfo_i;
3239  PgFdwRelationInfo *fpinfo_o;
3240  QualCost join_cost;
3241  QualCost remote_conds_cost;
3242  double nrows;
3243 
3244  /* Use rows/width estimates made by the core code. */
3245  rows = foreignrel->rows;
3246  width = foreignrel->reltarget->width;
3247 
3248  /* For join we expect inner and outer relations set */
3249  Assert(fpinfo->innerrel && fpinfo->outerrel);
3250 
3251  fpinfo_i = (PgFdwRelationInfo *) fpinfo->innerrel->fdw_private;
3252  fpinfo_o = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
3253 
3254  /* Estimate of number of rows in cross product */
3255  nrows = fpinfo_i->rows * fpinfo_o->rows;
3256 
3257  /*
3258  * Back into an estimate of the number of retrieved rows. Just in
3259  * case this is nuts, clamp to at most nrows.
3260  */
3261  retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3262  retrieved_rows = Min(retrieved_rows, nrows);
3263 
3264  /*
3265  * The cost of foreign join is estimated as cost of generating
3266  * rows for the joining relations + cost for applying quals on the
3267  * rows.
3268  */
3269 
3270  /*
3271  * Calculate the cost of clauses pushed down to the foreign server
3272  */
3273  cost_qual_eval(&remote_conds_cost, fpinfo->remote_conds, root);
3274  /* Calculate the cost of applying join clauses */
3275  cost_qual_eval(&join_cost, fpinfo->joinclauses, root);
3276 
3277  /*
3278  * Startup cost includes startup cost of joining relations and the
3279  * startup cost for join and other clauses. We do not include the
3280  * startup cost specific to join strategy (e.g. setting up hash
3281  * tables) since we do not know what strategy the foreign server
3282  * is going to use.
3283  */
3284  startup_cost = fpinfo_i->rel_startup_cost + fpinfo_o->rel_startup_cost;
3285  startup_cost += join_cost.startup;
3286  startup_cost += remote_conds_cost.startup;
3287  startup_cost += fpinfo->local_conds_cost.startup;
3288 
3289  /*
3290  * Run time cost includes:
3291  *
3292  * 1. Run time cost (total_cost - startup_cost) of relations being
3293  * joined
3294  *
3295  * 2. Run time cost of applying join clauses on the cross product
3296  * of the joining relations.
3297  *
3298  * 3. Run time cost of applying pushed down other clauses on the
3299  * result of join
3300  *
3301  * 4. Run time cost of applying nonpushable other clauses locally
3302  * on the result fetched from the foreign server.
3303  */
3304  run_cost = fpinfo_i->rel_total_cost - fpinfo_i->rel_startup_cost;
3305  run_cost += fpinfo_o->rel_total_cost - fpinfo_o->rel_startup_cost;
3306  run_cost += nrows * join_cost.per_tuple;
3307  nrows = clamp_row_est(nrows * fpinfo->joinclause_sel);
3308  run_cost += nrows * remote_conds_cost.per_tuple;
3309  run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3310 
3311  /* Add in tlist eval cost for each output row */
3312  startup_cost += foreignrel->reltarget->cost.startup;
3313  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3314  }
3315  else if (IS_UPPER_REL(foreignrel))
3316  {
3317  RelOptInfo *outerrel = fpinfo->outerrel;
3318  PgFdwRelationInfo *ofpinfo;
3319  AggClauseCosts aggcosts;
3320  double input_rows;
3321  int numGroupCols;
3322  double numGroups = 1;
3323 
3324  /* The upper relation should have its outer relation set */
3325  Assert(outerrel);
3326  /* and that outer relation should have its reltarget set */
3327  Assert(outerrel->reltarget);
3328 
3329  /*
3330  * This cost model is mixture of costing done for sorted and
3331  * hashed aggregates in cost_agg(). We are not sure which
3332  * strategy will be considered at remote side, thus for
3333  * simplicity, we put all startup related costs in startup_cost
3334  * and all finalization and run cost are added in total_cost.
3335  */
3336 
3337  ofpinfo = (PgFdwRelationInfo *) outerrel->fdw_private;
3338 
3339  /* Get rows from input rel */
3340  input_rows = ofpinfo->rows;
3341 
3342  /* Collect statistics about aggregates for estimating costs. */
3343  MemSet(&aggcosts, 0, sizeof(AggClauseCosts));
3344  if (root->parse->hasAggs)
3345  {
3346  get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &aggcosts);
3347  }
3348 
3349  /* Get number of grouping columns and possible number of groups */
3350  numGroupCols = list_length(root->processed_groupClause);
3351  numGroups = estimate_num_groups(root,
3353  fpinfo->grouped_tlist),
3354  input_rows, NULL, NULL);
3355 
3356  /*
3357  * Get the retrieved_rows and rows estimates. If there are HAVING
3358  * quals, account for their selectivity.
3359  */
3360  if (root->hasHavingQual)
3361  {
3362  /* Factor in the selectivity of the remotely-checked quals */
3363  retrieved_rows =
3364  clamp_row_est(numGroups *
3366  fpinfo->remote_conds,
3367  0,
3368  JOIN_INNER,
3369  NULL));
3370  /* Factor in the selectivity of the locally-checked quals */
3371  rows = clamp_row_est(retrieved_rows * fpinfo->local_conds_sel);
3372  }
3373  else
3374  {
3375  rows = retrieved_rows = numGroups;
3376  }
3377 
3378  /* Use width estimate made by the core code. */
3379  width = foreignrel->reltarget->width;
3380 
3381  /*-----
3382  * Startup cost includes:
3383  * 1. Startup cost for underneath input relation, adjusted for
3384  * tlist replacement by apply_scanjoin_target_to_paths()
3385  * 2. Cost of performing aggregation, per cost_agg()
3386  *-----
3387  */
3388  startup_cost = ofpinfo->rel_startup_cost;
3389  startup_cost += outerrel->reltarget->cost.startup;
3390  startup_cost += aggcosts.transCost.startup;
3391  startup_cost += aggcosts.transCost.per_tuple * input_rows;
3392  startup_cost += aggcosts.finalCost.startup;
3393  startup_cost += (cpu_operator_cost * numGroupCols) * input_rows;
3394 
3395  /*-----
3396  * Run time cost includes:
3397  * 1. Run time cost of underneath input relation, adjusted for
3398  * tlist replacement by apply_scanjoin_target_to_paths()
3399  * 2. Run time cost of performing aggregation, per cost_agg()
3400  *-----
3401  */
3402  run_cost = ofpinfo->rel_total_cost - ofpinfo->rel_startup_cost;
3403  run_cost += outerrel->reltarget->cost.per_tuple * input_rows;
3404  run_cost += aggcosts.finalCost.per_tuple * numGroups;
3405  run_cost += cpu_tuple_cost * numGroups;
3406 
3407  /* Account for the eval cost of HAVING quals, if any */
3408  if (root->hasHavingQual)
3409  {
3410  QualCost remote_cost;
3411 
3412  /* Add in the eval cost of the remotely-checked quals */
3413  cost_qual_eval(&remote_cost, fpinfo->remote_conds, root);
3414  startup_cost += remote_cost.startup;
3415  run_cost += remote_cost.per_tuple * numGroups;
3416  /* Add in the eval cost of the locally-checked quals */
3417  startup_cost += fpinfo->local_conds_cost.startup;
3418  run_cost += fpinfo->local_conds_cost.per_tuple * retrieved_rows;
3419  }
3420 
3421  /* Add in tlist eval cost for each output row */
3422  startup_cost += foreignrel->reltarget->cost.startup;
3423  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3424  }
3425  else
3426  {
3427  Cost cpu_per_tuple;
3428 
3429  /* Use rows/width estimates made by set_baserel_size_estimates. */
3430  rows = foreignrel->rows;
3431  width = foreignrel->reltarget->width;
3432 
3433  /*
3434  * Back into an estimate of the number of retrieved rows. Just in
3435  * case this is nuts, clamp to at most foreignrel->tuples.
3436  */
3437  retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
3438  retrieved_rows = Min(retrieved_rows, foreignrel->tuples);
3439 
3440  /*
3441  * Cost as though this were a seqscan, which is pessimistic. We
3442  * effectively imagine the local_conds are being evaluated
3443  * remotely, too.
3444  */
3445  startup_cost = 0;
3446  run_cost = 0;
3447  run_cost += seq_page_cost * foreignrel->pages;
3448 
3449  startup_cost += foreignrel->baserestrictcost.startup;
3450  cpu_per_tuple = cpu_tuple_cost + foreignrel->baserestrictcost.per_tuple;
3451  run_cost += cpu_per_tuple * foreignrel->tuples;
3452 
3453  /* Add in tlist eval cost for each output row */
3454  startup_cost += foreignrel->reltarget->cost.startup;
3455  run_cost += foreignrel->reltarget->cost.per_tuple * rows;
3456  }
3457 
3458  /*
3459  * Without remote estimates, we have no real way to estimate the cost
3460  * of generating sorted output. It could be free if the query plan
3461  * the remote side would have chosen generates properly-sorted output
3462  * anyway, but in most cases it will cost something. Estimate a value
3463  * high enough that we won't pick the sorted path when the ordering
3464  * isn't locally useful, but low enough that we'll err on the side of
3465  * pushing down the ORDER BY clause when it's useful to do so.
3466  */
3467  if (pathkeys != NIL)
3468  {
3469  if (IS_UPPER_REL(foreignrel))
3470  {
3471  Assert(foreignrel->reloptkind == RELOPT_UPPER_REL &&
3472  fpinfo->stage == UPPERREL_GROUP_AGG);
3473  adjust_foreign_grouping_path_cost(root, pathkeys,
3474  retrieved_rows, width,
3475  fpextra->limit_tuples,
3476  &startup_cost, &run_cost);
3477  }
3478  else
3479  {
3480  startup_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3481  run_cost *= DEFAULT_FDW_SORT_MULTIPLIER;
3482  }
3483  }
3484 
3485  total_cost = startup_cost + run_cost;
3486 
3487  /* Adjust the cost estimates if we have LIMIT */
3488  if (fpextra && fpextra->has_limit)
3489  {
3490  adjust_limit_rows_costs(&rows, &startup_cost, &total_cost,
3491  fpextra->offset_est, fpextra->count_est);
3492  retrieved_rows = rows;
3493  }
3494  }
3495 
3496  /*
3497  * If this includes the final sort step, the given target, which will be
3498  * applied to the resulting path, might have different expressions from
3499  * the foreignrel's reltarget (see make_sort_input_target()); adjust tlist
3500  * eval costs.
3501  */
3502  if (fpextra && fpextra->has_final_sort &&
3503  fpextra->target != foreignrel->reltarget)
3504  {
3505  QualCost oldcost = foreignrel->reltarget->cost;
3506  QualCost newcost = fpextra->target->cost;
3507 
3508  startup_cost += newcost.startup - oldcost.startup;
3509  total_cost += newcost.startup - oldcost.startup;
3510  total_cost += (newcost.per_tuple - oldcost.per_tuple) * rows;
3511  }
3512 
3513  /*
3514  * Cache the retrieved rows and cost estimates for scans, joins, or
3515  * groupings without any parameterization, pathkeys, or additional
3516  * post-scan/join-processing steps, before adding the costs for
3517  * transferring data from the foreign server. These estimates are useful
3518  * for costing remote joins involving this relation or costing other
3519  * remote operations on this relation such as remote sorts and remote
3520  * LIMIT restrictions, when the costs can not be obtained from the foreign
3521  * server. This function will be called at least once for every foreign
3522  * relation without any parameterization, pathkeys, or additional
3523  * post-scan/join-processing steps.
3524  */
3525  if (pathkeys == NIL && param_join_conds == NIL && fpextra == NULL)
3526  {
3527  fpinfo->retrieved_rows = retrieved_rows;
3528  fpinfo->rel_startup_cost = startup_cost;
3529  fpinfo->rel_total_cost = total_cost;
3530  }
3531 
3532  /*
3533  * Add some additional cost factors to account for connection overhead
3534  * (fdw_startup_cost), transferring data across the network
3535  * (fdw_tuple_cost per retrieved row), and local manipulation of the data
3536  * (cpu_tuple_cost per retrieved row).
3537  */
3538  startup_cost += fpinfo->fdw_startup_cost;
3539  total_cost += fpinfo->fdw_startup_cost;
3540  total_cost += fpinfo->fdw_tuple_cost * retrieved_rows;
3541  total_cost += cpu_tuple_cost * retrieved_rows;
3542 
3543  /*
3544  * If we have LIMIT, we should prefer performing the restriction remotely
3545  * rather than locally, as the former avoids extra row fetches from the
3546  * remote that the latter might cause. But since the core code doesn't
3547  * account for such fetches when estimating the costs of the local
3548  * restriction (see create_limit_path()), there would be no difference
3549  * between the costs of the local restriction and the costs of the remote
3550  * restriction estimated above if we don't use remote estimates (except
3551  * for the case where the foreignrel is a grouping relation, the given
3552  * pathkeys is not NIL, and the effects of a bounded sort for that rel is
3553  * accounted for in costing the remote restriction). Tweak the costs of
3554  * the remote restriction to ensure we'll prefer it if LIMIT is a useful
3555  * one.
3556  */
3557  if (!fpinfo->use_remote_estimate &&
3558  fpextra && fpextra->has_limit &&
3559  fpextra->limit_tuples > 0 &&
3560  fpextra->limit_tuples < fpinfo->rows)
3561  {
3562  Assert(fpinfo->rows > 0);
3563  total_cost -= (total_cost - startup_cost) * 0.05 *
3564  (fpinfo->rows - fpextra->limit_tuples) / fpinfo->rows;
3565  }
3566 
3567  /* Return results. */
3568  *p_rows = rows;
3569  *p_width = width;
3570  *p_startup_cost = startup_cost;
3571  *p_total_cost = total_cost;
3572 }
#define Min(x, y)
Definition: c.h:993
#define MemSet(start, val, len)
Definition: c.h:1009
void ReleaseConnection(PGconn *conn)
Definition: connection.c:779
double cpu_operator_cost
Definition: costsize.c:124
double cpu_tuple_cost
Definition: costsize.c:122
double seq_page_cost
Definition: costsize.c:120
double clamp_row_est(double nrows)
Definition: costsize.c:203
void deparseSelectStmtForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *rel, List *tlist, List *remote_conds, List *pathkeys, bool has_final_sort, bool has_limit, bool is_subquery, List **retrieved_attrs, List **params_list)
Definition: deparse.c:1233
List * build_tlist_to_deparse(RelOptInfo *foreignrel)
Definition: deparse.c:1176
void classifyConditions(PlannerInfo *root, RelOptInfo *baserel, List *input_conds, List **remote_conds, List **local_conds)
Definition: deparse.c:218
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
double Selectivity
Definition: nodes.h:261
@ AGGSPLIT_SIMPLE
Definition: nodes.h:387
void adjust_limit_rows_costs(double *rows, Cost *startup_cost, Cost *total_cost, int64 offset_est, int64 count_est)
Definition: pathnode.c:3834
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:829
#define IS_UPPER_REL(rel)
Definition: pathnodes.h:834
static void get_remote_estimate(const char *sql, PGconn *conn, double *rows, int *width, Cost *startup_cost, Cost *total_cost)
static void adjust_foreign_grouping_path_cost(PlannerInfo *root, List *pathkeys, double retrieved_rows, double width, double limit_tuples, Cost *p_startup_cost, Cost *p_run_cost)
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:561
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3386
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
QualCost finalCost
Definition: pathnodes.h:61
QualCost transCost
Definition: pathnodes.h:60
QualCost cost
Definition: pathnodes.h:1507
Selectivity joinclause_sel
Definition: postgres_fdw.h:60
RelOptInfo * innerrel
Definition: postgres_fdw.h:103
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47
Index relid
Definition: pathnodes.h:903
Cardinality tuples
Definition: pathnodes.h:928
BlockNumber pages
Definition: pathnodes.h:927
QualCost baserestrictcost
Definition: pathnodes.h:966
Cardinality rows
Definition: pathnodes.h:862
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:392

References adjust_foreign_grouping_path_cost(), adjust_limit_rows_costs(), AGGSPLIT_SIMPLE, appendStringInfoString(), Assert(), RelOptInfo::baserestrictcost, build_tlist_to_deparse(), clamp_row_est(), classifyConditions(), clauselist_selectivity(), conn, PathTarget::cost, cost_qual_eval(), PgFdwPathExtraData::count_est, cpu_operator_cost, cpu_tuple_cost, StringInfoData::data, DEFAULT_FDW_SORT_MULTIPLIER, deparseSelectStmtForRel(), estimate_num_groups(), PgFdwRelationInfo::fdw_startup_cost, PgFdwRelationInfo::fdw_tuple_cost, AggClauseCosts::finalCost, get_agg_clause_costs(), get_remote_estimate(), get_sortgrouplist_exprs(), GetConnection(), PgFdwRelationInfo::grouped_tlist, PgFdwPathExtraData::has_final_sort, PgFdwPathExtraData::has_limit, PlannerInfo::hasHavingQual, initStringInfo(), PgFdwRelationInfo::innerrel, IS_JOIN_REL, IS_UPPER_REL, JOIN_INNER, PgFdwRelationInfo::joinclause_sel, PgFdwRelationInfo::joinclauses, PgFdwPathExtraData::limit_tuples, list_concat(), list_length(), PgFdwRelationInfo::local_conds_cost, PgFdwRelationInfo::local_conds_sel, MemSet, Min, NIL, PgFdwPathExtraData::offset_est, PgFdwRelationInfo::outerrel, RelOptInfo::pages, PlannerInfo::parse, QualCost::per_tuple, PlannerInfo::processed_groupClause, PgFdwRelationInfo::rel_startup_cost, PgFdwRelationInfo::rel_total_cost, ReleaseConnection(), RelOptInfo::relid, RELOPT_BASEREL, RELOPT_JOINREL, RELOPT_UPPER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, PgFdwRelationInfo::remote_conds, PgFdwRelationInfo::retrieved_rows, PgFdwRelationInfo::rows, RelOptInfo::rows, seq_page_cost, PgFdwRelationInfo::stage, QualCost::startup, PgFdwPathExtraData::target, AggClauseCosts::transCost, RelOptInfo::tuples, UPPERREL_GROUP_AGG, PgFdwRelationInfo::use_remote_estimate, PgFdwRelationInfo::user, PgFdwRelationInfo::width, and PathTarget::width.

Referenced by add_foreign_final_paths(), add_foreign_grouping_paths(), add_foreign_ordered_paths(), add_paths_with_pathkeys_for_rel(), postgresGetForeignJoinPaths(), postgresGetForeignPaths(), and postgresGetForeignRelSize().

◆ execute_dml_stmt()

static void execute_dml_stmt ( ForeignScanState node)
static

Definition at line 4537 of file postgres_fdw.c.

4538 {
4540  ExprContext *econtext = node->ss.ps.ps_ExprContext;
4541  int numParams = dmstate->numParams;
4542  const char **values = dmstate->param_values;
4543 
4544  /* First, process a pending asynchronous request, if any. */
4545  if (dmstate->conn_state->pendingAreq)
4547 
4548  /*
4549  * Construct array of query parameter values in text format.
4550  */
4551  if (numParams > 0)
4552  process_query_params(econtext,
4553  dmstate->param_flinfo,
4554  dmstate->param_exprs,
4555  values);
4556 
4557  /*
4558  * Notice that we pass NULL for paramTypes, thus forcing the remote server
4559  * to infer types for all parameters. Since we explicitly cast every
4560  * parameter (see deparse.c), the "inference" is trivial and will produce
4561  * the desired result. This allows us to avoid assuming that the remote
4562  * server has the same OIDs we do for the parameters' types.
4563  */
4564  if (!PQsendQueryParams(dmstate->conn, dmstate->query, numParams,
4565  NULL, values, NULL, NULL, 0))
4566  pgfdw_report_error(ERROR, NULL, dmstate->conn, false, dmstate->query);
4567 
4568  /*
4569  * Get the result, and check for success.
4570  *
4571  * We don't use a PG_TRY block here, so be careful not to throw error
4572  * without releasing the PGresult.
4573  */
4574  dmstate->result = pgfdw_get_result(dmstate->conn, dmstate->query);
4575  if (PQresultStatus(dmstate->result) !=
4577  pgfdw_report_error(ERROR, dmstate->result, dmstate->conn, true,
4578  dmstate->query);
4579 
4580  /* Get the number of rows affected. */
4581  if (dmstate->has_returning)
4582  dmstate->num_tuples = PQntuples(dmstate->result);
4583  else
4584  dmstate->num_tuples = atoi(PQcmdTuples(dmstate->result));
4585 }
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3763
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3422
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
PgFdwConnState * conn_state
Definition: postgres_fdw.c:232
const char ** param_values
Definition: postgres_fdw.c:236

References PgFdwDirectModifyState::conn, PgFdwDirectModifyState::conn_state, ERROR, ForeignScanState::fdw_state, PgFdwDirectModifyState::has_returning, if(), PgFdwDirectModifyState::num_tuples, PgFdwDirectModifyState::numParams, PgFdwDirectModifyState::param_exprs, PgFdwDirectModifyState::param_flinfo, PgFdwDirectModifyState::param_values, PgFdwConnState::pendingAreq, pgfdw_get_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQcmdTuples(), PQntuples(), PQresultStatus(), PQsendQueryParams(), process_pending_request(), process_query_params(), ScanState::ps, PlanState::ps_ExprContext, PgFdwDirectModifyState::query, PgFdwDirectModifyState::result, ForeignScanState::ss, and values.

Referenced by postgresIterateDirectModify().

◆ execute_foreign_modify()

static TupleTableSlot ** execute_foreign_modify ( EState estate,
ResultRelInfo resultRelInfo,
CmdType  operation,
TupleTableSlot **  slots,
TupleTableSlot **  planSlots,
int *  numSlots 
)
static

Definition at line 4076 of file postgres_fdw.c.

4082 {
4083  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
4084  ItemPointer ctid = NULL;
4085  const char **p_values;
4086  PGresult *res;
4087  int n_rows;
4088  StringInfoData sql;
4089 
4090  /* The operation should be INSERT, UPDATE, or DELETE */
4091  Assert(operation == CMD_INSERT ||
4092  operation == CMD_UPDATE ||
4093  operation == CMD_DELETE);
4094 
4095  /* First, process a pending asynchronous request, if any. */
4096  if (fmstate->conn_state->pendingAreq)
4098 
4099  /*
4100  * If the existing query was deparsed and prepared for a different number
4101  * of rows, rebuild it for the proper number.
4102  */
4103  if (operation == CMD_INSERT && fmstate->num_slots != *numSlots)
4104  {
4105  /* Destroy the prepared statement created previously */
4106  if (fmstate->p_name)
4107  deallocate_query(fmstate);
4108 
4109  /* Build INSERT string with numSlots records in its VALUES clause. */
4110  initStringInfo(&sql);
4111  rebuildInsertSql(&sql, fmstate->rel,
4112  fmstate->orig_query, fmstate->target_attrs,
4113  fmstate->values_end, fmstate->p_nums,
4114  *numSlots - 1);
4115  pfree(fmstate->query);
4116  fmstate->query = sql.data;
4117  fmstate->num_slots = *numSlots;
4118  }
4119 
4120  /* Set up the prepared statement on the remote server, if we didn't yet */
4121  if (!fmstate->p_name)
4122  prepare_foreign_modify(fmstate);
4123 
4124  /*
4125  * For UPDATE/DELETE, get the ctid that was passed up as a resjunk column
4126  */
4127  if (operation == CMD_UPDATE || operation == CMD_DELETE)
4128  {
4129  Datum datum;
4130  bool isNull;
4131 
4132  datum = ExecGetJunkAttribute(planSlots[0],
4133  fmstate->ctidAttno,
4134  &isNull);
4135  /* shouldn't ever get a null result... */
4136  if (isNull)
4137  elog(ERROR, "ctid is NULL");
4138  ctid = (ItemPointer) DatumGetPointer(datum);
4139  }
4140 
4141  /* Convert parameters needed by prepared statement to text form */
4142  p_values = convert_prep_stmt_params(fmstate, ctid, slots, *numSlots);
4143 
4144  /*
4145  * Execute the prepared statement.
4146  */
4147  if (!PQsendQueryPrepared(fmstate->conn,
4148  fmstate->p_name,
4149  fmstate->p_nums * (*numSlots),
4150  p_values,
4151  NULL,
4152  NULL,
4153  0))
4154  pgfdw_report_error(ERROR, NULL, fmstate->conn, false, fmstate->query);
4155 
4156  /*
4157  * Get the result, and check for success.
4158  *
4159  * We don't use a PG_TRY block here, so be careful not to throw error
4160  * without releasing the PGresult.
4161  */
4162  res = pgfdw_get_result(fmstate->conn, fmstate->query);
4163  if (PQresultStatus(res) !=
4165  pgfdw_report_error(ERROR, res, fmstate->conn, true, fmstate->query);
4166 
4167  /* Check number of rows affected, and fetch RETURNING tuple if any */
4168  if (fmstate->has_returning)
4169  {
4170  Assert(*numSlots == 1);
4171  n_rows = PQntuples(res);
4172  if (n_rows > 0)
4173  store_returning_result(fmstate, slots[0], res);
4174  }
4175  else
4176  n_rows = atoi(PQcmdTuples(res));
4177 
4178  /* And clean up */
4179  PQclear(res);
4180 
4181  MemoryContextReset(fmstate->temp_cxt);
4182 
4183  *numSlots = n_rows;
4184 
4185  /*
4186  * Return NULL if nothing was inserted/updated/deleted on the remote end
4187  */
4188  return (n_rows > 0) ? slots : NULL;
4189 }
void rebuildInsertSql(StringInfo buf, Relation rel, char *orig_query, List *target_attrs, int values_end_len, int num_params, int num_rows)
Definition: deparse.c:2156
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:190
int PQsendQueryPrepared(PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
Definition: fe-exec.c:1639
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:330
static const char ** convert_prep_stmt_params(PgFdwModifyState *fmstate, ItemPointer tupleid, TupleTableSlot **slots, int numSlots)
static void store_returning_result(PgFdwModifyState *fmstate, TupleTableSlot *slot, PGresult *res)
static void deallocate_query(PgFdwModifyState *fmstate)
static void prepare_foreign_modify(PgFdwModifyState *fmstate)
void * ri_FdwState
Definition: execnodes.h:499

References Assert(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, PgFdwModifyState::conn, PgFdwModifyState::conn_state, convert_prep_stmt_params(), PgFdwModifyState::ctidAttno, DatumGetPointer(), deallocate_query(), elog(), ERROR, ExecGetJunkAttribute(), PgFdwModifyState::has_returning, initStringInfo(), MemoryContextReset(), PgFdwModifyState::num_slots, PgFdwModifyState::orig_query, PgFdwModifyState::p_name, PgFdwModifyState::p_nums, PgFdwConnState::pendingAreq, pfree(), pgfdw_get_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdTuples(), PQntuples(), PQresultStatus(), PQsendQueryPrepared(), prepare_foreign_modify(), process_pending_request(), PgFdwModifyState::query, rebuildInsertSql(), PgFdwModifyState::rel, res, ResultRelInfo::ri_FdwState, store_returning_result(), PgFdwModifyState::target_attrs, PgFdwModifyState::temp_cxt, and PgFdwModifyState::values_end.

Referenced by postgresExecForeignBatchInsert(), postgresExecForeignDelete(), postgresExecForeignInsert(), and postgresExecForeignUpdate().

◆ fetch_more_data()

static void fetch_more_data ( ForeignScanState node)
static

Definition at line 3784 of file postgres_fdw.c.

3785 {
3786  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3787  PGresult *volatile res = NULL;
3788  MemoryContext oldcontext;
3789 
3790  /*
3791  * We'll store the tuples in the batch_cxt. First, flush the previous
3792  * batch.
3793  */
3794  fsstate->tuples = NULL;
3795  MemoryContextReset(fsstate->batch_cxt);
3796  oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
3797 
3798  /* PGresult must be released before leaving this function. */
3799  PG_TRY();
3800  {
3801  PGconn *conn = fsstate->conn;
3802  int numrows;
3803  int i;
3804 
3805  if (fsstate->async_capable)
3806  {
3807  Assert(fsstate->conn_state->pendingAreq);
3808 
3809  /*
3810  * The query was already sent by an earlier call to
3811  * fetch_more_data_begin. So now we just fetch the result.
3812  */
3813  res = pgfdw_get_result(conn, fsstate->query);
3814  /* On error, report the original query, not the FETCH. */
3816  pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3817 
3818  /* Reset per-connection state */
3819  fsstate->conn_state->pendingAreq = NULL;
3820  }
3821  else
3822  {
3823  char sql[64];
3824 
3825  /* This is a regular synchronous fetch. */
3826  snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
3827  fsstate->fetch_size, fsstate->cursor_number);
3828 
3829  res = pgfdw_exec_query(conn, sql, fsstate->conn_state);
3830  /* On error, report the original query, not the FETCH. */
3832  pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3833  }
3834 
3835  /* Convert the data into HeapTuples */
3836  numrows = PQntuples(res);
3837  fsstate->tuples = (HeapTuple *) palloc0(numrows * sizeof(HeapTuple));
3838  fsstate->num_tuples = numrows;
3839  fsstate->next_tuple = 0;
3840 
3841  for (i = 0; i < numrows; i++)
3842  {
3843  Assert(IsA(node->ss.ps.plan, ForeignScan));
3844 
3845  fsstate->tuples[i] =
3847  fsstate->rel,
3848  fsstate->attinmeta,
3849  fsstate->retrieved_attrs,
3850  node,
3851  fsstate->temp_cxt);
3852  }
3853 
3854  /* Update fetch_ct_2 */
3855  if (fsstate->fetch_ct_2 < 2)
3856  fsstate->fetch_ct_2++;
3857 
3858  /* Must be EOF if we didn't get as many tuples as we asked for. */
3859  fsstate->eof_reached = (numrows < fsstate->fetch_size);
3860  }
3861  PG_FINALLY();
3862  {
3863  PQclear(res);
3864  }
3865  PG_END_TRY();
3866 
3867  MemoryContextSwitchTo(oldcontext);
3868 }
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_FINALLY(...)
Definition: elog.h:387
List * retrieved_attrs
Definition: postgres_fdw.c:147
AttInMetadata * attinmeta
Definition: postgres_fdw.c:143
MemoryContext batch_cxt
Definition: postgres_fdw.c:172
MemoryContext temp_cxt
Definition: postgres_fdw.c:173

References Assert(), PgFdwScanState::async_capable, PgFdwScanState::attinmeta, PgFdwScanState::batch_cxt, PgFdwScanState::conn, conn, PgFdwScanState::conn_state, PgFdwScanState::cursor_number, PgFdwScanState::eof_reached, ERROR, ForeignScanState::fdw_state, PgFdwScanState::fetch_ct_2, PgFdwScanState::fetch_size, i, IsA, make_tuple_from_result_row(), MemoryContextReset(), MemoryContextSwitchTo(), PgFdwScanState::next_tuple, PgFdwScanState::num_tuples, palloc0(), PgFdwConnState::pendingAreq, PG_END_TRY, PG_FINALLY, PG_TRY, pgfdw_exec_query(), pgfdw_get_result(), pgfdw_report_error(), PGRES_TUPLES_OK, PlanState::plan, PQclear(), PQntuples(), PQresultStatus(), ScanState::ps, PgFdwScanState::query, PgFdwScanState::rel, res, PgFdwScanState::retrieved_attrs, snprintf, ForeignScanState::ss, PgFdwScanState::temp_cxt, and PgFdwScanState::tuples.

Referenced by postgresForeignAsyncNotify(), postgresIterateForeignScan(), postgresReScanForeignScan(), and process_pending_request().

◆ fetch_more_data_begin()

static void fetch_more_data_begin ( AsyncRequest areq)
static

Definition at line 7420 of file postgres_fdw.c.

7421 {
7422  ForeignScanState *node = (ForeignScanState *) areq->requestee;
7423  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7424  char sql[64];
7425 
7426  Assert(!fsstate->conn_state->pendingAreq);
7427 
7428  /* Create the cursor synchronously. */
7429  if (!fsstate->cursor_exists)
7430  create_cursor(node);
7431 
7432  /* We will send this query, but not wait for the response. */
7433  snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
7434  fsstate->fetch_size, fsstate->cursor_number);
7435 
7436  if (!PQsendQuery(fsstate->conn, sql))
7437  pgfdw_report_error(ERROR, NULL, fsstate->conn, false, fsstate->query);
7438 
7439  /* Remember that the request is in process */
7440  fsstate->conn_state->pendingAreq = areq;
7441 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1422
static void create_cursor(ForeignScanState *node)

References Assert(), create_cursor(), ERROR, ForeignScanState::fdw_state, pgfdw_report_error(), PQsendQuery(), AsyncRequest::requestee, and snprintf.

Referenced by postgresForeignAsyncConfigureWait(), and produce_tuple_asynchronously().

◆ find_em_for_rel()

EquivalenceMember* find_em_for_rel ( PlannerInfo root,
EquivalenceClass ec,
RelOptInfo rel 
)

Definition at line 7774 of file postgres_fdw.c.

7775 {
7776  ListCell *lc;
7777 
7778  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
7779 
7780  foreach(lc, ec->ec_members)
7781  {
7783 
7784  /*
7785  * Note we require !bms_is_empty, else we'd accept constant
7786  * expressions which are not suitable for the purpose.
7787  */
7788  if (bms_is_subset(em->em_relids, rel->relids) &&
7789  !bms_is_empty(em->em_relids) &&
7791  is_foreign_expr(root, rel, em->em_expr))
7792  return em;
7793  }
7794 
7795  return NULL;
7796 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:363
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:248
#define bms_is_empty(a)
Definition: bitmapset.h:105
Relids hidden_subquery_rels
Definition: postgres_fdw.h:121
Relids relids
Definition: pathnodes.h:856

References bms_intersect(), bms_is_empty, bms_is_subset(), EquivalenceClass::ec_members, EquivalenceMember::em_expr, EquivalenceMember::em_relids, PgFdwRelationInfo::hidden_subquery_rels, is_foreign_expr(), lfirst, and RelOptInfo::relids.

Referenced by appendOrderByClause(), get_useful_pathkeys_for_relation(), and is_foreign_pathkey().

◆ find_em_for_rel_target()

EquivalenceMember* find_em_for_rel_target ( PlannerInfo root,
EquivalenceClass ec,
RelOptInfo rel 
)

Definition at line 7810 of file postgres_fdw.c.

7812 {
7813  PathTarget *target = rel->reltarget;
7814  ListCell *lc1;
7815  int i;
7816 
7817  i = 0;
7818  foreach(lc1, target->exprs)
7819  {
7820  Expr *expr = (Expr *) lfirst(lc1);
7821  Index sgref = get_pathtarget_sortgroupref(target, i);
7822  ListCell *lc2;
7823 
7824  /* Ignore non-sort expressions */
7825  if (sgref == 0 ||
7827  root->parse->sortClause) == NULL)
7828  {
7829  i++;
7830  continue;
7831  }
7832 
7833  /* We ignore binary-compatible relabeling on both ends */
7834  while (expr && IsA(expr, RelabelType))
7835  expr = ((RelabelType *) expr)->arg;
7836 
7837  /* Locate an EquivalenceClass member matching this expr, if any */
7838  foreach(lc2, ec->ec_members)
7839  {
7841  Expr *em_expr;
7842 
7843  /* Don't match constants */
7844  if (em->em_is_const)
7845  continue;
7846 
7847  /* Ignore child members */
7848  if (em->em_is_child)
7849  continue;
7850 
7851  /* Match if same expression (after stripping relabel) */
7852  em_expr = em->em_expr;
7853  while (em_expr && IsA(em_expr, RelabelType))
7854  em_expr = ((RelabelType *) em_expr)->arg;
7855 
7856  if (!equal(em_expr, expr))
7857  continue;
7858 
7859  /* Check that expression (including relabels!) is shippable */
7860  if (is_foreign_expr(root, rel, em->em_expr))
7861  return em;
7862  }
7863 
7864  i++;
7865  }
7866 
7867  return NULL;
7868 }
unsigned int Index
Definition: c.h:603
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1517
List * exprs
Definition: pathnodes.h:1501
List * sortClause
Definition: parsenodes.h:201
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:443

References arg, EquivalenceClass::ec_members, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, equal(), PathTarget::exprs, get_pathtarget_sortgroupref, get_sortgroupref_clause_noerr(), i, is_foreign_expr(), IsA, lfirst, PlannerInfo::parse, RelOptInfo::reltarget, and Query::sortClause.

Referenced by add_foreign_ordered_paths(), and appendOrderByClause().

◆ find_modifytable_subplan()

static ForeignScan* find_modifytable_subplan ( PlannerInfo root,
ModifyTable plan,
Index  rtindex,
int  subplan_index 
)
static

Definition at line 2374 of file postgres_fdw.c.

2378 {
2379  Plan *subplan = outerPlan(plan);
2380 
2381  /*
2382  * The cases we support are (1) the desired ForeignScan is the immediate
2383  * child of ModifyTable, or (2) it is the subplan_index'th child of an
2384  * Append node that is the immediate child of ModifyTable. There is no
2385  * point in looking further down, as that would mean that local joins are
2386  * involved, so we can't do the update directly.
2387  *
2388  * There could be a Result atop the Append too, acting to compute the
2389  * UPDATE targetlist values. We ignore that here; the tlist will be
2390  * checked by our caller.
2391  *
2392  * In principle we could examine all the children of the Append, but it's
2393  * currently unlikely that the core planner would generate such a plan
2394  * with the children out-of-order. Moreover, such a search risks costing
2395  * O(N^2) time when there are a lot of children.
2396  */
2397  if (IsA(subplan, Append))
2398  {
2399  Append *appendplan = (Append *) subplan;
2400 
2401  if (subplan_index < list_length(appendplan->appendplans))
2402  subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2403  }
2404  else if (IsA(subplan, Result) &&
2405  outerPlan(subplan) != NULL &&
2406  IsA(outerPlan(subplan), Append))
2407  {
2408  Append *appendplan = (Append *) outerPlan(subplan);
2409 
2410  if (subplan_index < list_length(appendplan->appendplans))
2411  subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2412  }
2413 
2414  /* Now, have we got a ForeignScan on the desired rel? */
2415  if (IsA(subplan, ForeignScan))
2416  {
2417  ForeignScan *fscan = (ForeignScan *) subplan;
2418 
2419  if (bms_is_member(rtindex, fscan->fs_base_relids))
2420  return fscan;
2421  }
2422 
2423  return NULL;
2424 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:460
#define plan(x)
Definition: pg_regress.c:162
#define outerPlan(node)
Definition: plannodes.h:182
List * appendplans
Definition: plannodes.h:267
Bitmapset * fs_base_relids
Definition: plannodes.h:718

References Append::appendplans, bms_is_member(), ForeignScan::fs_base_relids, IsA, list_length(), list_nth(), outerPlan, and plan.

Referenced by postgresPlanDirectModify().

◆ finish_foreign_modify()

static void finish_foreign_modify ( PgFdwModifyState fmstate)
static

Definition at line 4363 of file postgres_fdw.c.

4364 {
4365  Assert(fmstate != NULL);
4366 
4367  /* If we created a prepared statement, destroy it */
4368  deallocate_query(fmstate);
4369 
4370  /* Release remote connection */
4371  ReleaseConnection(fmstate->conn);
4372  fmstate->conn = NULL;
4373 }

References Assert(), PgFdwModifyState::conn, deallocate_query(), and ReleaseConnection().

Referenced by postgresEndForeignInsert(), and postgresEndForeignModify().

◆ foreign_grouping_ok()

static bool foreign_grouping_ok ( PlannerInfo root,
RelOptInfo grouped_rel,
Node havingQual 
)
static

Definition at line 6458 of file postgres_fdw.c.

6460 {
6461  Query *query = root->parse;
6462  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) grouped_rel->fdw_private;
6463  PathTarget *grouping_target = grouped_rel->reltarget;
6464  PgFdwRelationInfo *ofpinfo;
6465  ListCell *lc;
6466  int i;
6467  List *tlist = NIL;
6468 
6469  /* We currently don't support pushing Grouping Sets. */
6470  if (query->groupingSets)
6471  return false;
6472 
6473  /* Get the fpinfo of the underlying scan relation. */
6474  ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
6475 
6476  /*
6477  * If underlying scan relation has any local conditions, those conditions
6478  * are required to be applied before performing aggregation. Hence the
6479  * aggregate cannot be pushed down.
6480  */
6481  if (ofpinfo->local_conds)
6482  return false;
6483 
6484  /*
6485  * Examine grouping expressions, as well as other expressions we'd need to
6486  * compute, and check whether they are safe to push down to the foreign
6487  * server. All GROUP BY expressions will be part of the grouping target
6488  * and thus there is no need to search for them separately. Add grouping
6489  * expressions into target list which will be passed to foreign server.
6490  *
6491  * A tricky fine point is that we must not put any expression into the
6492  * target list that is just a foreign param (that is, something that
6493  * deparse.c would conclude has to be sent to the foreign server). If we
6494  * do, the expression will also appear in the fdw_exprs list of the plan
6495  * node, and setrefs.c will get confused and decide that the fdw_exprs
6496  * entry is actually a reference to the fdw_scan_tlist entry, resulting in
6497  * a broken plan. Somewhat oddly, it's OK if the expression contains such
6498  * a node, as long as it's not at top level; then no match is possible.
6499  */
6500  i = 0;
6501  foreach(lc, grouping_target->exprs)
6502  {
6503  Expr *expr = (Expr *) lfirst(lc);
6504  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
6505  ListCell *l;
6506 
6507  /*
6508  * Check whether this expression is part of GROUP BY clause. Note we
6509  * check the whole GROUP BY clause not just processed_groupClause,
6510  * because we will ship all of it, cf. appendGroupByClause.
6511  */
6512  if (sgref && get_sortgroupref_clause_noerr(sgref, query->groupClause))
6513  {
6514  TargetEntry *tle;
6515 
6516  /*
6517  * If any GROUP BY expression is not shippable, then we cannot
6518  * push down aggregation to the foreign server.
6519  */
6520  if (!is_foreign_expr(root, grouped_rel, expr))
6521  return false;
6522 
6523  /*
6524  * If it would be a foreign param, we can't put it into the tlist,
6525  * so we have to fail.
6526  */
6527  if (is_foreign_param(root, grouped_rel, expr))
6528  return false;
6529 
6530  /*
6531  * Pushable, so add to tlist. We need to create a TLE for this
6532  * expression and apply the sortgroupref to it. We cannot use
6533  * add_to_flat_tlist() here because that avoids making duplicate
6534  * entries in the tlist. If there are duplicate entries with
6535  * distinct sortgrouprefs, we have to duplicate that situation in
6536  * the output tlist.
6537  */
6538  tle = makeTargetEntry(expr, list_length(tlist) + 1, NULL, false);
6539  tle->ressortgroupref = sgref;
6540  tlist = lappend(tlist, tle);
6541  }
6542  else
6543  {
6544  /*
6545  * Non-grouping expression we need to compute. Can we ship it
6546  * as-is to the foreign server?
6547  */
6548  if (is_foreign_expr(root, grouped_rel, expr) &&
6549  !is_foreign_param(root, grouped_rel, expr))
6550  {
6551  /* Yes, so add to tlist as-is; OK to suppress duplicates */
6552  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6553  }
6554  else
6555  {
6556  /* Not pushable as a whole; extract its Vars and aggregates */
6557  List *aggvars;
6558 
6559  aggvars = pull_var_clause((Node *) expr,
6561 
6562  /*
6563  * If any aggregate expression is not shippable, then we
6564  * cannot push down aggregation to the foreign server. (We
6565  * don't have to check is_foreign_param, since that certainly
6566  * won't return true for any such expression.)
6567  */
6568  if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars))
6569  return false;
6570 
6571  /*
6572  * Add aggregates, if any, into the targetlist. Plain Vars
6573  * outside an aggregate can be ignored, because they should be
6574  * either same as some GROUP BY column or part of some GROUP
6575  * BY expression. In either case, they are already part of
6576  * the targetlist and thus no need to add them again. In fact
6577  * including plain Vars in the tlist when they do not match a
6578  * GROUP BY column would cause the foreign server to complain
6579  * that the shipped query is invalid.
6580  */
6581  foreach(l, aggvars)
6582  {
6583  Expr *aggref = (Expr *) lfirst(l);
6584 
6585  if (IsA(aggref, Aggref))
6586  tlist = add_to_flat_tlist(tlist, list_make1(aggref));
6587  }
6588  }
6589  }
6590 
6591  i++;
6592  }
6593 
6594  /*
6595  * Classify the pushable and non-pushable HAVING clauses and save them in
6596  * remote_conds and local_conds of the grouped rel's fpinfo.
6597  */
6598  if (havingQual)
6599  {
6600  foreach(lc, (List *) havingQual)
6601  {
6602  Expr *expr = (Expr *) lfirst(lc);
6603  RestrictInfo *rinfo;
6604 
6605  /*
6606  * Currently, the core code doesn't wrap havingQuals in
6607  * RestrictInfos, so we must make our own.
6608  */
6609  Assert(!IsA(expr, RestrictInfo));
6610  rinfo = make_restrictinfo(root,
6611  expr,
6612  true,
6613  false,
6614  false,
6615  false,
6616  root->qual_security_level,
6617  grouped_rel->relids,
6618  NULL,
6619  NULL);
6620  if (is_foreign_expr(root, grouped_rel, expr))
6621  fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
6622  else
6623  fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
6624  }
6625  }
6626 
6627  /*
6628  * If there are any local conditions, pull Vars and aggregates from it and
6629  * check whether they are safe to pushdown or not.
6630  */
6631  if (fpinfo->local_conds)
6632  {
6633  List *aggvars = NIL;
6634 
6635  foreach(lc, fpinfo->local_conds)
6636  {
6637  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
6638 
6639  aggvars = list_concat(aggvars,
6640  pull_var_clause((Node *) rinfo->clause,
6642  }
6643 
6644  foreach(lc, aggvars)
6645  {
6646  Expr *expr = (Expr *) lfirst(lc);
6647 
6648  /*
6649  * If aggregates within local conditions are not safe to push
6650  * down, then we cannot push down the query. Vars are already
6651  * part of GROUP BY clause which are checked above, so no need to
6652  * access them again here. Again, we need not check
6653  * is_foreign_param for a foreign aggregate.
6654  */
6655  if (IsA(expr, Aggref))
6656  {
6657  if (!is_foreign_expr(root, grouped_rel, expr))
6658  return false;
6659 
6660  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6661  }
6662  }
6663  }
6664 
6665  /* Store generated targetlist */
6666  fpinfo->grouped_tlist = tlist;
6667 
6668  /* Safe to pushdown */
6669  fpinfo->pushdown_safe = true;
6670 
6671  /*
6672  * Set # of retrieved rows and cached relation costs to some negative
6673  * value, so that we can detect when they are set to some sensible values,
6674  * during one (usually the first) of the calls to estimate_path_cost_size.
6675  */
6676  fpinfo->retrieved_rows = -1;
6677  fpinfo->rel_startup_cost = -1;
6678  fpinfo->rel_total_cost = -1;
6679 
6680  /*
6681  * Set the string describing this grouped relation to be used in EXPLAIN
6682  * output of corresponding ForeignScan. Note that the decoration we add
6683  * to the base relation name mustn't include any digits, or it'll confuse
6684  * postgresExplainForeignScan.
6685  */
6686  fpinfo->relation_name = psprintf("Aggregate on (%s)",
6687  ofpinfo->relation_name);
6688 
6689  return true;
6690 }
bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:1082
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:185
#define list_make1(x1)
Definition: pg_list.h:212
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
RestrictInfo * make_restrictinfo(PlannerInfo *root, Expr *clause, bool is_pushed_down, bool has_clone, bool is_clone, bool pseudoconstant, Index security_level, Relids required_relids, Relids incompatible_relids, Relids outer_relids)
Definition: restrictinfo.c:63
Index qual_security_level
Definition: pathnodes.h:486
List * groupClause
Definition: parsenodes.h:190
List * groupingSets
Definition: parsenodes.h:193
Index ressortgroupref
Definition: primnodes.h:1928
List * add_to_flat_tlist(List *tlist, List *exprs)
Definition: tlist.c:132

References add_to_flat_tlist(), Assert(), RestrictInfo::clause, get_pathtarget_sortgroupref, get_sortgroupref_clause_noerr(), Query::groupClause, PgFdwRelationInfo::grouped_tlist, Query::groupingSets, i, if(), is_foreign_expr(), is_foreign_param(), IsA, lappend(), lfirst, lfirst_node, list_concat(), list_length(), list_make1, PgFdwRelationInfo::local_conds, make_restrictinfo(), makeTargetEntry(), NIL, PgFdwRelationInfo::outerrel, PlannerInfo::parse, psprintf(), pull_var_clause(), PgFdwRelationInfo::pushdown_safe, PVC_INCLUDE_AGGREGATES, PlannerInfo::qual_security_level, PgFdwRelationInfo::rel_startup_cost, PgFdwRelationInfo::rel_total_cost, PgFdwRelationInfo::relation_name, RelOptInfo::relids, RelOptInfo::reltarget, PgFdwRelationInfo::remote_conds, TargetEntry::ressortgroupref, and PgFdwRelationInfo::retrieved_rows.

Referenced by add_foreign_grouping_paths().

◆ foreign_join_ok()

static bool foreign_join_ok ( PlannerInfo root,
RelOptInfo joinrel,
JoinType  jointype,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinPathExtraData extra 
)
static

Definition at line 5773 of file postgres_fdw.c.

5776 {
5777  PgFdwRelationInfo *fpinfo;
5778  PgFdwRelationInfo *fpinfo_o;
5779  PgFdwRelationInfo *fpinfo_i;
5780  ListCell *lc;
5781  List *joinclauses;
5782 
5783  /*
5784  * We support pushing down INNER, LEFT, RIGHT, FULL OUTER and SEMI joins.
5785  * Constructing queries representing ANTI joins is hard, hence not
5786  * considered right now.
5787  */
5788  if (jointype != JOIN_INNER && jointype != JOIN_LEFT &&
5789  jointype != JOIN_RIGHT && jointype != JOIN_FULL &&
5790  jointype != JOIN_SEMI)
5791  return false;
5792 
5793  /*
5794  * We can't push down semi-join if its reltarget is not safe
5795  */
5796  if ((jointype == JOIN_SEMI) && !semijoin_target_ok(root, joinrel, outerrel, innerrel))
5797  return false;
5798 
5799  /*
5800  * If either of the joining relations is marked as unsafe to pushdown, the
5801  * join can not be pushed down.
5802  */
5803  fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private;
5804  fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private;
5805  fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private;
5806  if (!fpinfo_o || !fpinfo_o->pushdown_safe ||
5807  !fpinfo_i || !fpinfo_i->pushdown_safe)
5808  return false;
5809 
5810  /*
5811  * If joining relations have local conditions, those conditions are
5812  * required to be applied before joining the relations. Hence the join can
5813  * not be pushed down.
5814  */
5815  if (fpinfo_o->local_conds || fpinfo_i->local_conds)
5816  return false;
5817 
5818  /*
5819  * Merge FDW options. We might be tempted to do this after we have deemed
5820  * the foreign join to be OK. But we must do this beforehand so that we
5821  * know which quals can be evaluated on the foreign server, which might
5822  * depend on shippable_extensions.
5823  */
5824  fpinfo->server = fpinfo_o->server;
5825  merge_fdw_options(fpinfo, fpinfo_o, fpinfo_i);
5826 
5827  /*
5828  * Separate restrict list into join quals and pushed-down (other) quals.
5829  *
5830  * Join quals belonging to an outer join must all be shippable, else we
5831  * cannot execute the join remotely. Add such quals to 'joinclauses'.
5832  *
5833  * Add other quals to fpinfo->remote_conds if they are shippable, else to
5834  * fpinfo->local_conds. In an inner join it's okay to execute conditions
5835  * either locally or remotely; the same is true for pushed-down conditions
5836  * at an outer join.
5837  *
5838  * Note we might return failure after having already scribbled on
5839  * fpinfo->remote_conds and fpinfo->local_conds. That's okay because we
5840  * won't consult those lists again if we deem the join unshippable.
5841  */
5842  joinclauses = NIL;
5843  foreach(lc, extra->restrictlist)
5844  {
5845  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
5846  bool is_remote_clause = is_foreign_expr(root, joinrel,
5847  rinfo->clause);
5848 
5849  if (IS_OUTER_JOIN(jointype) &&
5850  !RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5851  {
5852  if (!is_remote_clause)
5853  return false;
5854  joinclauses = lappend(joinclauses, rinfo);
5855  }
5856  else
5857  {
5858  if (is_remote_clause)
5859  fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
5860  else
5861  fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
5862  }
5863  }
5864 
5865  /*
5866  * deparseExplicitTargetList() isn't smart enough to handle anything other
5867  * than a Var. In particular, if there's some PlaceHolderVar that would
5868  * need to be evaluated within this join tree (because there's an upper
5869  * reference to a quantity that may go to NULL as a result of an outer
5870  * join), then we can't try to push the join down because we'll fail when
5871  * we get to deparseExplicitTargetList(). However, a PlaceHolderVar that
5872  * needs to be evaluated *at the top* of this join tree is OK, because we
5873  * can do that locally after fetching the results from the remote side.
5874  */
5875  foreach(lc, root->placeholder_list)
5876  {
5877  PlaceHolderInfo *phinfo = lfirst(lc);
5878  Relids relids;
5879 
5880  /* PlaceHolderInfo refers to parent relids, not child relids. */
5881  relids = IS_OTHER_REL(joinrel) ?
5882  joinrel->top_parent_relids : joinrel->relids;
5883 
5884  if (bms_is_subset(phinfo->ph_eval_at, relids) &&
5885  bms_nonempty_difference(relids, phinfo->ph_eval_at))
5886  return false;
5887  }
5888 
5889  /* Save the join clauses, for later use. */
5890  fpinfo->joinclauses = joinclauses;
5891 
5892  fpinfo->outerrel = outerrel;
5893  fpinfo->innerrel = innerrel;
5894  fpinfo->jointype = jointype;
5895 
5896  /*
5897  * By default, both the input relations are not required to be deparsed as
5898  * subqueries, but there might be some relations covered by the input
5899  * relations that are required to be deparsed as subqueries, so save the
5900  * relids of those relations for later use by the deparser.
5901  */
5902  fpinfo->make_outerrel_subquery = false;
5903  fpinfo->make_innerrel_subquery = false;
5904  Assert(bms_is_subset(fpinfo_o->lower_subquery_rels, outerrel->relids));
5905  Assert(bms_is_subset(fpinfo_i->lower_subquery_rels, innerrel->relids));
5907  fpinfo_i->lower_subquery_rels);
5909  fpinfo_i->hidden_subquery_rels);
5910 
5911  /*
5912  * Pull the other remote conditions from the joining relations into join
5913  * clauses or other remote clauses (remote_conds) of this relation
5914  * wherever possible. This avoids building subqueries at every join step.
5915  *
5916  * For an inner join, clauses from both the relations are added to the
5917  * other remote clauses. For LEFT and RIGHT OUTER join, the clauses from
5918  * the outer side are added to remote_conds since those can be evaluated
5919  * after the join is evaluated. The clauses from inner side are added to
5920  * the joinclauses, since they need to be evaluated while constructing the
5921  * join.
5922  *
5923  * For SEMI-JOIN clauses from inner relation can not be added to
5924  * remote_conds, but should be treated as join clauses (as they are
5925  * deparsed to EXISTS subquery, where inner relation can be referred). A
5926  * list of relation ids, which can't be referred to from higher levels, is
5927  * preserved as a hidden_subquery_rels list.
5928  *
5929  * For a FULL OUTER JOIN, the other clauses from either relation can not
5930  * be added to the joinclauses or remote_conds, since each relation acts
5931  * as an outer relation for the other.
5932  *
5933  * The joining sides can not have local conditions, thus no need to test
5934  * shippability of the clauses being pulled up.
5935  */
5936  switch (jointype)
5937  {
5938  case JOIN_INNER:
5939  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5940  fpinfo_i->remote_conds);
5941  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5942  fpinfo_o->remote_conds);
5943  break;
5944 
5945  case JOIN_LEFT:
5946  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5947  fpinfo_i->remote_conds);
5948  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5949  fpinfo_o->remote_conds);
5950  break;
5951 
5952  case JOIN_RIGHT:
5953  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5954  fpinfo_o->remote_conds);
5955  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5956  fpinfo_i->remote_conds);
5957  break;
5958 
5959  case JOIN_SEMI:
5960  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5961  fpinfo_i->remote_conds);
5962  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5963  fpinfo->remote_conds);
5964  fpinfo->remote_conds = list_copy(fpinfo_o->remote_conds);
5966  innerrel->relids);
5967  break;
5968 
5969  case JOIN_FULL:
5970 
5971  /*
5972  * In this case, if any of the input relations has conditions, we
5973  * need to deparse that relation as a subquery so that the
5974  * conditions can be evaluated before the join. Remember it in
5975  * the fpinfo of this relation so that the deparser can take
5976  * appropriate action. Also, save the relids of base relations
5977  * covered by that relation for later use by the deparser.
5978  */
5979  if (fpinfo_o->remote_conds)
5980  {
5981  fpinfo->make_outerrel_subquery = true;
5982  fpinfo->lower_subquery_rels =
5984  outerrel->relids);
5985  }
5986  if (fpinfo_i->remote_conds)
5987  {
5988  fpinfo->make_innerrel_subquery = true;
5989  fpinfo->lower_subquery_rels =
5991  innerrel->relids);
5992  }
5993  break;
5994 
5995  default:
5996  /* Should not happen, we have just checked this above */
5997  elog(ERROR, "unsupported join type %d", jointype);
5998  }
5999 
6000  /*
6001  * For an inner join, all restrictions can be treated alike. Treating the
6002  * pushed down conditions as join conditions allows a top level full outer
6003  * join to be deparsed without requiring subqueries.
6004  */
6005  if (jointype == JOIN_INNER)
6006  {
6007  Assert(!fpinfo->joinclauses);
6008  fpinfo->joinclauses = fpinfo->remote_conds;
6009  fpinfo->remote_conds = NIL;
6010  }
6011  else if (jointype == JOIN_LEFT || jointype == JOIN_RIGHT || jointype == JOIN_FULL)
6012  {
6013  /*
6014  * Conditions, generated from semi-joins, should be evaluated before
6015  * LEFT/RIGHT/FULL join.
6016  */
6017  if (!bms_is_empty(fpinfo_o->hidden_subquery_rels))
6018  {
6019  fpinfo->make_outerrel_subquery = true;
6020  fpinfo->lower_subquery_rels = bms_add_members(fpinfo->lower_subquery_rels, outerrel->relids);
6021  }
6022 
6023  if (!bms_is_empty(fpinfo_i->hidden_subquery_rels))
6024  {
6025  fpinfo->make_innerrel_subquery = true;
6026  fpinfo->lower_subquery_rels = bms_add_members(fpinfo->lower_subquery_rels, innerrel->relids);
6027  }
6028  }
6029 
6030  /* Mark that this join can be pushed down safely */
6031  fpinfo->pushdown_safe = true;
6032 
6033  /* Get user mapping */
6034  if (fpinfo->use_remote_estimate)
6035  {
6036  if (fpinfo_o->use_remote_estimate)
6037  fpinfo->user = fpinfo_o->user;
6038  else
6039  fpinfo->user = fpinfo_i->user;
6040  }
6041  else
6042  fpinfo->user = NULL;
6043 
6044  /*
6045  * Set # of retrieved rows and cached relation costs to some negative
6046  * value, so that we can detect when they are set to some sensible values,
6047  * during one (usually the first) of the calls to estimate_path_cost_size.
6048  */
6049  fpinfo->retrieved_rows = -1;
6050  fpinfo->rel_startup_cost = -1;
6051  fpinfo->rel_total_cost = -1;
6052 
6053  /*
6054  * Set the string describing this join relation to be used in EXPLAIN
6055  * output of corresponding ForeignScan. Note that the decoration we add
6056  * to the base relation names mustn't include any digits, or it'll confuse
6057  * postgresExplainForeignScan.
6058  */
6059  fpinfo->relation_name = psprintf("(%s) %s JOIN (%s)",
6060  fpinfo_o->relation_name,
6061  get_jointype_name(fpinfo->jointype),
6062  fpinfo_i->relation_name);
6063 
6064  /*
6065  * Set the relation index. This is defined as the position of this
6066  * joinrel in the join_rel_list list plus the length of the rtable list.
6067  * Note that since this joinrel is at the end of the join_rel_list list
6068  * when we are called, we can get the position by list_length.
6069  */
6070  Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */
6071  fpinfo->relation_index =
6073 
6074  return true;
6075 }
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:211
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:835
bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:581
const char * get_jointype_name(JoinType jointype)
Definition: deparse.c:1641
List * list_copy(const List *oldlist)
Definition: list.c:1572
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:348
@ JOIN_SEMI
Definition: nodes.h:318
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_RIGHT
Definition: nodes.h:307
@ JOIN_LEFT
Definition: nodes.h:305
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2683
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:839
static bool semijoin_target_ok(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel)
Relids lower_subquery_rels
Definition: postgres_fdw.h:119
Relids ph_eval_at
Definition: pathnodes.h:3047
List * join_rel_list
Definition: pathnodes.h:277
List * placeholder_list
Definition: pathnodes.h:371
List * rtable
Definition: parsenodes.h:167
Relids top_parent_relids
Definition: pathnodes.h:988

References Assert(), bms_add_members(), bms_is_empty, bms_is_subset(), bms_nonempty_difference(), bms_union(), RestrictInfo::clause, elog(), ERROR, get_jointype_name(), PgFdwRelationInfo::hidden_subquery_rels, if(), PgFdwRelationInfo::innerrel, is_foreign_expr(), IS_OTHER_REL, IS_OUTER_JOIN, JOIN_FULL, JOIN_INNER, JOIN_LEFT, PlannerInfo::join_rel_list, JOIN_RIGHT, JOIN_SEMI, PgFdwRelationInfo::joinclauses, PgFdwRelationInfo::jointype, lappend(), lfirst, lfirst_node, list_concat(), list_copy(), list_length(), PgFdwRelationInfo::local_conds, PgFdwRelationInfo::lower_subquery_rels, PgFdwRelationInfo::make_innerrel_subquery, PgFdwRelationInfo::make_outerrel_subquery, merge_fdw_options(), NIL, PgFdwRelationInfo::outerrel, PlannerInfo::parse, PlaceHolderInfo::ph_eval_at, PlannerInfo::placeholder_list, psprintf(), PgFdwRelationInfo::pushdown_safe, PgFdwRelationInfo::rel_startup_cost, PgFdwRelationInfo::rel_total_cost, PgFdwRelationInfo::relation_index, PgFdwRelationInfo::relation_name, RelOptInfo::relids, PgFdwRelationInfo::remote_conds, JoinPathExtraData::restrictlist, PgFdwRelationInfo::retrieved_rows, RINFO_IS_PUSHED_DOWN, Query::rtable, semijoin_target_ok(), PgFdwRelationInfo::server, RelOptInfo::top_parent_relids, PgFdwRelationInfo::use_remote_estimate, and PgFdwRelationInfo::user.

Referenced by postgresGetForeignJoinPaths().

◆ get_batch_size_option()

static int get_batch_size_option ( Relation  rel)
static

Definition at line 7875 of file postgres_fdw.c.

7876 {
7877  Oid foreigntableid = RelationGetRelid(rel);
7878  ForeignTable *table;
7879  ForeignServer *server;
7880  List *options;
7881  ListCell *lc;
7882 
7883  /* we use 1 by default, which means "no batching" */
7884  int batch_size = 1;
7885 
7886  /*
7887  * Load options for table and server. We append server options after table
7888  * options, because table options take precedence.
7889  */
7890  table = GetForeignTable(foreigntableid);
7891  server = GetForeignServer(table->serverid);
7892 
7893  options = NIL;
7894  options = list_concat(options, table->options);
7895  options = list_concat(options, server->options);
7896 
7897  /* See if either table or server specifies batch_size. */
7898  foreach(lc, options)
7899  {
7900  DefElem *def = (DefElem *) lfirst(lc);
7901 
7902  if (strcmp(def->defname, "batch_size") == 0)
7903  {
7904  (void) parse_int(defGetString(def), &batch_size, 0, NULL);
7905  break;
7906  }
7907  }
7908 
7909  return batch_size;
7910 }
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:111
static char ** options

References defGetString(), DefElem::defname, GetForeignServer(), GetForeignTable(), lfirst, list_concat(), NIL, options, ForeignServer::options, ForeignTable::options, parse_int(), RelationGetRelid, and ForeignTable::serverid.

Referenced by create_foreign_modify(), and postgresGetForeignModifyBatchSize().

◆ get_remote_estimate()

static void get_remote_estimate ( const char *  sql,
PGconn conn,
double *  rows,
int *  width,
Cost startup_cost,
Cost total_cost 
)
static

Definition at line 3579 of file postgres_fdw.c.

3582 {
3583  PGresult *volatile res = NULL;
3584 
3585  /* PGresult must be released before leaving this function. */
3586  PG_TRY();
3587  {
3588  char *line;
3589  char *p;
3590  int n;
3591 
3592  /*
3593  * Execute EXPLAIN remotely.
3594  */
3595  res = pgfdw_exec_query(conn, sql, NULL);
3597  pgfdw_report_error(ERROR, res, conn, false, sql);
3598 
3599  /*
3600  * Extract cost numbers for topmost plan node. Note we search for a
3601  * left paren from the end of the line to avoid being confused by
3602  * other uses of parentheses.
3603  */
3604  line = PQgetvalue(res, 0, 0);
3605  p = strrchr(line, '(');
3606  if (p == NULL)
3607  elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3608  n = sscanf(p, "(cost=%lf..%lf rows=%lf width=%d)",
3609  startup_cost, total_cost, rows, width);
3610  if (n != 4)
3611  elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3612  }
3613  PG_FINALLY();
3614  {
3615  PQclear(res);
3616  }
3617  PG_END_TRY();
3618 }
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3817

References conn, elog(), ERROR, PG_END_TRY, PG_FINALLY, PG_TRY, pgfdw_exec_query(), pgfdw_report_error(), PGRES_TUPLES_OK, PQclear(), PQgetvalue(), PQresultStatus(), and res.

Referenced by estimate_path_cost_size().

◆ get_returning_data()

static TupleTableSlot * get_returning_data ( ForeignScanState node)
static

Definition at line 4591 of file postgres_fdw.c.

4592 {
4594  EState *estate = node->ss.ps.state;
4595  ResultRelInfo *resultRelInfo = node->resultRelInfo;
4596  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
4597  TupleTableSlot *resultSlot;
4598 
4599  Assert(resultRelInfo->ri_projectReturning);
4600 
4601  /* If we didn't get any tuples, must be end of data. */
4602  if (dmstate->next_tuple >= dmstate->num_tuples)
4603  return ExecClearTuple(slot);
4604 
4605  /* Increment the command es_processed count if necessary. */
4606  if (dmstate->set_processed)
4607  estate->es_processed += 1;
4608 
4609  /*
4610  * Store a RETURNING tuple. If has_returning is false, just emit a dummy
4611  * tuple. (has_returning is false when the local query is of the form
4612  * "UPDATE/DELETE .. RETURNING 1" for example.)
4613  */
4614  if (!dmstate->has_returning)
4615  {
4616  ExecStoreAllNullTuple(slot);
4617  resultSlot = slot;
4618  }
4619  else
4620  {
4621  /*
4622  * On error, be sure to release the PGresult on the way out. Callers
4623  * do not have PG_TRY blocks to ensure this happens.
4624  */
4625  PG_TRY();
4626  {
4627  HeapTuple newtup;
4628 
4629  newtup = make_tuple_from_result_row(dmstate->result,
4630  dmstate->next_tuple,
4631  dmstate->rel,
4632  dmstate->attinmeta,
4633  dmstate->retrieved_attrs,
4634  node,
4635  dmstate->temp_cxt);
4636  ExecStoreHeapTuple(newtup, slot, false);
4637  }
4638  PG_CATCH();
4639  {
4640  PQclear(dmstate->result);
4641  PG_RE_THROW();
4642  }
4643  PG_END_TRY();
4644 
4645  /* Get the updated/deleted tuple. */
4646  if (dmstate->rel)
4647  resultSlot = slot;
4648  else
4649  resultSlot = apply_returning_filter(dmstate, resultRelInfo, slot, estate);
4650  }
4651  dmstate->next_tuple++;
4652 
4653  /* Make slot available for evaluation of the local query RETURNING list. */
4654  resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple =
4655  resultSlot;
4656 
4657  return slot;
4658 }
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_CATCH(...)
Definition: elog.h:380
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:1577
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1353
static TupleTableSlot * apply_returning_filter(PgFdwDirectModifyState *dmstate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1956
MemoryContext temp_cxt
Definition: postgres_fdw.c:249
AttInMetadata * attinmeta
Definition: postgres_fdw.c:222
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1476

References apply_returning_filter(), Assert(), PgFdwDirectModifyState::attinmeta, ExecClearTuple(), ExecStoreAllNullTuple(), ExecStoreHeapTuple(), ForeignScanState::fdw_state, PgFdwDirectModifyState::has_returning, make_tuple_from_result_row(), PgFdwDirectModifyState::next_tuple, PgFdwDirectModifyState::num_tuples, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PQclear(), ScanState::ps, PgFdwDirectModifyState::rel, PgFdwDirectModifyState::result, ForeignScanState::resultRelInfo, PgFdwDirectModifyState::retrieved_attrs, PgFdwDirectModifyState::set_processed, ForeignScanState::ss, ScanState::ss_ScanTupleSlot, PlanState::state, and PgFdwDirectModifyState::temp_cxt.

Referenced by postgresIterateDirectModify().

◆ get_tupdesc_for_join_scan_tuples()

static TupleDesc get_tupdesc_for_join_scan_tuples ( ForeignScanState node)
static

Definition at line 1439 of file postgres_fdw.c.

1440 {
1441  ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1442  EState *estate = node->ss.ps.state;
1443  TupleDesc tupdesc;
1444 
1445  /*
1446  * The core code has already set up a scan tuple slot based on
1447  * fsplan->fdw_scan_tlist, and this slot's tupdesc is mostly good enough,
1448  * but there's one case where it isn't. If we have any whole-row row
1449  * identifier Vars, they may have vartype RECORD, and we need to replace
1450  * that with the associated table's actual composite type. This ensures
1451  * that when we read those ROW() expression values from the remote server,
1452  * we can convert them to a composite type the local server knows.
1453  */
1455  for (int i = 0; i < tupdesc->natts; i++)
1456  {
1457  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1458  Var *var;
1459  RangeTblEntry *rte;
1460  Oid reltype;
1461 
1462  /* Nothing to do if it's not a generic RECORD attribute */
1463  if (att->atttypid != RECORDOID || att->atttypmod >= 0)
1464  continue;
1465 
1466  /*
1467  * If we can't identify the referenced table, do nothing. This'll
1468  * likely lead to failure later, but perhaps we can muddle through.
1469  */
1470  var = (Var *) list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
1471  i)->expr;
1472  if (!IsA(var, Var) || var->varattno != 0)
1473  continue;
1474  rte = list_nth(estate->es_range_table, var->varno - 1);
1475  if (rte->rtekind != RTE_RELATION)
1476  continue;
1477  reltype = get_rel_type_id(rte->relid);
1478  if (!OidIsValid(reltype))
1479  continue;
1480  att->atttypid = reltype;
1481  /* shouldn't need to change anything else */
1482  }
1483  return tupdesc;
1484 }
#define OidIsValid(objectId)
Definition: c.h:764
Oid get_rel_type_id(Oid relid)
Definition: lsyscache.c:1983
@ RTE_RELATION
Definition: parsenodes.h:1006
RTEKind rtekind
Definition: parsenodes.h:1025
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133

References CreateTupleDescCopy(), ForeignScan::fdw_scan_tlist, get_rel_type_id(), i, IsA, list_nth(), list_nth_node, OidIsValid, PlanState::plan, ScanState::ps, RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, ForeignScanState::ss, ScanState::ss_ScanTupleSlot, PlanState::state, TupleTableSlot::tts_tupleDescriptor, TupleDescAttr, Var::varattno, and Var::varno.

Referenced by postgresBeginDirectModify(), and postgresBeginForeignScan().

◆ get_useful_ecs_for_relation()

static List * get_useful_ecs_for_relation ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 808 of file postgres_fdw.c.

809 {
810  List *useful_eclass_list = NIL;
811  ListCell *lc;
812  Relids relids;
813 
814  /*
815  * First, consider whether any active EC is potentially useful for a merge
816  * join against this relation.
817  */
818  if (rel->has_eclass_joins)
819  {
820  foreach(lc, root->eq_classes)
821  {
822  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc);
823 
824  if (eclass_useful_for_merging(root, cur_ec, rel))
825  useful_eclass_list = lappend(useful_eclass_list, cur_ec);
826  }
827  }
828 
829  /*
830  * Next, consider whether there are any non-EC derivable join clauses that
831  * are merge-joinable. If the joininfo list is empty, we can exit
832  * quickly.
833  */
834  if (rel->joininfo == NIL)
835  return useful_eclass_list;
836 
837  /* If this is a child rel, we must use the topmost parent rel to search. */
838  if (IS_OTHER_REL(rel))
839  {
841  relids = rel->top_parent_relids;
842  }
843  else
844  relids = rel->relids;
845 
846  /* Check each join clause in turn. */
847  foreach(lc, rel->joininfo)
848  {
849  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
850 
851  /* Consider only mergejoinable clauses */
852  if (restrictinfo->mergeopfamilies == NIL)
853  continue;
854 
855  /* Make sure we've got canonical ECs. */
856  update_mergeclause_eclasses(root, restrictinfo);
857 
858  /*
859  * restrictinfo->mergeopfamilies != NIL is sufficient to guarantee
860  * that left_ec and right_ec will be initialized, per comments in
861  * distribute_qual_to_rels.
862  *
863  * We want to identify which side of this merge-joinable clause
864  * contains columns from the relation produced by this RelOptInfo. We
865  * test for overlap, not containment, because there could be extra
866  * relations on either side. For example, suppose we've got something
867  * like ((A JOIN B ON A.x = B.x) JOIN C ON A.y = C.y) LEFT JOIN D ON
868  * A.y = D.y. The input rel might be the joinrel between A and B, and
869  * we'll consider the join clause A.y = D.y. relids contains a
870  * relation not involved in the join class (B) and the equivalence
871  * class for the left-hand side of the clause contains a relation not
872  * involved in the input rel (C). Despite the fact that we have only
873  * overlap and not containment in either direction, A.y is potentially
874  * useful as a sort column.
875  *
876  * Note that it's even possible that relids overlaps neither side of
877  * the join clause. For example, consider A LEFT JOIN B ON A.x = B.x
878  * AND A.x = 1. The clause A.x = 1 will appear in B's joininfo list,
879  * but overlaps neither side of B. In that case, we just skip this
880  * join clause, since it doesn't suggest a useful sort order for this
881  * relation.
882  */
883  if (bms_overlap(relids, restrictinfo->right_ec->ec_relids))
884  useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
885  restrictinfo->right_ec);
886  else if (bms_overlap(relids, restrictinfo->left_ec->ec_relids))
887  useful_eclass_list = list_append_unique_ptr(useful_eclass_list,
888  restrictinfo->left_ec);
889  }
890 
891  return useful_eclass_list;
892 }
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:527
bool eclass_useful_for_merging(PlannerInfo *root, EquivalenceClass *eclass, RelOptInfo *rel)
Definition: equivclass.c:3136
List * list_append_unique_ptr(List *list, void *datum)
Definition: list.c:1355
void update_mergeclause_eclasses(PlannerInfo *root, RestrictInfo *restrictinfo)
Definition: pathkeys.c:1279
List * eq_classes
Definition: pathnodes.h:311
List * joininfo
Definition: pathnodes.h:970
bool has_eclass_joins
Definition: pathnodes.h:972

References Assert(), bms_is_empty, bms_overlap(), eclass_useful_for_merging(), PlannerInfo::eq_classes, RelOptInfo::has_eclass_joins, IS_OTHER_REL, RelOptInfo::joininfo, lappend(), lfirst, list_append_unique_ptr(), NIL, RelOptInfo::relids, RelOptInfo::top_parent_relids, and update_mergeclause_eclasses().

Referenced by get_useful_pathkeys_for_relation().

◆ get_useful_pathkeys_for_relation()

static List * get_useful_pathkeys_for_relation ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 904 of file postgres_fdw.c.

905 {
906  List *useful_pathkeys_list = NIL;
907  List *useful_eclass_list;
908  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
909  EquivalenceClass *query_ec = NULL;
910  ListCell *lc;
911 
912  /*
913  * Pushing the query_pathkeys to the remote server is always worth
914  * considering, because it might let us avoid a local sort.
915  */
916  fpinfo->qp_is_pushdown_safe = false;
917  if (root->query_pathkeys)
918  {
919  bool query_pathkeys_ok = true;
920 
921  foreach(lc, root->query_pathkeys)
922  {
923  PathKey *pathkey = (PathKey *) lfirst(lc);
924 
925  /*
926  * The planner and executor don't have any clever strategy for
927  * taking data sorted by a prefix of the query's pathkeys and
928  * getting it to be sorted by all of those pathkeys. We'll just
929  * end up resorting the entire data set. So, unless we can push
930  * down all of the query pathkeys, forget it.
931  */
932  if (!is_foreign_pathkey(root, rel, pathkey))
933  {
934  query_pathkeys_ok = false;
935  break;
936  }
937  }
938 
939  if (query_pathkeys_ok)
940  {
941  useful_pathkeys_list = list_make1(list_copy(root->query_pathkeys));
942  fpinfo->qp_is_pushdown_safe = true;
943  }
944  }
945 
946  /*
947  * Even if we're not using remote estimates, having the remote side do the
948  * sort generally won't be any worse than doing it locally, and it might
949  * be much better if the remote side can generate data in the right order
950  * without needing a sort at all. However, what we're going to do next is
951  * try to generate pathkeys that seem promising for possible merge joins,
952  * and that's more speculative. A wrong choice might hurt quite a bit, so
953  * bail out if we can't use remote estimates.
954  */
955  if (!fpinfo->use_remote_estimate)
956  return useful_pathkeys_list;
957 
958  /* Get the list of interesting EquivalenceClasses. */
959  useful_eclass_list = get_useful_ecs_for_relation(root, rel);
960 
961  /* Extract unique EC for query, if any, so we don't consider it again. */
962  if (list_length(root->query_pathkeys) == 1)
963  {
964  PathKey *query_pathkey = linitial(root->query_pathkeys);
965 
966  query_ec = query_pathkey->pk_eclass;
967  }
968 
969  /*
970  * As a heuristic, the only pathkeys we consider here are those of length
971  * one. It's surely possible to consider more, but since each one we
972  * choose to consider will generate a round-trip to the remote side, we
973  * need to be a bit cautious here. It would sure be nice to have a local
974  * cache of information about remote index definitions...
975  */
976  foreach(lc, useful_eclass_list)
977  {
978  EquivalenceClass *cur_ec = lfirst(lc);
979  PathKey *pathkey;
980 
981  /* If redundant with what we did above, skip it. */
982  if (cur_ec == query_ec)
983  continue;
984 
985  /* Can't push down the sort if the EC's opfamily is not shippable. */
987  OperatorFamilyRelationId, fpinfo))
988  continue;
989 
990  /* If no pushable expression for this rel, skip it. */
991  if (find_em_for_rel(root, cur_ec, rel) == NULL)
992  continue;
993 
994  /* Looks like we can generate a pathkey, so let's do it. */
995  pathkey = make_canonical_pathkey(root, cur_ec,
996  linitial_oid(cur_ec->ec_opfamilies),
998  false);
999  useful_pathkeys_list = lappend(useful_pathkeys_list,
1000  list_make1(pathkey));
1001  }
1002 
1003  return useful_pathkeys_list;
1004 }
bool is_foreign_pathkey(PlannerInfo *root, RelOptInfo *baserel, PathKey *pathkey)
Definition: deparse.c:1123
PathKey * make_canonical_pathkey(PlannerInfo *root, EquivalenceClass *eclass, Oid opfamily, int strategy, bool nulls_first)
Definition: pathkeys.c:54
#define linitial(l)
Definition: pg_list.h:178
#define linitial_oid(l)
Definition: pg_list.h:180
EquivalenceMember * find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
static List * get_useful_ecs_for_relation(PlannerInfo *root, RelOptInfo *rel)
Definition: postgres_fdw.c:808
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * ec_opfamilies
Definition: pathnodes.h:1368

References BTLessStrategyNumber, EquivalenceClass::ec_opfamilies, find_em_for_rel(), get_useful_ecs_for_relation(), if(), is_foreign_pathkey(), is_shippable(), lappend(), lfirst, linitial, linitial_oid, list_copy(), list_length(), list_make1, make_canonical_pathkey(), NIL, PgFdwRelationInfo::qp_is_pushdown_safe, PlannerInfo::query_pathkeys, and PgFdwRelationInfo::use_remote_estimate.

Referenced by add_paths_with_pathkeys_for_rel().

◆ init_returning_filter()

static void init_returning_filter ( PgFdwDirectModifyState dmstate,
List fdw_scan_tlist,
Index  rtindex 
)
static

Definition at line 4664 of file postgres_fdw.c.

4667 {
4668  TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4669  ListCell *lc;
4670  int i;
4671 
4672  /*
4673  * Calculate the mapping between the fdw_scan_tlist's entries and the
4674  * result tuple's attributes.
4675  *
4676  * The "map" is an array of indexes of the result tuple's attributes in
4677  * fdw_scan_tlist, i.e., one entry for every attribute of the result
4678  * tuple. We store zero for any attributes that don't have the
4679  * corresponding entries in that list, marking that a NULL is needed in
4680  * the result tuple.
4681  *
4682  * Also get the indexes of the entries for ctid and oid if any.
4683  */
4684  dmstate->attnoMap = (AttrNumber *)
4685  palloc0(resultTupType->natts * sizeof(AttrNumber));
4686 
4687  dmstate->ctidAttno = dmstate->oidAttno = 0;
4688 
4689  i = 1;
4690  dmstate->hasSystemCols = false;
4691  foreach(lc, fdw_scan_tlist)
4692  {
4693  TargetEntry *tle = (TargetEntry *) lfirst(lc);
4694  Var *var = (Var *) tle->expr;
4695 
4696  Assert(IsA(var, Var));
4697 
4698  /*
4699  * If the Var is a column of the target relation to be retrieved from
4700  * the foreign server, get the index of the entry.
4701  */
4702  if (var->varno == rtindex &&
4703  list_member_int(dmstate->retrieved_attrs, i))
4704  {
4705  int attrno = var->varattno;
4706 
4707  if (attrno < 0)
4708  {
4709  /*
4710  * We don't retrieve system columns other than ctid and oid.
4711  */
4712  if (attrno == SelfItemPointerAttributeNumber)
4713  dmstate->ctidAttno = i;
4714  else
4715  Assert(false);
4716  dmstate->hasSystemCols = true;
4717  }
4718  else
4719  {
4720  /*
4721  * We don't retrieve whole-row references to the target
4722  * relation either.
4723  */
4724  Assert(attrno > 0);
4725 
4726  dmstate->attnoMap[attrno - 1] = i;
4727  }
4728  }
4729  i++;
4730  }
4731 }
bool list_member_int(const List *list, int datum)
Definition: list.c:701

References Assert(), PgFdwDirectModifyState::attnoMap, PgFdwDirectModifyState::ctidAttno, TargetEntry::expr, PgFdwDirectModifyState::hasSystemCols, i, IsA, lfirst, list_member_int(), TupleDescData::natts, PgFdwDirectModifyState::oidAttno, palloc0(), RelationGetDescr, PgFdwDirectModifyState::resultRel, PgFdwDirectModifyState::retrieved_attrs, SelfItemPointerAttributeNumber, Var::varattno, and Var::varno.

Referenced by postgresBeginDirectModify().

◆ make_tuple_from_result_row()

static HeapTuple make_tuple_from_result_row ( PGresult res,
int  row,
Relation  rel,
AttInMetadata attinmeta,
List retrieved_attrs,
ForeignScanState fsstate,
MemoryContext  temp_context 
)
static

Definition at line 7514 of file postgres_fdw.c.

7521 {
7522  HeapTuple tuple;
7523  TupleDesc tupdesc;
7524  Datum *values;
7525  bool *nulls;
7526  ItemPointer ctid = NULL;
7527  ConversionLocation errpos;
7528  ErrorContextCallback errcallback;
7529  MemoryContext oldcontext;
7530  ListCell *lc;
7531  int j;
7532 
7533  Assert(row < PQntuples(res));
7534 
7535  /*
7536  * Do the following work in a temp context that we reset after each tuple.
7537  * This cleans up not only the data we have direct access to, but any
7538  * cruft the I/O functions might leak.
7539  */
7540  oldcontext = MemoryContextSwitchTo(temp_context);
7541 
7542  /*
7543  * Get the tuple descriptor for the row. Use the rel's tupdesc if rel is
7544  * provided, otherwise look to the scan node's ScanTupleSlot.
7545  */
7546  if (rel)
7547  tupdesc = RelationGetDescr(rel);
7548  else
7549  {
7550  Assert(fsstate);
7551  tupdesc = fsstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
7552  }
7553 
7554  values = (Datum *) palloc0(tupdesc->natts * sizeof(Datum));
7555  nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
7556  /* Initialize to nulls for any columns not present in result */
7557  memset(nulls, true, tupdesc->natts * sizeof(bool));
7558 
7559  /*
7560  * Set up and install callback to report where conversion error occurs.
7561  */
7562  errpos.cur_attno = 0;
7563  errpos.rel = rel;
7564  errpos.fsstate = fsstate;
7565  errcallback.callback = conversion_error_callback;
7566  errcallback.arg = (void *) &errpos;
7567  errcallback.previous = error_context_stack;
7568  error_context_stack = &errcallback;
7569 
7570  /*
7571  * i indexes columns in the relation, j indexes columns in the PGresult.
7572  */
7573  j = 0;
7574  foreach(lc, retrieved_attrs)
7575  {
7576  int i = lfirst_int(lc);
7577  char *valstr;
7578 
7579  /* fetch next column's textual value */
7580  if (PQgetisnull(res, row, j))
7581  valstr = NULL;
7582  else
7583  valstr = PQgetvalue(res, row, j);
7584 
7585  /*
7586  * convert value to internal representation
7587  *
7588  * Note: we ignore system columns other than ctid and oid in result
7589  */
7590  errpos.cur_attno = i;
7591  if (i > 0)
7592  {
7593  /* ordinary column */
7594  Assert(i <= tupdesc->natts);
7595  nulls[i - 1] = (valstr == NULL);
7596  /* Apply the input function even to nulls, to support domains */
7597  values[i - 1] = InputFunctionCall(&attinmeta->attinfuncs[i - 1],
7598  valstr,
7599  attinmeta->attioparams[i - 1],
7600  attinmeta->atttypmods[i - 1]);
7601  }
7602  else if (i == SelfItemPointerAttributeNumber)
7603  {
7604  /* ctid */
7605  if (valstr != NULL)
7606  {
7607  Datum datum;
7608 
7609  datum = DirectFunctionCall1(tidin, CStringGetDatum(valstr));
7610  ctid = (ItemPointer) DatumGetPointer(datum);
7611  }
7612  }
7613  errpos.cur_attno = 0;
7614 
7615  j++;
7616  }
7617 
7618  /* Uninstall error context callback. */
7619  error_context_stack = errcallback.previous;
7620 
7621  /*
7622  * Check we got the expected number of columns. Note: j == 0 and
7623  * PQnfields == 1 is expected, since deparse emits a NULL if no columns.
7624  */
7625  if (j > 0 && j != PQnfields(res))
7626  elog(ERROR, "remote query result does not match the foreign table");
7627 
7628  /*
7629  * Build the result tuple in caller's memory context.
7630  */
7631  MemoryContextSwitchTo(oldcontext);
7632 
7633  tuple = heap_form_tuple(tupdesc, values, nulls);
7634 
7635  /*
7636  * If we have a CTID to return, install it in both t_self and t_ctid.
7637  * t_self is the normal place, but if the tuple is converted to a
7638  * composite Datum, t_self will be lost; setting t_ctid allows CTID to be
7639  * preserved during EvalPlanQual re-evaluations (see ROW_MARK_COPY code).
7640  */
7641  if (ctid)
7642  tuple->t_self = tuple->t_data->t_ctid = *ctid;
7643 
7644  /*
7645  * Stomp on the xmin, xmax, and cmin fields from the tuple created by
7646  * heap_form_tuple. heap_form_tuple actually creates the tuple with
7647  * DatumTupleFields, not HeapTupleFields, but the executor expects
7648  * HeapTupleFields and will happily extract system columns on that
7649  * assumption. If we don't do this then, for example, the tuple length
7650  * ends up in the xmin field, which isn't what we want.
7651  */
7655 
7656  /* Clean up */
7657  MemoryContextReset(temp_context);
7658 
7659  return tuple;
7660 }
ErrorContextCallback * error_context_stack
Definition: elog.c:95
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3842
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3430
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1513
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
static void conversion_error_callback(void *arg)
FmgrInfo * attinfuncs
Definition: funcapi.h:41
Oid * attioparams
Definition: funcapi.h:44
int32 * atttypmods
Definition: funcapi.h:47
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
ItemPointerData t_ctid
Definition: htup_details.h:161
Datum tidin(PG_FUNCTION_ARGS)
Definition: tid.c:52

References ErrorContextCallback::arg, Assert(), AttInMetadata::attinfuncs, AttInMetadata::attioparams, AttInMetadata::atttypmods, ErrorContextCallback::callback, conversion_error_callback(), CStringGetDatum(), ConversionLocation::cur_attno, DatumGetPointer(), DirectFunctionCall1, elog(), ERROR, error_context_stack, ConversionLocation::fsstate, heap_form_tuple(), HeapTupleHeaderSetCmin, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXmin, i, InputFunctionCall(), InvalidTransactionId, j, lfirst_int, MemoryContextReset(), MemoryContextSwitchTo(), TupleDescData::natts, palloc(), palloc0(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), ErrorContextCallback::previous, ConversionLocation::rel, RelationGetDescr, res, SelfItemPointerAttributeNumber, ForeignScanState::ss, ScanState::ss_ScanTupleSlot, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, tidin(), TupleTableSlot::tts_tupleDescriptor, and values.

Referenced by analyze_row_processor(), fetch_more_data(), get_returning_data(), and store_returning_result().

◆ merge_fdw_options()

static void merge_fdw_options ( PgFdwRelationInfo fpinfo,
const PgFdwRelationInfo fpinfo_o,
const PgFdwRelationInfo fpinfo_i 
)
static

Definition at line 6256 of file postgres_fdw.c.

6259 {
6260  /* We must always have fpinfo_o. */
6261  Assert(fpinfo_o);
6262 
6263  /* fpinfo_i may be NULL, but if present the servers must both match. */
6264  Assert(!fpinfo_i ||
6265  fpinfo_i->server->serverid == fpinfo_o->server->serverid);
6266 
6267  /*
6268  * Copy the server specific FDW options. (For a join, both relations come
6269  * from the same server, so the server options should have the same value
6270  * for both relations.)
6271  */
6272  fpinfo->fdw_startup_cost = fpinfo_o->fdw_startup_cost;
6273  fpinfo->fdw_tuple_cost = fpinfo_o->fdw_tuple_cost;
6274  fpinfo->shippable_extensions = fpinfo_o->shippable_extensions;
6275  fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate;
6276  fpinfo->fetch_size = fpinfo_o->fetch_size;
6277  fpinfo->async_capable = fpinfo_o->async_capable;
6278 
6279  /* Merge the table level options from either side of the join. */
6280  if (fpinfo_i)
6281  {
6282  /*
6283  * We'll prefer to use remote estimates for this join if any table
6284  * from either side of the join is using remote estimates. This is
6285  * most likely going to be preferred since they're already willing to
6286  * pay the price of a round trip to get the remote EXPLAIN. In any
6287  * case it's not entirely clear how we might otherwise handle this
6288  * best.
6289  */
6290  fpinfo->use_remote_estimate = fpinfo_o->use_remo