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 "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 len, 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 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)
 
Exprfind_em_expr_for_input_target (PlannerInfo *root, EquivalenceClass *ec, PathTarget *target)
 

Variables

 PG_MODULE_MAGIC
 

Macro Definition Documentation

◆ DEFAULT_FDW_SORT_MULTIPLIER

#define DEFAULT_FDW_SORT_MULTIPLIER   1.2

Definition at line 61 of file postgres_fdw.c.

Referenced by adjust_foreign_grouping_path_cost(), and estimate_path_cost_size().

◆ DEFAULT_FDW_STARTUP_COST

#define DEFAULT_FDW_STARTUP_COST   100.0

Definition at line 55 of file postgres_fdw.c.

Referenced by postgresGetForeignRelSize().

◆ DEFAULT_FDW_TUPLE_COST

#define DEFAULT_FDW_TUPLE_COST   0.01

Definition at line 58 of file postgres_fdw.c.

Referenced by postgresGetForeignRelSize().

Typedef Documentation

◆ ConversionLocation

◆ PgFdwAnalyzeState

◆ PgFdwDirectModifyState

◆ PgFdwModifyState

◆ PgFdwScanState

Enumeration Type Documentation

◆ FdwDirectModifyPrivateIndex

Enumerator
FdwDirectModifyPrivateUpdateSql 
FdwDirectModifyPrivateHasReturning 
FdwDirectModifyPrivateRetrievedAttrs 
FdwDirectModifyPrivateSetProcessed 

Definition at line 121 of file postgres_fdw.c.

122 {
123  /* SQL statement to execute remotely (as a String node) */
125  /* has-returning flag (as an integer Value node) */
127  /* Integer list of attribute numbers retrieved by RETURNING */
129  /* set-processed flag (as an integer Value node) */
131 };

◆ FdwModifyPrivateIndex

Enumerator
FdwModifyPrivateUpdateSql 
FdwModifyPrivateTargetAttnums 
FdwModifyPrivateLen 
FdwModifyPrivateHasReturning 
FdwModifyPrivateRetrievedAttrs 

Definition at line 98 of file postgres_fdw.c.

99 {
100  /* SQL statement to execute remotely (as a String node) */
102  /* Integer list of target attribute numbers for INSERT/UPDATE */
104  /* Length till the end of VALUES clause (as an integer Value node) */
106  /* has-returning flag (as an integer Value node) */
108  /* Integer list of attribute numbers retrieved by RETURNING */
110 };

◆ FdwPathPrivateIndex

Enumerator
FdwPathPrivateHasFinalSort 
FdwPathPrivateHasLimit 

Definition at line 281 of file postgres_fdw.c.

282 {
283  /* has-final-sort flag (as an integer Value node) */
285  /* has-limit flag (as an integer Value node) */
287 };

◆ FdwScanPrivateIndex

Enumerator
FdwScanPrivateSelectSql 
FdwScanPrivateRetrievedAttrs 
FdwScanPrivateFetchSize 
FdwScanPrivateRelations 

Definition at line 70 of file postgres_fdw.c.

71 {
72  /* SQL statement to execute remotely (as a String node) */
74  /* Integer list of attribute numbers retrieved by the SELECT */
76  /* Integer representing the desired fetch_size */
78 
79  /*
80  * String describing join i.e. names of relations being joined and types
81  * of join, added when the scan is join
82  */
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 6563 of file postgres_fdw.c.

References add_path(), Assert, CMD_SELECT, Query::commandType, PgFdwPathExtraData::count_est, FinalPathExtraData::count_est, create_foreign_upper_path(), estimate_path_cost_size(), RelOptInfo::fdw_private, PgFdwPathExtraData::has_final_sort, PgFdwPathExtraData::has_limit, Query::hasTargetSRFs, is_foreign_expr(), IsA, lfirst, FinalPathExtraData::limit_needed, PgFdwPathExtraData::limit_tuples, FinalPathExtraData::limit_tuples, Query::limitCount, Query::limitOffset, list_make2, PgFdwRelationInfo::local_conds, makeInteger(), merge_fdw_options(), NIL, PgFdwPathExtraData::offset_est, FinalPathExtraData::offset_est, PgFdwRelationInfo::outerrel, palloc0(), parse(), PlannerInfo::parse, RelOptInfo::pathlist, RELOPT_BASEREL, RELOPT_JOINREL, RELOPT_UPPER_REL, RelOptInfo::reloptkind, Query::rowMarks, PgFdwRelationInfo::server, PlannerInfo::sort_pathkeys, PgFdwRelationInfo::stage, subpath(), PgFdwRelationInfo::table, PgFdwPathExtraData::target, PlannerInfo::upper_targets, UPPERREL_FINAL, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, PgFdwRelationInfo::use_remote_estimate, and PgFdwRelationInfo::user.

Referenced by postgresGetForeignUpperPaths().

6566 {
6567  Query *parse = root->parse;
6568  PgFdwRelationInfo *ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
6569  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) final_rel->fdw_private;
6570  bool has_final_sort = false;
6571  List *pathkeys = NIL;
6572  PgFdwPathExtraData *fpextra;
6573  bool save_use_remote_estimate = false;
6574  double rows;
6575  int width;
6576  Cost startup_cost;
6577  Cost total_cost;
6578  List *fdw_private;
6579  ForeignPath *final_path;
6580 
6581  /*
6582  * Currently, we only support this for SELECT commands
6583  */
6584  if (parse->commandType != CMD_SELECT)
6585  return;
6586 
6587  /*
6588  * No work if there is no FOR UPDATE/SHARE clause and if there is no need
6589  * to add a LIMIT node
6590  */
6591  if (!parse->rowMarks && !extra->limit_needed)
6592  return;
6593 
6594  /* We don't support cases where there are any SRFs in the targetlist */
6595  if (parse->hasTargetSRFs)
6596  return;
6597 
6598  /* Save the input_rel as outerrel in fpinfo */
6599  fpinfo->outerrel = input_rel;
6600 
6601  /*
6602  * Copy foreign table, foreign server, user mapping, FDW options etc.
6603  * details from the input relation's fpinfo.
6604  */
6605  fpinfo->table = ifpinfo->table;
6606  fpinfo->server = ifpinfo->server;
6607  fpinfo->user = ifpinfo->user;
6608  merge_fdw_options(fpinfo, ifpinfo, NULL);
6609 
6610  /*
6611  * If there is no need to add a LIMIT node, there might be a ForeignPath
6612  * in the input_rel's pathlist that implements all behavior of the query.
6613  * Note: we would already have accounted for the query's FOR UPDATE/SHARE
6614  * (if any) before we get here.
6615  */
6616  if (!extra->limit_needed)
6617  {
6618  ListCell *lc;
6619 
6620  Assert(parse->rowMarks);
6621 
6622  /*
6623  * Grouping and aggregation are not supported with FOR UPDATE/SHARE,
6624  * so the input_rel should be a base, join, or ordered relation; and
6625  * if it's an ordered relation, its input relation should be a base or
6626  * join relation.
6627  */
6628  Assert(input_rel->reloptkind == RELOPT_BASEREL ||
6629  input_rel->reloptkind == RELOPT_JOINREL ||
6630  (input_rel->reloptkind == RELOPT_UPPER_REL &&
6631  ifpinfo->stage == UPPERREL_ORDERED &&
6632  (ifpinfo->outerrel->reloptkind == RELOPT_BASEREL ||
6633  ifpinfo->outerrel->reloptkind == RELOPT_JOINREL)));
6634 
6635  foreach(lc, input_rel->pathlist)
6636  {
6637  Path *path = (Path *) lfirst(lc);
6638 
6639  /*
6640  * apply_scanjoin_target_to_paths() uses create_projection_path()
6641  * to adjust each of its input paths if needed, whereas
6642  * create_ordered_paths() uses apply_projection_to_path() to do
6643  * that. So the former might have put a ProjectionPath on top of
6644  * the ForeignPath; look through ProjectionPath and see if the
6645  * path underneath it is ForeignPath.
6646  */
6647  if (IsA(path, ForeignPath) ||
6648  (IsA(path, ProjectionPath) &&
6649  IsA(((ProjectionPath *) path)->subpath, ForeignPath)))
6650  {
6651  /*
6652  * Create foreign final path; this gets rid of a
6653  * no-longer-needed outer plan (if any), which makes the
6654  * EXPLAIN output look cleaner
6655  */
6656  final_path = create_foreign_upper_path(root,
6657  path->parent,
6658  path->pathtarget,
6659  path->rows,
6660  path->startup_cost,
6661  path->total_cost,
6662  path->pathkeys,
6663  NULL, /* no extra plan */
6664  NULL); /* no fdw_private */
6665 
6666  /* and add it to the final_rel */
6667  add_path(final_rel, (Path *) final_path);
6668 
6669  /* Safe to push down */
6670  fpinfo->pushdown_safe = true;
6671 
6672  return;
6673  }
6674  }
6675 
6676  /*
6677  * If we get here it means no ForeignPaths; since we would already
6678  * have considered pushing down all operations for the query to the
6679  * remote server, give up on it.
6680  */
6681  return;
6682  }
6683 
6684  Assert(extra->limit_needed);
6685 
6686  /*
6687  * If the input_rel is an ordered relation, replace the input_rel with its
6688  * input relation
6689  */
6690  if (input_rel->reloptkind == RELOPT_UPPER_REL &&
6691  ifpinfo->stage == UPPERREL_ORDERED)
6692  {
6693  input_rel = ifpinfo->outerrel;
6694  ifpinfo = (PgFdwRelationInfo *) input_rel->fdw_private;
6695  has_final_sort = true;
6696  pathkeys = root->sort_pathkeys;
6697  }
6698 
6699  /* The input_rel should be a base, join, or grouping relation */
6700  Assert(input_rel->reloptkind == RELOPT_BASEREL ||
6701  input_rel->reloptkind == RELOPT_JOINREL ||
6702  (input_rel->reloptkind == RELOPT_UPPER_REL &&
6703  ifpinfo->stage == UPPERREL_GROUP_AGG));
6704 
6705  /*
6706  * We try to create a path below by extending a simple foreign path for
6707  * the underlying base, join, or grouping relation to perform the final
6708  * sort (if has_final_sort) and the LIMIT restriction remotely, which is
6709  * stored into the fdw_private list of the resulting path. (We
6710  * re-estimate the costs of sorting the underlying relation, if
6711  * has_final_sort.)
6712  */
6713 
6714  /*
6715  * Assess if it is safe to push down the LIMIT and OFFSET to the remote
6716  * server
6717  */
6718 
6719  /*
6720  * If the underlying relation has any local conditions, the LIMIT/OFFSET
6721  * cannot be pushed down.
6722  */
6723  if (ifpinfo->local_conds)
6724  return;
6725 
6726  /*
6727  * Also, the LIMIT/OFFSET cannot be pushed down, if their expressions are
6728  * not safe to remote.
6729  */
6730  if (!is_foreign_expr(root, input_rel, (Expr *) parse->limitOffset) ||
6731  !is_foreign_expr(root, input_rel, (Expr *) parse->limitCount))
6732  return;
6733 
6734  /* Safe to push down */
6735  fpinfo->pushdown_safe = true;
6736 
6737  /* Construct PgFdwPathExtraData */
6738  fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
6739  fpextra->target = root->upper_targets[UPPERREL_FINAL];
6740  fpextra->has_final_sort = has_final_sort;
6741  fpextra->has_limit = extra->limit_needed;
6742  fpextra->limit_tuples = extra->limit_tuples;
6743  fpextra->count_est = extra->count_est;
6744  fpextra->offset_est = extra->offset_est;
6745 
6746  /*
6747  * Estimate the costs of performing the final sort and the LIMIT
6748  * restriction remotely. If has_final_sort is false, we wouldn't need to
6749  * execute EXPLAIN anymore if use_remote_estimate, since the costs can be
6750  * roughly estimated using the costs we already have for the underlying
6751  * relation, in the same way as when use_remote_estimate is false. Since
6752  * it's pretty expensive to execute EXPLAIN, force use_remote_estimate to
6753  * false in that case.
6754  */
6755  if (!fpextra->has_final_sort)
6756  {
6757  save_use_remote_estimate = ifpinfo->use_remote_estimate;
6758  ifpinfo->use_remote_estimate = false;
6759  }
6760  estimate_path_cost_size(root, input_rel, NIL, pathkeys, fpextra,
6761  &rows, &width, &startup_cost, &total_cost);
6762  if (!fpextra->has_final_sort)
6763  ifpinfo->use_remote_estimate = save_use_remote_estimate;
6764 
6765  /*
6766  * Build the fdw_private list that will be used by postgresGetForeignPlan.
6767  * Items in the list must match order in enum FdwPathPrivateIndex.
6768  */
6769  fdw_private = list_make2(makeInteger(has_final_sort),
6770  makeInteger(extra->limit_needed));
6771 
6772  /*
6773  * Create foreign final path; this gets rid of a no-longer-needed outer
6774  * plan (if any), which makes the EXPLAIN output look cleaner
6775  */
6776  final_path = create_foreign_upper_path(root,
6777  input_rel,
6779  rows,
6780  startup_cost,
6781  total_cost,
6782  pathkeys,
6783  NULL, /* no extra plan */
6784  fdw_private);
6785 
6786  /* and add it to the final_rel */
6787  add_path(final_rel, (Path *) final_path);
6788 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
Node * limitOffset
Definition: parsenodes.h:171
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
PathTarget * pathtarget
Definition: pathnodes.h:1175
Query * parse
Definition: pathnodes.h:161
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:2301
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
RelOptKind reloptkind
Definition: pathnodes.h:673
PathTarget * target
Definition: postgres_fdw.c:292
ForeignServer * server
Definition: postgres_fdw.h:86
List * rowMarks
Definition: parsenodes.h:175
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_i)
Cost startup_cost
Definition: pathnodes.h:1185
RelOptInfo * parent
Definition: pathnodes.h:1174
Node * limitCount
Definition: parsenodes.h:172
List * sort_pathkeys
Definition: pathnodes.h:298
Value * makeInteger(int i)
Definition: value.c:23
UserMapping * user
Definition: postgres_fdw.h:87
void * palloc0(Size size)
Definition: mcxt.c:1093
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)
void * fdw_private
Definition: pathnodes.h:732
Cost total_cost
Definition: pathnodes.h:1186
CmdType commandType
Definition: parsenodes.h:120
bool hasTargetSRFs
Definition: parsenodes.h:135
List * pathkeys
Definition: pathnodes.h:1188
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
ForeignTable * table
Definition: postgres_fdw.h:85
double rows
Definition: pathnodes.h:1184
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:231
UpperRelationKind stage
Definition: postgres_fdw.h:109
List * pathlist
Definition: pathnodes.h:690
Definition: pg_list.h:50
double Cost
Definition: nodes.h:673
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: pathnodes.h:309

