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
 

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)
 
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)
 
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, char *orig_query, int values_end_len, int num_cols, 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 deparseAnalyzeSql (StringInfo buf, Relation rel, List **retrieved_attrs)
 
void deparseTruncateSql (StringInfo buf, List *rels, DropBehavior behavior, bool restart_seqs)
 
void deparseStringLiteral (StringInfo buf, const char *val)
 
Exprfind_em_expr_for_rel (EquivalenceClass *ec, RelOptInfo *rel)
 
Exprfind_em_expr_for_input_target (PlannerInfo *root, EquivalenceClass *ec, PathTarget *target)
 
Listbuild_tlist_to_deparse (RelOptInfo *foreignrel)
 
void deparseSelectStmtForRel (StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, 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)
 

Typedef Documentation

◆ PgFdwConnState

◆ PgFdwRelationInfo

Function Documentation

◆ build_tlist_to_deparse()

List* build_tlist_to_deparse ( RelOptInfo foreignrel)

Definition at line 944 of file deparse.c.

References add_to_flat_tlist(), RestrictInfo::clause, PathTarget::exprs, RelOptInfo::fdw_private, PgFdwRelationInfo::grouped_tlist, 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().

945 {
946  List *tlist = NIL;
947  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
948  ListCell *lc;
949 
950  /*
951  * For an upper relation, we have already built the target list while
952  * checking shippability, so just return that.
953  */
954  if (IS_UPPER_REL(foreignrel))
955  return fpinfo->grouped_tlist;
956 
957  /*
958  * We require columns specified in foreignrel->reltarget->exprs and those
959  * required for evaluating the local conditions.
960  */
961  tlist = add_to_flat_tlist(tlist,
962  pull_var_clause((Node *) foreignrel->reltarget->exprs,
964  foreach(lc, fpinfo->local_conds)
965  {
966  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
967 
968  tlist = add_to_flat_tlist(tlist,
969  pull_var_clause((Node *) rinfo->clause,
971  }
972 
973  return tlist;
974 }
#define NIL
Definition: pg_list.h:65
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:192
Definition: nodes.h:539
List * pull_var_clause(Node *node, int flags)
Definition: var.c:562
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Expr * clause
Definition: pathnodes.h:2045
List * exprs
Definition: pathnodes.h:1102
void * fdw_private
Definition: pathnodes.h:732
List * add_to_flat_tlist(List *tlist, List *exprs)
Definition: tlist.c:121
#define IS_UPPER_REL(rel)
Definition: pathnodes.h:659
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:687

◆ classifyConditions()

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

Definition at line 205 of file deparse.c.

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

Referenced by estimate_path_cost_size(), and postgresGetForeignRelSize().

210 {
211  ListCell *lc;
212 
213  *remote_conds = NIL;
214  *local_conds = NIL;
215 
216  foreach(lc, input_conds)
217  {
219 
220  if (is_foreign_expr(root, baserel, ri->clause))
221  *remote_conds = lappend(*remote_conds, ri);
222  else
223  *local_conds = lappend(*local_conds, ri);
224  }
225 }
#define NIL
Definition: pg_list.h:65
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
bool is_foreign_expr(PlannerInfo *root, RelOptInfo *baserel, Expr *expr)
Definition: deparse.c:231

◆ deparseAnalyzeSizeSql()

void deparseAnalyzeSizeSql ( StringInfo  buf,
Relation  rel 
)

Definition at line 2103 of file deparse.c.

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

Referenced by postgresAnalyzeForeignTable().

2104 {
2106 
2107  /* We'll need the remote relation name as a literal. */
2108  initStringInfo(&relname);
2109  deparseRelation(&relname, rel);
2110 
2111  appendStringInfoString(buf, "SELECT pg_catalog.pg_relation_size(");
2112  deparseStringLiteral(buf, relname.data);
2113  appendStringInfo(buf, "::pg_catalog.regclass) / %d", BLCKSZ);
2114 }
NameData relname
Definition: pg_class.h:38
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void deparseStringLiteral(StringInfo buf, const char *val)
Definition: deparse.c:2384
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344

◆ deparseAnalyzeSql()

void deparseAnalyzeSql ( StringInfo  buf,
Relation  rel,
List **  retrieved_attrs 
)

Definition at line 2123 of file deparse.c.

References appendStringInfoString(), attname, defGetString(), DefElem::defname, deparseRelation(), GetForeignColumnOptions(), i, lappend_int(), lfirst, NameStr, TupleDescData::natts, NIL, options, quote_identifier(), RelationGetDescr, RelationGetRelid, and TupleDescAttr.

Referenced by postgresAcquireSampleRowsFunc().

2124 {
2125  Oid relid = RelationGetRelid(rel);
2126  TupleDesc tupdesc = RelationGetDescr(rel);
2127  int i;
2128  char *colname;
2129  List *options;
2130  ListCell *lc;
2131  bool first = true;
2132 
2133  *retrieved_attrs = NIL;
2134 
2135  appendStringInfoString(buf, "SELECT ");
2136  for (i = 0; i < tupdesc->natts; i++)
2137  {
2138  /* Ignore dropped columns. */
2139  if (TupleDescAttr(tupdesc, i)->attisdropped)
2140  continue;
2141 
2142  if (!first)
2143  appendStringInfoString(buf, ", ");
2144  first = false;
2145 
2146  /* Use attribute name or column_name option. */
2147  colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
2148  options = GetForeignColumnOptions(relid, i + 1);
2149 
2150  foreach(lc, options)
2151  {
2152  DefElem *def = (DefElem *) lfirst(lc);
2153 
2154  if (strcmp(def->defname, "column_name") == 0)
2155  {
2156  colname = defGetString(def);
2157  break;
2158  }
2159  }
2160 
2162 
2163  *retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
2164  }
2165 
2166  /* Don't generate bad syntax for zero-column relation. */
2167  if (first)
2168  appendStringInfoString(buf, "NULL");
2169 
2170  /*
2171  * Construct FROM clause
2172  */
2173  appendStringInfoString(buf, " FROM ");
2174  deparseRelation(buf, rel);
2175 }
#define NIL
Definition: pg_list.h:65
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
#define RelationGetDescr(relation)
Definition: rel.h:503
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
unsigned int Oid
Definition: postgres_ext.h:31
List * GetForeignColumnOptions(Oid relid, AttrNumber attnum)
Definition: foreign.c:286
NameData attname
Definition: pg_attribute.h:41
char * defGetString(DefElem *def)
Definition: define.c:49
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
List * lappend_int(List *list, int datum)
Definition: list.c:354
static char ** options
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344
#define lfirst(lc)
Definition: pg_list.h:169
int i
#define NameStr(name)
Definition: c.h:681
char * defname
Definition: parsenodes.h:746
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:477

◆ deparseDeleteSql()

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

Definition at line 1966 of file deparse.c.

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

Referenced by postgresPlanForeignModify().

1970 {
1971  appendStringInfoString(buf, "DELETE FROM ");
1972  deparseRelation(buf, rel);
1973  appendStringInfoString(buf, " WHERE ctid = $1");
1974 
1975  deparseReturningList(buf, rte, rtindex, rel,
1976  rel->trigdesc && rel->trigdesc->trig_delete_after_row,
1977  NIL, returningList, retrieved_attrs);
1978 }
#define NIL
Definition: pg_list.h:65
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:2046
TriggerDesc * trigdesc
Definition: rel.h:115
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
bool trig_delete_after_row
Definition: reltrigger.h:67
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344

◆ 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 1995 of file deparse.c.

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

Referenced by postgresPlanDirectModify().

2002 {
2003  deparse_expr_cxt context;
2004 
2005  /* Set up context struct for recursion */
2006  context.root = root;
2007  context.foreignrel = foreignrel;
2008  context.scanrel = foreignrel;
2009  context.buf = buf;
2010  context.params_list = params_list;
2011 
2012  appendStringInfoString(buf, "DELETE FROM ");
2013  deparseRelation(buf, rel);
2014  if (foreignrel->reloptkind == RELOPT_JOINREL)
2015  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
2016 
2017  if (foreignrel->reloptkind == RELOPT_JOINREL)
2018  {
2019  List *ignore_conds = NIL;
2020 
2021  appendStringInfoString(buf, " USING ");
2022  deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
2023  &ignore_conds, params_list);
2024  remote_conds = list_concat(remote_conds, ignore_conds);
2025  }
2026 
2027  if (remote_conds)
2028  {
2029  appendStringInfoString(buf, " WHERE ");
2030  appendConditions(remote_conds, &context);
2031  }
2032 
2033  if (foreignrel->reloptkind == RELOPT_JOINREL)
2034  deparseExplicitTargetList(returningList, true, retrieved_attrs,
2035  &context);
2036  else
2037  deparseReturningList(buf, planner_rt_fetch(rtindex, root),
2038  rtindex, rel, false,
2039  NIL, returningList, retrieved_attrs);
2040 }
#define NIL
Definition: pg_list.h:65
RelOptKind reloptkind
Definition: pathnodes.h:673
List ** params_list
Definition: deparse.c:103
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
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:2046
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
#define REL_ALIAS_PREFIX
Definition: deparse.c:106
static void deparseExplicitTargetList(List *tlist, bool is_returning, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1412
static void appendConditions(List *exprs, deparse_expr_cxt *context)
Definition: deparse.c:1341
StringInfo buf
Definition: deparse.c:102
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344
PlannerInfo * root
Definition: deparse.c:97
static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool use_alias, Index ignore_rel, List **ignore_conds, List **params_list)
Definition: deparse.c:1489
RelOptInfo * scanrel
Definition: deparse.c:99
Definition: pg_list.h:50
RelOptInfo * foreignrel
Definition: deparse.c:98

◆ 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 1881 of file deparse.c.

References appendConditions(), appendStringInfo(), appendStringInfoString(), Assert, attnum, buf, deparse_expr_cxt::buf, deparseColumnRef(), deparseExplicitTargetList(), deparseExpr(), deparseFromExprForRel(), deparseRelation(), deparseReturningList(), TargetEntry::expr, forboth, foreign_glob_cxt::foreignrel, 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(), TargetEntry::resjunk, foreign_glob_cxt::root, deparse_expr_cxt::root, deparse_expr_cxt::scanrel, and set_transmission_modes().

Referenced by postgresPlanDirectModify().

1890 {
1891  deparse_expr_cxt context;
1892  int nestlevel;
1893  bool first;
1894  RangeTblEntry *rte = planner_rt_fetch(rtindex, root);
1895  ListCell *lc,
1896  *lc2;
1897 
1898  /* Set up context struct for recursion */
1899  context.root = root;
1900  context.foreignrel = foreignrel;
1901  context.scanrel = foreignrel;
1902  context.buf = buf;
1903  context.params_list = params_list;
1904 
1905  appendStringInfoString(buf, "UPDATE ");
1906  deparseRelation(buf, rel);
1907  if (foreignrel->reloptkind == RELOPT_JOINREL)
1908  appendStringInfo(buf, " %s%d", REL_ALIAS_PREFIX, rtindex);
1909  appendStringInfoString(buf, " SET ");
1910 
1911  /* Make sure any constants in the exprs are printed portably */
1912  nestlevel = set_transmission_modes();
1913 
1914  first = true;
1915  forboth(lc, targetlist, lc2, targetAttrs)
1916  {
1917  TargetEntry *tle = lfirst_node(TargetEntry, lc);
1918  int attnum = lfirst_int(lc2);
1919 
1920  /* update's new-value expressions shouldn't be resjunk */
1921  Assert(!tle->resjunk);
1922 
1923  if (!first)
1924  appendStringInfoString(buf, ", ");
1925  first = false;
1926 
1927  deparseColumnRef(buf, rtindex, attnum, rte, false);
1928  appendStringInfoString(buf, " = ");
1929  deparseExpr((Expr *) tle->expr, &context);
1930  }
1931 
1932  reset_transmission_modes(nestlevel);
1933 
1934  if (foreignrel->reloptkind == RELOPT_JOINREL)
1935  {
1936  List *ignore_conds = NIL;
1937 
1938  appendStringInfoString(buf, " FROM ");
1939  deparseFromExprForRel(buf, root, foreignrel, true, rtindex,
1940  &ignore_conds, params_list);
1941  remote_conds = list_concat(remote_conds, ignore_conds);
1942  }
1943 
1944  if (remote_conds)
1945  {
1946  appendStringInfoString(buf, " WHERE ");
1947  appendConditions(remote_conds, &context);
1948  }
1949 
1950  if (foreignrel->reloptkind == RELOPT_JOINREL)
1951  deparseExplicitTargetList(returningList, true, retrieved_attrs,
1952  &context);
1953  else
1954  deparseReturningList(buf, rte, rtindex, rel, false,
1955  NIL, returningList, retrieved_attrs);
1956 }
#define NIL
Definition: pg_list.h:65
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
RelOptKind reloptkind
Definition: pathnodes.h:673
List ** params_list
Definition: deparse.c:103
int set_transmission_modes(void)
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
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:2046
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool resjunk
Definition: primnodes.h:1451
#define lfirst_int(lc)
Definition: pg_list.h:170
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
#define REL_ALIAS_PREFIX
Definition: deparse.c:106
static void deparseExplicitTargetList(List *tlist, bool is_returning, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1412
static void appendConditions(List *exprs, deparse_expr_cxt *context)
Definition: deparse.c:1341
StringInfo buf
Definition: deparse.c:102
int16 attnum
Definition: pg_attribute.h:83
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344
PlannerInfo * root
Definition: deparse.c:97
#define Assert(condition)
Definition: c.h:804
Expr * expr
Definition: primnodes.h:1444
void reset_transmission_modes(int nestlevel)
static void deparseExpr(Expr *expr, deparse_expr_cxt *context)
Definition: deparse.c:2419
static void deparseFromExprForRel(StringInfo buf, PlannerInfo *root, RelOptInfo *foreignrel, bool use_alias, Index ignore_rel, List **ignore_conds, List **params_list)
Definition: deparse.c:1489
RelOptInfo * scanrel
Definition: deparse.c:99
Definition: pg_list.h:50
RelOptInfo * foreignrel
Definition: deparse.c:98
static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col)
Definition: deparse.c:2216

◆ 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 1714 of file deparse.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), attnum, deparseColumnRef(), deparseRelation(), deparseReturningList(), StringInfoData::len, lfirst_int, TriggerDesc::trig_insert_after_row, and RelationData::trigdesc.

Referenced by postgresBeginForeignInsert(), and postgresPlanForeignModify().

1719 {
1720  AttrNumber pindex;
1721  bool first;
1722  ListCell *lc;
1723 
1724  appendStringInfoString(buf, "INSERT INTO ");
1725  deparseRelation(buf, rel);
1726 
1727  if (targetAttrs)
1728  {
1729  appendStringInfoChar(buf, '(');
1730 
1731  first = true;
1732  foreach(lc, targetAttrs)
1733  {
1734  int attnum = lfirst_int(lc);
1735 
1736  if (!first)
1737  appendStringInfoString(buf, ", ");
1738  first = false;
1739 
1740  deparseColumnRef(buf, rtindex, attnum, rte, false);
1741  }
1742 
1743  appendStringInfoString(buf, ") VALUES (");
1744 
1745  pindex = 1;
1746  first = true;
1747  foreach(lc, targetAttrs)
1748  {
1749  if (!first)
1750  appendStringInfoString(buf, ", ");
1751  first = false;
1752 
1753  appendStringInfo(buf, "$%d", pindex);
1754  pindex++;
1755  }
1756 
1757  appendStringInfoChar(buf, ')');
1758  }
1759  else
1760  appendStringInfoString(buf, " DEFAULT VALUES");
1761  *values_end_len = buf->len;
1762 
1763  if (doNothing)
1764  appendStringInfoString(buf, " ON CONFLICT DO NOTHING");
1765 
1766  deparseReturningList(buf, rte, rtindex, rel,
1767  rel->trigdesc && rel->trigdesc->trig_insert_after_row,
1768  withCheckOptionList, returningList, retrieved_attrs);
1769 }
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:2046
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define lfirst_int(lc)
Definition: pg_list.h:170
TriggerDesc * trigdesc
Definition: rel.h:115
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
bool trig_insert_after_row
Definition: reltrigger.h:57
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
int16 attnum
Definition: pg_attribute.h:83
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344
int16 AttrNumber
Definition: attnum.h:21
static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col)
Definition: deparse.c:2216

◆ deparseSelectStmtForRel()

void deparseSelectStmtForRel ( StringInfo  buf,
PlannerInfo root,
RelOptInfo foreignrel,
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 1001 of file deparse.c.

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

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

1005 {
1006  deparse_expr_cxt context;
1007  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) rel->fdw_private;
1008  List *quals;
1009 
1010  /*
1011  * We handle relations for foreign tables, joins between those and upper
1012  * relations.
1013  */
1014  Assert(IS_JOIN_REL(rel) || IS_SIMPLE_REL(rel) || IS_UPPER_REL(rel));
1015 
1016  /* Fill portions of context common to upper, join and base relation */
1017  context.buf = buf;
1018  context.root = root;
1019  context.foreignrel = rel;
1020  context.scanrel = IS_UPPER_REL(rel) ? fpinfo->outerrel : rel;
1021  context.params_list = params_list;
1022 
1023  /* Construct SELECT clause */
1024  deparseSelectSql(tlist, is_subquery, retrieved_attrs, &context);
1025 
1026  /*
1027  * For upper relations, the WHERE clause is built from the remote
1028  * conditions of the underlying scan relation; otherwise, we can use the
1029  * supplied list of remote conditions directly.
1030  */
1031  if (IS_UPPER_REL(rel))
1032  {
1033  PgFdwRelationInfo *ofpinfo;
1034 
1035  ofpinfo = (PgFdwRelationInfo *) fpinfo->outerrel->fdw_private;
1036  quals = ofpinfo->remote_conds;
1037  }
1038  else
1039  quals = remote_conds;
1040 
1041  /* Construct FROM and WHERE clauses */
1042  deparseFromExpr(quals, &context);
1043 
1044  if (IS_UPPER_REL(rel))
1045  {
1046  /* Append GROUP BY clause */
1047  appendGroupByClause(tlist, &context);
1048 
1049  /* Append HAVING clause */
1050  if (remote_conds)
1051  {
1052  appendStringInfoString(buf, " HAVING ");
1053  appendConditions(remote_conds, &context);
1054  }
1055  }
1056 
1057  /* Add ORDER BY clause if we found any useful pathkeys */
1058  if (pathkeys)
1059  appendOrderByClause(pathkeys, has_final_sort, &context);
1060 
1061  /* Add LIMIT clause if necessary */
1062  if (has_limit)
1063  appendLimitClause(&context);
1064 
1065  /* Add any necessary FOR UPDATE/SHARE. */
1066  deparseLockingClause(&context);
1067 }
static void appendGroupByClause(List *tlist, deparse_expr_cxt *context)
Definition: deparse.c:3230
List ** params_list
Definition: deparse.c:103
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:654
static void appendLimitClause(deparse_expr_cxt *context)
Definition: deparse.c:3321
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:649
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
static void appendOrderByClause(List *pathkeys, bool has_final_sort, deparse_expr_cxt *context)
Definition: deparse.c:3267
static void deparseSelectSql(List *tlist, bool is_subquery, List **retrieved_attrs, deparse_expr_cxt *context)
Definition: deparse.c:1083
static void appendConditions(List *exprs, deparse_expr_cxt *context)
Definition: deparse.c:1341
StringInfo buf
Definition: deparse.c:102
void * fdw_private
Definition: pathnodes.h:732
PlannerInfo * root
Definition: deparse.c:97
#define Assert(condition)
Definition: c.h:804
static void deparseFromExpr(List *quals, deparse_expr_cxt *context)
Definition: deparse.c:1141
#define IS_UPPER_REL(rel)
Definition: pathnodes.h:659
static void deparseLockingClause(deparse_expr_cxt *context)
Definition: deparse.c:1251
RelOptInfo * scanrel
Definition: deparse.c:99
Definition: pg_list.h:50
RelOptInfo * foreignrel
Definition: deparse.c:98

◆ deparseStringLiteral()

void deparseStringLiteral ( StringInfo  buf,
const char *  val 
)

Definition at line 2384 of file deparse.c.

References appendStringInfoChar(), ESCAPE_STRING_SYNTAX, and SQL_STR_DOUBLE.

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

2385 {
2386  const char *valptr;
2387 
2388  /*
2389  * Rather than making assumptions about the remote server's value of
2390  * standard_conforming_strings, always use E'foo' syntax if there are any
2391  * backslashes. This will fail on remote servers before 8.1, but those
2392  * are long out of support.
2393  */
2394  if (strchr(val, '\\') != NULL)
2396  appendStringInfoChar(buf, '\'');
2397  for (valptr = val; *valptr; valptr++)
2398  {
2399  char ch = *valptr;
2400 
2401  if (SQL_STR_DOUBLE(ch, true))
2402  appendStringInfoChar(buf, ch);
2403  appendStringInfoChar(buf, ch);
2404  }
2405  appendStringInfoChar(buf, '\'');
2406 }
#define ESCAPE_STRING_SYNTAX
Definition: c.h:1167
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1164
long val
Definition: informix.c:664

◆ deparseTruncateSql()

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

Definition at line 2181 of file deparse.c.

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

Referenced by postgresExecForeignTruncate().

2185 {
2186  ListCell *cell;
2187 
2188  appendStringInfoString(buf, "TRUNCATE ");
2189 
2190  foreach(cell, rels)
2191  {
2192  Relation rel = lfirst(cell);
2193 
2194  if (cell != list_head(rels))
2195  appendStringInfoString(buf, ", ");
2196 
2197  deparseRelation(buf, rel);
2198  }
2199 
2200  appendStringInfo(buf, " %s IDENTITY",
2201  restart_seqs ? "RESTART" : "CONTINUE");
2202 
2203  if (behavior == DROP_RESTRICT)
2204  appendStringInfoString(buf, " RESTRICT");
2205  else if (behavior == DROP_CASCADE)
2206  appendStringInfoString(buf, " CASCADE");
2207 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344
#define lfirst(lc)
Definition: pg_list.h:169

◆ deparseUpdateSql()

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

Definition at line 1828 of file deparse.c.

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

Referenced by postgresPlanForeignModify().

1833 {
1834  AttrNumber pindex;
1835  bool first;
1836  ListCell *lc;
1837 
1838  appendStringInfoString(buf, "UPDATE ");
1839  deparseRelation(buf, rel);
1840  appendStringInfoString(buf, " SET ");
1841 
1842  pindex = 2; /* ctid is always the first param */
1843  first = true;
1844  foreach(lc, targetAttrs)
1845  {
1846  int attnum = lfirst_int(lc);
1847 
1848  if (!first)
1849  appendStringInfoString(buf, ", ");
1850  first = false;
1851 
1852  deparseColumnRef(buf, rtindex, attnum, rte, false);
1853  appendStringInfo(buf, " = $%d", pindex);
1854  pindex++;
1855  }
1856  appendStringInfoString(buf, " WHERE ctid = $1");
1857 
1858  deparseReturningList(buf, rte, rtindex, rel,
1859  rel->trigdesc && rel->trigdesc->trig_update_after_row,
1860  withCheckOptionList, returningList, retrieved_attrs);
1861 }
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:2046
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define lfirst_int(lc)
Definition: pg_list.h:170
TriggerDesc * trigdesc
Definition: rel.h:115
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
bool trig_update_after_row
Definition: reltrigger.h:62
int16 attnum
Definition: pg_attribute.h:83
static void deparseRelation(StringInfo buf, Relation rel)
Definition: deparse.c:2344
int16 AttrNumber
Definition: attnum.h:21
static void deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, bool qualify_col)
Definition: deparse.c:2216

◆ do_sql_command()

void do_sql_command ( PGconn conn,
const char *  sql 
)

Definition at line 571 of file connection.c.

References ERROR, pgfdw_get_result(), pgfdw_report_error(), PGRES_COMMAND_OK, PQclear(), PQresultStatus(), and PQsendQuery().

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

572 {
573  PGresult *res;
574 
575  if (!PQsendQuery(conn, sql))
576  pgfdw_report_error(ERROR, NULL, conn, false, sql);
577  res = pgfdw_get_result(conn, sql);
578  if (PQresultStatus(res) != PGRES_COMMAND_OK)
579  pgfdw_report_error(ERROR, res, conn, true, sql);
580  PQclear(res);
581 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3106
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1279
#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
PGresult * pgfdw_get_result(PGconn *conn, const char *query)
Definition: connection.c:713

◆ ExtractConnectionOptions()

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

Definition at line 357 of file option.c.

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

Referenced by connect_pg_server().

359 {
360  ListCell *lc;
361  int i;
362 
363  /* Build our options lists if we didn't yet. */
365 
366  i = 0;
367  foreach(lc, defelems)
368  {
369  DefElem *d = (DefElem *) lfirst(lc);
370 
371  if (is_libpq_option(d->defname))
372  {
373  keywords[i] = d->defname;
374  values[i] = defGetString(d);
375  i++;
376  }
377  }
378  return i;
379 }
char * defGetString(DefElem *def)
Definition: define.c:49
#define lfirst(lc)
Definition: pg_list.h:169
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int i
static bool is_libpq_option(const char *keyword)
Definition: option.c:336
char * defname
Definition: parsenodes.h:746
static void InitPgFdwOptions(void)
Definition: option.c:195

◆ ExtractExtensionList()

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

Definition at line 388 of file option.c.

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

389 {
390  List *extensionOids = NIL;
391  List *extlist;
392  ListCell *lc;
393 
394  /* SplitIdentifierString scribbles on its input, so pstrdup first */
395  if (!SplitIdentifierString(pstrdup(extensionsString), ',', &extlist))
396  {
397  /* syntax error in name list */
398  ereport(ERROR,
399  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
400  errmsg("parameter \"%s\" must be a list of extension names",
401  "extensions")));
402  }
403 
404  foreach(lc, extlist)
405  {
406  const char *extension_name = (const char *) lfirst(lc);
407  Oid extension_oid = get_extension_oid(extension_name, true);
408 
409  if (OidIsValid(extension_oid))
410  {
411  extensionOids = lappend_oid(extensionOids, extension_oid);
412  }
413  else if (warnOnMissing)
414  {
416  (errcode(ERRCODE_UNDEFINED_OBJECT),
417  errmsg("extension \"%s\" is not installed",
418  extension_name)));
419  }
420  }
421 
422  list_free(extlist);
423  return extensionOids;
424 }
#define NIL
Definition: pg_list.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3753
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition: extension.c:140
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
Definition: pg_list.h:50

