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/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.01
 
#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)
 
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)
 
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 62 of file postgres_fdw.c.

◆ DEFAULT_FDW_STARTUP_COST

#define DEFAULT_FDW_STARTUP_COST   100.0

Definition at line 56 of file postgres_fdw.c.

◆ DEFAULT_FDW_TUPLE_COST

#define DEFAULT_FDW_TUPLE_COST   0.01

Definition at line 59 of file postgres_fdw.c.

Typedef Documentation

◆ ConversionLocation

◆ PgFdwAnalyzeState

◆ PgFdwDirectModifyState

◆ PgFdwModifyState

◆ PgFdwScanState

Enumeration Type Documentation

◆ FdwDirectModifyPrivateIndex

Enumerator
FdwDirectModifyPrivateUpdateSql 
FdwDirectModifyPrivateHasReturning 
FdwDirectModifyPrivateRetrievedAttrs 
FdwDirectModifyPrivateSetProcessed 

Definition at line 122 of file postgres_fdw.c.

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

◆ FdwModifyPrivateIndex

Enumerator
FdwModifyPrivateUpdateSql 
FdwModifyPrivateTargetAttnums 
FdwModifyPrivateLen 
FdwModifyPrivateHasReturning 
FdwModifyPrivateRetrievedAttrs 

Definition at line 99 of file postgres_fdw.c.

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

◆ FdwPathPrivateIndex

Enumerator
FdwPathPrivateHasFinalSort 
FdwPathPrivateHasLimit 

Definition at line 282 of file postgres_fdw.c.

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

◆ FdwScanPrivateIndex

Enumerator
FdwScanPrivateSelectSql 
FdwScanPrivateRetrievedAttrs 
FdwScanPrivateFetchSize 
FdwScanPrivateRelations 

Definition at line 71 of file postgres_fdw.c.

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

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 6669 of file postgres_fdw.c.

6672 {
6673  Query *parse = root->parse;
6674  PgFdwRelationInfo *ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
6675  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) final_rel->fdw_private;
6676  bool has_final_sort = false;
6677  List *pathkeys = NIL;
6678  PgFdwPathExtraData *fpextra;
6679  bool save_use_remote_estimate = false;
6680  double rows;
6681  int width;
6682  Cost startup_cost;
6683  Cost total_cost;
6684  List *fdw_private;
6685  ForeignPath *final_path;
6686 
6687  /*
6688  * Currently, we only support this for SELECT commands
6689  */
6690  if (parse->commandType != CMD_SELECT)
6691  return;
6692 
6693  /*
6694  * No work if there is no FOR UPDATE/SHARE clause and if there is no need
6695  * to add a LIMIT node
6696  */
6697  if (!parse->rowMarks && !extra->limit_needed)
6698  return;
6699 
6700  /* We don't support cases where there are any SRFs in the targetlist */
6701  if (parse->hasTargetSRFs)
6702  return;
6703 
6704  /* Save the input_rel as outerrel in fpinfo */
6705  fpinfo->outerrel = input_rel;
6706 
6707  /*
6708  * Copy foreign table, foreign server, user mapping, FDW options etc.
6709  * details from the input relation's fpinfo.
6710  */
6711  fpinfo->table = ifpinfo->table;
6712  fpinfo->server = ifpinfo->server;
6713  fpinfo->user = ifpinfo->user;
6714  merge_fdw_options(fpinfo, ifpinfo, NULL);
6715 
6716  /*
6717  * If there is no need to add a LIMIT node, there might be a ForeignPath
6718  * in the input_rel's pathlist that implements all behavior of the query.
6719  * Note: we would already have accounted for the query's FOR UPDATE/SHARE
6720  * (if any) before we get here.
6721  */
6722  if (!extra->limit_needed)
6723  {
6724  ListCell *lc;
6725 
6726  Assert(parse->rowMarks);
6727 
6728  /*
6729  * Grouping and aggregation are not supported with FOR UPDATE/SHARE,
6730  * so the input_rel should be a base, join, or ordered relation; and
6731  * if it's an ordered relation, its input relation should be a base or
6732  * join relation.
6733  */
6734  Assert(input_rel->reloptkind == RELOPT_BASEREL ||
6735  input_rel->reloptkind == RELOPT_JOINREL ||
6736  (input_rel->reloptkind == RELOPT_UPPER_REL &&
6737  ifpinfo->stage == UPPERREL_ORDERED &&
6738  (ifpinfo->outerrel->reloptkind == RELOPT_BASEREL ||
6739  ifpinfo->outerrel->reloptkind == RELOPT_JOINREL)));
6740 
6741  foreach(lc, input_rel->pathlist)
6742  {
6743  Path *path = (Path *) lfirst(lc);
6744 
6745  /*
6746  * apply_scanjoin_target_to_paths() uses create_projection_path()
6747  * to adjust each of its input paths if needed, whereas
6748  * create_ordered_paths() uses apply_projection_to_path() to do
6749  * that. So the former might have put a ProjectionPath on top of
6750  * the ForeignPath; look through ProjectionPath and see if the
6751  * path underneath it is ForeignPath.
6752  */
6753  if (IsA(path, ForeignPath) ||
6754  (IsA(path, ProjectionPath) &&
6755  IsA(((ProjectionPath *) path)->subpath, ForeignPath)))
6756  {
6757  /*
6758  * Create foreign final path; this gets rid of a
6759  * no-longer-needed outer plan (if any), which makes the
6760  * EXPLAIN output look cleaner
6761  */
6762  final_path = create_foreign_upper_path(root,
6763  path->parent,
6764  path->pathtarget,
6765  path->rows,
6766  path->startup_cost,
6767  path->total_cost,
6768  path->pathkeys,
6769  NULL, /* no extra plan */
6770  NULL); /* no fdw_private */
6771 
6772  /* and add it to the final_rel */
6773  add_path(final_rel, (Path *) final_path);
6774 
6775  /* Safe to push down */
6776  fpinfo->pushdown_safe = true;
6777 
6778  return;
6779  }
6780  }
6781 
6782  /*
6783  * If we get here it means no ForeignPaths; since we would already
6784  * have considered pushing down all operations for the query to the
6785  * remote server, give up on it.
6786  */
6787  return;
6788  }
6789 
6790  Assert(extra->limit_needed);
6791 
6792  /*
6793  * If the input_rel is an ordered relation, replace the input_rel with its
6794  * input relation
6795  */
6796  if (input_rel->reloptkind == RELOPT_UPPER_REL &&
6797  ifpinfo->stage == UPPERREL_ORDERED)
6798  {
6799  input_rel = ifpinfo->outerrel;
6800  ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
6801  has_final_sort = true;
6802  pathkeys = root->sort_pathkeys;
6803  }
6804 
6805  /* The input_rel should be a base, join, or grouping relation */
6806  Assert(input_rel->reloptkind == RELOPT_BASEREL ||
6807  input_rel->reloptkind == RELOPT_JOINREL ||
6808  (input_rel->reloptkind == RELOPT_UPPER_REL &&
6809  ifpinfo->stage == UPPERREL_GROUP_AGG));
6810 
6811  /*
6812  * We try to create a path below by extending a simple foreign path for
6813  * the underlying base, join, or grouping relation to perform the final
6814  * sort (if has_final_sort) and the LIMIT restriction remotely, which is
6815  * stored into the fdw_private list of the resulting path. (We
6816  * re-estimate the costs of sorting the underlying relation, if
6817  * has_final_sort.)
6818  */
6819 
6820  /*
6821  * Assess if it is safe to push down the LIMIT and OFFSET to the remote
6822  * server
6823  */
6824 
6825  /*
6826  * If the underlying relation has any local conditions, the LIMIT/OFFSET
6827  * cannot be pushed down.
6828  */
6829  if (ifpinfo->local_conds)
6830  return;
6831 
6832  /*
6833  * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are
6834  * not safe to remote.
6835  */
6836  if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) ||
6837  !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount))
6838  return;
6839 
6840  /* Safe to push down */
6841  fpinfo->pushdown_safe = true;
6842 
6843  /* Construct PgFdwPathExtraData */
6844  fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
6845  fpextra->target = root->upper_targets[UPPERREL_FINAL];
6846  fpextra->has_final_sort = has_final_sort;
6847  fpextra->has_limit = extra->limit_needed;
6848  fpextra->limit_tuples = extra->limit_tuples;
6849  fpextra->count_est = extra->count_est;
6850  fpextra->offset_est = extra->offset_est;
6851 
6852  /*
6853  * Estimate the costs of performing the final sort and the LIMIT
6854  * restriction remotely. If has_final_sort is false, we wouldn't need to
6855  * execute EXPLAIN anymore if use_remote_estimate, since the costs can be
6856  * roughly estimated using the costs we already have for the underlying
6857  * relation, in the same way as when use_remote_estimate is false. Since
6858  * it's pretty expensive to execute EXPLAIN, force use_remote_estimate to
6859  * false in that case.
6860  */
6861  if (!fpextra->has_final_sort)
6862  {
6863  save_use_remote_estimate = ifpinfo->use_remote_estimate;
6864  ifpinfo->use_remote_estimate = false;
6865  }
6866  estimate_path_cost_size(root, input_rel, NIL, pathkeys, fpextra,
6867  &rows, &width, &startup_cost, &total_cost);
6868  if (!fpextra->has_final_sort)
6869  ifpinfo->use_remote_estimate = save_use_remote_estimate;
6870 
6871  /*
6872  * Build the fdw_private list that will be used by postgresGetForeignPlan.
6873  * Items in the list must match order in enum FdwPathPrivateIndex.
6874  */
6875  fdw_private = list_make2(makeBoolean(has_final_sort),
6876  makeBoolean(extra->limit_needed));
6877 
6878  /*
6879  * Create foreign final path; this gets rid of a no-longer-needed outer
6880  * plan (if any), which makes the EXPLAIN output look cleaner
6881  */
6882  final_path = create_foreign_upper_path(root,
6883  input_rel,
6884  root->upper_targets[UPPERREL_FINAL],
6885  rows,
6886  startup_cost,
6887  total_cost,
6888  pathkeys,
6889  NULL, /* no extra plan */
6890  fdw_private);
6891 
6892  /* and add it to the final_rel */
6893  add_path(final_rel, (Path *) final_path);
6894 }
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:240
Assert(fmt[strlen(fmt) - 1] !='\n')
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void * palloc0(Size size)
Definition: mcxt.c:1230
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
double Cost
Definition: nodes.h:251
@ CMD_SELECT
Definition: nodes.h:265
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_private)
Definition: pathnode.c:2320
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:776
@ RELOPT_UPPER_REL
Definition: pathnodes.h:780
@ RELOPT_JOINREL
Definition: pathnodes.h:777
#define lfirst(lc)
Definition: pg_list.h:170
#define NIL
Definition: pg_list.h:66
#define list_make2(x1, x2)
Definition: pg_list.h:212
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:717
Cardinality limit_tuples
Definition: pathnodes.h:3101
Definition: pg_list.h:52
List * pathkeys
Definition: pathnodes.h:1549
Cardinality rows
Definition: pathnodes.h:1544
Cost startup_cost
Definition: pathnodes.h:1545
Cost total_cost
Definition: pathnodes.h:1546
PathTarget * target
Definition: postgres_fdw.c:293
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:389
Query * parse
Definition: pathnodes.h:199
List * pathlist
Definition: pathnodes.h:848
RelOptKind reloptkind
Definition: pathnodes.h:815
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 6445 of file postgres_fdw.c.