◆ add_foreign_grouping_paths()

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

Definition at line 6345 of file postgres_fdw.c.

References add_path(), Assert, clauselist_selectivity(), cost_qual_eval(), create_foreign_upper_path(), estimate_path_cost_size(), RelOptInfo::fdw_private, foreign_grouping_ok(), Query::groupClause, Query::groupingSets, Query::hasAggs, 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().

6348 {
6349  Query *parse = root->parse;
6350  PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6351  PgFdwRelationInfo *fpinfo = grouped_rel->fdw_private;
6352  ForeignPath *grouppath;
6353  double rows;
6354  int width;
6355  Cost startup_cost;
6356  Cost total_cost;
6357 
6358  /* Nothing to be done, if there is no grouping or aggregation required. */
6359  if (!parse->groupClause && !parse->groupingSets && !parse->hasAggs &&
6360  !root->hasHavingQual)
6361  return;
6362 
6365 
6366  /* save the input_rel as outerrel in fpinfo */
6367  fpinfo->outerrel = input_rel;
6368 
6369  /*
6370  * Copy foreign table, foreign server, user mapping, FDW options etc.
6371  * details from the input relation's fpinfo.
6372  */
6373  fpinfo->table = ifpinfo->table;
6374  fpinfo->server = ifpinfo->server;
6375  fpinfo->user = ifpinfo->user;
6376  merge_fdw_options(fpinfo, ifpinfo, NULL);
6377 
6378  /*
6379  * Assess if it is safe to push down aggregation and grouping.
6380  *
6381  * Use HAVING qual from extra. In case of child partition, it will have
6382  * translated Vars.
6383  */
6384  if (!foreign_grouping_ok(root, grouped_rel, extra->havingQual))
6385  return;
6386 
6387  /*
6388  * Compute the selectivity and cost of the local_conds, so we don't have
6389  * to do it over again for each path. (Currently we create just a single
6390  * path here, but in future it would be possible that we build more paths
6391  * such as pre-sorted paths as in postgresGetForeignPaths and
6392  * postgresGetForeignJoinPaths.) The best we can do for these conditions
6393  * is to estimate selectivity on the basis of local statistics.
6394  */
6395  fpinfo->local_conds_sel = clauselist_selectivity(root,
6396  fpinfo->local_conds,
6397  0,
6398  JOIN_INNER,
6399  NULL);
6400 
6401  cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
6402 
6403  /* Estimate the cost of push down */
6404  estimate_path_cost_size(root, grouped_rel, NIL, NIL, NULL,
6405  &rows, &width, &startup_cost, &total_cost);
6406 
6407  /* Now update this information in the fpinfo */
6408  fpinfo->rows = rows;
6409  fpinfo->width = width;
6410  fpinfo->startup_cost = startup_cost;
6411  fpinfo->total_cost = total_cost;
6412 
6413  /* Create and add foreign path to the grouping relation. */
6414  grouppath = create_foreign_upper_path(root,
6415  grouped_rel,
6416  grouped_rel->reltarget,
6417  rows,
6418  startup_cost,
6419  total_cost,
6420  NIL, /* no pathkeys */
6421  NULL,
6422  NIL); /* no fdw_private */
6423 
6424  /* Add generated path into grouped_rel by add_path(). */
6425  add_path(grouped_rel, (Path *) grouppath);
6426 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
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:2301
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool hasAggs
Definition: parsenodes.h:133
ForeignServer * server
Definition: postgres_fdw.h:86
List * groupingSets
Definition: parsenodes.h:161
PartitionwiseAggregateType patype
Definition: pathnodes.h:2588
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_i)
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4311
Selectivity local_conds_sel
Definition: postgres_fdw.h:57
UserMapping * user
Definition: postgres_fdw.h:87
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)
void * fdw_private
Definition: pathnodes.h:732
#define Assert(condition)
Definition: c.h:804
ForeignTable * table
Definition: postgres_fdw.h:85
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel, Node *havingQual)
List * groupClause
Definition: parsenodes.h:158
bool hasHavingQual
Definition: pathnodes.h:347
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
struct PathTarget * reltarget
Definition: pathnodes.h:687
double Cost
Definition: nodes.h:673
QualCost local_conds_cost
Definition: postgres_fdw.h:56
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

◆ add_foreign_ordered_paths()

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

Definition at line 6436 of file postgres_fdw.c.

References add_path(), Assert, create_foreign_upper_path(), EquivalenceClass::ec_has_volatile, estimate_path_cost_size(), RelOptInfo::fdw_private, find_em_expr_for_input_target(), PgFdwPathExtraData::has_final_sort, Query::hasTargetSRFs, is_foreign_expr(), lfirst, list_make2, makeInteger(), merge_fdw_options(), NIL, PgFdwRelationInfo::outerrel, palloc0(), parse(), PlannerInfo::parse, PathKey::pk_eclass, PgFdwRelationInfo::pushdown_safe, PgFdwRelationInfo::qp_is_pushdown_safe, PlannerInfo::query_pathkeys, RELOPT_BASEREL, RELOPT_JOINREL, RELOPT_UPPER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, PgFdwRelationInfo::server, PlannerInfo::sort_pathkeys, Query::sortClause, PgFdwRelationInfo::stage, PgFdwRelationInfo::table, PgFdwPathExtraData::target, PlannerInfo::upper_targets, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, and PgFdwRelationInfo::user.

Referenced by postgresGetForeignUpperPaths().

6438 {
6439  Query *parse = root->parse;
6440  PgFdwRelationInfo *ifpinfo = input_rel->fdw_private;
6441  PgFdwRelationInfo *fpinfo = ordered_rel->fdw_private;
6442  PgFdwPathExtraData *fpextra;
6443  double rows;
6444  int width;
6445  Cost startup_cost;
6446  Cost total_cost;
6447  List *fdw_private;
6448  ForeignPath *ordered_path;
6449  ListCell *lc;
6450 
6451  /* Shouldn't get here unless the query has ORDER BY */
6452  Assert(parse->sortClause);
6453 
6454  /* We don't support cases where there are any SRFs in the targetlist */
6455  if (parse->hasTargetSRFs)
6456  return;
6457 
6458  /* Save the input_rel as outerrel in fpinfo */
6459  fpinfo->outerrel = input_rel;
6460 
6461  /*
6462  * Copy foreign table, foreign server, user mapping, FDW options etc.
6463  * details from the input relation's fpinfo.
6464  */
6465  fpinfo->table = ifpinfo->table;
6466  fpinfo->server = ifpinfo->server;
6467  fpinfo->user = ifpinfo->user;
6468  merge_fdw_options(fpinfo, ifpinfo, NULL);
6469 
6470  /*
6471  * If the input_rel is a base or join relation, we would already have
6472  * considered pushing down the final sort to the remote server when
6473  * creating pre-sorted foreign paths for that relation, because the
6474  * query_pathkeys is set to the root->sort_pathkeys in that case (see
6475  * standard_qp_callback()).
6476  */
6477  if (input_rel->reloptkind == RELOPT_BASEREL ||
6478  input_rel->reloptkind == RELOPT_JOINREL)
6479  {
6480  Assert(root->query_pathkeys == root->sort_pathkeys);
6481 
6482  /* Safe to push down if the query_pathkeys is safe to push down */
6483  fpinfo->pushdown_safe = ifpinfo->qp_is_pushdown_safe;
6484 
6485  return;
6486  }
6487 
6488  /* The input_rel should be a grouping relation */
6489  Assert(input_rel->reloptkind == RELOPT_UPPER_REL &&
6490  ifpinfo->stage == UPPERREL_GROUP_AGG);
6491 
6492  /*
6493  * We try to create a path below by extending a simple foreign path for
6494  * the underlying grouping relation to perform the final sort remotely,
6495  * which is stored into the fdw_private list of the resulting path.
6496  */
6497 
6498  /* Assess if it is safe to push down the final sort */
6499  foreach(lc, root->sort_pathkeys)
6500  {
6501  PathKey *pathkey = (PathKey *) lfirst(lc);
6502  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
6503  Expr *sort_expr;
6504 
6505  /*
6506  * is_foreign_expr would detect volatile expressions as well, but
6507  * checking ec_has_volatile here saves some cycles.
6508  */
6509  if (pathkey_ec->ec_has_volatile)
6510  return;
6511 
6512  /* Get the sort expression for the pathkey_ec */
6513  sort_expr = find_em_expr_for_input_target(root,
6514  pathkey_ec,
6515  input_rel->reltarget);
6516 
6517  /* If it's unsafe to remote, we cannot push down the final sort */
6518  if (!is_foreign_expr(root, input_rel, sort_expr))
6519  return;
6520  }
6521 
6522  /* Safe to push down */
6523  fpinfo->pushdown_safe = true;
6524 
6525  /* Construct PgFdwPathExtraData */
6526  fpextra = (PgFdwPathExtraData *) palloc0(sizeof(PgFdwPathExtraData));
6527  fpextra->target = root->upper_targets[UPPERREL_ORDERED];
6528  fpextra->has_final_sort = true;
6529 
6530  /* Estimate the costs of performing the final sort remotely */
6531  estimate_path_cost_size(root, input_rel, NIL, root->sort_pathkeys, fpextra,
6532  &rows, &width, &startup_cost, &total_cost);
6533 
6534  /*
6535  * Build the fdw_private list that will be used by postgresGetForeignPlan.
6536  * Items in the list must match order in enum FdwPathPrivateIndex.
6537  */
6538  fdw_private = list_make2(makeInteger(true), makeInteger(false));
6539 
6540  /* Create foreign ordering path */
6541  ordered_path = create_foreign_upper_path(root,
6542  input_rel,
6544  rows,
6545  startup_cost,
6546  total_cost,
6547  root->sort_pathkeys,
6548  NULL, /* no extra plan */
6549  fdw_private);
6550 
6551  /* and add it to the ordered_rel */
6552  add_path(ordered_rel, (Path *) ordered_path);
6553 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
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:2301
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * sortClause
Definition: parsenodes.h:169
RelOptKind reloptkind
Definition: pathnodes.h:673
List * query_pathkeys
Definition: pathnodes.h:293
PathTarget * target
Definition: postgres_fdw.c:292
ForeignServer * server
Definition: postgres_fdw.h:86
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_i)
Expr * find_em_expr_for_input_target(PlannerInfo *root, EquivalenceClass *ec, PathTarget *target)
List * sort_pathkeys
Definition: pathnodes.h:298
Value * makeInteger(int i)
Definition: value.c:23
UserMapping * user
Definition: postgres_fdw.h:87
void * palloc0(Size size)
Definition: mcxt.c:1093
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)
void * fdw_private
Definition: pathnodes.h:732
bool hasTargetSRFs
Definition: parsenodes.h:135
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
ForeignTable * table
Definition: postgres_fdw.h:85
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1058
bool ec_has_volatile
Definition: pathnodes.h:987
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:231
UpperRelationKind stage
Definition: postgres_fdw.h:109
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:687
double Cost
Definition: nodes.h:673
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: pathnodes.h:309

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

References add_path(), create_foreign_join_path(), create_foreignscan_path(), create_sort_path(), estimate_path_cost_size(), get_useful_pathkeys_for_relation(), IS_SIMPLE_REL, RelOptInfo::lateral_relids, lfirst, NIL, Path::pathkeys, and pathkeys_contained_in().

Referenced by postgresGetForeignJoinPaths(), and postgresGetForeignPaths().

5730 {
5731  List *useful_pathkeys_list = NIL; /* List of all pathkeys */
5732  ListCell *lc;
5733 
5734  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel);
5735 
5736  /* Create one path for each set of pathkeys we found above. */
5737  foreach(lc, useful_pathkeys_list)
5738  {
5739  double rows;
5740  int width;
5741  Cost startup_cost;
5742  Cost total_cost;
5743  List *useful_pathkeys = lfirst(lc);
5744  Path *sorted_epq_path;
5745 
5746  estimate_path_cost_size(root, rel, NIL, useful_pathkeys, NULL,
5747  &rows, &width, &startup_cost, &total_cost);
5748 
5749  /*
5750  * The EPQ path must be at least as well sorted as the path itself, in
5751  * case it gets used as input to a mergejoin.
5752  */
5753  sorted_epq_path = epq_path;
5754  if (sorted_epq_path != NULL &&
5755  !pathkeys_contained_in(useful_pathkeys,
5756  sorted_epq_path->pathkeys))
5757  sorted_epq_path = (Path *)
5758  create_sort_path(root,
5759  rel,
5760  sorted_epq_path,
5761  useful_pathkeys,
5762  -1.0);
5763 
5764  if (IS_SIMPLE_REL(rel))
5765  add_path(rel, (Path *)
5766  create_foreignscan_path(root, rel,
5767  NULL,
5768  rows,
5769  startup_cost,
5770  total_cost,
5771  useful_pathkeys,
5772  rel->lateral_relids,
5773  sorted_epq_path,
5774  NIL));
5775  else
5776  add_path(rel, (Path *)
5777  create_foreign_join_path(root, rel,
5778  NULL,
5779  rows,
5780  startup_cost,
5781  total_cost,
5782  useful_pathkeys,
5783  rel->lateral_relids,
5784  sorted_epq_path,
5785  NIL));
5786  }
5787 }
#define NIL
Definition: pg_list.h:65
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
Definition: postgres_fdw.c:899
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:649
Relids lateral_relids
Definition: pathnodes.h:701
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:2207
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:2251
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
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)
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2942
List * pathkeys
Definition: pathnodes.h:1188
#define lfirst(lc)
Definition: pg_list.h:169
Definition: pg_list.h:50
double Cost
Definition: nodes.h:673

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

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().