◆ find_em_expr_for_input_target()

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

Definition at line 7259 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().

7262 {
7263  ListCell *lc1;
7264  int i;
7265 
7266  i = 0;
7267  foreach(lc1, target->exprs)
7268  {
7269  Expr *expr = (Expr *) lfirst(lc1);
7270  Index sgref = get_pathtarget_sortgroupref(target, i);
7271  ListCell *lc2;
7272 
7273  /* Ignore non-sort expressions */
7274  if (sgref == 0 ||
7276  root->parse->sortClause) == NULL)
7277  {
7278  i++;
7279  continue;
7280  }
7281 
7282  /* We ignore binary-compatible relabeling on both ends */
7283  while (expr && IsA(expr, RelabelType))
7284  expr = ((RelabelType *) expr)->arg;
7285 
7286  /* Locate an EquivalenceClass member matching this expr, if any */
7287  foreach(lc2, ec->ec_members)
7288  {
7290  Expr *em_expr;
7291 
7292  /* Don't match constants */
7293  if (em->em_is_const)
7294  continue;
7295 
7296  /* Ignore child members */
7297  if (em->em_is_child)
7298  continue;
7299 
7300  /* Match if same expression (after stripping relabel) */
7301  em_expr = em->em_expr;
7302  while (em_expr && IsA(em_expr, RelabelType))
7303  em_expr = ((RelabelType *) em_expr)->arg;
7304 
7305  if (equal(em_expr, expr))
7306  return em->em_expr;
7307  }
7308 
7309  i++;
7310  }
7311 
7312  elog(ERROR, "could not find pathkey item to sort");
7313  return NULL; /* keep compiler quiet */
7314 }
#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:3116
#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_em_expr_for_rel()