6448 {
6449  Query *parse = root->parse;
6450  PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6451  PgFdwRelationInfo *fpinfo = grouped_rel->fdw_private;
6452  ForeignPath *grouppath;
6453  double rows;
6454  int width;
6455  Cost startup_cost;
6456  Cost total_cost;
6457 
6458  /* Nothing to be done, if there is no grouping or aggregation required. */
6459  if (!parse->groupClause && !parse->groupingSets && !parse->hasAggs &&
6460  !root->hasHavingQual)
6461  return;
6462 
6465 
6466  /* save the input_rel as outerrel in fpinfo */
6467  fpinfo->outerrel = input_rel;
6468 
6469  /*
6470  * Copy foreign table, foreign server, user mapping, FDW options etc.
6471  * details from the input relation's fpinfo.
6472  */
6473  fpinfo->table = ifpinfo->table;
6474  fpinfo->server = ifpinfo->server;
6475  fpinfo->user = ifpinfo->user;
6476  merge_fdw_options(fpinfo, ifpinfo, NULL);
6477 
6478  /*
6479  * Assess if it is safe to push down aggregation and grouping.
6480  *
6481  * Use HAVING qual from extra. In case of child partition, it will have
6482  * translated Vars.
6483  */
6484  if (!foreign_grouping_ok(root, grouped_rel, extra->havingQual))
6485  return;
6486 
6487  /*
6488  * Compute the selectivity and cost of the local_conds, so we don't have
6489  * to do it over again for each path. (Currently we create just a single
6490  * path here, but in future it would be possible that we build more paths
6491  * such as pre-sorted paths as in postgresGetForeignPaths and
6492  * postgresGetForeignJoinPaths.) The best we can do for these conditions
6493  * is to estimate selectivity on the basis of local statistics.
6494  */
6495  fpinfo->local_conds_sel = clauselist_selectivity(root,
6496  fpinfo->local_conds,
6497  0,
6498  JOIN_INNER,
6499  NULL);
6500 
6501  cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
6502 
6503  /* Estimate the cost of push down */
6504  estimate_path_cost_size(root, grouped_rel, NIL, NIL, NULL,
6505  &rows, &width, &startup_cost, &total_cost);
6506 
6507  /* Now update this information in the fpinfo */
6508  fpinfo->rows = rows;
6509  fpinfo->width = width;
6510  fpinfo->startup_cost = startup_cost;
6511  fpinfo->total_cost = total_cost;
6512 
6513  /* Create and add foreign path to the grouping relation. */
6514  grouppath = create_foreign_upper_path(root,
6515  grouped_rel,
6516  grouped_rel->reltarget,
6517  rows,
6518  startup_cost,
6519  total_cost,
6520  NIL, /* no pathkeys */
6521  NULL,
6522  NIL); /* no fdw_private */
6523 
6524  /* Add generated path into grouped_rel by add_path(). */
6525  add_path(grouped_rel, (Path *) grouppath);
6526 }
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:4368
@ JOIN_INNER
Definition: nodes.h:293
@ PARTITIONWISE_AGGREGATE_FULL
Definition: pathnodes.h:3056
@ PARTITIONWISE_AGGREGATE_NONE
Definition: pathnodes.h:3055
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, Node *havingQual)
PartitionwiseAggregateType patype
Definition: pathnodes.h:3085
Selectivity local_conds_sel
Definition: postgres_fdw.h:57
QualCost local_conds_cost
Definition: postgres_fdw.h:56
bool hasHavingQual
Definition: pathnodes.h:455
struct PathTarget * reltarget
Definition: pathnodes.h:843

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 6536 of file postgres_fdw.c.