3605 {
3606  /*
3607  * If the GROUP BY clause isn't sort-able, the plan chosen by the remote
3608  * side is unlikely to generate properly-sorted output, so it would need
3609  * an explicit sort; adjust the given costs with cost_sort(). Likewise,
3610  * if the GROUP BY clause is sort-able but isn't a superset of the given
3611  * pathkeys, adjust the costs with that function. Otherwise, adjust the
3612  * costs by applying the same heuristic as for the scan or join case.
3613  */
3614  if (!grouping_is_sortable(root->parse->groupClause) ||
3615  !pathkeys_contained_in(pathkeys, root->group_pathkeys))
3616  {
3617  Path sort_path; /* dummy for result of cost_sort */
3618 
3619  cost_sort(&sort_path,
3620  root,
3621  pathkeys,
3622  *p_startup_cost + *p_run_cost,
3623  retrieved_rows,
3624  width,
3625  0.0,
3626  work_mem,
3627  limit_tuples);
3628 
3629  *p_startup_cost = sort_path.startup_cost;
3630  *p_run_cost = sort_path.total_cost - sort_path.startup_cost;
3631  }
3632  else
3633  {
3634  /*
3635  * The default extra cost seems too large for foreign-grouping cases;
3636  * add 1/4th of that default.
3637  */
3638  double sort_multiplier = 1.0 + (DEFAULT_FDW_SORT_MULTIPLIER
3639  - 1.0) * 0.25;
3640 
3641  *p_startup_cost *= sort_multiplier;
3642  *p_run_cost *= sort_multiplier;
3643  }
3644 }
List * group_pathkeys
Definition: pathnodes.h:295
Query * parse
Definition: pathnodes.h:161
Cost startup_cost
Definition: pathnodes.h:1185
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
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:2036
int work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1186
#define DEFAULT_FDW_SORT_MULTIPLIER
Definition: postgres_fdw.c:61
List * groupClause
Definition: parsenodes.h:158
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:529

◆ analyze_row_processor()

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

Definition at line 5118 of file postgres_fdw.c.

References PgFdwAnalyzeState::anl_cxt, Assert, PgFdwAnalyzeState::attinmeta, heap_freetuple(), make_tuple_from_result_row(), MemoryContextSwitchTo(), PgFdwAnalyzeState::numrows, ReservoirStateData::randstate, PgFdwAnalyzeState::rel, 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().

5119 {
5120  int targrows = astate->targrows;
5121  int pos; /* array index to store tuple in */
5122  MemoryContext oldcontext;
5123 
5124  /* Always increment sample row counter. */
5125  astate->samplerows += 1;
5126 
5127  /*
5128  * Determine the slot where this sample row should be stored. Set pos to
5129  * negative value to indicate the row should be skipped.
5130  */
5131  if (astate->numrows < targrows)
5132  {
5133  /* First targrows rows are always included into the sample */
5134  pos = astate->numrows++;
5135  }
5136  else
5137  {
5138  /*
5139  * Now we start replacing tuples in the sample until we reach the end
5140  * of the relation. Same algorithm as in acquire_sample_rows in
5141  * analyze.c; see Jeff Vitter's paper.
5142  */
5143  if (astate->rowstoskip < 0)
5144  astate->rowstoskip = reservoir_get_next_S(&astate->rstate, astate->samplerows, targrows);
5145 
5146  if (astate->rowstoskip <= 0)
5147  {
5148  /* Choose a random reservoir element to replace. */
5149  pos = (int) (targrows * sampler_random_fract(astate->rstate.randstate));
5150  Assert(pos >= 0 && pos < targrows);
5151  heap_freetuple(astate->rows[pos]);
5152  }
5153  else
5154  {
5155  /* Skip this tuple. */
5156  pos = -1;
5157  }
5158 
5159  astate->rowstoskip -= 1;
5160  }
5161 
5162  if (pos >= 0)
5163  {
5164  /*
5165  * Create sample tuple from current result row, and store it in the
5166  * position determined above. The tuple has to be created in anl_cxt.
5167  */
5168  oldcontext = MemoryContextSwitchTo(astate->anl_cxt);
5169 
5170  astate->rows[pos] = make_tuple_from_result_row(res, row,
5171  astate->rel,
5172  astate->attinmeta,
5173  astate->retrieved_attrs,
5174  NULL,
5175  astate->temp_cxt);
5176 
5177  MemoryContextSwitchTo(oldcontext);
5178  }
5179 }
static HeapTuple make_tuple_from_result_row(PGresult *res, int row, Relation rel, AttInMetadata *attinmeta, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context)
HeapTuple * rows
Definition: postgres_fdw.c:260
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:242
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
ReservoirStateData rstate
Definition: postgres_fdw.c:267
AttInMetadata * attinmeta
Definition: postgres_fdw.c:256
MemoryContext temp_cxt
Definition: postgres_fdw.c:271
#define Assert(condition)
Definition: c.h:804
MemoryContext anl_cxt
Definition: postgres_fdw.c:270
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:146

◆ apply_returning_filter()

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

Definition at line 4698 of file postgres_fdw.c.

References PgFdwDirectModifyState::attnoMap, PgFdwDirectModifyState::ctidAttno, DatumGetPointer, ExecClearTuple(), ExecFetchSlotHeapTuple(), ExecGetReturningSlot(), ExecStoreVirtualTuple(), PgFdwDirectModifyState::hasSystemCols, HeapTupleHeaderSetCmin, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXmin, i, InvalidTransactionId, 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().

4702 {
4703  TupleDesc resultTupType = RelationGetDescr(dmstate->resultRel);
4704  TupleTableSlot *resultSlot;
4705  Datum *values;
4706  bool *isnull;
4707  Datum *old_values;
4708  bool *old_isnull;
4709  int i;
4710 
4711  /*
4712  * Use the return tuple slot as a place to store the result tuple.
4713  */
4714  resultSlot = ExecGetReturningSlot(estate, resultRelInfo);
4715 
4716  /*
4717  * Extract all the values of the scan tuple.
4718  */
4719  slot_getallattrs(slot);
4720  old_values = slot->tts_values;
4721  old_isnull = slot->tts_isnull;
4722 
4723  /*
4724  * Prepare to build the result tuple.
4725  */
4726  ExecClearTuple(resultSlot);
4727  values = resultSlot->tts_values;
4728  isnull = resultSlot->tts_isnull;
4729 
4730  /*
4731  * Transpose data into proper fields of the result tuple.
4732  */
4733  for (i = 0; i < resultTupType->natts; i++)
4734  {
4735  int j = dmstate->attnoMap[i];
4736 
4737  if (j == 0)
4738  {
4739  values[i] = (Datum) 0;
4740  isnull[i] = true;
4741  }
4742  else
4743  {
4744  values[i] = old_values[j - 1];
4745  isnull[i] = old_isnull[j - 1];
4746  }
4747  }
4748 
4749  /*
4750  * Build the virtual tuple.
4751  */
4752  ExecStoreVirtualTuple(resultSlot);
4753 
4754  /*
4755  * If we have any system columns to return, materialize a heap tuple in
4756  * the slot from column values set above and install system columns in
4757  * that tuple.
4758  */
4759  if (dmstate->hasSystemCols)
4760  {
4761  HeapTuple resultTup = ExecFetchSlotHeapTuple(resultSlot, true, NULL);
4762 
4763  /* ctid */
4764  if (dmstate->ctidAttno)
4765  {
4766  ItemPointer ctid = NULL;
4767 
4768  ctid = (ItemPointer) DatumGetPointer(old_values[dmstate->ctidAttno - 1]);
4769  resultTup->t_self = *ctid;
4770  }
4771 
4772  /*
4773  * And remaining columns
4774  *
4775  * Note: since we currently don't allow the target relation to appear
4776  * on the nullable side of an outer join, any system columns wouldn't
4777  * go to NULL.
4778  *
4779  * Note: no need to care about tableoid here because it will be
4780  * initialized in ExecProcessReturning().
4781  */
4785  }
4786 
4787  /*
4788  * And return the result tuple.
4789  */
4790  return resultSlot;
4791 }
TupleTableSlot * ExecGetReturningSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1210
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define RelationGetDescr(relation)
Definition: rel.h:503
Datum * tts_values
Definition: tuptable.h:126
ItemPointerData * ItemPointer
Definition: itemptr.h:49
HeapTupleHeader t_data
Definition: htup.h:68
ItemPointerData t_self
Definition: htup.h:65
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
bool * tts_isnull
Definition: tuptable.h:128
#define HeapTupleHeaderSetXmax(tup, xid)
Definition: htup_details.h:380
#define InvalidTransactionId
Definition: transam.h:31
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetPointer(X)
Definition: postgres.h:593
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int i
#define HeapTupleHeaderSetCmin(tup, cid)
Definition: htup_details.h:397
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1552
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:319

◆ apply_server_options()

static void apply_server_options ( PgFdwRelationInfo fpinfo)
static

Definition at line 5795 of file postgres_fdw.c.

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().