Expr* find_em_expr_for_rel ( EquivalenceClass ec,
RelOptInfo rel 
)

Definition at line 939 of file equivclass.c.

Referenced by appendOrderByClause(), and get_useful_pathkeys_for_relation().

940 {
941  ListCell *lc_em;
942 
943  foreach(lc_em, ec->ec_members)
944  {
945  EquivalenceMember *em = lfirst(lc_em);
946 
947  if (bms_is_subset(em->em_relids, rel->relids) &&
948  !bms_is_empty(em->em_relids))
949  {
950  /*
951  * If there is more than one equivalence member whose Vars are
952  * taken entirely from this relation, we'll be content to choose
953  * any one of those.
954  */
955  return em->em_expr;
956  }
957  }
958 
959  /* We didn't find any suitable equivalence class expression */
960  return NULL;
961 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Relids relids
Definition: pathnodes.h:676
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
#define lfirst(lc)
Definition: pg_list.h:169
List * ec_members
Definition: pathnodes.h:981

◆ get_jointype_name()

const char* get_jointype_name ( JoinType  jointype)

Definition at line 1375 of file deparse.c.

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

Referenced by deparseFromExprForRel(), and foreign_join_ok().

1376 {
1377  switch (jointype)
1378  {
1379  case JOIN_INNER:
1380  return "INNER";
1381 
1382  case JOIN_LEFT:
1383  return "LEFT";
1384 
1385  case JOIN_RIGHT:
1386  return "RIGHT";
1387 
1388  case JOIN_FULL:
1389  return "FULL";
1390 
1391  default:
1392  /* Shouldn't come here, but protect from buggy code. */
1393  elog(ERROR, "unsupported join type %d", jointype);
1394  }
1395 
1396  /* Keep compiler happy */
1397  return NULL;
1398 }
#define ERROR
Definition: elog.h:46
#define elog(elevel,...)
Definition: elog.h:232

◆ GetConnection()

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

Definition at line 125 of file connection.c.

References Assert, begin_remote_xact(), CacheRegisterSyscacheCallback(), ConnCacheEntry::conn, CONNECTION_BAD, 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, ConnCacheEntry::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, UserMapping::umid, USERMAPPINGOID, ConnCacheEntry::xact_depth, and xact_got_connection.

Referenced by create_foreign_modify(), dumpBlobs(), dumpDatabase(), dumpDatabaseConfig(), 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(), postgresImportForeignSchema(), setup_connection(), StartLogStreamer(), StreamLog(), and StreamLogicalLog().

126 {
127  bool found;
128  bool retry = false;
129  ConnCacheEntry *entry;
132 
133  /* First time through, initialize connection cache hashtable */
134  if (ConnectionHash == NULL)
135  {
136  HASHCTL ctl;
137 
138  ctl.keysize = sizeof(ConnCacheKey);
139  ctl.entrysize = sizeof(ConnCacheEntry);
140  ConnectionHash = hash_create("postgres_fdw connections", 8,
141  &ctl,
143 
144  /*
145  * Register some callback functions that manage connection cleanup.
146  * This should be done just once in each backend.
147  */
154  }
155 
156  /* Set flag that we did GetConnection during the current transaction */
157  xact_got_connection = true;
158 
159  /* Create hash key for the entry. Assume no pad bytes in key struct */
160  key = user->umid;
161 
162  /*
163  * Find or create cached entry for requested connection.
164  */
165  entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
166  if (!found)
167  {
168  /*
169  * We need only clear "conn" here; remaining fields will be filled
170  * later when "conn" is set.
171  */
172  entry->conn = NULL;
173  }
174 
175  /* Reject further use of connections which failed abort cleanup. */
177 
178  /*
179  * If the connection needs to be remade due to invalidation, disconnect as
180  * soon as we're out of all transactions.
181  */
182  if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
183  {
184  elog(DEBUG3, "closing connection %p for option changes to take effect",
185  entry->conn);
186  disconnect_pg_server(entry);
187  }
188 
189  /*
190  * If cache entry doesn't have a connection, we have to establish a new
191  * connection. (If connect_pg_server throws an error, the cache entry
192  * will remain in a valid empty state, ie conn == NULL.)
193  */
194  if (entry->conn == NULL)
195  make_new_connection(entry, user);
196 
197  /*
198  * We check the health of the cached connection here when starting a new
199  * remote transaction. If a broken connection is detected, we try to
200  * reestablish a new connection later.
201  */
202  PG_TRY();
203  {
204  /* Process a pending asynchronous request if any. */
205  if (entry->state.pendingAreq)
207  /* Start a new transaction or subtransaction if needed. */
208  begin_remote_xact(entry);
209  }
210  PG_CATCH();
211  {
213  ErrorData *errdata = CopyErrorData();
214 
215  /*
216  * If connection failure is reported when starting a new remote
217  * transaction (not subtransaction), new connection will be
218  * reestablished later.
219  *
220  * After a broken connection is detected in libpq, any error other
221  * than connection failure (e.g., out-of-memory) can be thrown
222  * somewhere between return from libpq and the expected ereport() call
223  * in pgfdw_report_error(). In this case, since PQstatus() indicates
224  * CONNECTION_BAD, checking only PQstatus() causes the false detection
225  * of connection failure. To avoid this, we also verify that the
226  * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
227  * checking only the sqlstate can cause another false detection
228  * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
229  * for any libpq-originated error condition.
230  */
231  if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
232  PQstatus(entry->conn) != CONNECTION_BAD ||
233  entry->xact_depth > 0)
234  {
235  MemoryContextSwitchTo(ecxt);
236  PG_RE_THROW();
237  }
238 
239  /* Clean up the error state */
240  FlushErrorState();
241  FreeErrorData(errdata);
242  errdata = NULL;
243 
244  retry = true;
245  }
246  PG_END_TRY();
247 
248  /*
249  * If a broken connection is detected, disconnect it, reestablish a new
250  * connection and retry a new remote transaction. If connection failure is
251  * reported again, we give up getting a connection.
252  */
253  if (retry)
254  {
255  Assert(entry->xact_depth == 0);
256 
257  ereport(DEBUG3,
258  (errmsg_internal("could not start remote transaction on connection %p",
259  entry->conn)),
260  errdetail_internal("%s", pchomp(PQerrorMessage(entry->conn))));
261 
262  elog(DEBUG3, "closing connection %p to reestablish a new one",
263  entry->conn);
264  disconnect_pg_server(entry);
265 
266  if (entry->conn == NULL)
267  make_new_connection(entry, user);
268 
269  begin_remote_xact(entry);
270  }
271 
272  /* Remember if caller will prepare statements */
273  entry->have_prep_stmt |= will_prep_stmt;
274 
275  /* If caller needs access to the per-connection state, return it. */
276  if (state)
277  *state = &entry->state;
278 
279  return entry->conn;
280 }
Oid umid
Definition: foreign.h:47
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
#define HASH_ELEM
Definition: hsearch.h:95
int sqlerrcode
Definition: elog.h:381
#define DEBUG3
Definition: elog.h:23
struct ConnCacheEntry ConnCacheEntry
ErrorData * CopyErrorData(void)
Definition: elog.c:1560
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:76
bool have_prep_stmt
Definition: connection.c:58
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
void FlushErrorState(void)
Definition: elog.c:1654
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
char * pchomp(const char *in)
Definition: mcxt.c:1327
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1616
void process_pending_request(AsyncRequest *areq)
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
PgFdwConnState state
Definition: connection.c:67
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
bool invalidated
Definition: connection.c:61
static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
Definition: connection.c:1143
#define HASH_BLOBS
Definition: hsearch.h:97
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1435
static void pgfdw_xact_callback(XactEvent event, void *arg)
Definition: connection.c:833
static HTAB * ConnectionHash
Definition: connection.c:73
uintptr_t Datum
Definition: postgres.h:411
void RegisterSubXactCallback(SubXactCallback callback, void *arg)
Definition: xact.c:3582
Size keysize
Definition: hsearch.h:75
#define ereport(elevel,...)
Definition: elog.h:157
AsyncRequest * pendingAreq
Definition: postgres_fdw.h:134
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define PG_CATCH()
Definition: elog.h:323
PGconn * conn
Definition: connection.c:54
static void disconnect_pg_server(ConnCacheEntry *entry)
Definition: connection.c:460
#define Assert(condition)
Definition: c.h:804
void RegisterXactCallback(XactCallback callback, void *arg)
Definition: xact.c:3527
static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
Definition: connection.c:1193
static bool xact_got_connection
Definition: connection.c:80
#define PG_RE_THROW()
Definition: elog.h:354
static void make_new_connection(ConnCacheEntry *entry, UserMapping *user)
Definition: connection.c:287
#define elog(elevel,...)
Definition: elog.h:232
static void pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
Definition: connection.c:1026
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6682
#define PG_TRY()
Definition: elog.h:313
static void begin_remote_xact(ConnCacheEntry *entry)
Definition: connection.c:594
Oid ConnCacheKey
Definition: connection.c:49
#define PG_END_TRY()
Definition: elog.h:338

◆ GetCursorNumber()

unsigned int GetCursorNumber ( PGconn conn)

Definition at line 658 of file connection.c.

References cursor_number.

Referenced by postgresAcquireSampleRowsFunc(), and postgresBeginForeignScan().

659 {
660  return ++cursor_number;
661 }
static unsigned int cursor_number
Definition: connection.c:76

◆ GetPrepStmtNumber()

unsigned int GetPrepStmtNumber ( PGconn conn)

Definition at line 672 of file connection.c.

References prep_stmt_number.

Referenced by prepare_foreign_modify().

673 {
674  return ++prep_stmt_number;
675 }
static unsigned int prep_stmt_number
Definition: connection.c:77

◆ is_builtin()

bool is_builtin ( Oid  objectId)

Definition at line 152 of file shippable.c.

References FirstGenbkiObjectId.

Referenced by deparse_type_name(), and is_shippable().

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

◆ is_foreign_expr()

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

Definition at line 231 of file deparse.c.

References foreign_loc_cxt::collation, contain_mutable_functions(), FDW_COLLATE_NONE, FDW_COLLATE_UNSAFE, RelOptInfo::fdw_private, foreign_expr_walker(), foreign_glob_cxt::foreignrel, 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(), add_foreign_ordered_paths(), classifyConditions(), foreign_grouping_ok(), foreign_join_ok(), get_useful_pathkeys_for_relation(), postgresGetForeignPaths(), postgresGetForeignPlan(), and postgresPlanDirectModify().

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

◆ is_foreign_param()

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

Definition at line 877 of file deparse.c.

References bms_is_member(), RelOptInfo::fdw_private, IS_UPPER_REL, nodeTag, PgFdwRelationInfo::outerrel, foreign_glob_cxt::relids, RelOptInfo::relids, T_Param, T_Var, Var::varlevelsup, and Var::varno.

Referenced by foreign_grouping_ok().

880 {
881  if (expr == NULL)
882  return false;
883 
884  switch (nodeTag(expr))
885  {
886  case T_Var:
887  {
888  /* It would have to be sent unless it's a foreign Var */
889  Var *var = (Var *) expr;
890  PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) (baserel->fdw_private);
891  Relids relids;
892 
893  if (IS_UPPER_REL(baserel))
894  relids = fpinfo->outerrel->relids;
895  else
896  relids = baserel->relids;
897 
898  if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
899  return false; /* foreign Var, so not a param */
900  else
901  return true; /* it'd have to be a param */
902  break;
903  }
904  case T_Param:
905  /* Params always have to be sent to the foreign server */
906  return true;
907  default:
908  break;
909  }
910  return false;
911 }
Index varlevelsup
Definition: primnodes.h:196
Definition: primnodes.h:186
RelOptInfo * outerrel
Definition: postgres_fdw.h:102
Relids relids
Definition: pathnodes.h:676
Index varno
Definition: primnodes.h:189
Definition: nodes.h:157
void * fdw_private
Definition: pathnodes.h:732
#define IS_UPPER_REL(rel)
Definition: pathnodes.h:659
#define nodeTag(nodeptr)
Definition: nodes.h:544
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Definition: nodes.h:159