6538 {
6539  Query *parse = root->parse;
6540  PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6541  PgFdwRelationInfo *fpinfo = ordered_rel->fdw_private;
6542  PgFdwPathExtraData *fpextra;
6543  double rows;
6544  int width;
6545  Cost startup_cost;
6546  Cost total_cost;
6547  List *fdw_private;
6548  ForeignPath *ordered_path;
6549  ListCell *lc;
6550 
6551  /* Shouldn't get here unless the query has ORDER BY */
6552  Assert(parse->sortClause);
6553 
6554  /* We don't support cases where there are any SRFs in the targetlist */
6555  if (parse->hasTargetSRFs)
6556  return;
6557 
6558  /* Save the input_rel as outerrel in fpinfo */
6559  fpinfo->outerrel = input_rel;
6560 
6561  /*
6562  * Copy foreign table, foreign server, user mapping, FDW options etc.
6563  * details from the input relation's fpinfo.
6564  */
6565  fpinfo->table = ifpinfo->table;
6566  fpinfo->server = ifpinfo->server;
6567  fpinfo->user = ifpinfo->user;
6568  merge_fdw_options(fpinfo, ifpinfo, NULL);
6569 
6570  /*
6571  * If the input_rel is a base or join relation, we would already have
6572  * considered pushing down the final sort to the remote server when
6573  * creating pre-sorted foreign paths for that relation, because the
6574  * query_pathkeys is set to the root->sort_pathkeys in that case (see
6575  * standard_qp_callback()).
6576  */
6577  if (input_rel->reloptkind == RELOPT_BASEREL ||
6578  input_rel->reloptkind == RELOPT_JOINREL)
6579  {
6580  Assert(root->query_pathkeys == root->sort_pathkeys);
6581 
6582  /* Safe to push down if the query_pathkeys is safe to push down */
6583  fpinfo->pushdown_safe = ifpinfo->qp_is_pushdown_safe;
6584 
6585  return;
6586  }
6587 
6588  /* The input_rel should be a grouping relation */
6589  Assert(input_rel->reloptkind == RELOPT_UPPER_REL &&
6590  ifpinfo->stage == UPPERREL_GROUP_AGG);
6591 
6592  /*
6593  * We try to create a path below by extending a simple foreign path for
6594  * the underlying grouping relation to perform the final sort remotely,
6595  * which is stored into the fdw_private list of the resulting path.
6596  */
6597 
6598  /* Assess if it is safe to push down the final sort */
6599  foreach(lc, root->sort_pathkeys)
6600  {
6601  PathKey *pathkey = (PathKey *) lfirst(lc);
6602  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
6603 
6604  /*
6605  * is_foreign_expr would detect volatile expressions as well, but
6606  * checking ec_has_volatile here saves some cycles.
6607  */
6608  if (pathkey_ec->ec_has_volatile)
6609  return;
6610 
6611  /*
6612  * Can't push down the sort if pathkey's opfamily is not shippable.
6613  */
6614  if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId,
6615  fpinfo))
6616  return;
6617 
6618  /*
6619  * The EC must contain a shippable EM that is computed in input_rel's
6620  * reltarget, else we can't push down the sort.
6621  */
6622  if (find_em_for_rel_target(root,
6623  pathkey_ec,
6624  input_rel) == NULL)
6625  return;
6626  }
6627 
6628  /* Safe to push down */
6629  fpinfo->pushdown_safe = true;
6630 
6631  /* Construct PgFdwPathExtraData */
6632  fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
6633  fpextra->target = root->upper_targets[UPPERREL_ORDERED];
6634  fpextra->has_final_sort = true;
6635 
6636  /* Estimate the costs of performing the final sort remotely */
6637  estimate_path_cost_size(root, input_rel, NIL, root->sort_pathkeys, fpextra,
6638  &rows, &width, &startup_cost, &total_cost);
6639 
6640  /*
6641  * Build the fdw_private list that will be used by postgresGetForeignPlan.
6642  * Items in the list must match order in enum FdwPathPrivateIndex.
6643  */
6644  fdw_private = list_make2(makeBoolean(true), makeBoolean(false));
6645 
6646  /* Create foreign ordering path */
6647  ordered_path = create_foreign_upper_path(root,
6648  input_rel,
6649  root->upper_targets[UPPERREL_ORDERED],
6650  rows,
6651  startup_cost,
6652  total_cost,
6653  root->sort_pathkeys,
6654  NULL, /* no extra plan */
6655  fdw_private);
6656 
6657  /* and add it to the ordered_rel */
6658  add_path(ordered_rel, (Path *) ordered_path);
6659 }
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:1377
List * query_pathkeys
Definition: pathnodes.h:372

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 
)
static

Definition at line 5782 of file postgres_fdw.c.

5784 {
5785  List *useful_pathkeys_list = NIL; /* List of all pathkeys */
5786  ListCell *lc;
5787 
5788  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel);
5789 
5790  /*
5791  * Before creating sorted paths, arrange for the passed-in EPQ path, if
5792  * any, to return columns needed by the parent ForeignScan node so that
5793  * they will propagate up through Sort nodes injected below, if necessary.
5794  */
5795  if (epq_path != NULL && useful_pathkeys_list != NIL)
5796  {
5797  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
5798  PathTarget *target = copy_pathtarget(epq_path->pathtarget);
5799 
5800  /* Include columns required for evaluating PHVs in the tlist. */
5802  pull_var_clause((Node *) target->exprs,
5804 
5805  /* Include columns required for evaluating the local conditions. */
5806  foreach(lc, fpinfo->local_conds)
5807  {
5808  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
5809 
5811  pull_var_clause((Node *) rinfo->clause,
5813  }
5814 
5815  /*
5816  * If we have added any new columns, adjust the tlist of the EPQ path.
5817  *
5818  * Note: the plan created using this path will only be used to execute
5819  * EPQ checks, where accuracy of the plan cost and width estimates
5820  * would not be important, so we do not do set_pathtarget_cost_width()
5821  * for the new pathtarget here. See also postgresGetForeignPlan().
5822  */
5823  if (list_length(target->exprs) > list_length(epq_path->pathtarget->exprs))
5824  {
5825  /* The EPQ path is a join path, so it is projection-capable. */
5827 
5828  /*
5829  * Use create_projection_path() here, so as to avoid modifying it
5830  * in place.
5831  */
5832  epq_path = (Path *) create_projection_path(root,
5833  rel,
5834  epq_path,
5835  target);
5836  }
5837  }
5838 
5839  /* Create one path for each set of pathkeys we found above. */
5840  foreach(lc, useful_pathkeys_list)
5841  {
5842  double rows;
5843  int width;
5844  Cost startup_cost;
5845  Cost total_cost;
5846  List *useful_pathkeys = lfirst(lc);
5847  Path *sorted_epq_path;
5848 
5849  estimate_path_cost_size(root, rel, NIL, useful_pathkeys, NULL,
5850  &rows, &width, &startup_cost, &total_cost);
5851 
5852  /*
5853  * The EPQ path must be at least as well sorted as the path itself, in
5854  * case it gets used as input to a mergejoin.
5855  */
5856  sorted_epq_path = epq_path;
5857  if (sorted_epq_path != NULL &&
5858  !pathkeys_contained_in(useful_pathkeys,
5859  sorted_epq_path->pathkeys))
5860  sorted_epq_path = (Path *)
5861  create_sort_path(root,
5862  rel,
5863  sorted_epq_path,
5864  useful_pathkeys,
5865  -1.0);
5866 
5867  if (IS_SIMPLE_REL(rel))
5868  add_path(rel, (Path *)
5869  create_foreignscan_path(root, rel,
5870  NULL,
5871  rows,
5872  startup_cost,
5873  total_cost,
5874  useful_pathkeys,
5875  rel->lateral_relids,
5876  sorted_epq_path,
5877  NIL));
5878  else
5879  add_path(rel, (Path *)
5880  create_foreign_join_path(root, rel,
5881  NULL,
5882  rows,
5883  startup_cost,
5884  total_cost,
5885  useful_pathkeys,
5886  rel->lateral_relids,
5887  sorted_epq_path,
5888  NIL));
5889  }
5890 }
bool is_projection_capable_path(Path *path)
Definition: createplan.c:7159
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:188
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:346
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2961
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_private)
Definition: pathnode.c:2226
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2646
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_private)
Definition: pathnode.c:2270
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:789
#define lfirst_node(type, lc)
Definition: pg_list.h:174
static int list_length(const List *l)
Definition: pg_list.h:150
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
Definition: postgres_fdw.c:902
Definition: nodes.h:118
Relids lateral_relids
Definition: pathnodes.h:863
Expr * clause
Definition: pathnodes.h:2432
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:597

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 3621 of file postgres_fdw.c.

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

References cost_sort(), DEFAULT_FDW_SORT_MULTIPLIER, PlannerInfo::group_pathkeys, Query::groupClause, grouping_is_sortable(), PlannerInfo::parse, pathkeys_contained_in(), 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 5154 of file postgres_fdw.c.