5796 {
5797  ListCell *lc;
5798 
5799  foreach(lc, fpinfo->server->options)
5800  {
5801  DefElem *def = (DefElem *) lfirst(lc);
5802 
5803  if (strcmp(def->defname, "use_remote_estimate") == 0)
5804  fpinfo->use_remote_estimate = defGetBoolean(def);
5805  else if (strcmp(def->defname, "fdw_startup_cost") == 0)
5806  (void) parse_real(defGetString(def), &fpinfo->fdw_startup_cost, 0,
5807  NULL);
5808  else if (strcmp(def->defname, "fdw_tuple_cost") == 0)
5809  (void) parse_real(defGetString(def), &fpinfo->fdw_tuple_cost, 0,
5810  NULL);
5811  else if (strcmp(def->defname, "extensions") == 0)
5812  fpinfo->shippable_extensions =
5813  ExtractExtensionList(defGetString(def), false);
5814  else if (strcmp(def->defname, "fetch_size") == 0)
5815  (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
5816  else if (strcmp(def->defname, "async_capable") == 0)
5817  fpinfo->async_capable = defGetBoolean(def);
5818  }
5819 }
ForeignServer * server
Definition: postgres_fdw.h:86
bool parse_real(const char *value, double *result, int flags, const char **hintmsg)
Definition: guc.c:6925
bool defGetBoolean(DefElem *def)
Definition: define.c:111
char * defGetString(DefElem *def)
Definition: define.c:49
List * ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
Definition: option.c:398
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition: guc.c:6835
#define lfirst(lc)
Definition: pg_list.h:169
char * defname
Definition: parsenodes.h:746
List * shippable_extensions
Definition: postgres_fdw.h:81
List * options
Definition: foreign.h:42

◆ apply_table_options()

static void apply_table_options ( PgFdwRelationInfo fpinfo)
static

Definition at line 5827 of file postgres_fdw.c.

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().

5828 {
5829  ListCell *lc;
5830 
5831  foreach(lc, fpinfo->table->options)
5832  {
5833  DefElem *def = (DefElem *) lfirst(lc);
5834 
5835  if (strcmp(def->defname, "use_remote_estimate") == 0)
5836  fpinfo->use_remote_estimate = defGetBoolean(def);
5837  else if (strcmp(def->defname, "fetch_size") == 0)
5838  (void) parse_int(defGetString(def), &fpinfo->fetch_size, 0, NULL);
5839  else if (strcmp(def->defname, "async_capable") == 0)
5840  fpinfo->async_capable = defGetBoolean(def);
5841  }
5842 }
bool defGetBoolean(DefElem *def)
Definition: define.c:111
char * defGetString(DefElem *def)
Definition: define.c:49
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition: guc.c:6835
#define lfirst(lc)
Definition: pg_list.h:169
ForeignTable * table
Definition: postgres_fdw.h:85
List * options
Definition: foreign.h:57
char * defname
Definition: parsenodes.h:746

◆ build_remote_returning()

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

Definition at line 4370 of file postgres_fdw.c.

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(), PgFdwScanState::tupdesc, TupleDescAttr, Var::varattno, and Var::varno.

Referenced by postgresPlanDirectModify().

4371 {
4372  bool have_wholerow = false;
4373  List *tlist = NIL;
4374  List *vars;
4375  ListCell *lc;
4376 
4377  Assert(returningList);
4378 
4379  vars = pull_var_clause((Node *) returningList, PVC_INCLUDE_PLACEHOLDERS);
4380 
4381  /*
4382  * If there's a whole-row reference to the target relation, then we'll
4383  * need all the columns of the relation.
4384  */
4385  foreach(lc, vars)
4386  {
4387  Var *var = (Var *) lfirst(lc);
4388 
4389  if (IsA(var, Var) &&
4390  var->varno == rtindex &&
4391  var->varattno == InvalidAttrNumber)
4392  {
4393  have_wholerow = true;
4394  break;
4395  }
4396  }
4397 
4398  if (have_wholerow)
4399  {
4400  TupleDesc tupdesc = RelationGetDescr(rel);
4401  int i;
4402 
4403  for (i = 1; i <= tupdesc->natts; i++)
4404  {
4405  Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
4406  Var *var;
4407 
4408  /* Ignore dropped attributes. */
4409  if (attr->attisdropped)
4410  continue;
4411 
4412  var = makeVar(rtindex,
4413  i,
4414  attr->atttypid,
4415  attr->atttypmod,
4416  attr->attcollation,
4417  0);
4418 
4419  tlist = lappend(tlist,
4420  makeTargetEntry((Expr *) var,
4421  list_length(tlist) + 1,
4422  NULL,
4423  false));
4424  }
4425  }
4426 
4427  /* Now add any remaining columns to tlist. */
4428  foreach(lc, vars)
4429  {
4430  Var *var = (Var *) lfirst(lc);
4431 
4432  /*
4433  * No need for whole-row references to the target relation. We don't
4434  * need system columns other than ctid and oid either, since those are
4435  * set locally.
4436  */
4437  if (IsA(var, Var) &&
4438  var->varno == rtindex &&
4439  var->varattno <= InvalidAttrNumber &&
4441  continue; /* don't need it */
4442 
4443  if (tlist_member((Expr *) var, tlist))
4444  continue; /* already got it */
4445 
4446  tlist = lappend(tlist,
4447  makeTargetEntry((Expr *) var,
4448  list_length(tlist) + 1,
4449  NULL,
4450  false));
4451  }
4452 
4453  list_free(vars);
4454 
4455  return tlist;
4456 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Definition: nodes.h:539
AttrNumber varattno
Definition: primnodes.h:191
List * pull_var_clause(Node *node, int flags)
Definition: var.c:562
Definition: primnodes.h:186
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
List * lappend(List *list, void *datum)
Definition: list.c:336
Index varno
Definition: primnodes.h:189
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition: tlist.c:68
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define InvalidAttrNumber
Definition: attnum.h:23
void list_free(List *list)
Definition: list.c:1391
int i
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
Definition: regcomp.c:237
Definition: pg_list.h:50

◆ close_cursor()

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

Definition at line 3898 of file postgres_fdw.c.

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

Referenced by postgresAcquireSampleRowsFunc(), and postgresEndForeignScan().

3900 {
3901  char sql[64];
3902  PGresult *res;
3903 
3904  snprintf(sql, sizeof(sql), "CLOSE c%u", cursor_number);
3905 
3906  /*
3907  * We don't use a PG_TRY block here, so be careful not to throw error
3908  * without releasing the PGresult.
3909  */
3910  res = pgfdw_exec_query(conn, sql, conn_state);
3911  if (PQresultStatus(res) != PGRES_COMMAND_OK)
3912  pgfdw_report_error(ERROR, res, conn, true, sql);
3913  PQclear(res);
3914 }
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:685
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
#define ERROR
Definition: elog.h:46
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
static unsigned int cursor_number
Definition: connection.c:76
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define snprintf
Definition: port.h:216

◆ conversion_error_callback()

static void conversion_error_callback ( void *  arg)
static

Definition at line 7189 of file postgres_fdw.c.

References Alias::aliasname, 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, PlanState::plan, ScanState::ps, relname, ForeignScan::scan, Scan::scanrelid, SelfItemPointerAttributeNumber, ForeignScanState::ss, PlanState::state, strVal, Var::varattno, and Var::varno.

Referenced by make_tuple_from_result_row().

7190 {
7192  ForeignScanState *fsstate = errpos->fsstate;
7193  ForeignScan *fsplan = castNode(ForeignScan, fsstate->ss.ps.plan);
7194  int varno = 0;
7195  AttrNumber colno = 0;
7196  const char *attname = NULL;
7197  const char *relname = NULL;
7198  bool is_wholerow = false;
7199 
7200  if (fsplan->scan.scanrelid > 0)
7201  {
7202  /* error occurred in a scan against a foreign table */
7203  varno = fsplan->scan.scanrelid;
7204  colno = errpos->cur_attno;
7205  }
7206  else
7207  {
7208  /* error occurred in a scan against a foreign join */
7209  TargetEntry *tle;
7210 
7211  tle = list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
7212  errpos->cur_attno - 1);
7213 
7214  /*
7215  * Target list can have Vars and expressions. For Vars, we can get
7216  * some information, however for expressions we can't. Thus for
7217  * expressions, just show generic context message.
7218  */
7219  if (IsA(tle->expr, Var))
7220  {
7221  Var *var = (Var *) tle->expr;
7222 
7223  varno = var->varno;
7224  colno = var->varattno;
7225  }
7226  }
7227 
7228  if (varno > 0)
7229  {
7230  EState *estate = fsstate->ss.ps.state;
7231  RangeTblEntry *rte = exec_rt_fetch(varno, estate);
7232 
7233  relname = rte->eref->aliasname;
7234 
7235  if (colno == 0)
7236  is_wholerow = true;
7237  else if (colno > 0 && colno <= list_length(rte->eref->colnames))
7238  attname = strVal(list_nth(rte->eref->colnames, colno - 1));
7239  else if (colno == SelfItemPointerAttributeNumber)
7240  attname = "ctid";
7241  }
7242 
7243  if (relname && is_wholerow)
7244  errcontext("whole-row reference to foreign table \"%s\"", relname);
7245  else if (relname && attname)
7246  errcontext("column \"%s\" of foreign table \"%s\"", attname, relname);
7247  else
7248  errcontext("processing expression at position %d in select list",
7249  errpos->cur_attno);
7250 }
ScanState ss
Definition: execnodes.h:1857
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Index scanrelid
Definition: plannodes.h:344
List * colnames
Definition: primnodes.h:43
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
#define strVal(v)
Definition: value.h:54
AttrNumber varattno
Definition: primnodes.h:191
List * fdw_scan_tlist
Definition: plannodes.h:639
EState * state
Definition: execnodes.h:968
NameData relname
Definition: pg_class.h:38
Definition: primnodes.h:186
PlanState ps
Definition: execnodes.h:1377
ForeignScanState * fsstate
Definition: postgres_fdw.c:306
NameData attname
Definition: pg_attribute.h:41
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
#define list_nth_node(type, list, n)
Definition: pg_list.h:306
static RangeTblEntry * exec_rt_fetch(Index rti, EState *estate)
Definition: executor.h:571
Index varno
Definition: primnodes.h:189
Plan * plan
Definition: execnodes.h:966
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1454
static int list_length(const List *l)
Definition: pg_list.h:149
#define errcontext
Definition: elog.h:204
void * arg
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
Alias * eref
Definition: parsenodes.h:1141
AttrNumber cur_attno
Definition: postgres_fdw.c:305
int16 AttrNumber
Definition: attnum.h:21

◆ convert_prep_stmt_params()

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

Definition at line 4215 of file postgres_fdw.c.

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

Referenced by execute_foreign_modify().

4219 {
4220  const char **p_values;
4221  int i;
4222  int j;
4223  int pindex = 0;
4224  MemoryContext oldcontext;
4225 
4226  oldcontext = MemoryContextSwitchTo(fmstate->temp_cxt);
4227 
4228  p_values = (const char **) palloc(sizeof(char *) * fmstate->p_nums * numSlots);
4229 
4230  /* ctid is provided only for UPDATE/DELETE, which don't allow batching */
4231  Assert(!(tupleid != NULL && numSlots > 1));
4232 
4233  /* 1st parameter should be ctid, if it's in use */
4234  if (tupleid != NULL)
4235  {
4236  Assert(numSlots == 1);
4237  /* don't need set_transmission_modes for TID output */
4238  p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[pindex],
4239  PointerGetDatum(tupleid));
4240  pindex++;
4241  }
4242 
4243  /* get following parameters from slots */
4244  if (slots != NULL && fmstate->target_attrs != NIL)
4245  {
4246  int nestlevel;
4247  ListCell *lc;
4248 
4249  nestlevel = set_transmission_modes();
4250 
4251  for (i = 0; i < numSlots; i++)
4252  {
4253  j = (tupleid != NULL) ? 1 : 0;
4254  foreach(lc, fmstate->target_attrs)
4255  {
4256  int attnum = lfirst_int(lc);
4257  Datum value;
4258  bool isnull;
4259 
4260  value = slot_getattr(slots[i], attnum, &isnull);
4261  if (isnull)
4262  p_values[pindex] = NULL;
4263  else
4264  p_values[pindex] = OutputFunctionCall(&fmstate->p_flinfo[j],
4265  value);
4266  pindex++;
4267  j++;
4268  }
4269  }
4270 
4271  reset_transmission_modes(nestlevel);
4272  }
4273 
4274  Assert(pindex == fmstate->p_nums * numSlots);
4275 
4276  MemoryContextSwitchTo(oldcontext);
4277 
4278  return p_values;
4279 }
#define NIL
Definition: pg_list.h:65
#define PointerGetDatum(X)
Definition: postgres.h:600
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int set_transmission_modes(void)
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1573
#define lfirst_int(lc)
Definition: pg_list.h:170
FmgrInfo * p_flinfo
Definition: postgres_fdw.c:201
uintptr_t Datum
Definition: postgres.h:411
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
int16 attnum
Definition: pg_attribute.h:83
static struct @143 value
MemoryContext temp_cxt
Definition: postgres_fdw.c:207
#define Assert(condition)
Definition: c.h:804
void reset_transmission_modes(int nestlevel)
void * palloc(Size size)
Definition: mcxt.c:1062
int i

◆ create_cursor()

static void create_cursor ( ForeignScanState node)
static

Definition at line 3681 of file postgres_fdw.c.

References appendStringInfo(), buf, PgFdwScanState::conn, PgFdwScanState::conn_state, PgFdwScanState::cursor_exists, PgFdwScanState::cursor_number, PgFdwScanState::eof_reached, ERROR, ForeignScanState::fdw_state, PgFdwScanState::fetch_ct_2, 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, ForeignScanState::ss, PgFdwScanState::tuples, and values.

Referenced by fetch_more_data_begin(), and postgresIterateForeignScan().

3682 {
3683  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3684  ExprContext *econtext = node->ss.ps.ps_ExprContext;
3685  int numParams = fsstate->numParams;
3686  const char **values = fsstate->param_values;
3687  PGconn *conn = fsstate->conn;
3689  PGresult *res;
3690 
3691  /* First, process a pending asynchronous request, if any. */
3692  if (fsstate->conn_state->pendingAreq)
3694 
3695  /*
3696  * Construct array of query parameter values in text format. We do the
3697  * conversions in the short-lived per-tuple context, so as not to cause a
3698  * memory leak over repeated scans.
3699  */
3700  if (numParams > 0)
3701  {
3702  MemoryContext oldcontext;
3703 
3704  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3705 
3706  process_query_params(econtext,
3707  fsstate->param_flinfo,
3708  fsstate->param_exprs,
3709  values);
3710 
3711  MemoryContextSwitchTo(oldcontext);
3712  }
3713 
3714  /* Construct the DECLARE CURSOR command */
3715  initStringInfo(&buf);
3716  appendStringInfo(&buf, "DECLARE c%u CURSOR FOR\n%s",
3717  fsstate->cursor_number, fsstate->query);
3718 
3719  /*
3720  * Notice that we pass NULL for paramTypes, thus forcing the remote server
3721  * to infer types for all parameters. Since we explicitly cast every
3722  * parameter (see deparse.c), the "inference" is trivial and will produce
3723  * the desired result. This allows us to avoid assuming that the remote
3724  * server has the same OIDs we do for the parameters' types.
3725  */
3726  if (!PQsendQueryParams(conn, buf.data, numParams,
3727  NULL, values, NULL, NULL, 0))
3728  pgfdw_report_error(ERROR, NULL, conn, false, buf.data);
3729 
3730  /*
3731  * Get the result, and check for success.
3732  *
3733  * We don't use a PG_TRY block here, so be careful not to throw error
3734  * without releasing the PGresult.
3735  */
3736  res = pgfdw_get_result(conn, buf.data);
3737  if (PQresultStatus(res) != PGRES_COMMAND_OK)
3738  pgfdw_report_error(ERROR, res, conn, true, fsstate->query);
3739  PQclear(res);
3740 
3741  /* Mark the cursor as created, and show no tuples have been retrieved */
3742  fsstate->cursor_exists = true;
3743  fsstate->tuples = NULL;
3744  fsstate->num_tuples = 0;
3745  fsstate->next_tuple = 0;
3746  fsstate->fetch_ct_2 = 0;
3747  fsstate->eof_reached = false;
3748 
3749  /* Clean up */
3750  pfree(buf.data);
3751 }
ScanState ss
Definition: execnodes.h:1857
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:1424
List * param_exprs
Definition: postgres_fdw.c:154
ExprContext * ps_ExprContext
Definition: execnodes.h:1005
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void process_query_params(ExprContext *econtext, FmgrInfo *param_flinfo, List *param_exprs, const char **param_values)
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
unsigned int cursor_number
Definition: postgres_fdw.c:150
PlanState ps
Definition: execnodes.h:1377
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
const char ** param_values
Definition: postgres_fdw.c:155
PGconn * conn
Definition: streamutil.c:54
void process_pending_request(AsyncRequest *areq)
static char * buf
Definition: pg_test_fsync.c:68
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
FmgrInfo * param_flinfo
Definition: postgres_fdw.c:153
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void PQclear(PGresult *res)
Definition: fe-exec.c:680
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:134
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:713
PgFdwConnState * conn_state
Definition: postgres_fdw.c:149
HeapTuple * tuples
Definition: postgres_fdw.c:158
static Datum values[MAXATTR]
Definition: bootstrap.c:166

◆ create_foreign_modify()

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

Definition at line 3922 of file postgres_fdw.c.

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, PgFdwModifyState::orig_query, PgFdwModifyState::p_flinfo, PgFdwModifyState::p_name, PgFdwModifyState::p_nums, palloc0(), pstrdup(), PgFdwScanState::query, PgFdwModifyState::query, PgFdwScanState::rel, PgFdwModifyState::rel, RelationGetDescr, RelationGetRelid, PgFdwScanState::retrieved_attrs, PgFdwModifyState::retrieved_attrs, ResultRelInfo::ri_RelationDesc, ForeignTable::serverid, PgFdwModifyState::target_attrs, Plan::targetlist, PgFdwModifyState::temp_cxt, PgFdwScanState::tupdesc, TupleDescAttr, TupleDescGetAttInMetadata(), user, and PgFdwModifyState::values_end.

Referenced by postgresBeginForeignInsert(), and postgresBeginForeignModify().

3932 {
3933  PgFdwModifyState *fmstate;
3934  Relation rel = resultRelInfo->ri_RelationDesc;
3935  TupleDesc tupdesc = RelationGetDescr(rel);
3936  Oid userid;
3937  ForeignTable *table;
3938  UserMapping *user;
3939  AttrNumber n_params;
3940  Oid typefnoid;
3941  bool isvarlena;
3942  ListCell *lc;
3943 
3944  /* Begin constructing PgFdwModifyState. */
3945  fmstate = (PgFdwModifyState *) palloc0(sizeof(PgFdwModifyState));
3946  fmstate->rel = rel;
3947 
3948  /*
3949  * Identify which user to do the remote access as. This should match what
3950  * ExecCheckRTEPerms() does.
3951  */
3952  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
3953 
3954  /* Get info about foreign table. */
3955  table = GetForeignTable(RelationGetRelid(rel));
3956  user = GetUserMapping(userid, table->serverid);
3957 
3958  /* Open connection; report that we'll create a prepared statement. */
3959  fmstate->conn = GetConnection(user, true, &fmstate->conn_state);
3960  fmstate->p_name = NULL; /* prepared statement not made yet */
3961 
3962  /* Set up remote query information. */
3963  fmstate->query = query;
3964  if (operation == CMD_INSERT)
3965  {
3966  fmstate->query = pstrdup(fmstate->query);
3967  fmstate->orig_query = pstrdup(fmstate->query);
3968  }
3969  fmstate->target_attrs = target_attrs;
3970  fmstate->values_end = values_end;
3971  fmstate->has_returning = has_returning;
3972  fmstate->retrieved_attrs = retrieved_attrs;
3973 
3974  /* Create context for per-tuple temp workspace. */
3975  fmstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
3976  "postgres_fdw temporary data",
3978 
3979  /* Prepare for input conversion of RETURNING results. */
3980  if (fmstate->has_returning)
3981  fmstate->attinmeta = TupleDescGetAttInMetadata(tupdesc);
3982 
3983  /* Prepare for output conversion of parameters used in prepared stmt. */
3984  n_params = list_length(fmstate->target_attrs) + 1;
3985  fmstate->p_flinfo = (FmgrInfo *) palloc0(sizeof(FmgrInfo) * n_params);
3986  fmstate->p_nums = 0;
3987 
3988  if (operation == CMD_UPDATE || operation == CMD_DELETE)
3989  {
3990  Assert(subplan != NULL);
3991 
3992  /* Find the ctid resjunk column in the subplan's result */
3994  "ctid");
3995  if (!AttributeNumberIsValid(fmstate->ctidAttno))
3996  elog(ERROR, "could not find junk ctid column");
3997 
3998  /* First transmittable parameter will be ctid */
3999  getTypeOutputInfo(TIDOID, &typefnoid, &isvarlena);
4000  fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4001  fmstate->p_nums++;
4002  }
4003 
4004  if (operation == CMD_INSERT || operation == CMD_UPDATE)
4005  {
4006  /* Set up for remaining transmittable parameters */
4007  foreach(lc, fmstate->target_attrs)
4008  {
4009  int attnum = lfirst_int(lc);
4010  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
4011 
4012  Assert(!attr->attisdropped);
4013 
4014  getTypeOutputInfo(attr->atttypid, &typefnoid, &isvarlena);
4015  fmgr_info(typefnoid, &fmstate->p_flinfo[fmstate->p_nums]);
4016  fmstate->p_nums++;
4017  }
4018  }
4019 
4020  Assert(fmstate->p_nums <= n_params);
4021 
4022  /* Set batch_size from foreign server/table options. */
4023  if (operation == CMD_INSERT)
4024  fmstate->batch_size = get_batch_size_option(rel);
4025 
4026  fmstate->num_slots = 1;
4027 
4028  /* Initialize auxiliary state */
4029  fmstate->aux_fmstate = NULL;
4030 
4031  return fmstate;
4032 }
Definition: fmgr.h:56
Relation ri_RelationDesc
Definition: execnodes.h:411
#define AllocSetContextCreate
Definition: memutils.h:173
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
AttrNumber ExecFindJunkAttributeInTlist(List *targetlist, const char *attrName)
Definition: execJunk.c:222
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:205
static int get_batch_size_option(Relation rel)
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:248
unsigned int Oid
Definition: postgres_ext.h:31
List * retrieved_attrs
Definition: postgres_fdw.c:196
PgFdwConnState * conn_state
Definition: postgres_fdw.c:186
MemoryContext es_query_cxt
Definition: execnodes.h:600
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:125
#define ERROR
Definition: elog.h:46
#define lfirst_int(lc)
Definition: pg_list.h:170
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
struct PgFdwModifyState * aux_fmstate
Definition: postgres_fdw.c:210
AttrNumber ctidAttno
Definition: postgres_fdw.c:199
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
FmgrInfo * p_flinfo
Definition: postgres_fdw.c:201
void * palloc0(Size size)
Definition: mcxt.c:1093
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
int16 attnum
Definition: pg_attribute.h:83
MemoryContext temp_cxt
Definition: postgres_fdw.c:207
#define Assert(condition)
Definition: c.h:804
Oid serverid
Definition: foreign.h:56
static int list_length(const List *l)
Definition: pg_list.h:149
List * targetlist
Definition: plannodes.h:141
static char * user
Definition: pg_regress.c:95
#define elog(elevel,...)
Definition: elog.h:232
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:198
AttInMetadata * attinmeta
Definition: postgres_fdw.c:182
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ deallocate_query()