◆ is_shippable()

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

Definition at line 162 of file shippable.c.

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

Referenced by foreign_expr_walker().

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  (void *) &key,
188  HASH_FIND,
189  NULL);
190 
191  if (!entry)
192  {
193  /* Not found in cache, so perform shippability lookup. */
194  bool shippable = lookup_shippable(objectId, classId, fpinfo);
195 
196  /*
197  * Don't create a new hash entry until *after* we have the shippable
198  * result in hand, as the underlying catalog lookups might trigger a
199  * cache invalidation.
200  */
201  entry = (ShippableCacheEntry *)
203  (void *) &key,
204  HASH_ENTER,
205  NULL);
206 
207  entry->shippable = shippable;
208  }
209 
210  return entry->shippable;
211 }
#define NIL
Definition: pg_list.h:65
bool is_builtin(Oid objectId)
Definition: shippable.c:152
ForeignServer * server
Definition: postgres_fdw.h:86
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
static void InitializeShippableCache(void)
Definition: shippable.c:91
static bool lookup_shippable(Oid objectId, Oid classId, PgFdwRelationInfo *fpinfo)
Definition: shippable.c:116
static HTAB * ShippableCacheHash
Definition: shippable.c:34
List * shippable_extensions
Definition: postgres_fdw.h:81
Oid serverid
Definition: foreign.h:36