5155 {
5156  int targrows = astate->targrows;
5157  int pos; /* array index to store tuple in */
5158  MemoryContext oldcontext;
5159 
5160  /* Always increment sample row counter. */
5161  astate->samplerows += 1;
5162 
5163  /*
5164  * Determine the slot where this sample row should be stored. Set pos to
5165  * negative value to indicate the row should be skipped.
5166  */
5167  if (astate->numrows < targrows)
5168  {
5169  /* First targrows rows are always included into the sample */
5170  pos = astate->numrows++;
5171  }
5172  else
5173  {
5174  /*
5175  * Now we start replacing tuples in the sample until we reach the end
5176  * of the relation. Same algorithm as in acquire_sample_rows in
5177  * analyze.c; see Jeff Vitter's paper.
5178  */
5179  if (astate->rowstoskip < 0)
5180  astate->rowstoskip = reservoir_get_next_S(&astate->rstate, astate->samplerows, targrows);
5181 
5182  if (astate->rowstoskip <= 0)
5183  {
5184  /* Choose a random reservoir element to replace. */
5185  pos = (int) (targrows * sampler_random_fract(&astate->rstate.randstate));
5186  Assert(pos >= 0 && pos < targrows);
5187  heap_freetuple(astate->rows[pos]);
5188  }
5189  else
5190  {
5191  /* Skip this tuple. */
5192  pos = -1;
5193  }
5194 
5195  astate->rowstoskip -= 1;
5196  }
5197 
5198  if (pos >= 0)
5199  {
5200  /*
5201  * Create sample tuple from current result row, and store it in the
5202  * position determined above. The tuple has to be created in anl_cxt.
5203  */
5204  oldcontext = MemoryContextSwitchTo(astate->anl_cxt);
5205 
5206  astate->rows[pos] = make_tuple_from_result_row(res, row,
5207  astate->rel,
5208  astate->attinmeta,
5209  astate->retrieved_attrs,
5210  NULL,
5211  astate->temp_cxt);
5212 
5213  MemoryContextSwitchTo(oldcontext);
5214  }
5215 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
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:268
AttInMetadata * attinmeta
Definition: postgres_fdw.c:257
MemoryContext anl_cxt
Definition: postgres_fdw.c:271
HeapTuple * rows
Definition: postgres_fdw.c:261
MemoryContext temp_cxt
Definition: postgres_fdw.c:272
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 4736 of file postgres_fdw.c.

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

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 5898 of file postgres_fdw.c.

5899 {
5900  ListCell *lc;
5901 
5902  foreach(lc, fpinfo->server->options)
5903  {
5904  DefElem *def = (DefElem *) lfirst(lc);
5905 
5906  if (strcmp(def->defname, "use_remote_estimate") == 0)
5907  fpinfo->use_remote_estimate = defGetBoolean(def);
5908  else if (strcmp(def->defname, "fdw_startup_cost") == 0)
5909  (void) parse_real(defGetString(def), &fpinfo->fdw_startup_cost, 0,
5910  NULL);
5911  else if (strcmp(def->defname, "fdw_tuple_cost") == 0)
5912  (void) parse_real(defGetString(def), &fpinfo->fdw_tuple_cost, 0,
5913  NULL);
5914  else if (strcmp(def->defname, "extensions") == 0)
5915  fpinfo->shippable_extensions =
5916  ExtractExtensionList(defGetString(def), false);
5917  else if (strcmp(def->defname, "fetch_size") == 0)
5918  (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
5919  else if (strcmp(def->defname, "async_capable") == 0)
5920  fpinfo->async_capable = defGetBoolean(def);
5921  }
5922 }
List * ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
Definition: option.c:416
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:2806
bool parse_real(const char *value, double *result, int flags, const char **hintmsg)
Definition: guc.c:2896
char * defname
Definition: parsenodes.h:777
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 5930 of file postgres_fdw.c.

5931 {
5932  ListCell *lc;
5933 
5934  foreach(lc, fpinfo->table->options)
5935  {
5936  DefElem *def = (DefElem *) lfirst(lc);
5937 
5938  if (strcmp(def->defname, "use_remote_estimate") == 0)
5939  fpinfo->use_remote_estimate = defGetBoolean(def);
5940  else if (strcmp(def->defname, "fetch_size") == 0)
5941  (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
5942  else if (strcmp(def->defname, "async_capable") == 0)
5943  fpinfo->async_capable = defGetBoolean(def);
5944  }
5945 }
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 4409 of file postgres_fdw.c.

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

3930 {
3931  char sql[64];
3932  PGresult *res;
3933 
3934  snprintf(sql, sizeof(sql), "CLOSE c%u", cursor_number);
3935 
3936  /*
3937  * We don't use a PG_TRY block here, so be careful not to throw error
3938  * without releasing the PGresult.
3939  */
3940  res = pgfdw_exec_query(conn, sql, conn_state);
3942  pgfdw_report_error(ERROR, res, conn, true, sql);
3943  PQclear(res);
3944 }
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:865
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:772
static unsigned int cursor_number
Definition: connection.c:77
#define ERROR
Definition: elog.h:35
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
@ 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 7168 of file postgres_fdw.c.

7169 {
7170  /* The request would have been pending for a callback */
7171  Assert(areq->callback_pending);
7172 
7173  /* Unlike AsyncNotify, we unset callback_pending ourselves */
7174  areq->callback_pending = false;
7175 
7176  /* We begin a fetch afterwards if necessary; don't fetch */
7177  produce_tuple_asynchronously(areq, false);
7178 
7179  /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
7180  ExecAsyncResponse(areq);
7181 
7182  /* Also, we do instrumentation ourselves, if required */
7183  if (areq->requestee->instrument)
7185  TupIsNull(areq->result) ? 0.0 : 1.0);
7186 }
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:596
bool callback_pending
Definition: execnodes.h:594
struct PlanState * requestee
Definition: execnodes.h:592
Instrumentation * instrument
Definition: execnodes.h:1039
#define TupIsNull(slot)
Definition: tuptable.h:300

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 7359 of file postgres_fdw.c.

7360 {
7362  Relation rel = errpos->rel;
7363  ForeignScanState *fsstate = errpos->fsstate;
7364  const char *attname = NULL;
7365  const char *relname = NULL;
7366  bool is_wholerow = false;
7367 
7368  /*
7369  * If we're in a scan node, always use aliases from the rangetable, for
7370  * consistency between the simple-relation and remote-join cases. Look at
7371  * the relation's tupdesc only if we're not in a scan node.
7372  */
7373  if (fsstate)
7374  {
7375  /* ForeignScan case */
7376  ForeignScan *fsplan = castNode(ForeignScan, fsstate->ss.ps.plan);
7377  int varno = 0;
7378  AttrNumber colno = 0;
7379 
7380  if (fsplan->scan.scanrelid > 0)
7381  {
7382  /* error occurred in a scan against a foreign table */
7383  varno = fsplan->scan.scanrelid;
7384  colno = errpos->cur_attno;
7385  }
7386  else
7387  {
7388  /* error occurred in a scan against a foreign join */
7389  TargetEntry *tle;
7390 
7391  tle = list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
7392  errpos->cur_attno - 1);
7393 
7394  /*
7395  * Target list can have Vars and expressions. For Vars, we can
7396  * get some information, however for expressions we can't. Thus
7397  * for expressions, just show generic context message.
7398  */
7399  if (IsA(tle->expr, Var))
7400  {
7401  Var *var = (Var *) tle->expr;
7402 
7403  varno = var->varno;
7404  colno = var->varattno;
7405  }
7406  }
7407 
7408  if (varno > 0)
7409  {
7410  EState *estate = fsstate->ss.ps.state;
7411  RangeTblEntry *rte = exec_rt_fetch(varno, estate);
7412 
7413  relname = rte->eref->aliasname;
7414 
7415  if (colno == 0)
7416  is_wholerow = true;
7417  else if (colno > 0 && colno <= list_length(rte->eref->colnames))
7418  attname = strVal(list_nth(rte->eref->colnames, colno - 1));
7419  else if (colno == SelfItemPointerAttributeNumber)
7420  attname = "ctid";
7421  }
7422  }
7423  else if (rel)
7424  {
7425  /* Non-ForeignScan case (we should always have a rel here) */
7426  TupleDesc tupdesc = RelationGetDescr(rel);
7427 
7429  if (errpos->cur_attno > 0 && errpos->cur_attno <= tupdesc->natts)
7430  {
7431  Form_pg_attribute attr = TupleDescAttr(tupdesc,
7432  errpos->cur_attno - 1);
7433 
7434  attname = NameStr(attr->attname);
7435  }
7436  else if (errpos->cur_attno == SelfItemPointerAttributeNumber)
7437  attname = "ctid";
7438  }
7439 
7440  if (relname && is_wholerow)
7441  errcontext("whole-row reference to foreign table \"%s\"", relname);
7442  else if (relname && attname)
7443  errcontext("column \"%s\" of foreign table \"%s\"", attname, relname);
7444  else
7445  errcontext("processing expression at position %d in select list",
7446  errpos->cur_attno);
7447 }
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:682
#define errcontext
Definition: elog.h:192
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:573
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
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:297
#define list_nth_node(type, list, n)
Definition: pg_list.h:325
#define RelationGetRelationName(relation)
Definition: rel.h:535
char * aliasname
Definition: primnodes.h:42
List * colnames
Definition: primnodes.h:43
AttrNumber cur_attno
Definition: postgres_fdw.c:306
ForeignScanState * fsstate
Definition: postgres_fdw.c:308
ScanState ss
Definition: execnodes.h:1934
List * fdw_scan_tlist
Definition: plannodes.h:714
Plan * plan
Definition: execnodes.h:1029
EState * state
Definition: execnodes.h:1031
Alias * eref
Definition: parsenodes.h:1176
PlanState ps
Definition: execnodes.h:1454
Index scanrelid
Definition: plannodes.h:387
Expr * expr
Definition: primnodes.h:1555
#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 4250 of file postgres_fdw.c.

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

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 3704 of file postgres_fdw.c.

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

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 3952 of file postgres_fdw.c.

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

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert(), PgFdwModifyState::attinmeta, attnum, AttributeNumberIsValid, PgFdwModifyState::aux_fmstate, PgFdwModifyState::batch_size, RangeTblEntry::checkAsUser, CMD_DELETE, CMD_INSERT, CMD_UPDATE, PgFdwModifyState::conn, PgFdwModifyState::conn_state, PgFdwModifyState::ctidAttno, elog(), ERROR, EState::es_query_cxt, ExecFindJunkAttributeInTlist(), fmgr_info(), get_batch_size_option(), GetConnection(), GetForeignTable(), getTypeOutputInfo(), GetUserId(), GetUserMapping(), PgFdwModifyState::has_returning, lfirst_int, list_length(), PgFdwModifyState::num_slots, OidIsValid, 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 4380 of file postgres_fdw.c.

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

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 3675 of file postgres_fdw.c.

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

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 3071 of file postgres_fdw.c.

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

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

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 4075 of file postgres_fdw.c.

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

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 3780 of file postgres_fdw.c.

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

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 7108 of file postgres_fdw.c.

7109 {
7110  ForeignScanState *node = (ForeignScanState *) areq->requestee;
7111  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7112  char sql[64];
7113 
7114  Assert(!fsstate->conn_state->pendingAreq);
7115 
7116  /* Create the cursor synchronously. */
7117  if (!fsstate->cursor_exists)
7118  create_cursor(node);
7119 
7120  /* We will send this query, but not wait for the response. */
7121  snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
7122  fsstate->fetch_size, fsstate->cursor_number);
7123 
7124  if (!PQsendQuery(fsstate->conn, sql))
7125  pgfdw_report_error(ERROR, NULL, fsstate->conn, false, fsstate->query);
7126 
7127  /* Remember that the request is in process */
7128  fsstate->conn_state->pendingAreq = areq;
7129 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1418
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 7462 of file postgres_fdw.c.

7463 {
7464  ListCell *lc;
7465 
7466  foreach(lc, ec->ec_members)
7467  {
7469 
7470  /*
7471  * Note we require !bms_is_empty, else we'd accept constant
7472  * expressions which are not suitable for the purpose.
7473  */
7474  if (bms_is_subset(em->em_relids, rel->relids) &&
7475  !bms_is_empty(em->em_relids) &&
7476  is_foreign_expr(root, rel, em->em_expr))
7477  return em;
7478  }
7479 
7480  return NULL;
7481 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:316
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704
Relids relids
Definition: pathnodes.h:821

References bms_is_empty(), bms_is_subset(), EquivalenceClass::ec_members, EquivalenceMember::em_expr, EquivalenceMember::em_relids, 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 7495 of file postgres_fdw.c.

7497 {
7498  PathTarget *target = rel->reltarget;
7499  ListCell *lc1;
7500  int i;
7501 
7502  i = 0;
7503  foreach(lc1, target->exprs)
7504  {
7505  Expr *expr = (Expr *) lfirst(lc1);
7506  Index sgref = get_pathtarget_sortgroupref(target, i);
7507  ListCell *lc2;
7508 
7509  /* Ignore non-sort expressions */
7510  if (sgref == 0 ||
7512  root->parse->sortClause) == NULL)
7513  {
7514  i++;
7515  continue;
7516  }
7517 
7518  /* We ignore binary-compatible relabeling on both ends */
7519  while (expr && IsA(expr, RelabelType))
7520  expr = ((RelabelType *) expr)->arg;
7521 
7522  /* Locate an EquivalenceClass member matching this expr, if any */
7523  foreach(lc2, ec->ec_members)
7524  {
7526  Expr *em_expr;
7527 
7528  /* Don't match constants */
7529  if (em->em_is_const)
7530  continue;
7531 
7532  /* Ignore child members */
7533  if (em->em_is_child)
7534  continue;
7535 
7536  /* Match if same expression (after stripping relabel) */
7537  em_expr = em->em_expr;
7538  while (em_expr && IsA(em_expr, RelabelType))
7539  em_expr = ((RelabelType *) em_expr)->arg;
7540 
7541  if (!equal(em_expr, expr))
7542  continue;
7543 
7544  /* Check that expression (including relabels!) is shippable */
7545  if (is_foreign_expr(root, rel, em->em_expr))
7546  return em;
7547  }
7548 
7549  i++;
7550  }
7551 
7552  return NULL;
7553 }
unsigned int Index
Definition: c.h:550
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1440
List * exprs
Definition: pathnodes.h:1424
List * sortClause
Definition: parsenodes.h:181
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 2370 of file postgres_fdw.c.

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

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

Referenced by postgresPlanDirectModify().

◆ finish_foreign_modify()

static void finish_foreign_modify ( PgFdwModifyState fmstate)
static

Definition at line 4362 of file postgres_fdw.c.

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

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 6157 of file postgres_fdw.c.

6159 {
6160  Query *query = root->parse;
6161  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) grouped_rel->fdw_private;
6162  PathTarget *grouping_target = grouped_rel->reltarget;
6163  PgFdwRelationInfo *ofpinfo;
6164  ListCell *lc;
6165  int i;
6166  List *tlist = NIL;
6167 
6168  /* We currently don't support pushing Grouping Sets. */
6169  if (query->groupingSets)
6170  return false;
6171 
6172  /* Get the fpinfo of the underlying scan relation. */
6173  ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
6174 
6175  /*
6176  * If underlying scan relation has any local conditions, those conditions
6177  * are required to be applied before performing aggregation. Hence the
6178  * aggregate cannot be pushed down.
6179  */
6180  if (ofpinfo->local_conds)
6181  return false;
6182 
6183  /*
6184  * Examine grouping expressions, as well as other expressions we'd need to
6185  * compute, and check whether they are safe to push down to the foreign
6186  * server. All GROUP BY expressions will be part of the grouping target
6187  * and thus there is no need to search for them separately. Add grouping
6188  * expressions into target list which will be passed to foreign server.
6189  *
6190  * A tricky fine point is that we must not put any expression into the
6191  * target list that is just a foreign param (that is, something that
6192  * deparse.c would conclude has to be sent to the foreign server). If we
6193  * do, the expression will also appear in the fdw_exprs list of the plan
6194  * node, and setrefs.c will get confused and decide that the fdw_exprs
6195  * entry is actually a reference to the fdw_scan_tlist entry, resulting in
6196  * a broken plan. Somewhat oddly, it's OK if the expression contains such
6197  * a node, as long as it's not at top level; then no match is possible.
6198  */
6199  i = 0;
6200  foreach(lc, grouping_target->exprs)
6201  {
6202  Expr *expr = (Expr *) lfirst(lc);
6203  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
6204  ListCell *l;
6205 
6206  /* Check whether this expression is part of GROUP BY clause */
6207  if (sgref && get_sortgroupref_clause_noerr(sgref, query->groupClause))
6208  {
6209  TargetEntry *tle;
6210 
6211  /*
6212  * If any GROUP BY expression is not shippable, then we cannot
6213  * push down aggregation to the foreign server.
6214  */
6215  if (!is_foreign_expr(root, grouped_rel, expr))
6216  return false;
6217 
6218  /*
6219  * If it would be a foreign param, we can't put it into the tlist,
6220  * so we have to fail.
6221  */
6222  if (is_foreign_param(root, grouped_rel, expr))
6223  return false;
6224 
6225  /*
6226  * Pushable, so add to tlist. We need to create a TLE for this
6227  * expression and apply the sortgroupref to it. We cannot use
6228  * add_to_flat_tlist() here because that avoids making duplicate
6229  * entries in the tlist. If there are duplicate entries with
6230  * distinct sortgrouprefs, we have to duplicate that situation in
6231  * the output tlist.
6232  */
6233  tle = makeTargetEntry(expr, list_length(tlist) + 1, NULL, false);
6234  tle->ressortgroupref = sgref;
6235  tlist = lappend(tlist, tle);
6236  }
6237  else
6238  {
6239  /*
6240  * Non-grouping expression we need to compute. Can we ship it
6241  * as-is to the foreign server?
6242  */
6243  if (is_foreign_expr(root, grouped_rel, expr) &&
6244  !is_foreign_param(root, grouped_rel, expr))
6245  {
6246  /* Yes, so add to tlist as-is; OK to suppress duplicates */
6247  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6248  }
6249  else
6250  {
6251  /* Not pushable as a whole; extract its Vars and aggregates */
6252  List *aggvars;
6253 
6254  aggvars = pull_var_clause((Node *) expr,
6256 
6257  /*
6258  * If any aggregate expression is not shippable, then we
6259  * cannot push down aggregation to the foreign server. (We
6260  * don't have to check is_foreign_param, since that certainly
6261  * won't return true for any such expression.)
6262  */
6263  if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars))
6264  return false;
6265 
6266  /*
6267  * Add aggregates, if any, into the targetlist. Plain Vars
6268  * outside an aggregate can be ignored, because they should be
6269  * either same as some GROUP BY column or part of some GROUP
6270  * BY expression. In either case, they are already part of
6271  * the targetlist and thus no need to add them again. In fact
6272  * including plain Vars in the tlist when they do not match a
6273  * GROUP BY column would cause the foreign server to complain
6274  * that the shipped query is invalid.
6275  */
6276  foreach(l, aggvars)
6277  {
6278  Expr *aggref = (Expr *) lfirst(l);
6279 
6280  if (IsA(aggref, Aggref))
6281  tlist = add_to_flat_tlist(tlist, list_make1(aggref));
6282  }
6283  }
6284  }
6285 
6286  i++;
6287  }
6288 
6289  /*
6290  * Classify the pushable and non-pushable HAVING clauses and save them in
6291  * remote_conds and local_conds of the grouped rel's fpinfo.
6292  */
6293  if (havingQual)
6294  {
6295  foreach(lc, (List *) havingQual)
6296  {
6297  Expr *expr = (Expr *) lfirst(lc);
6298  RestrictInfo *rinfo;
6299 
6300  /*
6301  * Currently, the core code doesn't wrap havingQuals in
6302  * RestrictInfos, so we must make our own.
6303  */
6304  Assert(!IsA(expr, RestrictInfo));
6305  rinfo = make_restrictinfo(root,
6306  expr,
6307  true,
6308  false,
6309  false,
6310  root->qual_security_level,
6311  grouped_rel->relids,
6312  NULL,
6313  NULL);
6314  if (is_foreign_expr(root, grouped_rel, expr))
6315  fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
6316  else
6317  fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
6318  }
6319  }
6320 
6321  /*
6322  * If there are any local conditions, pull Vars and aggregates from it and
6323  * check whether they are safe to pushdown or not.
6324  */
6325  if (fpinfo->local_conds)
6326  {
6327  List *aggvars = NIL;
6328 
6329  foreach(lc, fpinfo->local_conds)
6330  {
6331  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
6332 
6333  aggvars = list_concat(aggvars,
6334  pull_var_clause((Node *) rinfo->clause,
6336  }
6337 
6338  foreach(lc, aggvars)
6339  {
6340  Expr *expr = (Expr *) lfirst(lc);
6341 
6342  /*
6343  * If aggregates within local conditions are not safe to push
6344  * down, then we cannot push down the query. Vars are already
6345  * part of GROUP BY clause which are checked above, so no need to
6346  * access them again here. Again, we need not check
6347  * is_foreign_param for a foreign aggregate.
6348  */
6349  if (IsA(expr, Aggref))
6350  {
6351  if (!is_foreign_expr(root, grouped_rel, expr))
6352  return false;
6353 
6354  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6355  }
6356  }
6357  }
6358 
6359  /* Store generated targetlist */
6360  fpinfo->grouped_tlist = tlist;
6361 
6362  /* Safe to pushdown */
6363  fpinfo->pushdown_safe = true;
6364 
6365  /*
6366  * Set # of retrieved rows and cached relation costs to some negative
6367  * value, so that we can detect when they are set to some sensible values,
6368  * during one (usually the first) of the calls to estimate_path_cost_size.
6369  */
6370  fpinfo->retrieved_rows = -1;
6371  fpinfo->rel_startup_cost = -1;
6372  fpinfo->rel_total_cost = -1;
6373 
6374  /*
6375  * Set the string describing this grouped relation to be used in EXPLAIN
6376  * output of corresponding ForeignScan. Note that the decoration we add
6377  * to the base relation name mustn't include any digits, or it'll confuse
6378  * postgresExplainForeignScan.
6379  */
6380  fpinfo->relation_name = psprintf("Aggregate on (%s)",
6381  ofpinfo->relation_name);
6382 
6383  return true;
6384 }
bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:1078
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:183
#define list_make1(x1)
Definition: pg_list.h:210
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
RestrictInfo * make_restrictinfo(PlannerInfo *root, Expr *clause, bool is_pushed_down, bool outerjoin_delayed, bool pseudoconstant, Index security_level, Relids required_relids, Relids outer_relids, Relids nullable_relids)
Definition: restrictinfo.c:61
Index qual_security_level
Definition: pathnodes.h:448
List * groupingSets
Definition: parsenodes.h:173
Index ressortgroupref
Definition: primnodes.h:1558
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 5520 of file postgres_fdw.c.

5523 {
5524  PgFdwRelationInfo *fpinfo;
5525  PgFdwRelationInfo *fpinfo_o;
5526  PgFdwRelationInfo *fpinfo_i;
5527  ListCell *lc;
5528  List *joinclauses;
5529 
5530  /*
5531  * We support pushing down INNER, LEFT, RIGHT and FULL OUTER joins.
5532  * Constructing queries representing SEMI and ANTI joins is hard, hence
5533  * not considered right now.
5534  */
5535  if (jointype != JOIN_INNER && jointype != JOIN_LEFT &&
5536  jointype != JOIN_RIGHT && jointype != JOIN_FULL)
5537  return false;
5538 
5539  /*
5540  * If either of the joining relations is marked as unsafe to pushdown, the
5541  * join can not be pushed down.
5542  */
5543  fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private;
5544  fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private;
5545  fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private;
5546  if (!fpinfo_o || !fpinfo_o->pushdown_safe ||
5547  !fpinfo_i || !fpinfo_i->pushdown_safe)
5548  return false;
5549 
5550  /*
5551  * If joining relations have local conditions, those conditions are
5552  * required to be applied before joining the relations. Hence the join can
5553  * not be pushed down.
5554  */
5555  if (fpinfo_o->local_conds || fpinfo_i->local_conds)
5556  return false;
5557 
5558  /*
5559  * Merge FDW options. We might be tempted to do this after we have deemed
5560  * the foreign join to be OK. But we must do this beforehand so that we
5561  * know which quals can be evaluated on the foreign server, which might
5562  * depend on shippable_extensions.
5563  */
5564  fpinfo->server = fpinfo_o->server;
5565  merge_fdw_options(fpinfo, fpinfo_o, fpinfo_i);
5566 
5567  /*
5568  * Separate restrict list into join quals and pushed-down (other) quals.
5569  *
5570  * Join quals belonging to an outer join must all be shippable, else we
5571  * cannot execute the join remotely. Add such quals to 'joinclauses'.
5572  *
5573  * Add other quals to fpinfo->remote_conds if they are shippable, else to
5574  * fpinfo->local_conds. In an inner join it's okay to execute conditions
5575  * either locally or remotely; the same is true for pushed-down conditions
5576  * at an outer join.
5577  *
5578  * Note we might return failure after having already scribbled on
5579  * fpinfo->remote_conds and fpinfo->local_conds. That's okay because we
5580  * won't consult those lists again if we deem the join unshippable.
5581  */
5582  joinclauses = NIL;
5583  foreach(lc, extra->restrictlist)
5584  {
5585  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
5586  bool is_remote_clause = is_foreign_expr(root, joinrel,
5587  rinfo->clause);
5588 
5589  if (IS_OUTER_JOIN(jointype) &&
5590  !RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5591  {
5592  if (!is_remote_clause)
5593  return false;
5594  joinclauses = lappend(joinclauses, rinfo);
5595  }
5596  else
5597  {
5598  if (is_remote_clause)
5599  fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
5600  else
5601  fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
5602  }
5603  }
5604 
5605  /*
5606  * deparseExplicitTargetList() isn't smart enough to handle anything other
5607  * than a Var. In particular, if there's some PlaceHolderVar that would
5608  * need to be evaluated within this join tree (because there's an upper
5609  * reference to a quantity that may go to NULL as a result of an outer
5610  * join), then we can't try to push the join down because we'll fail when
5611  * we get to deparseExplicitTargetList(). However, a PlaceHolderVar that
5612  * needs to be evaluated *at the top* of this join tree is OK, because we
5613  * can do that locally after fetching the results from the remote side.
5614  */
5615  foreach(lc, root->placeholder_list)
5616  {
5617  PlaceHolderInfo *phinfo = lfirst(lc);
5618  Relids relids;
5619 
5620  /* PlaceHolderInfo refers to parent relids, not child relids. */
5621  relids = IS_OTHER_REL(joinrel) ?
5622  joinrel->top_parent_relids : joinrel->relids;
5623 
5624  if (bms_is_subset(phinfo->ph_eval_at, relids) &&
5625  bms_nonempty_difference(relids, phinfo->ph_eval_at))
5626  return false;
5627  }
5628 
5629  /* Save the join clauses, for later use. */
5630  fpinfo->joinclauses = joinclauses;
5631 
5632  fpinfo->outerrel = outerrel;
5633  fpinfo->innerrel = innerrel;
5634  fpinfo->jointype = jointype;
5635 
5636  /*
5637  * By default, both the input relations are not required to be deparsed as
5638  * subqueries, but there might be some relations covered by the input
5639  * relations that are required to be deparsed as subqueries, so save the
5640  * relids of those relations for later use by the deparser.
5641  */
5642  fpinfo->make_outerrel_subquery = false;
5643  fpinfo->make_innerrel_subquery = false;
5644  Assert(bms_is_subset(fpinfo_o->lower_subquery_rels, outerrel->relids));
5645  Assert(bms_is_subset(fpinfo_i->lower_subquery_rels, innerrel->relids));
5647  fpinfo_i->lower_subquery_rels);
5648 
5649  /*
5650  * Pull the other remote conditions from the joining relations into join
5651  * clauses or other remote clauses (remote_conds) of this relation
5652  * wherever possible. This avoids building subqueries at every join step.
5653  *
5654  * For an inner join, clauses from both the relations are added to the
5655  * other remote clauses. For LEFT and RIGHT OUTER join, the clauses from
5656  * the outer side are added to remote_conds since those can be evaluated
5657  * after the join is evaluated. The clauses from inner side are added to
5658  * the joinclauses, since they need to be evaluated while constructing the
5659  * join.
5660  *
5661  * For a FULL OUTER JOIN, the other clauses from either relation can not
5662  * be added to the joinclauses or remote_conds, since each relation acts
5663  * as an outer relation for the other.
5664  *
5665  * The joining sides can not have local conditions, thus no need to test
5666  * shippability of the clauses being pulled up.
5667  */
5668  switch (jointype)
5669  {
5670  case JOIN_INNER:
5671  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5672  fpinfo_i->remote_conds);
5673  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5674  fpinfo_o->remote_conds);
5675  break;
5676 
5677  case JOIN_LEFT:
5678  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5679  fpinfo_i->remote_conds);
5680  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5681  fpinfo_o->remote_conds);
5682  break;
5683 
5684  case JOIN_RIGHT:
5685  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5686  fpinfo_o->remote_conds);
5687  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5688  fpinfo_i->remote_conds);
5689  break;
5690 
5691  case JOIN_FULL:
5692 
5693  /*
5694  * In this case, if any of the input relations has conditions, we
5695  * need to deparse that relation as a subquery so that the
5696  * conditions can be evaluated before the join. Remember it in
5697  * the fpinfo of this relation so that the deparser can take
5698  * appropriate action. Also, save the relids of base relations
5699  * covered by that relation for later use by the deparser.
5700  */
5701  if (fpinfo_o->remote_conds)
5702  {
5703  fpinfo->make_outerrel_subquery = true;
5704  fpinfo->lower_subquery_rels =
5706  outerrel->relids);
5707  }
5708  if (fpinfo_i->remote_conds)
5709  {
5710  fpinfo->make_innerrel_subquery = true;
5711  fpinfo->lower_subquery_rels =
5713  innerrel->relids);
5714  }
5715  break;
5716 
5717  default:
5718  /* Should not happen, we have just checked this above */
5719  elog(ERROR, "unsupported join type %d", jointype);
5720  }
5721 
5722  /*
5723  * For an inner join, all restrictions can be treated alike. Treating the
5724  * pushed down conditions as join conditions allows a top level full outer
5725  * join to be deparsed without requiring subqueries.
5726  */
5727  if (jointype == JOIN_INNER)
5728  {
5729  Assert(!fpinfo->joinclauses);
5730  fpinfo->joinclauses = fpinfo->remote_conds;
5731  fpinfo->remote_conds = NIL;
5732  }
5733 
5734  /* Mark that this join can be pushed down safely */
5735  fpinfo->pushdown_safe = true;
5736 
5737  /* Get user mapping */
5738  if (fpinfo->use_remote_estimate)
5739  {
5740  if (fpinfo_o->use_remote_estimate)
5741  fpinfo->user = fpinfo_o->user;
5742  else
5743  fpinfo->user = fpinfo_i->user;
5744  }
5745  else
5746  fpinfo->user = NULL;
5747 
5748  /*
5749  * Set # of retrieved rows and cached relation costs to some negative
5750  * value, so that we can detect when they are set to some sensible values,
5751  * during one (usually the first) of the calls to estimate_path_cost_size.
5752  */
5753  fpinfo->retrieved_rows = -1;
5754  fpinfo->rel_startup_cost = -1;
5755  fpinfo->rel_total_cost = -1;
5756 
5757  /*
5758  * Set the string describing this join relation to be used in EXPLAIN
5759  * output of corresponding ForeignScan. Note that the decoration we add
5760  * to the base relation names mustn't include any digits, or it'll confuse
5761  * postgresExplainForeignScan.
5762  */
5763  fpinfo->relation_name = psprintf("(%s) %s JOIN (%s)",
5764  fpinfo_o->relation_name,
5765  get_jointype_name(fpinfo->jointype),
5766  fpinfo_i->relation_name);
5767 
5768  /*
5769  * Set the relation index. This is defined as the position of this
5770  * joinrel in the join_rel_list list plus the length of the rtable list.
5771  * Note that since this joinrel is at the end of the join_rel_list list
5772  * when we are called, we can get the position by list_length.
5773  */
5774  Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */
5775  fpinfo->relation_index =
5777 
5778  return true;
5779 }
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:226
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:796
bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:548
const char * get_jointype_name(JoinType jointype)
Definition: deparse.c:1603
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:336
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_LEFT
Definition: nodes.h:294
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2566
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:804
Relids lower_subquery_rels
Definition: postgres_fdw.h:119
Relids ph_eval_at
Definition: pathnodes.h:2873
List * join_rel_list
Definition: pathnodes.h:273
List * placeholder_list
Definition: pathnodes.h:361
List * rtable
Definition: parsenodes.h:155
Relids top_parent_relids
Definition: pathnodes.h:954