static void deallocate_query ( PgFdwModifyState fmstate)
static

Definition at line 4341 of file postgres_fdw.c.

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

Referenced by execute_foreign_modify(), and finish_foreign_modify().

4342 {
4343  char sql[64];
4344  PGresult *res;
4345 
4346  /* do nothing if the query is not allocated */
4347  if (!fmstate->p_name)
4348  return;
4349 
4350  snprintf(sql, sizeof(sql), "DEALLOCATE %s", fmstate->p_name);
4351 
4352  /*
4353  * We don't use a PG_TRY block here, so be careful not to throw error
4354  * without releasing the PGresult.
4355  */
4356  res = pgfdw_exec_query(fmstate->conn, sql, fmstate->conn_state);
4357  if (PQresultStatus(res) != PGRES_COMMAND_OK)
4358  pgfdw_report_error(ERROR, res, fmstate->conn, true, sql);
4359  PQclear(res);
4360  pfree(fmstate->p_name);
4361  fmstate->p_name = NULL;
4362 }
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:685
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
PgFdwConnState * conn_state
Definition: postgres_fdw.c:186
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define snprintf
Definition: port.h:216

◆ ec_member_matches_foreign()

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

Definition at line 3652 of file postgres_fdw.c.

References ec_member_foreign_arg::already_used, ec_member_foreign_arg::current, EquivalenceMember::em_expr, equal(), and list_member().

Referenced by postgresGetForeignPaths().