◆ pgfdw_exec_query()

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

Definition at line 685 of file connection.c.

References ERROR, PgFdwConnState::pendingAreq, 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(), postgresImportForeignSchema(), and postgresReScanForeignScan().

686 {
687  /* First, process a pending asynchronous request, if any. */
688  if (state && state->pendingAreq)
690 
691  /*
692  * Submit a query. Since we don't use non-blocking mode, this also can
693  * block. But its risk is relatively small, so we ignore that for now.
694  */
695  if (!PQsendQuery(conn, query))
696  pgfdw_report_error(ERROR, NULL, conn, false, query);
697 
698  /* Wait for the result. */
699  return pgfdw_get_result(conn, query);
700 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1279
#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

◆ pgfdw_get_result()

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

Definition at line 713 of file connection.c.

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

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

714 {
715  PGresult *volatile last_res = NULL;
716 
717  /* In what follows, do not leak any PGresults on an error. */
718  PG_TRY();
719  {
720  for (;;)
721  {
722  PGresult *res;
723 
724  while (PQisBusy(conn))
725  {
726  int wc;
727 
728  /* Sleep until there's something to do */
732  PQsocket(conn),
733  -1L, PG_WAIT_EXTENSION);
735 
737 
738  /* Data available in socket? */
739  if (wc & WL_SOCKET_READABLE)
740  {
741  if (!PQconsumeInput(conn))
742  pgfdw_report_error(ERROR, NULL, conn, false, query);
743  }
744  }
745 
746  res = PQgetResult(conn);
747  if (res == NULL)
748  break; /* query is complete */
749 
750  PQclear(last_res);
751  last_res = res;
752  }
753  }
754  PG_CATCH();
755  {
756  PQclear(last_res);
757  PG_RE_THROW();
758  }
759  PG_END_TRY();
760 
761  return last_res;
762 }
#define PG_WAIT_EXTENSION
Definition: wait_event.h:23
#define WL_SOCKET_READABLE
Definition: latch.h:126
void ResetLatch(Latch *latch)
Definition: latch.c:660
#define ERROR
Definition: elog.h:46
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:500
void pgfdw_report_error(int elevel, PGresult *res, PGconn *conn, bool clear, const char *sql)
Definition: connection.c:778
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1862
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_CATCH()
Definition: elog.h:323
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1909
#define PG_RE_THROW()
Definition: elog.h:354
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define PG_TRY()
Definition: elog.h:313
#define WL_LATCH_SET
Definition: latch.h:125
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:6753
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1936
#define PG_END_TRY()
Definition: elog.h:338
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