References Assert(), bms_add_members(), bms_is_subset(), bms_nonempty_difference(), bms_union(), RestrictInfo::clause, elog(), ERROR, get_jointype_name(), if(), PgFdwRelationInfo::innerrel, is_foreign_expr(), IS_OTHER_REL, IS_OUTER_JOIN, JOIN_FULL, JOIN_INNER, JOIN_LEFT, PlannerInfo::join_rel_list, JOIN_RIGHT, PgFdwRelationInfo::joinclauses, PgFdwRelationInfo::jointype, lappend(), lfirst, lfirst_node, list_concat(), 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, 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 7560 of file postgres_fdw.c.

7561 {
7562  Oid foreigntableid = RelationGetRelid(rel);
7563  ForeignTable *table;
7564  ForeignServer *server;
7565  List *options;
7566  ListCell *lc;
7567 
7568  /* we use 1 by default, which means "no batching" */
7569  int batch_size = 1;
7570 
7571  /*
7572  * Load options for table and server. We append server options after table
7573  * options, because table options take precedence.
7574  */
7575  table = GetForeignTable(foreigntableid);
7576  server = GetForeignServer(table->serverid);
7577 
7578  options = NIL;
7579  options = list_concat(options, table->options);
7580  options = list_concat(options, server->options);
7581 
7582  /* See if either table or server specifies batch_size. */
7583  foreach(lc, options)
7584  {
7585  DefElem *def = (DefElem *) lfirst(lc);
7586 
7587  if (strcmp(def->defname, "batch_size") == 0)
7588  {
7589  (void) parse_int(defGetString(def), &batch_size, 0, NULL);
7590  break;
7591  }
7592  }
7593 
7594  return batch_size;
7595 }
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 3575 of file postgres_fdw.c.

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

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 4590 of file postgres_fdw.c.

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

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 1435 of file postgres_fdw.c.

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

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 806 of file postgres_fdw.c.

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

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 902 of file postgres_fdw.c.

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

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 4663 of file postgres_fdw.c.

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

