PostgreSQL Source Code  git master
postgres_fdw.h File Reference
#include "foreign/foreign.h"
#include "lib/stringinfo.h"
#include "libpq-fe.h"
#include "nodes/execnodes.h"
#include "nodes/pathnodes.h"
#include "utils/relcache.h"
Include dependency graph for postgres_fdw.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PgFdwRelationInfo
 
struct  PgFdwConnState
 

Typedefs

typedef struct PgFdwRelationInfo PgFdwRelationInfo
 
typedef struct PgFdwConnState PgFdwConnState
 
typedef enum PgFdwSamplingMethod PgFdwSamplingMethod
 

Enumerations

enum  PgFdwSamplingMethod {
  ANALYZE_SAMPLE_OFF , ANALYZE_SAMPLE_AUTO , ANALYZE_SAMPLE_RANDOM , ANALYZE_SAMPLE_SYSTEM ,
  ANALYZE_SAMPLE_BERNOULLI
}
 

Functions

int set_transmission_modes (void)
 
void reset_transmission_modes (int nestlevel)
 
void process_pending_request (AsyncRequest *areq)
 
PGconnGetConnection (UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
 
void ReleaseConnection (PGconn *conn)
 
unsigned int GetCursorNumber (PGconn *conn)
 
unsigned int GetPrepStmtNumber (PGconn *conn)
 
void do_sql_command (PGconn *conn, const char *sql)
 
PGresultpgfdw_get_result (PGconn *conn, const char *query)
 
PGresultpgfdw_exec_query (PGconn *conn, const char *query, PgFdwConnState *state)
 
void pgfdw_report_error (int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
 
int ExtractConnectionOptions (List *defelems, const char **keywords, const char **values)
 
ListExtractExtensionList (const char *extensionsString, bool warnOnMissing)
 
char * process_pgfdw_appname (const char *appname)
 
void classifyConditions (PlannerInfo *root, RelOptInfo *baserel, List *input_conds, List **remote_conds, List **local_conds)
 
bool is_foreign_expr (PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
 
bool is_foreign_param (PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
 
bool is_foreign_pathkey (PlannerInfo *root, RelOptInfo *baserel, PathKey *pathkey)
 
void deparseInsertSql (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *targetAttrs, bool doNothing, List *withCheckOptionList, List *returningList, List **retrieved_attrs, int *values_end_len)
 
void rebuildInsertSql (StringInfo buf, Relation rel, char *orig_query, List *target_attrs, int values_end_len, int num_params, int num_rows)
 
void deparseUpdateSql (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *targetAttrs, List *withCheckOptionList, List *returningList, List **retrieved_attrs)
 
void deparseDirectUpdateSql (StringInfo buf, PlannerInfo *root, Index rtindex, Relation rel, RelOptInfo *foreignrel, List *targetlist, List *targetAttrs, List *remote_conds, List **params_list, List *returningList, List **retrieved_attrs)
 
void deparseDeleteSql (StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *returningList, List **retrieved_attrs)
 
void deparseDirectDeleteSql (StringInfo buf, PlannerInfo *root, Index rtindex, Relation rel, RelOptInfo *foreignrel, List *remote_conds, List **params_list, List *returningList, List **retrieved_attrs)
 
void deparseAnalyzeSizeSql (StringInfo buf, Relation rel)
 
void deparseAnalyzeInfoSql (StringInfo buf, Relation rel)
 
void deparseAnalyzeSql (StringInfo buf, Relation rel, PgFdwSamplingMethod sample_method, double sample_frac, List **retrieved_attrs)
 
void deparseTruncateSql (StringInfo buf, List *rels, DropBehavior behavior, bool restart_seqs)
 
void deparseStringLiteral (StringInfo buf, const char *val)
 
EquivalenceMemberfind_em_for_rel (PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
 
EquivalenceMemberfind_em_for_rel_target (PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
 
Listbuild_tlist_to_deparse (RelOptInfo *foreignrel)
 
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)
 
const char * get_jointype_name (JoinType jointype)
 
bool is_builtin (Oid objectId)
 
bool is_shippable (Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo)
 

Variables

char * pgfdw_application_name
 

Typedef Documentation

◆ PgFdwConnState

◆ PgFdwRelationInfo

◆ PgFdwSamplingMethod

Enumeration Type Documentation

◆ PgFdwSamplingMethod

Enumerator
ANALYZE_SAMPLE_OFF 
ANALYZE_SAMPLE_AUTO 
ANALYZE_SAMPLE_RANDOM 
ANALYZE_SAMPLE_SYSTEM 
ANALYZE_SAMPLE_BERNOULLI 

Definition at line 140 of file postgres_fdw.h.

141 {
142  ANALYZE_SAMPLE_OFF, /* no remote sampling */
143  ANALYZE_SAMPLE_AUTO, /* choose by server version */
144  ANALYZE_SAMPLE_RANDOM, /* remote random() */
145  ANALYZE_SAMPLE_SYSTEM, /* TABLESAMPLE system */
146  ANALYZE_SAMPLE_BERNOULLI /* TABLESAMPLE bernoulli */
PgFdwSamplingMethod
Definition: postgres_fdw.h:141
@ ANALYZE_SAMPLE_AUTO
Definition: postgres_fdw.h:143
@ ANALYZE_SAMPLE_OFF
Definition: postgres_fdw.h:142
@ ANALYZE_SAMPLE_BERNOULLI
Definition: postgres_fdw.h:146
@ ANALYZE_SAMPLE_SYSTEM
Definition: postgres_fdw.h:145
@ ANALYZE_SAMPLE_RANDOM
Definition: postgres_fdw.h:144

Function Documentation

◆ build_tlist_to_deparse()

List* build_tlist_to_deparse ( RelOptInfo foreignrel)

Definition at line 1172 of file deparse.c.

1173 {
1174  List *tlist = NIL;
1175  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
1176  ListCell *lc;
1177 
1178  /*
1179  * For an upper relation, we have already built the target list while
1180  * checking shippability, so just return that.
1181  */
1182  if (IS_UPPER_REL(foreignrel))
1183  return fpinfo->grouped_tlist;
1184 
1185  /*
1186  * We require columns specified in foreignrel->reltarget->exprs and those
1187  * required for evaluating the local conditions.
1188  */
1189  tlist = add_to_flat_tlist(tlist,
1190  pull_var_clause((Node *) foreignrel->reltarget->exprs,
1192  foreach(lc, fpinfo->local_conds)
1193  {
1194  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1195 
1196  tlist = add_to_flat_tlist(tlist,
1197  pull_var_clause((Node *) rinfo->clause,
1199  }
1200 
1201  return tlist;
1202 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:188
#define IS_UPPER_REL(rel)
Definition: pathnodes.h:840
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
Definition: pg_list.h:54
Definition: nodes.h:129
List * exprs
Definition: pathnodes.h:1507
struct PathTarget * reltarget
Definition: pathnodes.h:884
Expr * clause
Definition: pathnodes.h:2513
List * add_to_flat_tlist(List *tlist, List *exprs)
Definition: tlist.c:132
List * pull_var_clause(Node *node, int flags)
Definition: var.c:607

References add_to_flat_tlist(), RestrictInfo::clause, PathTarget::exprs, PgFdwRelationInfo::grouped_tlist, if(), IS_UPPER_REL, lfirst_node, PgFdwRelationInfo::local_conds, NIL, pull_var_clause(), PVC_RECURSE_PLACEHOLDERS, and RelOptInfo::reltarget.

Referenced by estimate_path_cost_size(), and postgresGetForeignPlan().

◆ classifyConditions()

void classifyConditions ( PlannerInfo root,
RelOptInfo baserel,
List input_conds,
List **  remote_conds,
List **  local_conds 
)

Definition at line 214 of file deparse.c.

219 {
220  ListCell *lc;
221 
222  *remote_conds = NIL;
223  *local_conds = NIL;
224 
225  foreach(lc, input_conds)
226  {
228 
229  if (is_foreign_expr(root, baserel, ri->clause))
230  *remote_conds = lappend(*remote_conds, ri);
231  else
232  *local_conds = lappend(*local_conds, ri);
233  }
234 }
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:240
List * lappend(List *list, void *datum)
Definition: list.c:338

References RestrictInfo::clause, is_foreign_expr(), lappend(), lfirst_node, and NIL.

Referenced by estimate_path_cost_size(), and postgresGetForeignRelSize().

◆ deparseAnalyzeInfoSql()

void deparseAnalyzeInfoSql ( StringInfo  buf,
Relation  rel 
)

Definition at line 2379 of file deparse.c.

2380 {
2382 
2383  /* We'll need the remote relation name as a literal. */
2385  deparseRelation(&relname, rel);
2386 
2387  appendStringInfoString(buf, "SELECT reltuples, relkind FROM pg_catalog.pg_class WHERE oid = ");
2389  appendStringInfoString(buf, "::pg_catalog.regclass");
2390 }
void deparseStringLiteral(StringInfo buf, const char *val)
Definition: deparse.c:2707
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2667
NameData relname
Definition: pg_class.h:38
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char data[NAMEDATALEN]
Definition: c.h:726

References appendStringInfoString(), buf, nameData::data, deparseRelation(), deparseStringLiteral(), initStringInfo(), and relname.

Referenced by postgresGetAnalyzeInfoForForeignTable().

◆ deparseAnalyzeSizeSql()

void deparseAnalyzeSizeSql ( StringInfo  buf,
Relation  rel 
)

Definition at line 2357 of file deparse.c.

2358 {
2360 
2361  /* We'll need the remote relation name as a literal. */
2363  deparseRelation(&relname, rel);
2364 
2365  appendStringInfoString(buf, "SELECT pg_catalog.pg_relation_size(");
2367  appendStringInfo(buf, "::pg_catalog.regclass) / %d", BLCKSZ);
2368 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91

References appendStringInfo(), appendStringInfoString(), buf, nameData::data, deparseRelation(), deparseStringLiteral(), initStringInfo(), and relname.

Referenced by postgresAnalyzeForeignTable().

◆ deparseAnalyzeSql()

void deparseAnalyzeSql ( StringInfo  buf,
Relation  rel,
PgFdwSamplingMethod  sample_method,
double  sample_frac,
List **  retrieved_attrs 
)

Definition at line 2419 of file deparse.c.

2422 {
2423  Oid relid = RelationGetRelid(rel);
2424  TupleDesc tupdesc = RelationGetDescr(rel);
2425  int i;
2426  char *colname;
2427  List *options;
2428  ListCell *lc;
2429  bool first = true;
2430 
2431  *retrieved_attrs = NIL;
2432 
2433  appendStringInfoString(buf, "SELECT ");
2434  for (i = 0; i < tupdesc->natts; i++)
2435  {
2436  /* Ignore dropped columns. */
2437  if (TupleDescAttr(tupdesc, i)->attisdropped)
2438  continue;
2439 
2440  if (!first)
2441  appendStringInfoString(buf, ", ");
2442  first = false;
2443 
2444  /* Use attribute name or column_name option. */
2445  colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
2446  options = GetForeignColumnOptions(relid, i + 1);
2447 
2448  foreach(lc, options)
2449  {
2450  DefElem *def = (DefElem *) lfirst(lc);
2451 
2452  if (strcmp(def->defname, "column_name") == 0)
2453  {
2454  colname = defGetString(def);
2455  break;
2456  }
2457  }
2458 
2460 
2461  *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
2462  }
2463 
2464  /* Don't generate bad syntax for zero-column relation. */
2465  if (first)
2466  appendStringInfoString(buf, "NULL");
2467 
2468  /*
2469  * Construct FROM clause, and perhaps WHERE clause too, depending on the
2470  * selected sampling method.
2471  */
2472  appendStringInfoString(buf, " FROM ");
2473  deparseRelation(buf, rel);
2474 
2475  switch (sample_method)
2476  {
2477  case ANALYZE_SAMPLE_OFF:
2478  /* nothing to do here */
2479  break;
2480 
2481  case ANALYZE_SAMPLE_RANDOM:
2482  appendStringInfo(buf, " WHERE pg_catalog.random() < %f", sample_frac);
2483  break;
2484 
2485  case ANALYZE_SAMPLE_SYSTEM:
2486  appendStringInfo(buf, " TABLESAMPLE SYSTEM(%f)", (100.0 * sample_frac));
2487  break;
2488 
2490  appendStringInfo(buf, " TABLESAMPLE BERNOULLI(%f)", (100.0 * sample_frac));
2491  break;
2492 
2493  case ANALYZE_SAMPLE_AUTO:
2494  /* should have been resolved into actual method */
2495  elog(ERROR, "unexpected sampling method");
2496  break;
2497  }
2498 }
#define NameStr(name)
Definition: c.h:730
char * defGetString(DefElem *def)
Definition: define.c:49
#define ERROR
Definition: elog.h:39
List * GetForeignColumnOptions(Oid relid, AttrNumber attnum)
Definition: foreign.c:288
int i
Definition: isn.c:73
List * lappend_int(List *list, int datum)
Definition: list.c:356
NameData attname
Definition: pg_attribute.h:41
#define lfirst(lc)
Definition: pg_list.h:172
static char ** options
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetRelid(relation)
Definition: rel.h:503
#define RelationGetDescr(relation)
Definition: rel.h:529
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11751
char * defname
Definition: parsenodes.h:810
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References ANALYZE_SAMPLE_AUTO, ANALYZE_SAMPLE_BERNOULLI, ANALYZE_SAMPLE_OFF, ANALYZE_SAMPLE_RANDOM, ANALYZE_SAMPLE_SYSTEM, appendStringInfo(), appendStringInfoString(), attname, buf, defGetString(), DefElem::defname, deparseRelation(), elog(), ERROR, GetForeignColumnOptions(), i, lappend_int(), lfirst, NameStr, TupleDescData::natts, NIL, options, quote_identifier(), RelationGetDescr, RelationGetRelid, and TupleDescAttr.

Referenced by postgresAcquireSampleRowsFunc().

◆ deparseDeleteSql()

void deparseDeleteSql ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2220 of file deparse.c.

2224 {
2225  appendStringInfoString(buf, "DELETE FROM ");
2226  deparseRelation(buf, rel);
2227  appendStringInfoString(buf, " WHERE ctid = $1");
2228 
2229  deparseReturningList(buf, rte, rtindex, rel,
2230  rel->trigdesc && rel->trigdesc->trig_delete_after_row,
2231  NIL, returningList, retrieved_attrs);
2232 }
static void deparseReturningList(StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, bool trig_after_row, List *withCheckOptionList, List *returningList, List **retrieved_attrs)
Definition: deparse.c:2300
TriggerDesc * trigdesc
Definition: rel.h:116
bool trig_delete_after_row
Definition: reltrigger.h:67

References appendStringInfoString(), buf, deparseRelation(), deparseReturningList(), NIL, TriggerDesc::trig_delete_after_row, and RelationData::trigdesc.

Referenced by postgresPlanForeignModify().

◆ deparseDirectDeleteSql()

void deparseDirectDeleteSql ( StringInfo  buf,
PlannerInfo root,
Index  rtindex,
Relation  rel,
RelOptInfo foreignrel,
List remote_conds,
List **  params_list,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2249 of file deparse.c.

2256 {
2257  deparse_expr_cxt context;
2258 
2259  /* Set up context struct for recursion */
2260  context.root = root;
2261  context.foreignrel = foreignrel;
2262  context.scanrel = foreignrel;
2263  context.buf = buf;
2264  context.params_list = params_list;
2265 
2266  appendStringInfoString(buf, "DELETE FROM ");
2267  deparseRelation(buf, rel);
2268  if (foreignrel->reloptkind == RELOPT_JOINREL)
2269  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2270 
2271  if (foreignrel->reloptkind == RELOPT_JOINREL)
2272  {
2273  List *ignore_conds = NIL;
2274 
2275  appendStringInfoString(buf, " USING ");
2276  deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2277  &ignore_conds, params_list);
2278  remote_conds = list_concat(remote_conds, ignore_conds);
2279  }
2280 
2281  if (remote_conds)
2282  {
2283  appendStringInfoString(buf, " WHERE ");
2284  appendConditions(remote_conds, &context);
2285  }
2286 
2287  if (foreignrel->reloptkind == RELOPT_JOINREL)
2288  deparseExplicitTargetList(returningList, true, retrieved_attrs,
2289  &context);
2290  else
2291  deparseReturningList(buf, planner_rt_fetch(rtindex, root),
2292  rtindex, rel, false,
2293  NIL, returningList, retrieved_attrs);
2294 }
#define REL_ALIAS_PREFIX
Definition: deparse.c:110
static void appendConditions(List *exprs, deparse_expr_cxt *context)
Definition: deparse.c:1569
static void deparseExplicitTargetList(List *tlist, bool is_returning, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1640
static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool use_alias, Index ignore_rel, List **ignore_conds, List **params_list)
Definition: deparse.c:1717
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:561
@ RELOPT_JOINREL
Definition: pathnodes.h:819
RelOptKind reloptkind
Definition: pathnodes.h:856
PlannerInfo * root
Definition: deparse.c:101
List ** params_list
Definition: deparse.c:107
RelOptInfo * foreignrel
Definition: deparse.c:102
StringInfo buf
Definition: deparse.c:106
RelOptInfo * scanrel
Definition: deparse.c:103

References appendConditions(), appendStringInfo(), appendStringInfoString(), deparse_expr_cxt::buf, buf, deparseExplicitTargetList(), deparseFromExprForRel(), deparseRelation(), deparseReturningList(), deparse_expr_cxt::foreignrel, list_concat(), NIL, deparse_expr_cxt::params_list, planner_rt_fetch, REL_ALIAS_PREFIX, RELOPT_JOINREL, RelOptInfo::reloptkind, deparse_expr_cxt::root, and deparse_expr_cxt::scanrel.

Referenced by postgresPlanDirectModify().

◆ deparseDirectUpdateSql()

void deparseDirectUpdateSql ( StringInfo  buf,
PlannerInfo root,
Index  rtindex,
Relation  rel,
RelOptInfo foreignrel,
List targetlist,
List targetAttrs,
List remote_conds,
List **  params_list,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2135 of file deparse.c.

2144 {
2145  deparse_expr_cxt context;
2146  int nestlevel;
2147  bool first;
2148  RangeTblEntry *rte = planner_rt_fetch(rtindex, root);
2149  ListCell *lc,
2150  *lc2;
2151 
2152  /* Set up context struct for recursion */
2153  context.root = root;
2154  context.foreignrel = foreignrel;
2155  context.scanrel = foreignrel;
2156  context.buf = buf;
2157  context.params_list = params_list;
2158 
2159  appendStringInfoString(buf, "UPDATE ");
2160  deparseRelation(buf, rel);
2161  if (foreignrel->reloptkind == RELOPT_JOINREL)
2162  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2163  appendStringInfoString(buf, " SET ");
2164 
2165  /* Make sure any constants in the exprs are printed portably */
2166  nestlevel = set_transmission_modes();
2167 
2168  first = true;
2169  forboth(lc, targetlist, lc2, targetAttrs)
2170  {
2171  TargetEntry *tle = lfirst_node(TargetEntry, lc);
2172  int attnum = lfirst_int(lc2);
2173 
2174  /* update's new-value expressions shouldn't be resjunk */
2175  Assert(!tle->resjunk);
2176 
2177  if (!first)
2178  appendStringInfoString(buf, ", ");
2179  first = false;
2180 
2181  deparseColumnRef(buf, rtindex, attnum, rte, false);
2182  appendStringInfoString(buf, " = ");
2183  deparseExpr((Expr *) tle->expr, &context);
2184  }
2185 
2186  reset_transmission_modes(nestlevel);
2187 
2188  if (foreignrel->reloptkind == RELOPT_JOINREL)
2189  {
2190  List *ignore_conds = NIL;
2191 
2192  appendStringInfoString(buf, " FROM ");
2193  deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2194  &ignore_conds, params_list);
2195  remote_conds = list_concat(remote_conds, ignore_conds);
2196  }
2197 
2198  if (remote_conds)
2199  {
2200  appendStringInfoString(buf, " WHERE ");
2201  appendConditions(remote_conds, &context);
2202  }
2203 
2204  if (foreignrel->reloptkind == RELOPT_JOINREL)
2205  deparseExplicitTargetList(returningList, true, retrieved_attrs,
2206  &context);
2207  else
2208  deparseReturningList(buf, rte, rtindex, rel, false,
2209  NIL, returningList, retrieved_attrs);
2210 }
static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col)
Definition: deparse.c:2539
static void deparseExpr(Expr *node, deparse_expr_cxt *context)
Definition: deparse.c:2742
Assert(fmt[strlen(fmt) - 1] !='\n')
int16 attnum
Definition: pg_attribute.h:74
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467
#define lfirst_int(lc)
Definition: pg_list.h:173
void reset_transmission_modes(int nestlevel)
int set_transmission_modes(void)
Expr * expr
Definition: primnodes.h:1816

References appendConditions(), appendStringInfo(), appendStringInfoString(), Assert(), attnum, deparse_expr_cxt::buf, buf, deparseColumnRef(), deparseExplicitTargetList(), deparseExpr(), deparseFromExprForRel(), deparseRelation(), deparseReturningList(), TargetEntry::expr, forboth, deparse_expr_cxt::foreignrel, lfirst_int, lfirst_node, list_concat(), NIL, deparse_expr_cxt::params_list, planner_rt_fetch, REL_ALIAS_PREFIX, RELOPT_JOINREL, RelOptInfo::reloptkind, reset_transmission_modes(), deparse_expr_cxt::root, deparse_expr_cxt::scanrel, and set_transmission_modes().

Referenced by postgresPlanDirectModify().

◆ deparseInsertSql()

void deparseInsertSql ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
List targetAttrs,
bool  doNothing,
List withCheckOptionList,
List returningList,
List **  retrieved_attrs,
int *  values_end_len 
)

Definition at line 1942 of file deparse.c.

1947 {
1948  TupleDesc tupdesc = RelationGetDescr(rel);
1949  AttrNumber pindex;
1950  bool first;
1951  ListCell *lc;
1952 
1953  appendStringInfoString(buf, "INSERT INTO ");
1954  deparseRelation(buf, rel);
1955 
1956  if (targetAttrs)
1957  {
1958  appendStringInfoChar(buf, '(');
1959 
1960  first = true;
1961  foreach(lc, targetAttrs)
1962  {
1963  int attnum = lfirst_int(lc);
1964 
1965  if (!first)
1966  appendStringInfoString(buf, ", ");
1967  first = false;
1968 
1969  deparseColumnRef(buf, rtindex, attnum, rte, false);
1970  }
1971 
1972  appendStringInfoString(buf, ") VALUES (");
1973 
1974  pindex = 1;
1975  first = true;
1976  foreach(lc, targetAttrs)
1977  {
1978  int attnum = lfirst_int(lc);
1979  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
1980 
1981  if (!first)
1982  appendStringInfoString(buf, ", ");
1983  first = false;
1984 
1985  if (attr->attgenerated)
1986  appendStringInfoString(buf, "DEFAULT");
1987  else
1988  {
1989  appendStringInfo(buf, "$%d", pindex);
1990  pindex++;
1991  }
1992  }
1993 
1994  appendStringInfoChar(buf, ')');
1995  }
1996  else
1997  appendStringInfoString(buf, " DEFAULT VALUES");
1998  *values_end_len = buf->len;
1999 
2000  if (doNothing)
2001  appendStringInfoString(buf, " ON CONFLICT DO NOTHING");
2002 
2003  deparseReturningList(buf, rte, rtindex, rel,
2004  rel->trigdesc && rel->trigdesc->trig_insert_after_row,
2005  withCheckOptionList, returningList, retrieved_attrs);
2006 }
int16 AttrNumber
Definition: attnum.h:21
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
bool trig_insert_after_row
Definition: reltrigger.h:57

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), attnum, buf, deparseColumnRef(), deparseRelation(), deparseReturningList(), lfirst_int, RelationGetDescr, TriggerDesc::trig_insert_after_row, RelationData::trigdesc, and TupleDescAttr.

Referenced by postgresBeginForeignInsert(), and postgresPlanForeignModify().

◆ deparseSelectStmtForRel()

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 at line 1229 of file deparse.c.

1233 {
1234  deparse_expr_cxt context;
1235  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1236  List *quals;
1237 
1238  /*
1239  * We handle relations for foreign tables, joins between those and upper
1240  * relations.
1241  */
1242  Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
1243 
1244  /* Fill portions of context common to upper, join and base relation */
1245  context.buf = buf;
1246  context.root = root;
1247  context.foreignrel = rel;
1248  context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
1249  context.params_list = params_list;
1250 
1251  /* Construct SELECT clause */
1252  deparseSelectSql(tlist, is_subquery, retrieved_attrs, &context);
1253 
1254  /*
1255  * For upper relations, the WHERE clause is built from the remote
1256  * conditions of the underlying scan relation; otherwise, we can use the
1257  * supplied list of remote conditions directly.
1258  */
1259  if (IS_UPPER_REL(rel))
1260  {
1261  PgFdwRelationInfo *ofpinfo;
1262 
1263  ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
1264  quals = ofpinfo->remote_conds;
1265  }
1266  else
1267  quals = remote_conds;
1268 
1269  /* Construct FROM and WHERE clauses */
1270  deparseFromExpr(quals, &context);
1271 
1272  if (IS_UPPER_REL(rel))
1273  {
1274  /* Append GROUP BY clause */
1275  appendGroupByClause(tlist, &context);
1276 
1277  /* Append HAVING clause */
1278  if (remote_conds)
1279  {
1280  appendStringInfoString(buf, " HAVING ");
1281  appendConditions(remote_conds, &context);
1282  }
1283  }
1284 
1285  /* Add ORDER BY clause if we found any useful pathkeys */
1286  if (pathkeys)
1287  appendOrderByClause(pathkeys, has_final_sort, &context);
1288 
1289  /* Add LIMIT clause if necessary */
1290  if (has_limit)
1291  appendLimitClause(&context);
1292 
1293  /* Add any necessary FOR UPDATE/SHARE. */
1294  deparseLockingClause(&context);
1295 }
static void appendGroupByClause(List *tlist, deparse_expr_cxt *context)
Definition: deparse.c:3720
static void deparseFromExpr(List *quals, deparse_expr_cxt *context)
Definition: deparse.c:1369
static void deparseLockingClause(deparse_expr_cxt *context)
Definition: deparse.c:1479
static void appendOrderByClause(List *pathkeys, bool has_final_sort, deparse_expr_cxt *context)
Definition: deparse.c:3768
static void appendLimitClause(deparse_expr_cxt *context)
Definition: deparse.c:3845
static void deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1311
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:830
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:835
RelOptInfo * outerrel
Definition: postgres_fdw.h:102

References appendConditions(), appendGroupByClause(), appendLimitClause(), appendOrderByClause(), appendStringInfoString(), Assert(), deparse_expr_cxt::buf, buf, deparseFromExpr(), deparseLockingClause(), deparseSelectSql(), deparse_expr_cxt::foreignrel, IS_JOIN_REL, IS_SIMPLE_REL, IS_UPPER_REL, PgFdwRelationInfo::outerrel, deparse_expr_cxt::params_list, PgFdwRelationInfo::remote_conds, deparse_expr_cxt::root, and deparse_expr_cxt::scanrel.

Referenced by deparseRangeTblRef(), estimate_path_cost_size(), and postgresGetForeignPlan().

◆ deparseStringLiteral()

void deparseStringLiteral ( StringInfo  buf,
const char *  val 
)

Definition at line 2707 of file deparse.c.

2708 {
2709  const char *valptr;
2710 
2711  /*
2712  * Rather than making assumptions about the remote server's value of
2713  * standard_conforming_strings, always use E'foo' syntax if there are any
2714  * backslashes. This will fail on remote servers before 8.1, but those
2715  * are long out of support.
2716  */
2717  if (strchr(val, '\\') != NULL)
2719  appendStringInfoChar(buf, '\'');
2720  for (valptr = val; *valptr; valptr++)
2721  {
2722  char ch = *valptr;
2723 
2724  if (SQL_STR_DOUBLE(ch, true))
2727  }
2728  appendStringInfoChar(buf, '\'');
2729 }
#define ESCAPE_STRING_SYNTAX
Definition: c.h:1156
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1153
long val
Definition: informix.c:664

References appendStringInfoChar(), buf, ESCAPE_STRING_SYNTAX, SQL_STR_DOUBLE, and val.

Referenced by deparseAnalyzeInfoSql(), deparseAnalyzeSizeSql(), deparseConst(), and postgresImportForeignSchema().

◆ deparseTruncateSql()

void deparseTruncateSql ( StringInfo  buf,
List rels,
DropBehavior  behavior,
bool  restart_seqs 
)

Definition at line 2504 of file deparse.c.

2508 {
2509  ListCell *cell;
2510 
2511  appendStringInfoString(buf, "TRUNCATE ");
2512 
2513  foreach(cell, rels)
2514  {
2515  Relation rel = lfirst(cell);
2516 
2517  if (cell != list_head(rels))
2518  appendStringInfoString(buf, ", ");
2519 
2520  deparseRelation(buf, rel);
2521  }
2522 
2523  appendStringInfo(buf, " %s IDENTITY",
2524  restart_seqs ? "RESTART" : "CONTINUE");
2525 
2526  if (behavior == DROP_RESTRICT)
2527  appendStringInfoString(buf, " RESTRICT");
2528  else if (behavior == DROP_CASCADE)
2529  appendStringInfoString(buf, " CASCADE");
2530 }
@ DROP_CASCADE
Definition: parsenodes.h:2156
@ DROP_RESTRICT
Definition: parsenodes.h:2155
static ListCell * list_head(const List *l)
Definition: pg_list.h:128

References appendStringInfo(), appendStringInfoString(), buf, deparseRelation(), DROP_CASCADE, DROP_RESTRICT, lfirst, and list_head().

Referenced by postgresExecForeignTruncate().

◆ deparseUpdateSql()

void deparseUpdateSql ( StringInfo  buf,
RangeTblEntry rte,
Index  rtindex,
Relation  rel,
List targetAttrs,
List withCheckOptionList,
List returningList,
List **  retrieved_attrs 
)

Definition at line 2075 of file deparse.c.

2080 {
2081  TupleDesc tupdesc = RelationGetDescr(rel);
2082  AttrNumber pindex;
2083  bool first;
2084  ListCell *lc;
2085 
2086  appendStringInfoString(buf, "UPDATE ");
2087  deparseRelation(buf, rel);
2088  appendStringInfoString(buf, " SET ");
2089 
2090  pindex = 2; /* ctid is always the first param */
2091  first = true;
2092  foreach(lc, targetAttrs)
2093  {
2094  int attnum = lfirst_int(lc);
2095  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2096 
2097  if (!first)
2098  appendStringInfoString(buf, ", ");
2099  first = false;
2100 
2101  deparseColumnRef(buf, rtindex, attnum, rte, false);
2102  if (attr->attgenerated)
2103  appendStringInfoString(buf, " = DEFAULT");
2104  else
2105  {
2106  appendStringInfo(buf, " = $%d", pindex);
2107  pindex++;
2108  }
2109  }
2110  appendStringInfoString(buf, " WHERE ctid = $1");
2111 
2112  deparseReturningList(buf, rte, rtindex, rel,
2113  rel->trigdesc && rel->trigdesc->trig_update_after_row,
2114  withCheckOptionList, returningList, retrieved_attrs);
2115 }
bool trig_update_after_row
Definition: reltrigger.h:62

References appendStringInfo(), appendStringInfoString(), attnum, buf, deparseColumnRef(), deparseRelation(), deparseReturningList(), lfirst_int, RelationGetDescr, TriggerDesc::trig_update_after_row, RelationData::trigdesc, and TupleDescAttr.

Referenced by postgresPlanForeignModify().

◆ do_sql_command()

void do_sql_command ( PGconn conn,
const char *  sql 
)

Definition at line 607 of file connection.c.

608 {
610  do_sql_command_end(conn, sql, false);
611 }
static void do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
Definition: connection.c:621
static void do_sql_command_begin(PGconn *conn, const char *sql)
Definition: connection.c:614
PGconn * conn
Definition: streamutil.c:54

References conn, do_sql_command_begin(), and do_sql_command_end().

Referenced by begin_remote_xact(), configure_remote_session(), pgfdw_subxact_callback(), pgfdw_xact_callback(), and postgresExecForeignTruncate().

◆ ExtractConnectionOptions()

int ExtractConnectionOptions ( List defelems,
const char **  keywords,
const char **  values 
)

Definition at line 406 of file option.c.

408 {
409  ListCell *lc;
410  int i;
411 
412  /* Build our options lists if we didn't yet. */
414 
415  i = 0;
416  foreach(lc, defelems)
417  {
418  DefElem *d = (DefElem *) lfirst(lc);
419 
420  if (is_libpq_option(d->defname))
421  {
422  keywords[i] = d->defname;
423  values[i] = defGetString(d);
424  i++;
425  }
426  }
427  return i;
428 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
static bool is_libpq_option(const char *keyword)
Definition: option.c:385
static void InitPgFdwOptions(void)
Definition: option.c:239

References defGetString(), DefElem::defname, i, InitPgFdwOptions(), is_libpq_option(), lfirst, and values.

Referenced by connect_pg_server().

◆ ExtractExtensionList()

List* ExtractExtensionList ( const char *  extensionsString,
bool  warnOnMissing 
)

Definition at line 437 of file option.c.

438 {
439  List *extensionOids = NIL;
440  List *extlist;
441  ListCell *lc;
442 
443  /* SplitIdentifierString scribbles on its input, so pstrdup first */
444  if (!SplitIdentifierString(pstrdup(extensionsString), ',', &extlist))
445  {
446  /* syntax error in name list */
447  ereport(ERROR,
448  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
449  errmsg("parameter \"%s\" must be a list of extension names",
450  "extensions")));
451  }
452 
453  foreach(lc, extlist)
454  {
455  const char *extension_name = (const char *) lfirst(lc);
456  Oid extension_oid = get_extension_oid(extension_name, true);
457 
458  if (OidIsValid(extension_oid))
459  {
460  extensionOids = lappend_oid(extensionOids, extension_oid);
461  }
462  else if (warnOnMissing)
463  {
465  (errcode(ERRCODE_UNDEFINED_OBJECT),
466  errmsg("extension \"%s\" is not installed",
467  extension_name)));
468  }
469  }
470 
471  list_free(extlist);
472  return extensionOids;
473 }
#define OidIsValid(objectId)
Definition: c.h:759
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define WARNING
Definition: elog.h:36
#define ereport(elevel,...)
Definition: elog.h:149
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition: extension.c:144
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
void list_free(List *list)
Definition: list.c:1545
char * pstrdup(const char *in)
Definition: mcxt.c:1624
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3455

References ereport, errcode(), errmsg(), ERROR, get_extension_oid(), lappend_oid(), lfirst, list_free(), NIL, OidIsValid, pstrdup(), SplitIdentifierString(), and WARNING.

Referenced by apply_server_options(), and postgres_fdw_validator().

◆ find_em_for_rel()

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

Definition at line 7676 of file postgres_fdw.c.

7677 {
7678  ListCell *lc;
7679 
7680  foreach(lc, ec->ec_members)
7681  {
7683 
7684  /*
7685  * Note we require !bms_is_empty, else we'd accept constant
7686  * expressions which are not suitable for the purpose.
7687  */
7688  if (bms_is_subset(em->em_relids, rel->relids) &&
7689  !bms_is_empty(em->em_relids) &&
7690  is_foreign_expr(root, rel, em->em_expr))
7691  return em;
7692  }
7693 
7694  return NULL;
7695 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:332
#define bms_is_empty(a)
Definition: bitmapset.h:105
Relids relids
Definition: pathnodes.h:862

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

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

◆ find_em_for_rel_target()

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

Definition at line 7709 of file postgres_fdw.c.

7711 {
7712  PathTarget *target = rel->reltarget;
7713  ListCell *lc1;
7714  int i;
7715 
7716  i = 0;
7717  foreach(lc1, target->exprs)
7718  {
7719  Expr *expr = (Expr *) lfirst(lc1);
7720  Index sgref = get_pathtarget_sortgroupref(target, i);
7721  ListCell *lc2;
7722 
7723  /* Ignore non-sort expressions */
7724  if (sgref == 0 ||
7726  root->parse->sortClause) == NULL)
7727  {
7728  i++;
7729  continue;
7730  }
7731 
7732  /* We ignore binary-compatible relabeling on both ends */
7733  while (expr && IsA(expr, RelabelType))
7734  expr = ((RelabelType *) expr)->arg;
7735 
7736  /* Locate an EquivalenceClass member matching this expr, if any */
7737  foreach(lc2, ec->ec_members)
7738  {
7740  Expr *em_expr;
7741 
7742  /* Don't match constants */
7743  if (em->em_is_const)
7744  continue;
7745 
7746  /* Ignore child members */
7747  if (em->em_is_child)
7748  continue;
7749 
7750  /* Match if same expression (after stripping relabel) */
7751  em_expr = em->em_expr;
7752  while (em_expr && IsA(em_expr, RelabelType))
7753  em_expr = ((RelabelType *) em_expr)->arg;
7754 
7755  if (!equal(em_expr, expr))
7756  continue;
7757 
7758  /* Check that expression (including relabels!) is shippable */
7759  if (is_foreign_expr(root, rel, em->em_expr))
7760  return em;
7761  }
7762 
7763  i++;
7764  }
7765 
7766  return NULL;
7767 }
unsigned int Index
Definition: c.h:598
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1523
void * arg
Query * parse
Definition: pathnodes.h:202
List * sortClause
Definition: parsenodes.h:209
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:443

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

Referenced by add_foreign_ordered_paths(), and appendOrderByClause().

◆ get_jointype_name()

const char* get_jointype_name ( JoinType  jointype)

Definition at line 1603 of file deparse.c.

1604 {
1605  switch (jointype)
1606  {
1607  case JOIN_INNER:
1608  return "INNER";
1609 
1610  case JOIN_LEFT:
1611  return "LEFT";
1612 
1613  case JOIN_RIGHT:
1614  return "RIGHT";
1615 
1616  case JOIN_FULL:
1617  return "FULL";
1618 
1619  default:
1620  /* Shouldn't come here, but protect from buggy code. */
1621  elog(ERROR, "unsupported join type %d", jointype);
1622  }
1623 
1624  /* Keep compiler happy */
1625  return NULL;
1626 }
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_INNER
Definition: nodes.h:304
@ JOIN_RIGHT
Definition: nodes.h:307
@ JOIN_LEFT
Definition: nodes.h:305

References elog(), ERROR, JOIN_FULL, JOIN_INNER, JOIN_LEFT, and JOIN_RIGHT.

Referenced by deparseFromExprForRel(), and foreign_join_ok().

◆ GetConnection()

PGconn* GetConnection ( UserMapping user,
bool  will_prep_stmt,
PgFdwConnState **  state 
)

Definition at line 135 of file connection.c.

136 {
137  bool found;
138  bool retry = false;
139  ConnCacheEntry *entry;
142 
143  /* First time through, initialize connection cache hashtable */
144  if (ConnectionHash == NULL)
145  {
146  HASHCTL ctl;
147 
148  ctl.keysize = sizeof(ConnCacheKey);
149  ctl.entrysize = sizeof(ConnCacheEntry);
150  ConnectionHash = hash_create("postgres_fdw connections", 8,
151  &ctl,
153 
154  /*
155  * Register some callback functions that manage connection cleanup.
156  * This should be done just once in each backend.
157  */
164  }
165 
166  /* Set flag that we did GetConnection during the current transaction */
167  xact_got_connection = true;
168 
169  /* Create hash key for the entry. Assume no pad bytes in key struct */
170  key = user->umid;
171 
172  /*
173  * Find or create cached entry for requested connection.
174  */
175  entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
176  if (!found)
177  {
178  /*
179  * We need only clear "conn" here; remaining fields will be filled
180  * later when "conn" is set.
181  */
182  entry->conn = NULL;
183  }
184 
185  /* Reject further use of connections which failed abort cleanup. */
187 
188  /*
189  * If the connection needs to be remade due to invalidation, disconnect as
190  * soon as we're out of all transactions.
191  */
192  if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
193  {
194  elog(DEBUG3, "closing connection %p for option changes to take effect",
195  entry->conn);
196  disconnect_pg_server(entry);
197  }
198 
199  /*
200  * If cache entry doesn't have a connection, we have to establish a new
201  * connection. (If connect_pg_server throws an error, the cache entry
202  * will remain in a valid empty state, ie conn == NULL.)
203  */
204  if (entry->conn == NULL)
205  make_new_connection(entry, user);
206 
207  /*
208  * We check the health of the cached connection here when using it. In
209  * cases where we're out of all transactions, if a broken connection is
210  * detected, we try to reestablish a new connection later.
211  */
212  PG_TRY();
213  {
214  /* Process a pending asynchronous request if any. */
215  if (entry->state.pendingAreq)
217  /* Start a new transaction or subtransaction if needed. */
218  begin_remote_xact(entry);
219  }
220  PG_CATCH();
221  {
223  ErrorData *errdata = CopyErrorData();
224 
225  /*
226  * Determine whether to try to reestablish the connection.
227  *
228  * After a broken connection is detected in libpq, any error other
229  * than connection failure (e.g., out-of-memory) can be thrown
230  * somewhere between return from libpq and the expected ereport() call
231  * in pgfdw_report_error(). In this case, since PQstatus() indicates
232  * CONNECTION_BAD, checking only PQstatus() causes the false detection
233  * of connection failure. To avoid this, we also verify that the
234  * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
235  * checking only the sqlstate can cause another false detection
236  * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
237  * for any libpq-originated error condition.
238  */
239  if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
240  PQstatus(entry->conn) != CONNECTION_BAD ||
241  entry->xact_depth > 0)
242  {
243  MemoryContextSwitchTo(ecxt);
244  PG_RE_THROW();
245  }
246 
247  /* Clean up the error state */
248  FlushErrorState();
249  FreeErrorData(errdata);
250  errdata = NULL;
251 
252  retry = true;
253  }
254  PG_END_TRY();
255 
256  /*
257  * If a broken connection is detected, disconnect it, reestablish a new
258  * connection and retry a new remote transaction. If connection failure is
259  * reported again, we give up getting a connection.
260  */
261  if (retry)
262  {
263  Assert(entry->xact_depth == 0);
264 
265  ereport(DEBUG3,
266  (errmsg_internal("could not start remote transaction on connection %p",
267  entry->conn)),
268  errdetail_internal("%s", pchomp(PQerrorMessage(entry->conn))));
269 
270  elog(DEBUG3, "closing connection %p to reestablish a new one",
271  entry->conn);
272  disconnect_pg_server(entry);
273 
274  make_new_connection(entry, user);
275 
276  begin_remote_xact(entry);
277  }
278 
279  /* Remember if caller will prepare statements */
280  entry->have_prep_stmt |= will_prep_stmt;
281 
282  /* If caller needs access to the per-connection state, return it. */
283  if (state)
284  *state = &entry->state;
285 
286  return entry->conn;
287 }
Oid ConnCacheKey
Definition: connection.c:50
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:497
static bool xact_got_connection
Definition: connection.c:82
struct ConnCacheEntry ConnCacheEntry
static HTAB * ConnectionHash
Definition: connection.c:75
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
Definition: connection.c:294
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
Definition: connection.c:1020
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1165
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
Definition: connection.c:1115
static void pgfdw_xact_callback(XactEvent event, void *arg)
Definition: connection.c:890
static void begin_remote_xact(ConnCacheEntry *entry)
Definition: connection.c:650
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1776
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
void FlushErrorState(void)
Definition: elog.c:1825
ErrorData * CopyErrorData(void)
Definition: elog.c:1720
#define PG_RE_THROW()
Definition: elog.h:411
#define DEBUG3
Definition: elog.h:28
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7020
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6967
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1519
@ CONNECTION_BAD
Definition: libpq-fe.h:61
char * pchomp(const char *in)
Definition: mcxt.c:1652
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static char * user
Definition: pg_regress.c:93
uintptr_t Datum
Definition: postgres.h:64
void process_pending_request(AsyncRequest *areq)
PGconn * conn
Definition: connection.c:55
bool have_prep_stmt
Definition: connection.c:59
PgFdwConnState state
Definition: connection.c:69
bool invalidated
Definition: connection.c:63
int sqlerrcode
Definition: elog.h:438
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:134
Definition: regguts.h:318
@ FOREIGNSERVEROID
Definition: syscache.h:64
@ USERMAPPINGOID
Definition: syscache.h:115
void RegisterXactCallback(XactCallback callback, void *arg)
Definition: xact.c:3651
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition: xact.c:3711

References Assert(), begin_remote_xact(), CacheRegisterSyscacheCallback(), ConnCacheEntry::conn, CONNECTION_BAD, ConnectionHash, CopyErrorData(), CurrentMemoryContext, DEBUG3, disconnect_pg_server(), elog(), HASHCTL::entrysize, ereport, errdetail_internal(), errmsg_internal(), FlushErrorState(), FOREIGNSERVEROID, FreeErrorData(), HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), ConnCacheEntry::have_prep_stmt, ConnCacheEntry::invalidated, sort-test::key, HASHCTL::keysize, make_new_connection(), MemoryContextSwitchTo(), pchomp(), PgFdwConnState::pendingAreq, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgfdw_inval_callback(), pgfdw_reject_incomplete_xact_state_change(), pgfdw_subxact_callback(), pgfdw_xact_callback(), PQerrorMessage(), PQstatus(), process_pending_request(), RegisterSubXactCallback(), RegisterXactCallback(), ErrorData::sqlerrcode, ConnCacheEntry::state, user, USERMAPPINGOID, ConnCacheEntry::xact_depth, and xact_got_connection.

Referenced by create_foreign_modify(), dumpDatabase(), dumpDatabaseConfig(), dumpLOs(), dumpTableData_copy(), estimate_path_cost_size(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), getTables(), main(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), setup_connection(), StartLogStreamer(), StreamLog(), and StreamLogicalLog().

◆ GetCursorNumber()

unsigned int GetCursorNumber ( PGconn conn)

Definition at line 714 of file connection.c.

715 {
716  return ++cursor_number;
717 }
static unsigned int cursor_number
Definition: connection.c:78

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

◆ GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconn conn)

Definition at line 728 of file connection.c.

729 {
730  return ++prep_stmt_number;
731 }
static unsigned int prep_stmt_number
Definition: connection.c:79

References prep_stmt_number.

Referenced by prepare_foreign_modify().

◆ is_builtin()

bool is_builtin ( Oid  objectId)

Definition at line 152 of file shippable.c.

153 {
154  return (objectId < FirstGenbkiObjectId);
155 }
#define FirstGenbkiObjectId
Definition: transam.h:195

References FirstGenbkiObjectId.

Referenced by deparse_type_name(), and is_shippable().

◆ is_foreign_expr()

bool is_foreign_expr ( PlannerInfo root,
RelOptInfo baserel,
Expr expr 
)

Definition at line 240 of file deparse.c.

243 {
244  foreign_glob_cxt glob_cxt;
245  foreign_loc_cxt loc_cxt;
246  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
247 
248  /*
249  * Check that the expression consists of nodes that are safe to execute
250  * remotely.
251  */
252  glob_cxt.root = root;
253  glob_cxt.foreignrel = baserel;
254 
255  /*
256  * For an upper relation, use relids from its underneath scan relation,
257  * because the upperrel's own relids currently aren't set to anything
258  * meaningful by the core code. For other relation, use their own relids.
259  */
260  if (IS_UPPER_REL(baserel))
261  glob_cxt.relids = fpinfo->outerrel->relids;
262  else
263  glob_cxt.relids = baserel->relids;
264  loc_cxt.collation = InvalidOid;
265  loc_cxt.state = FDW_COLLATE_NONE;
266  if (!foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt, NULL))
267  return false;
268 
269  /*
270  * If the expression has a valid collation that does not arise from a
271  * foreign var, the expression can not be sent over.
272  */
273  if (loc_cxt.state == FDW_COLLATE_UNSAFE)
274  return false;
275 
276  /*
277  * An expression which includes any mutable functions can't be sent over
278  * because its result is not stable. For example, sending now() remote
279  * side could cause confusion from clock offsets. Future versions might
280  * be able to make this choice with more granularity. (We check this last
281  * because it requires a lot of expensive catalog lookups.)
282  */
283  if (contain_mutable_functions((Node *) expr))
284  return false;
285 
286  /* OK to evaluate on the remote server */
287  return true;
288 }
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:367
@ FDW_COLLATE_UNSAFE
Definition: deparse.c:86
@ FDW_COLLATE_NONE
Definition: deparse.c:82
static bool foreign_expr_walker(Node *node, foreign_glob_cxt *glob_cxt, foreign_loc_cxt *outer_cxt, foreign_loc_cxt *case_arg_cxt)
Definition: deparse.c:308
#define InvalidOid
Definition: postgres_ext.h:36
RelOptInfo * foreignrel
Definition: deparse.c:71
Relids relids
Definition: deparse.c:72
PlannerInfo * root
Definition: deparse.c:70
FDWCollateState state
Definition: deparse.c:93

References foreign_loc_cxt::collation, contain_mutable_functions(), FDW_COLLATE_NONE, FDW_COLLATE_UNSAFE, foreign_expr_walker(), foreign_glob_cxt::foreignrel, if(), InvalidOid, IS_UPPER_REL, PgFdwRelationInfo::outerrel, foreign_glob_cxt::relids, RelOptInfo::relids, foreign_glob_cxt::root, and foreign_loc_cxt::state.

Referenced by add_foreign_final_paths(), classifyConditions(), find_em_for_rel(), find_em_for_rel_target(), foreign_grouping_ok(), foreign_join_ok(), postgresGetForeignPaths(), postgresGetForeignPlan(), and postgresPlanDirectModify().

◆ is_foreign_param()

bool is_foreign_param ( PlannerInfo root,
RelOptInfo baserel,
Expr expr 
)

Definition at line 1078 of file deparse.c.

1081 {
1082  if (expr == NULL)
1083  return false;
1084 
1085  switch (nodeTag(expr))
1086  {
1087  case T_Var:
1088  {
1089  /* It would have to be sent unless it's a foreign Var */
1090  Var *var = (Var *) expr;
1091  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
1092  Relids relids;
1093 
1094  if (IS_UPPER_REL(baserel))
1095  relids = fpinfo->outerrel->relids;
1096  else
1097  relids = baserel->relids;
1098 
1099  if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
1100  return false; /* foreign Var, so not a param */
1101  else
1102  return true; /* it'd have to be a param */
1103  break;
1104  }
1105  case T_Param:
1106  /* Params always have to be sent to the foreign server */
1107  return true;
1108  default:
1109  break;
1110  }
1111  return false;
1112 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:444
#define nodeTag(nodeptr)
Definition: nodes.h:133
Definition: primnodes.h:226
int varno
Definition: primnodes.h:233
Index varlevelsup
Definition: primnodes.h:258

References bms_is_member(), if(), IS_UPPER_REL, nodeTag, PgFdwRelationInfo::outerrel, RelOptInfo::relids, Var::varlevelsup, and Var::varno.

Referenced by foreign_grouping_ok().

◆ is_foreign_pathkey()

bool is_foreign_pathkey ( PlannerInfo root,
RelOptInfo baserel,
PathKey pathkey 
)

Definition at line 1119 of file deparse.c.

1122 {
1123  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
1124  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
1125 
1126  /*
1127  * is_foreign_expr would detect volatile expressions as well, but checking
1128  * ec_has_volatile here saves some cycles.
1129  */
1130  if (pathkey_ec->ec_has_volatile)
1131  return false;
1132 
1133  /* can't push down the sort if the pathkey's opfamily is not shippable */
1134  if (!is_shippable(pathkey->pk_opfamily, OperatorFamilyRelationId, fpinfo))
1135  return false;
1136 
1137  /* can push if a suitable EC member exists */
1138  return (find_em_for_rel(root, pathkey_ec, baserel) != NULL);
1139 }
EquivalenceMember * find_em_for_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel)
bool is_shippable(Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo)
Definition: shippable.c:162
Oid pk_opfamily
Definition: pathnodes.h:1460

References EquivalenceClass::ec_has_volatile, find_em_for_rel(), if(), is_shippable(), and PathKey::pk_opfamily.

Referenced by get_useful_pathkeys_for_relation().

◆ is_shippable()

bool is_shippable ( Oid  objectId,
Oid  classId,
PgFdwRelationInfo fpinfo 
)

Definition at line 162 of file shippable.c.

163 {
165  ShippableCacheEntry *entry;
166 
167  /* Built-in objects are presumed shippable. */
168  if (is_builtin(objectId))
169  return true;
170 
171  /* Otherwise, give up if user hasn't specified any shippable extensions. */
172  if (fpinfo->shippable_extensions == NIL)
173  return false;
174 
175  /* Initialize cache if first time through. */
176  if (!ShippableCacheHash)
178 
179  /* Set up cache hash key */
180  key.objid = objectId;
181  key.classid = classId;
182  key.serverid = fpinfo->server->serverid;
183 
184  /* See if we already cached the result. */
185  entry = (ShippableCacheEntry *)
187 
188  if (!entry)
189  {
190  /* Not found in cache, so perform shippability lookup. */
191  bool shippable = lookup_shippable(objectId, classId, fpinfo);
192 
193  /*
194  * Don't create a new hash entry until *after* we have the shippable
195  * result in hand, as the underlying catalog lookups might trigger a
196  * cache invalidation.
197  */
198  entry = (ShippableCacheEntry *)
200 
201  entry->shippable = shippable;
202  }
203 
204  return entry->shippable;
205 }
@ HASH_FIND
Definition: hsearch.h:113
static bool lookup_shippable(Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo)
Definition: shippable.c:116
bool is_builtin(Oid objectId)
Definition: shippable.c:152
static void InitializeShippableCache(void)
Definition: shippable.c:91
static HTAB * ShippableCacheHash
Definition: shippable.c:34
Oid serverid
Definition: foreign.h:36
List * shippable_extensions
Definition: postgres_fdw.h:81
ForeignServer * server
Definition: postgres_fdw.h:86

References HASH_ENTER, HASH_FIND, hash_search(), InitializeShippableCache(), is_builtin(), sort-test::key, lookup_shippable(), NIL, PgFdwRelationInfo::server, ForeignServer::serverid, ShippableCacheEntry::shippable, PgFdwRelationInfo::shippable_extensions, and ShippableCacheHash.

Referenced by add_foreign_ordered_paths(), foreign_expr_walker(), get_useful_pathkeys_for_relation(), and is_foreign_pathkey().

◆ pgfdw_exec_query()

PGresult* pgfdw_exec_query ( PGconn conn,
const char *  query,
PgFdwConnState state 
)

Definition at line 741 of file connection.c.

742 {
743  /* First, process a pending asynchronous request, if any. */
744  if (state && state->pendingAreq)
745  process_pending_request(state->pendingAreq);
746 
747  /*
748  * Submit a query. Since we don't use non-blocking mode, this also can
749  * block. But its risk is relatively small, so we ignore that for now.
750  */
751  if (!PQsendQuery(conn, query))
752  pgfdw_report_error(ERROR, NULL, conn, false, query);
753 
754  /* Wait for the result. */
755  return pgfdw_get_result(conn, query);
756 }
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:769
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:834
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1422

References conn, ERROR, pgfdw_get_result(), pgfdw_report_error(), PQsendQuery(), and process_pending_request().

Referenced by close_cursor(), deallocate_query(), fetch_more_data(), get_remote_estimate(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), and postgresReScanForeignScan().

◆ pgfdw_get_result()

PGresult* pgfdw_get_result ( PGconn conn,
const char *  query 
)

Definition at line 769 of file connection.c.

770 {
771  PGresult *volatile last_res = NULL;
772 
773  /* In what follows, do not leak any PGresults on an error. */
774  PG_TRY();
775  {
776  for (;;)
777  {
778  PGresult *res;
779 
780  while (PQisBusy(conn))
781  {
782  int wc;
783 
784  /* Sleep until there's something to do */
788  PQsocket(conn),
789  -1L, PG_WAIT_EXTENSION);
791 
793 
794  /* Data available in socket? */
795  if (wc & WL_SOCKET_READABLE)
796  {
797  if (!PQconsumeInput(conn))
798  pgfdw_report_error(ERROR, NULL, conn, false, query);
799  }
800  }
801 
802  res = PQgetResult(conn);
803  if (res == NULL)
804  break; /* query is complete */
805 
806  PQclear(last_res);
807  last_res = res;
808  }
809  }
810  PG_CATCH();
811  {
812  PQclear(last_res);
813  PG_RE_THROW();
814  }
815  PG_END_TRY();
816 
817  return last_res;
818 }
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7046
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1957
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2004
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
struct Latch * MyLatch
Definition: globals.c:58
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:540
void ResetLatch(Latch *latch)
Definition: latch.c:699
#define WL_SOCKET_READABLE
Definition: latch.h:126
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define PG_WAIT_EXTENSION
Definition: wait_event.h:23

References CHECK_FOR_INTERRUPTS, conn, ERROR, MyLatch, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PG_WAIT_EXTENSION, pgfdw_report_error(), PQclear(), PQconsumeInput(), PQgetResult(), PQisBusy(), PQsocket(), res, ResetLatch(), WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_SOCKET_READABLE.

Referenced by create_cursor(), do_sql_command_end(), execute_dml_stmt(), execute_foreign_modify(), fetch_more_data(), pgfdw_exec_query(), and prepare_foreign_modify().

◆ pgfdw_report_error()

void pgfdw_report_error ( int  elevel,
PGresult res,
PGconn conn,
bool  clear,
const char *  sql 
)

Definition at line 834 of file connection.c.

836 {
837  /* If requested, PGresult must be released before leaving this function. */
838  PG_TRY();
839  {
840  char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
841  char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
842  char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
843  char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
844  char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
845  int sqlstate;
846 
847  if (diag_sqlstate)
848  sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
849  diag_sqlstate[1],
850  diag_sqlstate[2],
851  diag_sqlstate[3],
852  diag_sqlstate[4]);
853  else
854  sqlstate = ERRCODE_CONNECTION_FAILURE;
855 
856  /*
857  * If we don't get a message from the PGresult, try the PGconn. This
858  * is needed because for connection-level failures, PQexec may just
859  * return NULL, not a PGresult at all.
860  */
861  if (message_primary == NULL)
862  message_primary = pchomp(PQerrorMessage(conn));
863 
864  ereport(elevel,
865  (errcode(sqlstate),
866  (message_primary != NULL && message_primary[0] != '\0') ?
867  errmsg_internal("%s", message_primary) :
868  errmsg("could not obtain message string for remote error"),
869  message_detail ? errdetail_internal("%s", message_detail) : 0,
870  message_hint ? errhint("%s", message_hint) : 0,
871  message_context ? errcontext("%s", message_context) : 0,
872  sql ? errcontext("remote SQL command: %s", sql) : 0));
873  }
874  PG_FINALLY();
875  {
876  if (clear)
877  PQclear(res);
878  }
879  PG_END_TRY();
880 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
#define errcontext
Definition: elog.h:196
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
#define PG_FINALLY(...)
Definition: elog.h:387
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3299
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:59
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:58
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:63

References conn, ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), MAKE_SQLSTATE, pchomp(), PG_DIAG_CONTEXT, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SQLSTATE, PG_END_TRY, PG_FINALLY, PG_TRY, PQclear(), PQerrorMessage(), PQresultErrorField(), and res.

Referenced by close_cursor(), create_cursor(), deallocate_query(), do_sql_command_begin(), do_sql_command_end(), execute_dml_stmt(), execute_foreign_modify(), fetch_more_data(), fetch_more_data_begin(), get_remote_estimate(), pgfdw_exec_cleanup_query(), pgfdw_exec_query(), pgfdw_get_result(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresForeignAsyncNotify(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), and prepare_foreign_modify().

◆ process_pending_request()

void process_pending_request ( AsyncRequest areq)

Definition at line 7349 of file postgres_fdw.c.

7350 {
7351  ForeignScanState *node = (ForeignScanState *) areq->requestee;
7352  PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
7353 
7354  /* The request would have been pending for a callback */
7355  Assert(areq->callback_pending);
7356 
7357  /* The request should be currently in-process */
7358  Assert(fsstate->conn_state->pendingAreq == areq);
7359 
7360  fetch_more_data(node);
7361 
7362  /*
7363  * If we didn't get any tuples, must be end of data; complete the request
7364  * now. Otherwise, we postpone completing the request until we are called
7365  * from postgresForeignAsyncConfigureWait()/postgresForeignAsyncNotify().
7366  */
7367  if (fsstate->next_tuple >= fsstate->num_tuples)
7368  {
7369  /* Unlike AsyncNotify, we unset callback_pending ourselves */
7370  areq->callback_pending = false;
7371  /* Mark the request as complete */
7372  ExecAsyncRequestDone(areq, NULL);
7373  /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
7374  ExecAsyncResponse(areq);
7375  }
7376 }
void ExecAsyncResponse(AsyncRequest *areq)
Definition: execAsync.c:117
void ExecAsyncRequestDone(AsyncRequest *areq, TupleTableSlot *result)
Definition: execAsync.c:137
static void fetch_more_data(ForeignScanState *node)
bool callback_pending
Definition: execnodes.h:598
struct PlanState * requestee
Definition: execnodes.h:596

References Assert(), AsyncRequest::callback_pending, ExecAsyncRequestDone(), ExecAsyncResponse(), ForeignScanState::fdw_state, fetch_more_data(), and AsyncRequest::requestee.

Referenced by create_cursor(), execute_dml_stmt(), execute_foreign_modify(), GetConnection(), pgfdw_exec_query(), and postgresForeignAsyncConfigureWait().

◆ process_pgfdw_appname()

char* process_pgfdw_appname ( const char *  appname)

Definition at line 483 of file option.c.

484 {
485  const char *p;
487 
489 
490  for (p = appname; *p != '\0'; p++)
491  {
492  if (*p != '%')
493  {
494  /* literal char, just copy */
496  continue;
497  }
498 
499  /* must be a '%', so skip to the next char */
500  p++;
501  if (*p == '\0')
502  break; /* format error - ignore it */
503  else if (*p == '%')
504  {
505  /* string contains %% */
506  appendStringInfoChar(&buf, '%');
507  continue;
508  }
509 
510  /* process the option */
511  switch (*p)
512  {
513  case 'a':
515  break;
516  case 'c':
517  appendStringInfo(&buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
518  break;
519  case 'C':
521  break;
522  case 'd':
523  if (MyProcPort)
524  {
525  const char *dbname = MyProcPort->database_name;
526 
527  if (dbname)
529  else
530  appendStringInfoString(&buf, "[unknown]");
531  }
532  break;
533  case 'p':
534  appendStringInfo(&buf, "%d", MyProcPid);
535  break;
536  case 'u':
537  if (MyProcPort)
538  {
539  const char *username = MyProcPort->user_name;
540 
541  if (username)
543  else
544  appendStringInfoString(&buf, "[unknown]");
545  }
546  break;
547  default:
548  /* format error - ignore it */
549  break;
550  }
551  }
552 
553  return buf.data;
554 }
int MyProcPid
Definition: globals.c:44
struct Port * MyProcPort
Definition: globals.c:47
pg_time_t MyStartTime
Definition: globals.c:45
char * cluster_name
Definition: guc_tables.c:527
char * application_name
Definition: guc_tables.c:535
const char * username
Definition: pgbench.c:306
char * dbname
Definition: streamutil.c:51
char * user_name
Definition: libpq-be.h:166
char * database_name
Definition: libpq-be.h:165

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), application_name, buf, cluster_name, Port::database_name, dbname, initStringInfo(), MyProcPid, MyProcPort, MyStartTime, Port::user_name, and username.

Referenced by connect_pg_server().

◆ rebuildInsertSql()

void rebuildInsertSql ( StringInfo  buf,
Relation  rel,
char *  orig_query,
List target_attrs,
int  values_end_len,
int  num_params,
int  num_rows 
)

Definition at line 2015 of file deparse.c.

2019 {
2020  TupleDesc tupdesc = RelationGetDescr(rel);
2021  int i;
2022  int pindex;
2023  bool first;
2024  ListCell *lc;
2025 
2026  /* Make sure the values_end_len is sensible */
2027  Assert((values_end_len > 0) && (values_end_len <= strlen(orig_query)));
2028 
2029  /* Copy up to the end of the first record from the original query */
2030  appendBinaryStringInfo(buf, orig_query, values_end_len);
2031 
2032  /*
2033  * Add records to VALUES clause (we already have parameters for the first
2034  * row, so start at the right offset).
2035  */
2036  pindex = num_params + 1;
2037  for (i = 0; i < num_rows; i++)
2038  {
2039  appendStringInfoString(buf, ", (");
2040 
2041  first = true;
2042  foreach(lc, target_attrs)
2043  {
2044  int attnum = lfirst_int(lc);
2045  Form_pg_attribute attr = TupleDescAttr(tupdesc, attnum - 1);
2046 
2047  if (!first)
2048  appendStringInfoString(buf, ", ");
2049  first = false;
2050 
2051  if (attr->attgenerated)
2052  appendStringInfoString(buf, "DEFAULT");
2053  else
2054  {
2055  appendStringInfo(buf, "$%d", pindex);
2056  pindex++;
2057  }
2058  }
2059 
2060  appendStringInfoChar(buf, ')');
2061  }
2062 
2063  /* Copy stuff after VALUES clause from the original query */
2064  appendStringInfoString(buf, orig_query + values_end_len);
2065 }
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:227

References appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), attnum, buf, i, lfirst_int, RelationGetDescr, and TupleDescAttr.

Referenced by execute_foreign_modify().

◆ ReleaseConnection()

void ReleaseConnection ( PGconn conn)

Definition at line 693 of file connection.c.

694 {
695  /*
696  * Currently, we don't actually track connection references because all
697  * cleanup is managed on a transaction or subtransaction basis instead. So
698  * there's nothing to do here.
699  */
700 }

Referenced by estimate_path_cost_size(), finish_foreign_modify(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresEndForeignScan(), postgresGetAnalyzeInfoForForeignTable(), and postgresImportForeignSchema().

◆ reset_transmission_modes()

void reset_transmission_modes ( int  nestlevel)

Definition at line 3921 of file postgres_fdw.c.

3922 {
3923  AtEOXact_GUC(true, nestlevel);
3924 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2215

References AtEOXact_GUC().

Referenced by appendConditions(), appendLimitClause(), appendOrderByClause(), convert_prep_stmt_params(), deparseDirectUpdateSql(), and process_query_params().

◆ set_transmission_modes()

int set_transmission_modes ( void  )

Definition at line 3885 of file postgres_fdw.c.

3886 {
3887  int nestlevel = NewGUCNestLevel();
3888 
3889  /*
3890  * The values set here should match what pg_dump does. See also
3891  * configure_remote_session in connection.c.
3892  */
3893  if (DateStyle != USE_ISO_DATES)
3894  (void) set_config_option("datestyle", "ISO",
3896  GUC_ACTION_SAVE, true, 0, false);
3898  (void) set_config_option("intervalstyle", "postgres",
3900  GUC_ACTION_SAVE, true, 0, false);
3901  if (extra_float_digits < 3)
3902  (void) set_config_option("extra_float_digits", "3",
3904  GUC_ACTION_SAVE, true, 0, false);
3905 
3906  /*
3907  * In addition force restrictive search_path, in case there are any
3908  * regproc or similar constants to be printed.
3909  */
3910  (void) set_config_option("search_path", "pg_catalog",
3912  GUC_ACTION_SAVE, true, 0, false);
3913 
3914  return nestlevel;
3915 }
int extra_float_digits
Definition: float.c:43
int DateStyle
Definition: globals.c:119
int IntervalStyle
Definition: globals.c:121
int NewGUCNestLevel(void)
Definition: guc.c:2201
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:3284
@ GUC_ACTION_SAVE
Definition: guc.h:199
@ PGC_S_SESSION
Definition: guc.h:122
@ PGC_USERSET
Definition: guc.h:75
#define USE_ISO_DATES
Definition: miscadmin.h:230
#define INTSTYLE_POSTGRES
Definition: miscadmin.h:250

References DateStyle, extra_float_digits, GUC_ACTION_SAVE, IntervalStyle, INTSTYLE_POSTGRES, NewGUCNestLevel(), PGC_S_SESSION, PGC_USERSET, set_config_option(), and USE_ISO_DATES.

Referenced by appendConditions(), appendLimitClause(), appendOrderByClause(), convert_prep_stmt_params(), deparseDirectUpdateSql(), and process_query_params().

Variable Documentation

◆ pgfdw_application_name

char* pgfdw_application_name
extern

Definition at line 52 of file option.c.

Referenced by _PG_init(), and connect_pg_server().