◆ pgfdw_report_error()

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

Definition at line 778 of file connection.c.

References 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(), and PQresultErrorField().

Referenced by close_cursor(), create_cursor(), deallocate_query(), do_sql_command(), 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(), postgresImportForeignSchema(), postgresReScanForeignScan(), and prepare_foreign_modify().

780 {
781  /* If requested, PGresult must be released before leaving this function. */
782  PG_TRY();
783  {
784  char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
785  char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
786  char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
787  char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
788  char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
789  int sqlstate;
790 
791  if (diag_sqlstate)
792  sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
793  diag_sqlstate[1],
794  diag_sqlstate[2],
795  diag_sqlstate[3],
796  diag_sqlstate[4]);
797  else
798  sqlstate = ERRCODE_CONNECTION_FAILURE;
799 
800  /*
801  * If we don't get a message from the PGresult, try the PGconn. This
802  * is needed because for connection-level failures, PQexec may just
803  * return NULL, not a PGresult at all.
804  */
805  if (message_primary == NULL)
806  message_primary = pchomp(PQerrorMessage(conn));
807 
808  ereport(elevel,
809  (errcode(sqlstate),
810  message_primary ? errmsg_internal("%s", message_primary) :
811  errmsg("could not obtain message string for remote error"),
812  message_detail ? errdetail_internal("%s", message_detail) : 0,
813  message_hint ? errhint("%s", message_hint) : 0,
814  message_context ? errcontext("%s", message_context) : 0,
815  sql ? errcontext("remote SQL command: %s", sql) : 0));
816  }
817  PG_FINALLY();
818  {
819  if (clear)
820  PQclear(res);
821  }
822  PG_END_TRY();
823 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:64
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
char * pchomp(const char *in)
Definition: mcxt.c:1327
static int elevel
Definition: vacuumlazy.c:403
#define PG_FINALLY()
Definition: elog.h:330
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define ereport(elevel,...)
Definition: elog.h:157
void PQclear(PGresult *res)
Definition: fe-exec.c:680
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3161
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define errcontext
Definition: elog.h:204
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64