7209 {
7210  HeapTuple tuple;
7211  TupleDesc tupdesc;
7212  Datum *values;
7213  bool *nulls;
7214  ItemPointer ctid = NULL;
7215  ConversionLocation errpos;
7216  ErrorContextCallback errcallback;
7217  MemoryContext oldcontext;
7218  ListCell *lc;
7219  int j;
7220 
7221  Assert(row < PQntuples(res));
7222 
7223  /*
7224  * Do the following work in a temp context that we reset after each tuple.
7225  * This cleans up not only the data we have direct access to, but any
7226  * cruft the I/O functions might leak.
7227  */
7228  oldcontext = MemoryContextSwitchTo(temp_context);
7229 
7230  /*
7231  * Get the tuple descriptor for the row. Use the rel's tupdesc if rel is
7232  * provided, otherwise look to the scan node's ScanTupleSlot.
7233  */
7234  if (rel)
7235  tupdesc = RelationGetDescr(rel);
7236  else
7237  {
7238  Assert(fsstate);
7239  tupdesc = fsstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
7240  }
7241 
7242  values = (Datum *) palloc0(tupdesc->natts * sizeof(Datum));
7243  nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
7244  /* Initialize to nulls for any columns not present in result */
7245  memset(nulls, true, tupdesc->natts * sizeof(bool));
7246 
7247  /*
7248  * Set up and install callback to report where conversion error occurs.
7249  */
7250  errpos.cur_attno = 0;
7251  errpos.rel = rel;
7252  errpos.fsstate = fsstate;
7253  errcallback.callback = conversion_error_callback;
7254  errcallback.arg = (void *) &errpos;
7255  errcallback.previous = error_context_stack;
7256  error_context_stack = &errcallback;
7257 
7258  /*
7259  * i indexes columns in the relation, j indexes columns in the PGresult.
7260  */
7261  j = 0;
7262  foreach(lc, retrieved_attrs)
7263  {
7264  int i = lfirst_int(lc);
7265  char *valstr;
7266 
7267  /* fetch next column's textual value */
7268  if (PQgetisnull(res, row, j))
7269  valstr = NULL;
7270  else
7271  valstr = PQgetvalue(res, row, j);
7272 
7273  /*
7274  * convert value to internal representation
7275  *
7276  * Note: we ignore system columns other than ctid and oid in result
7277  */
7278  errpos.cur_attno = i;
7279  if (i > 0)
7280  {
7281  /* ordinary column */
7282  Assert(i <= tupdesc->natts);
7283  nulls[i - 1] = (valstr == NULL);
7284  /* Apply the input function even to nulls, to support domains */
7285  values[i - 1] = InputFunctionCall(&attinmeta->attinfuncs[i - 1],
7286  valstr,
7287  attinmeta->attioparams[i - 1],
7288  attinmeta->atttypmods[i - 1]);
7289  }
7290  else if (i == SelfItemPointerAttributeNumber)
7291  {
7292  /* ctid */
7293  if (valstr != NULL)
7294  {
7295  Datum datum;
7296 
7297  datum = DirectFunctionCall1(tidin, CStringGetDatum(valstr));
7298  ctid = (ItemPointer) DatumGetPointer(datum);
7299  }
7300  }
7301  errpos.cur_attno = 0;
7302 
7303  j++;
7304  }
7305 
7306  /* Uninstall error context callback. */
7307  error_context_stack = errcallback.previous;
7308 
7309  /*
7310  * Check we got the expected number of columns. Note: j == 0 and
7311  * PQnfields == 1 is expected, since deparse emits a NULL if no columns.
7312  */
7313  if (j > 0 && j != PQnfields(res))
7314  elog(ERROR, "remote query result does not match the foreign table");
7315 
7316  /*
7317  * Build the result tuple in caller's memory context.
7318  */
7319  MemoryContextSwitchTo(oldcontext);
7320 
7321  tuple = heap_form_tuple(tupdesc, values, nulls);
7322 
7323  /*
7324  * If we have a CTID to return, install it in both t_self and t_ctid.
7325  * t_self is the normal place, but if the tuple is converted to a
7326  * composite Datum, t_self will be lost; setting t_ctid allows CTID to be
7327  * preserved during EvalPlanQual re-evaluations (see ROW_MARK_COPY code).
7328  */
7329  if (ctid)
7330  tuple->t_self = tuple->t_data->t_ctid = *ctid;
7331 
7332  /*
7333  * Stomp on the xmin, xmax, and cmin fields from the tuple created by
7334  * heap_form_tuple. heap_form_tuple actually creates the tuple with
7335  * DatumTupleFields, not HeapTupleFields, but the executor expects
7336  * HeapTupleFields and will happily extract system columns on that
7337  * assumption. If we don't do this then, for example, the tuple length
7338  * ends up in the xmin field, which isn't what we want.
7339  */
7343 
7344  /* Clean up */
7345  MemoryContextReset(temp_context);
7346 
7347  return tuple;
7348 }
ErrorContextCallback * error_context_stack
Definition: elog.c:94
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3730
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3318
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1515
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:698
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:234
void(* callback)(void *arg)
Definition: elog.h:235
ItemPointerData t_ctid
Definition: htup_details.h:160
Datum tidin(PG_FUNCTION_ARGS)
Definition: tid.c:57

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 5957 of file postgres_fdw.c.