3655 {
3657  Expr *expr = em->em_expr;
3658 
3659  /*
3660  * If we've identified what we're processing in the current scan, we only
3661  * want to match that expression.
3662  */
3663  if (state->current != NULL)
3664  return equal(expr, state->current);
3665 
3666  /*
3667  * Otherwise, ignore anything we've already processed.
3668  */
3669  if (list_member(state->already_used, expr))
3670  return false;
3671 
3672  /* This is the new target to process. */
3673  state->current = expr;
3674  return true;
3675 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
bool list_member(const List *list, const void *datum)
Definition: list.c:628
Definition: regguts.h:317
void * arg

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

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(), PgFdwScanState::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(), RelOptInfo::fdw_private, 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, Query::havingQual, 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, PgFdwScanState::retrieved_attrs, 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().

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

◆ execute_dml_stmt()

static void execute_dml_stmt ( ForeignScanState node)
static

Definition at line 4497 of file postgres_fdw.c.

References PgFdwDirectModifyState::conn, PgFdwDirectModifyState::conn_state, ERROR, ForeignScanState::fdw_state, PgFdwDirectModifyState::has_returning, PgFdwDirectModifyState::num_tuples, PgFdwScanState::numParams, 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().

4498 {
4500  ExprContext *econtext = node->ss.ps.ps_ExprContext;
4501  int numParams = dmstate->numParams;
4502  const char **values = dmstate->param_values;
4503 
4504  /* First, process a pending asynchronous request, if any. */
4505  if (dmstate->conn_state->pendingAreq)
4507 
4508  /*
4509  * Construct array of query parameter values in text format.
4510  */
4511  if (numParams > 0)
4512  process_query_params(econtext,
4513  dmstate->param_flinfo,
4514  dmstate->param_exprs,
4515  values);
4516 
4517  /*
4518  * Notice that we pass NULL for paramTypes, thus forcing the remote server
4519  * to infer types for all parameters. Since we explicitly cast every
4520  * parameter (see deparse.c), the "inference" is trivial and will produce
4521  * the desired result. This allows us to avoid assuming that the remote
4522  * server has the same OIDs we do for the parameters' types.
4523  */
4524  if (!PQsendQueryParams(dmstate->conn, dmstate->query, numParams,
4525  NULL, values, NULL, NULL, 0))
4526  pgfdw_report_error(ERROR, NULL, dmstate->conn, false, dmstate->query);
4527 
4528  /*
4529  * Get the result, and check for success.
4530  *
4531  * We don't use a PG_TRY block here, so be careful not to throw error
4532  * without releasing the PGresult.
4533  */
4534  dmstate->result = pgfdw_get_result(dmstate->conn, dmstate->query);
4535  if (PQresultStatus(dmstate->result) !=
4537  pgfdw_report_error(ERROR, dmstate->result, dmstate->conn, true,
4538  dmstate->query);
4539 
4540  /* Get the number of rows affected. */
4541  if (dmstate->has_returning)
4542  dmstate->num_tuples = PQntuples(dmstate->result);
4543  else
4544  dmstate->num_tuples = atoi(PQcmdTuples(dmstate->result));
4545 }
ScanState ss
Definition: execnodes.h:1857
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:1424
const char ** param_values
Definition: postgres_fdw.c:234
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3575
ExprContext * ps_ExprContext
Definition: execnodes.h:1005
static void process_query_params(ExprContext *econtext, FmgrInfo *param_flinfo, List *param_exprs, const char **param_values)
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3234
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
PlanState ps
Definition: execnodes.h:1377
#define ERROR
Definition: elog.h:46
void process_pending_request(AsyncRequest *areq)
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:134
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:713
static Datum values[MAXATTR]
Definition: bootstrap.c:166
PgFdwConnState * conn_state
Definition: postgres_fdw.c:230

◆ execute_foreign_modify()

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

Definition at line 4042 of file postgres_fdw.c.

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(), ResultRelInfo::ri_FdwState, store_returning_result(), PgFdwModifyState::temp_cxt, and PgFdwModifyState::values_end.

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

4048 {
4049  PgFdwModifyState *fmstate = (PgFdwModifyState *) resultRelInfo->ri_FdwState;
4050  ItemPointer ctid = NULL;
4051  const char **p_values;
4052  PGresult *res;
4053  int n_rows;
4054  StringInfoData sql;
4055 
4056  /* The operation should be INSERT, UPDATE, or DELETE */
4057  Assert(operation == CMD_INSERT ||
4058  operation == CMD_UPDATE ||
4059  operation == CMD_DELETE);
4060 
4061  /* First, process a pending asynchronous request, if any. */
4062  if (fmstate->conn_state->pendingAreq)
4064 
4065  /*
4066  * If the existing query was deparsed and prepared for a different number
4067  * of rows, rebuild it for the proper number.
4068  */
4069  if (operation == CMD_INSERT && fmstate->num_slots != *numSlots)
4070  {
4071  /* Destroy the prepared statement created previously */
4072  if (fmstate->p_name)
4073  deallocate_query(fmstate);
4074 
4075  /* Build INSERT string with numSlots records in its VALUES clause. */
4076  initStringInfo(&sql);
4077  rebuildInsertSql(&sql, fmstate->orig_query, fmstate->values_end,
4078  fmstate->p_nums, *numSlots - 1);
4079  pfree(fmstate->query);
4080  fmstate->query = sql.data;
4081  fmstate->num_slots = *numSlots;
4082  }
4083 
4084  /* Set up the prepared statement on the remote server, if we didn't yet */
4085  if (!fmstate->p_name)
4086  prepare_foreign_modify(fmstate);
4087 
4088  /*
4089  * For UPDATE/DELETE, get the ctid that was passed up as a resjunk column
4090  */
4091  if (operation == CMD_UPDATE || operation == CMD_DELETE)
4092  {
4093  Datum datum;
4094  bool isNull;
4095 
4096  datum = ExecGetJunkAttribute(planSlots[0],
4097  fmstate->ctidAttno,
4098  &isNull);
4099  /* shouldn't ever get a null result... */
4100  if (isNull)
4101  elog(ERROR, "ctid is NULL");
4102  ctid = (ItemPointer) DatumGetPointer(datum);
4103  }
4104 
4105  /* Convert parameters needed by prepared statement to text form */
4106  p_values = convert_prep_stmt_params(fmstate, ctid, slots, *numSlots);
4107 
4108  /*
4109  * Execute the prepared statement.
4110  */
4111  if (!PQsendQueryPrepared(fmstate->conn,
4112  fmstate->p_name,
4113  fmstate->p_nums * (*numSlots),
4114  p_values,
4115  NULL,
4116  NULL,
4117  0))
4118  pgfdw_report_error(ERROR, NULL, fmstate->conn, false, fmstate->query);
4119 
4120  /*
4121  * Get the result, and check for success.
4122  *
4123  * We don't use a PG_TRY block here, so be careful not to throw error
4124  * without releasing the PGresult.
4125  */
4126  res = pgfdw_get_result(fmstate->conn, fmstate->query);
4127  if (PQresultStatus(res) !=
4129  pgfdw_report_error(ERROR, res, fmstate->conn, true, fmstate->query);
4130 
4131  /* Check number of rows affected, and fetch RETURNING tuple if any */
4132  if (fmstate->has_returning)
4133  {
4134  Assert(*numSlots == 1);
4135  n_rows = PQntuples(res);
4136  if (n_rows > 0)
4137  store_returning_result(fmstate, slots[0], res);
4138  }
4139  else
4140  n_rows = atoi(PQcmdTuples(res));
4141 
4142  /* And clean up */
4143  PQclear(res);
4144 
4145  MemoryContextReset(fmstate->temp_cxt);
4146 
4147  *numSlots = n_rows;
4148 
4149  /*
4150  * Return NULL if nothing was inserted/updated/deleted on the remote end
4151  */
4152  return (n_rows > 0) ? slots : NULL;
4153 }
static void deallocate_query(PgFdwModifyState *fmstate)
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3575
static void store_returning_result(PgFdwModifyState *fmstate, TupleTableSlot *slot, PGresult *res)
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3234
void rebuildInsertSql(StringInfo buf, char *orig_query, int values_end_len, int num_cols, int num_rows)
Definition: deparse.c:1778
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
ItemPointerData * ItemPointer
Definition: itemptr.h:49
PgFdwConnState * conn_state
Definition: postgres_fdw.c:186
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
void process_pending_request(AsyncRequest *areq)
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
AttrNumber ctidAttno
Definition: postgres_fdw.c:199
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static Datum ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
Definition: executor.h:178
uintptr_t Datum
Definition: postgres.h:411
static const char ** convert_prep_stmt_params(PgFdwModifyState *fmstate, ItemPointer tupleid, TupleTableSlot **slots, int numSlots)
void * ri_FdwState
Definition: execnodes.h:458
void PQclear(PGresult *res)
Definition: fe-exec.c:680
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:134
MemoryContext temp_cxt
Definition: postgres_fdw.c:207
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:713
#define Assert(condition)
Definition: c.h:804
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:1570
#define DatumGetPointer(X)
Definition: postgres.h:593
static void prepare_foreign_modify(PgFdwModifyState *fmstate)
#define elog(elevel,...)
Definition: elog.h:232

◆ fetch_more_data()

static void fetch_more_data ( ForeignScanState node)
static

Definition at line 3757 of file postgres_fdw.c.

References Assert, PgFdwScanState::async_capable, PgFdwScanState::attinmeta, PgFdwScanState::batch_cxt, PgFdwScanState::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, PgFdwScanState::retrieved_attrs, snprintf, ForeignScanState::ss, PgFdwScanState::temp_cxt, and PgFdwScanState::tuples.

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

3758 {
3759  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
3760  PGresult *volatile res = NULL;
3761  MemoryContext oldcontext;
3762 
3763  /*
3764  * We'll store the tuples in the batch_cxt. First, flush the previous
3765  * batch.
3766  */
3767  fsstate->tuples = NULL;
3768  MemoryContextReset(fsstate->batch_cxt);
3769  oldcontext = MemoryContextSwitchTo(fsstate->batch_cxt);
3770 
3771  /* PGresult must be released before leaving this function. */
3772  PG_TRY();
3773  {
3774  PGconn *conn = fsstate->conn;
3775  int numrows;
3776  int i;
3777 
3778  if (fsstate->async_capable)
3779  {
3780  Assert(fsstate->conn_state->pendingAreq);
3781 
3782  /*
3783  * The query was already sent by an earlier call to
3784  * fetch_more_data_begin. So now we just fetch the result.
3785  */
3786  res = pgfdw_get_result(conn, fsstate->query);
3787  /* On error, report the original query, not the FETCH. */
3788  if (PQresultStatus(res) != PGRES_TUPLES_OK)
3789  pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3790 
3791  /* Reset per-connection state */
3792  fsstate->conn_state->pendingAreq = NULL;
3793  }
3794  else
3795  {
3796  char sql[64];
3797 
3798  /* This is a regular synchronous fetch. */
3799  snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
3800  fsstate->fetch_size, fsstate->cursor_number);
3801 
3802  res = pgfdw_exec_query(conn, sql, fsstate->conn_state);
3803  /* On error, report the original query, not the FETCH. */
3804  if (PQresultStatus(res) != PGRES_TUPLES_OK)
3805  pgfdw_report_error(ERROR, res, conn, false, fsstate->query);
3806  }
3807 
3808  /* Convert the data into HeapTuples */
3809  numrows = PQntuples(res);
3810  fsstate->tuples = (HeapTuple *) palloc0(numrows * sizeof(HeapTuple));
3811  fsstate->num_tuples = numrows;
3812  fsstate->next_tuple = 0;
3813 
3814  for (i = 0; i < numrows; i++)
3815  {
3816  Assert(IsA(node->ss.ps.plan, ForeignScan));
3817 
3818  fsstate->tuples[i] =
3820  fsstate->rel,
3821  fsstate->attinmeta,
3822  fsstate->retrieved_attrs,
3823  node,
3824  fsstate->temp_cxt);
3825  }
3826 
3827  /* Update fetch_ct_2 */
3828  if (fsstate->fetch_ct_2 < 2)
3829  fsstate->fetch_ct_2++;
3830 
3831  /* Must be EOF if we didn't get as many tuples as we asked for. */
3832  fsstate->eof_reached = (numrows < fsstate->fetch_size);
3833  }
3834  PG_FINALLY();
3835  {
3836  if (res)
3837  PQclear(res);
3838  }
3839  PG_END_TRY();
3840 
3841  MemoryContextSwitchTo(oldcontext);
3842 }
ScanState ss
Definition: execnodes.h:1857
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
static HeapTuple make_tuple_from_result_row(PGresult *res, int row, Relation rel, AttInMetadata *attinmeta, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:685
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
List * retrieved_attrs
Definition: postgres_fdw.c:145
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3234
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
unsigned int cursor_number
Definition: postgres_fdw.c:150
PlanState ps
Definition: execnodes.h:1377
#define ERROR
Definition: elog.h:46
PGconn * conn
Definition: streamutil.c:54
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
AttInMetadata * attinmeta
Definition: postgres_fdw.c:141
#define PG_FINALLY()
Definition: elog.h:330
void * palloc0(Size size)
Definition: mcxt.c:1093
MemoryContext temp_cxt
Definition: postgres_fdw.c:171
Plan * plan
Definition: execnodes.h:966
void PQclear(PGresult *res)
Definition: fe-exec.c:680
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:134
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:713
#define Assert(condition)
Definition: c.h:804
PgFdwConnState * conn_state
Definition: postgres_fdw.c:149
HeapTuple * tuples
Definition: postgres_fdw.c:158
int i
#define PG_TRY()
Definition: elog.h:313
MemoryContext batch_cxt
Definition: postgres_fdw.c:170
#define snprintf
Definition: port.h:216
#define PG_END_TRY()
Definition: elog.h:338

◆ fetch_more_data_begin()

static void fetch_more_data_begin ( AsyncRequest areq)
static

Definition at line 6967 of file postgres_fdw.c.

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

Referenced by postgresForeignAsyncConfigureWait(), and produce_tuple_asynchronously().

6968 {
6969  ForeignScanState *node = (ForeignScanState *) areq->requestee;
6970  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
6971  char sql[64];
6972 
6973  Assert(!fsstate->conn_state->pendingAreq);
6974 
6975  /* Create the cursor synchronously. */
6976  if (!fsstate->cursor_exists)
6977  create_cursor(node);
6978 
6979  /* We will send this query, but not wait for the response. */
6980  snprintf(sql, sizeof(sql), "FETCH %d FROM c%u",
6981  fsstate->fetch_size, fsstate->cursor_number);
6982 
6983  if (PQsendQuery(fsstate->conn, sql) < 0)
6984  pgfdw_report_error(ERROR, NULL, fsstate->conn, false, fsstate->query);
6985 
6986  /* Remember that the request is in process */
6987  fsstate->conn_state->pendingAreq = areq;
6988 }
static void create_cursor(ForeignScanState *node)
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1312
#define ERROR
Definition: elog.h:46
struct PlanState * requestee
Definition: execnodes.h:538
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
#define Assert(condition)
Definition: c.h:804
#define snprintf
Definition: port.h:216

◆ find_em_expr_for_input_target()

Expr* find_em_expr_for_input_target ( PlannerInfo root,
EquivalenceClass ec,
PathTarget target 
)

Definition at line 7257 of file postgres_fdw.c.

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

Referenced by add_foreign_ordered_paths(), and appendOrderByClause().

7260 {
7261  ListCell *lc1;
7262  int i;
7263 
7264  i = 0;
7265  foreach(lc1, target->exprs)
7266  {
7267  Expr *expr = (Expr *) lfirst(lc1);
7268  Index sgref = get_pathtarget_sortgroupref(target, i);
7269  ListCell *lc2;
7270 
7271  /* Ignore non-sort expressions */
7272  if (sgref == 0 ||
7274  root->parse->sortClause) == NULL)
7275  {
7276  i++;
7277  continue;
7278  }
7279 
7280  /* We ignore binary-compatible relabeling on both ends */
7281  while (expr && IsA(expr, RelabelType))
7282  expr = ((RelabelType *) expr)->arg;
7283 
7284  /* Locate an EquivalenceClass member matching this expr, if any */
7285  foreach(lc2, ec->ec_members)
7286  {
7288  Expr *em_expr;
7289 
7290  /* Don't match constants */
7291  if (em->em_is_const)
7292  continue;
7293 
7294  /* Ignore child members */
7295  if (em->em_is_child)
7296  continue;
7297 
7298  /* Match if same expression (after stripping relabel) */
7299  em_expr = em->em_expr;
7300  while (em_expr && IsA(em_expr, RelabelType))
7301  em_expr = ((RelabelType *) em_expr)->arg;
7302 
7303  if (equal(em_expr, expr))
7304  return em->em_expr;
7305  }
7306 
7307  i++;
7308  }
7309 
7310  elog(ERROR, "could not find pathkey item to sort");
7311  return NULL; /* keep compiler quiet */
7312 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Query * parse
Definition: pathnodes.h:161
List * sortClause
Definition: parsenodes.h:169
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
#define ERROR
Definition: elog.h:46
List * exprs
Definition: pathnodes.h:1102
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:432
unsigned int Index
Definition: c.h:549
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1111
#define lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:232
int i
void * arg
List * ec_members
Definition: pathnodes.h:981

◆ find_modifytable_subplan()

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

Definition at line 2343 of file postgres_fdw.c.

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

Referenced by postgresPlanDirectModify().

2347 {
2348  Plan *subplan = outerPlan(plan);
2349 
2350  /*
2351  * The cases we support are (1) the desired ForeignScan is the immediate
2352  * child of ModifyTable, or (2) it is the subplan_index'th child of an
2353  * Append node that is the immediate child of ModifyTable. There is no
2354  * point in looking further down, as that would mean that local joins are
2355  * involved, so we can't do the update directly.
2356  *
2357  * There could be a Result atop the Append too, acting to compute the
2358  * UPDATE targetlist values. We ignore that here; the tlist will be
2359  * checked by our caller.
2360  *
2361  * In principle we could examine all the children of the Append, but it's
2362  * currently unlikely that the core planner would generate such a plan
2363  * with the children out-of-order. Moreover, such a search risks costing
2364  * O(N^2) time when there are a lot of children.
2365  */
2366  if (IsA(subplan, Append))
2367  {
2368  Append *appendplan = (Append *) subplan;
2369 
2370  if (subplan_index < list_length(appendplan->appendplans))
2371  subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2372  }
2373  else if (IsA(subplan, Result) &&
2374  outerPlan(subplan) != NULL &&
2375  IsA(outerPlan(subplan), Append))
2376  {
2377  Append *appendplan = (Append *) outerPlan(subplan);
2378 
2379  if (subplan_index < list_length(appendplan->appendplans))
2380  subplan = (Plan *) list_nth(appendplan->appendplans, subplan_index);
2381  }
2382 
2383  /* Now, have we got a ForeignScan on the desired rel? */
2384  if (IsA(subplan, ForeignScan))
2385  {
2386  ForeignScan *fscan = (ForeignScan *) subplan;
2387 
2388  if (bms_is_member(rtindex, fscan->fs_relids))
2389  return fscan;
2390  }
2391 
2392  return NULL;
2393 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * appendplans
Definition: plannodes.h:253
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
#define outerPlan(node)
Definition: plannodes.h:171
static int list_length(const List *l)
Definition: pg_list.h:149
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Bitmapset * fs_relids
Definition: plannodes.h:641

◆ finish_foreign_modify()

static void finish_foreign_modify ( PgFdwModifyState fmstate)
static

Definition at line 4323 of file postgres_fdw.c.

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

Referenced by postgresEndForeignInsert(), and postgresEndForeignModify().

4324 {
4325  Assert(fmstate != NULL);
4326 
4327  /* If we created a prepared statement, destroy it */
4328  deallocate_query(fmstate);
4329 
4330  /* Release remote connection */
4331  ReleaseConnection(fmstate->conn);
4332  fmstate->conn = NULL;
4333 }
static void deallocate_query(PgFdwModifyState *fmstate)
void ReleaseConnection(PGconn *conn)
Definition: connection.c:637
#define Assert(condition)
Definition: c.h:804

◆ foreign_grouping_ok()

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

Definition at line 6054 of file postgres_fdw.c.

References add_to_flat_tlist(), Assert, RestrictInfo::clause, RelOptInfo::fdw_private, get_pathtarget_sortgroupref, get_sortgroupref_clause_noerr(), Query::groupClause, PgFdwRelationInfo::grouped_tlist, Query::groupingSets, i, 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, PgFdwScanState::query, 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().

6056 {
6057  Query *query = root->parse;
6058  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) grouped_rel->fdw_private;
6059  PathTarget *grouping_target = grouped_rel->reltarget;
6060  PgFdwRelationInfo *ofpinfo;
6061  ListCell *lc;
6062  int i;
6063  List *tlist = NIL;
6064 
6065  /* We currently don't support pushing Grouping Sets. */
6066  if (query->groupingSets)
6067  return false;
6068 
6069  /* Get the fpinfo of the underlying scan relation. */
6070  ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
6071 
6072  /*
6073  * If underlying scan relation has any local conditions, those conditions
6074  * are required to be applied before performing aggregation. Hence the
6075  * aggregate cannot be pushed down.
6076  */
6077  if (ofpinfo->local_conds)
6078  return false;
6079 
6080  /*
6081  * Examine grouping expressions, as well as other expressions we'd need to
6082  * compute, and check whether they are safe to push down to the foreign
6083  * server. All GROUP BY expressions will be part of the grouping target
6084  * and thus there is no need to search for them separately. Add grouping
6085  * expressions into target list which will be passed to foreign server.
6086  *
6087  * A tricky fine point is that we must not put any expression into the
6088  * target list that is just a foreign param (that is, something that
6089  * deparse.c would conclude has to be sent to the foreign server). If we
6090  * do, the expression will also appear in the fdw_exprs list of the plan
6091  * node, and setrefs.c will get confused and decide that the fdw_exprs
6092  * entry is actually a reference to the fdw_scan_tlist entry, resulting in
6093  * a broken plan. Somewhat oddly, it's OK if the expression contains such
6094  * a node, as long as it's not at top level; then no match is possible.
6095  */
6096  i = 0;
6097  foreach(lc, grouping_target->exprs)
6098  {
6099  Expr *expr = (Expr *) lfirst(lc);
6100  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
6101  ListCell *l;
6102 
6103  /* Check whether this expression is part of GROUP BY clause */
6104  if (sgref && get_sortgroupref_clause_noerr(sgref, query->groupClause))
6105  {
6106  TargetEntry *tle;
6107 
6108  /*
6109  * If any GROUP BY expression is not shippable, then we cannot
6110  * push down aggregation to the foreign server.
6111  */
6112  if (!is_foreign_expr(root, grouped_rel, expr))
6113  return false;
6114 
6115  /*
6116  * If it would be a foreign param, we can't put it into the tlist,
6117  * so we have to fail.
6118  */
6119  if (is_foreign_param(root, grouped_rel, expr))
6120  return false;
6121 
6122  /*
6123  * Pushable, so add to tlist. We need to create a TLE for this
6124  * expression and apply the sortgroupref to it. We cannot use
6125  * add_to_flat_tlist() here because that avoids making duplicate
6126  * entries in the tlist. If there are duplicate entries with
6127  * distinct sortgrouprefs, we have to duplicate that situation in
6128  * the output tlist.
6129  */
6130  tle = makeTargetEntry(expr, list_length(tlist) + 1, NULL, false);
6131  tle->ressortgroupref = sgref;
6132  tlist = lappend(tlist, tle);
6133  }
6134  else
6135  {
6136  /*
6137  * Non-grouping expression we need to compute. Can we ship it
6138  * as-is to the foreign server?
6139  */
6140  if (is_foreign_expr(root, grouped_rel, expr) &&
6141  !is_foreign_param(root, grouped_rel, expr))
6142  {
6143  /* Yes, so add to tlist as-is; OK to suppress duplicates */
6144  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6145  }
6146  else
6147  {
6148  /* Not pushable as a whole; extract its Vars and aggregates */
6149  List *aggvars;
6150 
6151  aggvars = pull_var_clause((Node *) expr,
6153 
6154  /*
6155  * If any aggregate expression is not shippable, then we
6156  * cannot push down aggregation to the foreign server. (We
6157  * don't have to check is_foreign_param, since that certainly
6158  * won't return true for any such expression.)
6159  */
6160  if (!is_foreign_expr(root, grouped_rel, (Expr *) aggvars))
6161  return false;
6162 
6163  /*
6164  * Add aggregates, if any, into the targetlist. Plain Vars
6165  * outside an aggregate can be ignored, because they should be
6166  * either same as some GROUP BY column or part of some GROUP
6167  * BY expression. In either case, they are already part of
6168  * the targetlist and thus no need to add them again. In fact
6169  * including plain Vars in the tlist when they do not match a
6170  * GROUP BY column would cause the foreign server to complain
6171  * that the shipped query is invalid.
6172  */
6173  foreach(l, aggvars)
6174  {
6175  Expr *expr = (Expr *) lfirst(l);
6176 
6177  if (IsA(expr, Aggref))
6178  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6179  }
6180  }
6181  }
6182 
6183  i++;
6184  }
6185 
6186  /*
6187  * Classify the pushable and non-pushable HAVING clauses and save them in
6188  * remote_conds and local_conds of the grouped rel's fpinfo.
6189  */
6190  if (havingQual)
6191  {
6192  ListCell *lc;
6193 
6194  foreach(lc, (List *) havingQual)
6195  {
6196  Expr *expr = (Expr *) lfirst(lc);
6197  RestrictInfo *rinfo;
6198 
6199  /*
6200  * Currently, the core code doesn't wrap havingQuals in
6201  * RestrictInfos, so we must make our own.
6202  */
6203  Assert(!IsA(expr, RestrictInfo));
6204  rinfo = make_restrictinfo(root,
6205  expr,
6206  true,
6207  false,
6208  false,
6209  root->qual_security_level,
6210  grouped_rel->relids,
6211  NULL,
6212  NULL);
6213  if (is_foreign_expr(root, grouped_rel, expr))
6214  fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
6215  else
6216  fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
6217  }
6218  }
6219 
6220  /*
6221  * If there are any local conditions, pull Vars and aggregates from it and
6222  * check whether they are safe to pushdown or not.
6223  */
6224  if (fpinfo->local_conds)
6225  {
6226  List *aggvars = NIL;
6227  ListCell *lc;
6228 
6229  foreach(lc, fpinfo->local_conds)
6230  {
6231  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
6232 
6233  aggvars = list_concat(aggvars,
6234  pull_var_clause((Node *) rinfo->clause,
6236  }
6237 
6238  foreach(lc, aggvars)
6239  {
6240  Expr *expr = (Expr *) lfirst(lc);
6241 
6242  /*
6243  * If aggregates within local conditions are not safe to push
6244  * down, then we cannot push down the query. Vars are already
6245  * part of GROUP BY clause which are checked above, so no need to
6246  * access them again here. Again, we need not check
6247  * is_foreign_param for a foreign aggregate.
6248  */
6249  if (IsA(expr, Aggref))
6250  {
6251  if (!is_foreign_expr(root, grouped_rel, expr))
6252  return false;
6253 
6254  tlist = add_to_flat_tlist(tlist, list_make1(expr));
6255  }
6256  }
6257  }
6258 
6259  /* Store generated targetlist */
6260  fpinfo->grouped_tlist = tlist;
6261 
6262  /* Safe to pushdown */
6263  fpinfo->pushdown_safe = true;
6264 
6265  /*
6266  * Set # of retrieved rows and cached relation costs to some negative
6267  * value, so that we can detect when they are set to some sensible values,
6268  * during one (usually the first) of the calls to estimate_path_cost_size.
6269  */
6270  fpinfo->retrieved_rows = -1;
6271  fpinfo->rel_startup_cost = -1;
6272  fpinfo->rel_total_cost = -1;
6273 
6274  /*
6275  * Set the string describing this grouped relation to be used in EXPLAIN
6276  * output of corresponding ForeignScan. Note that the decoration we add
6277  * to the base relation name mustn't include any digits, or it'll confuse
6278  * postgresExplainForeignScan.
6279  */
6280  fpinfo->relation_name = psprintf("Aggregate on (%s)",
6281  ofpinfo->relation_name);
6282 
6283  return true;
6284 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Query * parse
Definition: pathnodes.h:161
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
List * groupingSets
Definition: parsenodes.h:161
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
List * pull_var_clause(Node *node, int flags)
Definition: var.c:562
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:186
bool is_foreign_param(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:877
#define list_make1(x1)
Definition: pg_list.h:206
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Relids relids
Definition: pathnodes.h:676
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
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:432
unsigned int Index
Definition: c.h:549
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1111
void * fdw_private
Definition: pathnodes.h:732
#define Assert(condition)
Definition: c.h:804
List * add_to_flat_tlist(List *tlist, List *exprs)
Definition: tlist.c:121
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
Index qual_security_level
Definition: pathnodes.h:342
List * groupClause
Definition: parsenodes.h:158
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:231
int i
Index ressortgroupref
Definition: primnodes.h:1457
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:687

◆ foreign_join_ok()

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

Definition at line 5466 of file postgres_fdw.c.

References Assert, bms_add_members(), bms_is_subset(), bms_nonempty_difference(), bms_union(), RestrictInfo::clause, elog, ERROR, RelOptInfo::fdw_private, get_jointype_name(), 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().

5469 {
5470  PgFdwRelationInfo *fpinfo;
5471  PgFdwRelationInfo *fpinfo_o;
5472  PgFdwRelationInfo *fpinfo_i;
5473  ListCell *lc;
5474  List *joinclauses;
5475 
5476  /*
5477  * We support pushing down INNER, LEFT, RIGHT and FULL OUTER joins.
5478  * Constructing queries representing SEMI and ANTI joins is hard, hence
5479  * not considered right now.
5480  */
5481  if (jointype != JOIN_INNER && jointype != JOIN_LEFT &&
5482  jointype != JOIN_RIGHT && jointype != JOIN_FULL)
5483  return false;
5484 
5485  /*
5486  * If either of the joining relations is marked as unsafe to pushdown, the
5487  * join can not be pushed down.
5488  */
5489  fpinfo = (PgFdwRelationInfo *) joinrel->fdw_private;
5490  fpinfo_o = (PgFdwRelationInfo *) outerrel->fdw_private;
5491  fpinfo_i = (PgFdwRelationInfo *) innerrel->fdw_private;
5492  if (!fpinfo_o || !fpinfo_o->pushdown_safe ||
5493  !fpinfo_i || !fpinfo_i->pushdown_safe)
5494  return false;
5495 
5496  /*
5497  * If joining relations have local conditions, those conditions are
5498  * required to be applied before joining the relations. Hence the join can
5499  * not be pushed down.
5500  */
5501  if (fpinfo_o->local_conds || fpinfo_i->local_conds)
5502  return false;
5503 
5504  /*
5505  * Merge FDW options. We might be tempted to do this after we have deemed
5506  * the foreign join to be OK. But we must do this beforehand so that we
5507  * know which quals can be evaluated on the foreign server, which might
5508  * depend on shippable_extensions.
5509  */
5510  fpinfo->server = fpinfo_o->server;
5511  merge_fdw_options(fpinfo, fpinfo_o, fpinfo_i);
5512 
5513  /*
5514  * Separate restrict list into join quals and pushed-down (other) quals.
5515  *
5516  * Join quals belonging to an outer join must all be shippable, else we
5517  * cannot execute the join remotely. Add such quals to 'joinclauses'.
5518  *
5519  * Add other quals to fpinfo->remote_conds if they are shippable, else to
5520  * fpinfo->local_conds. In an inner join it's okay to execute conditions
5521  * either locally or remotely; the same is true for pushed-down conditions
5522  * at an outer join.
5523  *
5524  * Note we might return failure after having already scribbled on
5525  * fpinfo->remote_conds and fpinfo->local_conds. That's okay because we
5526  * won't consult those lists again if we deem the join unshippable.
5527  */
5528  joinclauses = NIL;
5529  foreach(lc, extra->restrictlist)
5530  {
5531  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
5532  bool is_remote_clause = is_foreign_expr(root, joinrel,
5533  rinfo->clause);
5534 
5535  if (IS_OUTER_JOIN(jointype) &&
5536  !RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5537  {
5538  if (!is_remote_clause)
5539  return false;
5540  joinclauses = lappend(joinclauses, rinfo);
5541  }
5542  else
5543  {
5544  if (is_remote_clause)
5545  fpinfo->remote_conds = lappend(fpinfo->remote_conds, rinfo);
5546  else
5547  fpinfo->local_conds = lappend(fpinfo->local_conds, rinfo);
5548  }
5549  }
5550 
5551  /*
5552  * deparseExplicitTargetList() isn't smart enough to handle anything other
5553  * than a Var. In particular, if there's some PlaceHolderVar that would
5554  * need to be evaluated within this join tree (because there's an upper
5555  * reference to a quantity that may go to NULL as a result of an outer
5556  * join), then we can't try to push the join down because we'll fail when
5557  * we get to deparseExplicitTargetList(). However, a PlaceHolderVar that
5558  * needs to be evaluated *at the top* of this join tree is OK, because we
5559  * can do that locally after fetching the results from the remote side.
5560  */
5561  foreach(lc, root->placeholder_list)
5562  {
5563  PlaceHolderInfo *phinfo = lfirst(lc);
5564  Relids relids;
5565 
5566  /* PlaceHolderInfo refers to parent relids, not child relids. */
5567  relids = IS_OTHER_REL(joinrel) ?
5568  joinrel->top_parent_relids : joinrel->relids;
5569 
5570  if (bms_is_subset(phinfo->ph_eval_at, relids) &&
5571  bms_nonempty_difference(relids, phinfo->ph_eval_at))
5572  return false;
5573  }
5574 
5575  /* Save the join clauses, for later use. */
5576  fpinfo->joinclauses = joinclauses;
5577 
5578  fpinfo->outerrel = outerrel;
5579  fpinfo->innerrel = innerrel;
5580  fpinfo->jointype = jointype;
5581 
5582  /*
5583  * By default, both the input relations are not required to be deparsed as
5584  * subqueries, but there might be some relations covered by the input
5585  * relations that are required to be deparsed as subqueries, so save the
5586  * relids of those relations for later use by the deparser.
5587  */
5588  fpinfo->make_outerrel_subquery = false;
5589  fpinfo->make_innerrel_subquery = false;
5590  Assert(bms_is_subset(fpinfo_o->lower_subquery_rels, outerrel->relids));
5591  Assert(bms_is_subset(fpinfo_i->lower_subquery_rels, innerrel->relids));
5593  fpinfo_i->lower_subquery_rels);
5594 
5595  /*
5596  * Pull the other remote conditions from the joining relations into join
5597  * clauses or other remote clauses (remote_conds) of this relation
5598  * wherever possible. This avoids building subqueries at every join step.
5599  *
5600  * For an inner join, clauses from both the relations are added to the
5601  * other remote clauses. For LEFT and RIGHT OUTER join, the clauses from
5602  * the outer side are added to remote_conds since those can be evaluated
5603  * after the join is evaluated. The clauses from inner side are added to
5604  * the joinclauses, since they need to be evaluated while constructing the
5605  * join.
5606  *
5607  * For a FULL OUTER JOIN, the other clauses from either relation can not
5608  * be added to the joinclauses or remote_conds, since each relation acts
5609  * as an outer relation for the other.
5610  *
5611  * The joining sides can not have local conditions, thus no need to test
5612  * shippability of the clauses being pulled up.
5613  */
5614  switch (jointype)
5615  {
5616  case JOIN_INNER:
5617  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5618  fpinfo_i->remote_conds);
5619  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5620  fpinfo_o->remote_conds);
5621  break;
5622 
5623  case JOIN_LEFT:
5624  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5625  fpinfo_i->remote_conds);
5626  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5627  fpinfo_o->remote_conds);
5628  break;
5629 
5630  case JOIN_RIGHT:
5631  fpinfo->joinclauses = list_concat(fpinfo->joinclauses,
5632  fpinfo_o->remote_conds);
5633  fpinfo->remote_conds = list_concat(fpinfo->remote_conds,
5634  fpinfo_i->remote_conds);
5635  break;
5636 
5637  case JOIN_FULL:
5638 
5639  /*
5640  * In this case, if any of the input relations has conditions, we
5641  * need to deparse that relation as a subquery so that the
5642  * conditions can be evaluated before the join. Remember it in
5643  * the fpinfo of this relation so that the deparser can take
5644  * appropriate action. Also, save the relids of base relations
5645  * covered by that relation for later use by the deparser.
5646  */
5647  if (fpinfo_o->remote_conds)
5648  {
5649  fpinfo->make_outerrel_subquery = true;
5650  fpinfo->lower_subquery_rels =
5652  outerrel->relids);
5653  }
5654  if (fpinfo_i->remote_conds)
5655  {
5656  fpinfo->make_innerrel_subquery = true;
5657  fpinfo->lower_subquery_rels =
5659  innerrel->relids);
5660  }
5661  break;
5662 
5663  default:
5664  /* Should not happen, we have just checked this above */
5665  elog(ERROR, "unsupported join type %d", jointype);
5666  }
5667 
5668  /*
5669  * For an inner join, all restrictions can be treated alike. Treating the
5670  * pushed down conditions as join conditions allows a top level full outer
5671  * join to be deparsed without requiring subqueries.
5672  */
5673  if (jointype == JOIN_INNER)
5674  {
5675  Assert(!fpinfo->joinclauses);
5676  fpinfo->joinclauses = fpinfo->remote_conds;
5677  fpinfo->remote_conds = NIL;
5678  }
5679 
5680  /* Mark that this join can be pushed down safely */
5681  fpinfo->pushdown_safe = true;
5682 
5683  /* Get user mapping */
5684  if (fpinfo->use_remote_estimate)
5685  {
5686  if (fpinfo_o->use_remote_estimate)
5687  fpinfo->user = fpinfo_o->user;
5688  else
5689  fpinfo->user = fpinfo_i->user;
5690  }
5691  else
5692  fpinfo->user = NULL;
5693 
5694  /*
5695  * Set # of retrieved rows and cached relation costs to some negative
5696  * value, so that we can detect when they are set to some sensible values,
5697  * during one (usually the first) of the calls to estimate_path_cost_size.
5698  */
5699  fpinfo->retrieved_rows = -1;
5700  fpinfo->rel_startup_cost = -1;
5701  fpinfo->rel_total_cost = -1;
5702 
5703  /*
5704  * Set the string describing this join relation to be used in EXPLAIN
5705  * output of corresponding ForeignScan. Note that the decoration we add
5706  * to the base relation names mustn't include any digits, or it'll confuse
5707  * postgresExplainForeignScan.
5708  */
5709  fpinfo->relation_name = psprintf("(%s) %s JOIN (%s)",
5710  fpinfo_o->relation_name,
5711  get_jointype_name(fpinfo->jointype),
5712  fpinfo_i->relation_name);
5713 
5714  /*
5715  * Set the relation index. This is defined as the position of this
5716  * joinrel in the join_rel_list list plus the length of the rtable list.
5717  * Note that since this joinrel is at the end of the join_rel_list list
5718  * when we are called, we can get the position by list_length.
5719  */
5720  Assert(fpinfo->relation_index == 0); /* shouldn't be set yet */
5721  fpinfo->relation_index =
5723 
5724  return true;
5725 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
Relids ph_eval_at
Definition: pathnodes.h:2402
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:664
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
ForeignServer * server
Definition: postgres_fdw.h:86
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:755
Relids lower_subquery_rels
Definition: postgres_fdw.h:119
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
List * join_rel_list
Definition: pathnodes.h:228
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
static void merge_fdw_options(PgFdwRelationInfo *fpinfo, const PgFdwRelationInfo *fpinfo_o, const PgFdwRelationInfo *fpinfo_i)
List * rtable
Definition: parsenodes.h:147
#define ERROR
Definition: elog.h:46
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
#define lfirst_node(type, lc)
Definition: pg_list.h:172
const char * get_jointype_name(JoinType jointype)
Definition: deparse.c:1375
Relids relids
Definition: pathnodes.h:676
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
UserMapping * user
Definition: postgres_fdw.h:87
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2128
void * fdw_private
Definition: pathnodes.h:732
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
static int list_length(const List *l)
Definition: pg_list.h:149
RelOptInfo * innerrel
Definition: postgres_fdw.h:103
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:231
#define elog(elevel,...)
Definition: elog.h:232
List * placeholder_list
Definition: pathnodes.h:289
Definition: pg_list.h:50
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793
Relids top_parent_relids
Definition: pathnodes.h:751
bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:545

◆ get_batch_size_option()

static int get_batch_size_option ( Relation  rel)
static

Definition at line 7319 of file postgres_fdw.c.

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

Referenced by create_foreign_modify(), and postgresGetForeignModifyBatchSize().

7320 {
7321  Oid foreigntableid = RelationGetRelid(rel);
7322  ForeignTable *table;
7323  ForeignServer *server;
7324  List *options;
7325  ListCell *lc;
7326 
7327  /* we use 1 by default, which means "no batching" */
7328  int batch_size = 1;
7329 
7330  /*
7331  * Load options for table and server. We append server options after table
7332  * options, because table options take precedence.
7333  */
7334  table = GetForeignTable(foreigntableid);
7335  server = GetForeignServer(table->serverid);
7336 
7337  options = NIL;
7338  options = list_concat(options, table->options);
7339  options = list_concat(options, server->options);
7340 
7341  /* See if either table or server specifies batch_size. */
7342  foreach(lc, options)
7343  {
7344  DefElem *def = (DefElem *) lfirst(lc);
7345 
7346  if (strcmp(def->defname, "batch_size") == 0)
7347  {
7348  (void) parse_int(defGetString(def), &batch_size, 0, NULL);
7349  break;
7350  }
7351  }
7352 
7353  return batch_size;
7354 }
#define NIL
Definition: pg_list.h:65
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
ForeignTable * GetForeignTable(Oid relid)
Definition: foreign.c:248
unsigned int Oid
Definition: postgres_ext.h:31
char * defGetString(DefElem *def)
Definition: define.c:49
static char ** options
ForeignServer * GetForeignServer(Oid serverid)
Definition: foreign.c:109
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition: guc.c:6835
#define lfirst(lc)
Definition: pg_list.h:169
Oid serverid
Definition: foreign.h:56
List * options
Definition: foreign.h:57
char * defname
Definition: parsenodes.h:746
Definition: pg_list.h:50
List * options
Definition: foreign.h:42
#define RelationGetRelid(relation)
Definition: rel.h:477

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

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

Referenced by estimate_path_cost_size().

3554 {
3555  PGresult *volatile res = NULL;
3556 
3557  /* PGresult must be released before leaving this function. */
3558  PG_TRY();
3559  {
3560  char *line;
3561  char *p;
3562  int n;
3563 
3564  /*
3565  * Execute EXPLAIN remotely.
3566  */
3567  res = pgfdw_exec_query(conn, sql, NULL);
3568  if (PQresultStatus(res) != PGRES_TUPLES_OK)
3569  pgfdw_report_error(ERROR, res, conn, false, sql);
3570 
3571  /*
3572  * Extract cost numbers for topmost plan node. Note we search for a
3573  * left paren from the end of the line to avoid being confused by
3574  * other uses of parentheses.
3575  */
3576  line = PQgetvalue(res, 0, 0);
3577  p = strrchr(line, '(');
3578  if (p == NULL)
3579  elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3580  n = sscanf(p, "(cost=%lf..%lf rows=%lf width=%d)",
3581  startup_cost, total_cost, rows, width);
3582  if (n != 4)
3583  elog(ERROR, "could not interpret EXPLAIN output: \"%s\"", line);
3584  }
3585  PG_FINALLY();
3586  {
3587  if (res)
3588  PQclear(res);
3589  }
3590  PG_END_TRY();
3591 }
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3628
PGresult * pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
Definition: connection.c:685
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3164
#define ERROR
Definition: elog.h:46
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
#define PG_FINALLY()
Definition: elog.h:330
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define elog(elevel,...)
Definition: elog.h:232
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338

◆ get_returning_data()

static TupleTableSlot * get_returning_data ( ForeignScanState node)
static

Definition at line 4551 of file postgres_fdw.c.

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().

4552 {
4554  EState *estate = node->ss.ps.state;
4555  ResultRelInfo *resultRelInfo = node->resultRelInfo;
4556  TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
4557  TupleTableSlot *resultSlot;
4558 
4559  Assert(resultRelInfo->ri_projectReturning);
4560 
4561  /* If we didn't get any tuples, must be end of data. */
4562  if (dmstate->next_tuple >= dmstate->num_tuples)
4563  return ExecClearTuple(slot);
4564 
4565  /* Increment the command es_processed count if necessary. */
4566  if (dmstate->set_processed)
4567  estate->es_processed += 1;
4568 
4569  /*
4570  * Store a RETURNING tuple. If has_returning is false, just emit a dummy
4571  * tuple. (has_returning is false when the local query is of the form
4572  * "UPDATE/DELETE .. RETURNING 1" for example.)
4573  */
4574  if (!dmstate->has_returning)
4575  {
4576  ExecStoreAllNullTuple(slot);
4577  resultSlot = slot;
4578  }
4579  else
4580  {
4581  /*
4582  * On error, be sure to release the PGresult on the way out. Callers
4583  * do not have PG_TRY blocks to ensure this happens.
4584  */
4585  PG_TRY();
4586  {
4587  HeapTuple newtup;
4588 
4589  newtup = make_tuple_from_result_row(dmstate->result,
4590  dmstate->next_tuple,
4591  dmstate->rel,
4592  dmstate->attinmeta,
4593  dmstate->retrieved_attrs,
4594  node,
4595  dmstate->temp_cxt);
4596  ExecStoreHeapTuple(newtup, slot, false);
4597  }
4598  PG_CATCH();
4599  {
4600  if (dmstate->result)
4601  PQclear(dmstate->result);
4602  PG_RE_THROW();
4603  }
4604  PG_END_TRY();
4605 
4606  /* Get the updated/deleted tuple. */
4607  if (dmstate->rel)
4608  resultSlot = slot;
4609  else
4610  resultSlot = apply_returning_filter(dmstate, resultRelInfo, slot, estate);
4611  }
4612  dmstate->next_tuple++;
4613 
4614  /* Make slot available for evaluation of the local query RETURNING list. */
4615  resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple =
4616  resultSlot;
4617 
4618  return slot;
4619 }
ScanState ss
Definition: execnodes.h:1857
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
static HeapTuple make_tuple_from_result_row(PGresult *res, int row, Relation rel, AttInMetadata *attinmeta, List *retrieved_attrs, ForeignScanState *fsstate, MemoryContext temp_context)
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:1576
AttInMetadata * attinmeta
Definition: postgres_fdw.c:220
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1380
EState * state
Definition: execnodes.h:968
PlanState ps
Definition: execnodes.h:1377
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1860
MemoryContext temp_cxt
Definition: postgres_fdw.c:247
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_CATCH()
Definition: elog.h:323
#define Assert(condition)
Definition: c.h:804
#define PG_RE_THROW()
Definition: elog.h:354
static TupleTableSlot * apply_returning_filter(PgFdwDirectModifyState *dmstate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352

◆ get_tupdesc_for_join_scan_tuples()

static TupleDesc get_tupdesc_for_join_scan_tuples ( ForeignScanState node)
static

Definition at line 1438 of file postgres_fdw.c.

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

Referenced by postgresBeginDirectModify(), and postgresBeginForeignScan().

1439 {
1440  ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
1441  EState *estate = node->ss.ps.state;
1442  TupleDesc tupdesc;
1443 
1444  /*
1445  * The core code has already set up a scan tuple slot based on
1446  * fsplan->fdw_scan_tlist, and this slot's tupdesc is mostly good enough,
1447  * but there's one case where it isn't. If we have any whole-row row
1448  * identifier Vars, they may have vartype RECORD, and we need to replace
1449  * that with the associated table's actual composite type. This ensures
1450  * that when we read those ROW() expression values from the remote server,
1451  * we can convert them to a composite type the local server knows.
1452  */
1454  for (int i = 0; i < tupdesc->natts; i++)
1455  {
1456  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1457  Var *var;
1458  RangeTblEntry *rte;
1459  Oid reltype;
1460 
1461  /* Nothing to do if it's not a generic RECORD attribute */
1462  if (att->atttypid != RECORDOID || att->atttypmod >= 0)
1463  continue;
1464 
1465  /*
1466  * If we can't identify the referenced table, do nothing. This'll
1467  * likely lead to failure later, but perhaps we can muddle through.
1468  */
1469  var = (Var *) list_nth_node(TargetEntry, fsplan->fdw_scan_tlist,
1470  i)->expr;
1471  if (!IsA(var, Var) || var->varattno != 0)
1472  continue;
1473  rte = list_nth(estate->es_range_table, var->varno - 1);
1474  if (rte->rtekind != RTE_RELATION)
1475  continue;
1476  reltype = get_rel_type_id(rte->relid);
1477  if (!OidIsValid(reltype))
1478  continue;
1479  att->atttypid = reltype;
1480  /* shouldn't need to change anything else */
1481  }
1482  return tupdesc;
1483 }
ScanState ss
Definition: execnodes.h:1857
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
AttrNumber varattno
Definition: primnodes.h:191
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1380
List * fdw_scan_tlist
Definition: plannodes.h:639
EState * state
Definition: execnodes.h:968
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
#define OidIsValid(objectId)
Definition: c.h:710
PlanState ps
Definition: execnodes.h:1377
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
#define list_nth_node(type, list, n)
Definition: pg_list.h:306
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
Index varno
Definition: primnodes.h:189
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
Oid get_rel_type_id(Oid relid)
Definition: lsyscache.c:1950
Plan * plan
Definition: execnodes.h:966
RTEKind rtekind
Definition: parsenodes.h:995
int i

◆ get_useful_ecs_for_relation()

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

Definition at line 803 of file postgres_fdw.c.

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

Referenced by get_useful_pathkeys_for_relation().

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