◆ process_pending_request()

void process_pending_request ( AsyncRequest areq)

Definition at line 6998 of file postgres_fdw.c.

References Assert, AsyncRequest::callback_pending, EState::es_query_cxt, ExecAsyncResponse(), ForeignScanState::fdw_state, fetch_more_data(), PlanState::instrument, InstrUpdateTupleCount(), MemoryContextSwitchTo(), PG_USED_FOR_ASSERTS_ONLY, produce_tuple_asynchronously(), ScanState::ps, AsyncRequest::requestee, AsyncRequest::result, ForeignScanState::ss, PlanState::state, and TupIsNull.

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

6999 {
7000  ForeignScanState *node = (ForeignScanState *) areq->requestee;
7002  EState *estate = node->ss.ps.state;
7003  MemoryContext oldcontext;
7004 
7005  /* The request should be currently in-process */
7006  Assert(fsstate->conn_state->pendingAreq == areq);
7007 
7008  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
7009 
7010  /* The request would have been pending for a callback */
7011  Assert(areq->callback_pending);
7012 
7013  /* Unlike AsyncNotify, we unset callback_pending ourselves */
7014  areq->callback_pending = false;
7015 
7016  fetch_more_data(node);
7017 
7018  /* We need to send a new query afterwards; don't fetch */
7019  produce_tuple_asynchronously(areq, false);
7020 
7021  /* Unlike AsyncNotify, we call ExecAsyncResponse ourselves */
7022  ExecAsyncResponse(areq);
7023 
7024  /* Also, we do instrumentation ourselves, if required */
7025  if (areq->requestee->instrument)
7027  TupIsNull(areq->result) ? 0.0 : 1.0);
7028 
7029  MemoryContextSwitchTo(oldcontext);
7030 }
ScanState ss
Definition: execnodes.h:1857
static void produce_tuple_asynchronously(AsyncRequest *areq, bool fetch)
Instrumentation * instrument
Definition: execnodes.h:976
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
EState * state
Definition: execnodes.h:968
PlanState ps
Definition: execnodes.h:1377
MemoryContext es_query_cxt
Definition: execnodes.h:600
struct PlanState * requestee
Definition: execnodes.h:538
#define TupIsNull(slot)
Definition: tuptable.h:292
TupleTableSlot * result
Definition: execnodes.h:542
bool callback_pending
Definition: execnodes.h:540
#define Assert(condition)
Definition: c.h:804
static void fetch_more_data(ForeignScanState *node)
void ExecAsyncResponse(AsyncRequest *areq)
Definition: execAsync.c:117
void InstrUpdateTupleCount(Instrumentation *instr, double nTuples)
Definition: instrument.c:132
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155