5960 {
5961  /* We must always have fpinfo_o. */
5962  Assert(fpinfo_o);
5963 
5964  /* fpinfo_i may be NULL, but if present the servers must both match. */
5965  Assert(!fpinfo_i ||
5966  fpinfo_i->server->serverid == fpinfo_o->server->serverid);
5967 
5968  /*
5969  * Copy the server specific FDW options. (For a join, both relations come
5970  * from the same server, so the server options should have the same value
5971  * for both relations.)
5972  */
5973  fpinfo->fdw_startup_cost = fpinfo_o->fdw_startup_cost;
5974  fpinfo->fdw_tuple_cost = fpinfo_o->fdw_tuple_cost;
5975  fpinfo->shippable_extensions = fpinfo_o->shippable_extensions;
5976  fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate;
5977  fpinfo->fetch_size = fpinfo_o->fetch_size;
5978  fpinfo->async_capable = fpinfo_o->async_capable;
5979 
5980  /* Merge the table level options from either side of the join. */
5981  if (fpinfo_i)
5982  {
5983  /*
5984  * We'll prefer to use remote estimates for this join if any table
5985  * from either side of the join is using remote estimates. This is
5986  * most likely going to be preferred since they're already willing to
5987  * pay the price of a round trip to get the remote EXPLAIN. In any
5988  * case it's not entirely clear how we might otherwise handle this
5989  * best.
5990  */
5991  fpinfo->use_remote_estimate = fpinfo_o->use_remote_estimate ||
5992  fpinfo_i->use_remote_estimate;
5993 
5994  /*
5995  * Set fetch size to maximum of the joining sides, since we are
5996  * expecting the rows returned by the join to be proportional to the
5997  * relation sizes.
5998  */
5999  fpinfo->fetch_size = Max(fpinfo_o->fetch_size, fpinfo_i->fetch_size);
6000 
6001  /*
6002  * We'll prefer to consider this join async-capable if any table from
6003  * either side of the join is considered async-capable. This would be
6004  * reasonable because in that case the foreign server would have its
6005  * own resources to scan that table asynchronously, and the join could
6006  * also be computed asynchronously using the resources.
6007  */
6008  fpinfo->async_capable = fpinfo_o->async_capable ||
6009  fpinfo_i->async_capable;
6010  }
6011 }
#define Max(x, y)
Definition: c.h:931
Oid serverid
Definition: foreign.h:36

References Assert(), PgFdwRelationInfo::async_capable, PgFdwRelationInfo::fdw_startup_cost, PgFdwRelationInfo::fdw_tuple_cost, PgFdwRelationInfo::fetch_size, Max, PgFdwRelationInfo::server, ForeignServer::serverid, PgFdwRelationInfo::shippable_extensions, and PgFdwRelationInfo::use_remote_estimate.

Referenced by add_foreign_final_paths(), add_foreign_grouping_paths(), add_foreign_ordered_paths(), and foreign_join_ok().

◆ PG_FUNCTION_INFO_V1()

PG_FUNCTION_INFO_V1 ( postgres_fdw_handler  )

◆ postgres_fdw_handler()

Datum postgres_fdw_handler ( PG_FUNCTION_ARGS  )

Definition at line 551 of file postgres_fdw.c.

552 {
553  FdwRoutine *routine = makeNode(FdwRoutine);
554 
555  /* Functions for scanning foreign tables */
563 
564  /* Functions for updating foreign tables */
581 
582  /* Function for EvalPlanQual rechecks */
584  /* Support functions for EXPLAIN */
588 
589  /* Support function for TRUNCATE */
590  routine->