◆ rebuildInsertSql()

void rebuildInsertSql ( StringInfo  buf,
char *  orig_query,
int  values_end_len,
int  num_cols,
int  num_rows 
)

Definition at line 1778 of file deparse.c.

References appendBinaryStringInfo(), appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert, and i.

Referenced by execute_foreign_modify().

1781 {
1782  int i,
1783  j;
1784  int pindex;
1785  bool first;
1786 
1787  /* Make sure the values_end_len is sensible */
1788  Assert((values_end_len > 0) && (values_end_len <= strlen(orig_query)));
1789 
1790  /* Copy up to the end of the first record from the original query */
1791  appendBinaryStringInfo(buf, orig_query, values_end_len);
1792 
1793  /*
1794  * Add records to VALUES clause (we already have parameters for the first
1795  * row, so start at the right offset).
1796  */
1797  pindex = num_cols + 1;
1798  for (i = 0; i < num_rows; i++)
1799  {
1800  appendStringInfoString(buf, ", (");
1801 
1802  first = true;
1803  for (j = 0; j < num_cols; j++)
1804  {
1805  if (!first)
1806  appendStringInfoString(buf, ", ");
1807  first = false;
1808 
1809  appendStringInfo(buf, "$%d", pindex);
1810  pindex++;
1811  }
1812 
1813  appendStringInfoChar(buf, ')');
1814  }
1815 
1816  /* Copy stuff after VALUES clause from the original query */
1817  appendStringInfoString(buf, orig_query + values_end_len);
1818 }
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
#define Assert(condition)
Definition: c.h:804
int i
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ ReleaseConnection()

void ReleaseConnection ( PGconn conn)

Definition at line 637 of file connection.c.

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

638 {
639  /*
640  * Currently, we don't actually track connection references because all
641  * cleanup is managed on a transaction or subtransaction basis instead. So
642  * there's nothing to do here.
643  */
644 }

◆ reset_transmission_modes()

void reset_transmission_modes ( int  nestlevel)

Definition at line 3895 of file postgres_fdw.c.

References AtEOXact_GUC().

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

3896 {
3897  AtEOXact_GUC(true, nestlevel);
3898 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6201

◆ set_transmission_modes()

int set_transmission_modes ( void  )

Definition at line 3867 of file postgres_fdw.c.

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

3868 {
3869  int nestlevel = NewGUCNestLevel();
3870 
3871  /*
3872  * The values set here should match what pg_dump does. See also
3873  * configure_remote_session in connection.c.
3874  */
3875  if (DateStyle != USE_ISO_DATES)
3876  (void) set_config_option("datestyle", "ISO",
3878  GUC_ACTION_SAVE, true, 0, false);
3880  (void) set_config_option("intervalstyle", "postgres",
3882  GUC_ACTION_SAVE, true, 0, false);
3883  if (extra_float_digits < 3)
3884  (void) set_config_option("extra_float_digits", "3",
3886  GUC_ACTION_SAVE, true, 0, false);
3887 
3888  return nestlevel;
3889 }
int IntervalStyle
Definition: globals.c:120
#define USE_ISO_DATES
Definition: miscadmin.h:229
int extra_float_digits
Definition: float.c:42
int DateStyle
Definition: globals.c:118
int NewGUCNestLevel(void)
Definition: guc.c:6187
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:7278
#define INTSTYLE_POSTGRES
Definition: miscadmin.h:249