PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
dblink.c File Reference
#include "postgres.h"
#include <limits.h>
#include "libpq-fe.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_type.h"
#include "catalog/pg_user_mapping.h"
#include "executor/spi.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "parser/scansup.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/tqual.h"
#include "utils/varlena.h"
#include "dblink.h"
Include dependency graph for dblink.c:

Go to the source code of this file.

Data Structures

struct  remoteConn
 
struct  storeInfo
 
struct  remoteConnHashEnt
 

Macros

#define NUMCONN   16
 
#define xpfree(var_)
 
#define xpstrdup(var_c, var_)
 
#define DBLINK_RES_INTERNALERROR(p2)
 
#define DBLINK_CONN_NOT_AVAIL
 
#define DBLINK_GET_CONN
 
#define DBLINK_GET_NAMED_CONN
 
#define DBLINK_INIT
 
#define DBLINK_NOTIFY_COLS   3
 

Typedefs

typedef struct remoteConn remoteConn
 
typedef struct storeInfo storeInfo
 
typedef struct remoteConnHashEnt remoteConnHashEnt
 

Functions

static Datum dblink_record_internal (FunctionCallInfo fcinfo, bool is_async)
 
static void prepTuplestoreResult (FunctionCallInfo fcinfo)
 
static void materializeResult (FunctionCallInfo fcinfo, PGconn *conn, PGresult *res)
 
static void materializeQueryResult (FunctionCallInfo fcinfo, PGconn *conn, const char *conname, const char *sql, bool fail)
 
static PGresultstoreQueryResult (volatile storeInfo *sinfo, PGconn *conn, const char *sql)
 
static void storeRow (volatile storeInfo *sinfo, PGresult *res, bool first)
 
static remoteConngetConnectionByName (const char *name)
 
static HTABcreateConnHash (void)
 
static void createNewConnection (const char *name, remoteConn *rconn)
 
static void deleteConnection (const char *name)
 
static char ** get_pkey_attnames (Relation rel, int16 *numatts)
 
static char ** get_text_array_contents (ArrayType *array, int *numitems)
 
static char * get_sql_insert (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static char * get_sql_delete (Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
 
static char * get_sql_update (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static char * quote_ident_cstr (char *rawstr)
 
static int get_attnum_pk_pos (int *pkattnums, int pknumatts, int key)
 
static HeapTuple get_tuple_of_interest (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
 
static Relation get_rel_from_relname (text *relname_text, LOCKMODE lockmode, AclMode aclmode)
 
static char * generate_relation_name (Relation rel)
 
static void dblink_connstr_check (const char *connstr)
 
static void dblink_security_check (PGconn *conn, remoteConn *rconn)
 
static void dblink_res_error (PGconn *conn, const char *conname, PGresult *res, const char *dblink_context_msg, bool fail)
 
static char * get_connect_string (const char *servername)
 
static char * escape_param_str (const char *from)
 
static void validate_pkattnums (Relation rel, int2vector *pkattnums_arg, int32 pknumatts_arg, int **pkattnums, int *pknumatts)
 
static bool is_valid_dblink_option (const PQconninfoOption *options, const char *option, Oid context)
 
static int applyRemoteGucs (PGconn *conn)
 
static void restoreLocalGucs (int nestlevel)
 
 PG_FUNCTION_INFO_V1 (dblink_connect)
 
Datum dblink_connect (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_disconnect)
 
Datum dblink_disconnect (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_open)
 
Datum dblink_open (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_close)
 
Datum dblink_close (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_fetch)
 
Datum dblink_fetch (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_record)
 
Datum dblink_record (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_send_query)
 
Datum dblink_send_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_result)
 
Datum dblink_get_result (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_connections)
 
Datum dblink_get_connections (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_is_busy)
 
Datum dblink_is_busy (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_cancel_query)
 
Datum dblink_cancel_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_error_message)
 
Datum dblink_error_message (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_exec)
 
Datum dblink_exec (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_pkey)
 
Datum dblink_get_pkey (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_insert)
 
Datum dblink_build_sql_insert (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_delete)
 
Datum dblink_build_sql_delete (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_update)
 
Datum dblink_build_sql_update (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_current_query)
 
Datum dblink_current_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_notify)
 
Datum dblink_get_notify (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_fdw_validator)
 
Datum dblink_fdw_validator (PG_FUNCTION_ARGS)
 

Variables

 PG_MODULE_MAGIC
 
static remoteConnpconn = NULL
 
static HTABremoteConnHash = NULL
 

Macro Definition Documentation

#define DBLINK_CONN_NOT_AVAIL
Value:
do { \
if(conname) \
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST), \
errmsg("connection \"%s\" not available", conname))); \
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST), \
errmsg("connection not available"))); \
} while (0)
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

Definition at line 175 of file dblink.c.

Referenced by dblink_close(), dblink_disconnect(), dblink_exec(), dblink_fetch(), dblink_open(), and dblink_record_internal().

#define DBLINK_GET_CONN

Definition at line 187 of file dblink.c.

Referenced by dblink_exec(), and dblink_record_internal().

#define DBLINK_GET_NAMED_CONN
Value:
do { \
rconn = getConnectionByName(conname); \
if (rconn) \
conn = rconn->conn; \
} while (0)
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: streamutil.c:45
char * text_to_cstring(const text *t)
Definition: varlena.c:184

Definition at line 221 of file dblink.c.

Referenced by dblink_cancel_query(), dblink_error_message(), dblink_get_notify(), dblink_is_busy(), dblink_record_internal(), and dblink_send_query().

#define DBLINK_INIT
Value:
do { \
if (!pconn) \
{ \
} \
} while (0)
int openCursorCount
Definition: dblink.c:71
PGconn * conn
Definition: dblink.c:70
#define FALSE
Definition: c.h:218
MemoryContext TopMemoryContext
Definition: mcxt.c:43
bool newXactForCursor
Definition: dblink.c:72
#define NULL
Definition: c.h:226
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:749

Definition at line 231 of file dblink.c.

Referenced by dblink_cancel_query(), dblink_close(), dblink_connect(), dblink_disconnect(), dblink_error_message(), dblink_exec(), dblink_fetch(), dblink_get_notify(), dblink_is_busy(), dblink_open(), and dblink_record_internal().

#define DBLINK_NOTIFY_COLS   3

Definition at line 1877 of file dblink.c.

Referenced by dblink_get_notify().

#define DBLINK_RES_INTERNALERROR (   p2)
Value:
do { \
if (res) \
PQclear(res); \
elog(ERROR, "%s: %s", p2, msg); \
} while (0)
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:45
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define elog
Definition: elog.h:219

Definition at line 167 of file dblink.c.

Referenced by dblink_close(), and dblink_open().

#define NUMCONN   16

Definition at line 147 of file dblink.c.

Referenced by createConnHash().

#define xpfree (   var_)
Value:
do { \
if (var_ != NULL) \
{ \
pfree(var_); \
var_ = NULL; \
} \
} while (0)
void pfree(void *pointer)
Definition: mcxt.c:992
#define NULL
Definition: c.h:226

Definition at line 150 of file dblink.c.

#define xpstrdup (   var_c,
  var_ 
)
Value:
do { \
if (var_ != NULL) \
var_c = pstrdup(var_); \
else \
var_c = NULL; \
} while (0)
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define NULL
Definition: c.h:226

Definition at line 159 of file dblink.c.

Referenced by dblink_res_error().

Typedef Documentation

Function Documentation

static int applyRemoteGucs ( PGconn conn)
static

Definition at line 2976 of file dblink.c.

References Assert, GetConfigOption(), GUC_ACTION_SAVE, i, lengthof, NewGUCNestLevel(), NULL, PGC_S_SESSION, PGC_USERSET, PQparameterStatus(), and set_config_option().

Referenced by materializeResult(), and storeQueryResult().

2977 {
2978  static const char *const GUCsAffectingIO[] = {
2979  "DateStyle",
2980  "IntervalStyle"
2981  };
2982 
2983  int nestlevel = -1;
2984  int i;
2985 
2986  for (i = 0; i < lengthof(GUCsAffectingIO); i++)
2987  {
2988  const char *gucName = GUCsAffectingIO[i];
2989  const char *remoteVal = PQparameterStatus(conn, gucName);
2990  const char *localVal;
2991 
2992  /*
2993  * If the remote server is pre-8.4, it won't have IntervalStyle, but
2994  * that's okay because its output format won't be ambiguous. So just
2995  * skip the GUC if we don't get a value for it. (We might eventually
2996  * need more complicated logic with remote-version checks here.)
2997  */
2998  if (remoteVal == NULL)
2999  continue;
3000 
3001  /*
3002  * Avoid GUC-setting overhead if the remote and local GUCs already
3003  * have the same value.
3004  */
3005  localVal = GetConfigOption(gucName, false, false);
3006  Assert(localVal != NULL);
3007 
3008  if (strcmp(remoteVal, localVal) == 0)
3009  continue;
3010 
3011  /* Create new GUC nest level if we didn't already */
3012  if (nestlevel < 0)
3013  nestlevel = NewGUCNestLevel();
3014 
3015  /* Apply the option (this will throw error on failure) */
3016  (void) set_config_option(gucName, remoteVal,
3018  GUC_ACTION_SAVE, true, 0, false);
3019  }
3020 
3021  return nestlevel;
3022 }
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
Definition: guc.c:6657
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:5925
#define lengthof(array)
Definition: c.h:557
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
int NewGUCNestLevel(void)
Definition: guc.c:5026
int i
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:5869
static HTAB * createConnHash ( void  )
static

Definition at line 2549 of file dblink.c.

References HASHCTL::entrysize, hash_create(), HASH_ELEM, HASHCTL::keysize, NAMEDATALEN, and NUMCONN.

Referenced by createNewConnection(), deleteConnection(), and getConnectionByName().

2550 {
2551  HASHCTL ctl;
2552 
2553  ctl.keysize = NAMEDATALEN;
2554  ctl.entrysize = sizeof(remoteConnHashEnt);
2555 
2556  return hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
2557 }
#define HASH_ELEM
Definition: hsearch.h:87
Size entrysize
Definition: hsearch.h:73
#define NAMEDATALEN
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
Size keysize
Definition: hsearch.h:72
static void createNewConnection ( const char *  name,
remoteConn rconn 
)
static

Definition at line 2560 of file dblink.c.

References remoteConn::conn, createConnHash(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, HASH_ENTER, hash_search(), remoteConnHashEnt::name, pfree(), PQfinish(), pstrdup(), remoteConnHashEnt::rconn, strlcpy(), and truncate_identifier().

Referenced by dblink_connect().

2561 {
2562  remoteConnHashEnt *hentry;
2563  bool found;
2564  char *key;
2565 
2566  if (!remoteConnHash)
2568 
2569  key = pstrdup(name);
2570  truncate_identifier(key, strlen(key), true);
2571  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2572  HASH_ENTER, &found);
2573 
2574  if (found)
2575  {
2576  PQfinish(rconn->conn);
2577  pfree(rconn);
2578 
2579  ereport(ERROR,
2581  errmsg("duplicate connection name")));
2582  }
2583 
2584  hentry->rconn = rconn;
2585  strlcpy(hentry->name, name, sizeof(hentry->name));
2586 }
char * pstrdup(const char *in)
Definition: mcxt.c:1165
remoteConn * rconn
Definition: dblink.c:143
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
char name[NAMEDATALEN]
Definition: dblink.c:142
PGconn * conn
Definition: dblink.c:70
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1705 of file dblink.c.

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg(), ERROR, get_rel_from_relname(), get_sql_delete(), get_text_array_contents(), PG_GETARG_ARRAYTYPE_P, PG_GETARG_INT32, PG_GETARG_POINTER, PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

1706 {
1707  text *relname_text = PG_GETARG_TEXT_P(0);
1708  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1709  int32 pknumatts_arg = PG_GETARG_INT32(2);
1710  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1711  Relation rel;
1712  int *pkattnums;
1713  int pknumatts;
1714  char **tgt_pkattvals;
1715  int tgt_nitems;
1716  char *sql;
1717 
1718  /*
1719  * Open target relation.
1720  */
1721  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1722 
1723  /*
1724  * Process pkattnums argument.
1725  */
1726  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1727  &pkattnums, &pknumatts);
1728 
1729  /*
1730  * Target array is made up of key values that will be used to build the
1731  * SQL string for use on the remote system.
1732  */
1733  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1734 
1735  /*
1736  * There should be one target array key value for each key attnum
1737  */
1738  if (tgt_nitems != pknumatts)
1739  ereport(ERROR,
1740  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1741  errmsg("target key array length must match number of key " \
1742  "attributes")));
1743 
1744  /*
1745  * Prep work is finally done. Go get the SQL string.
1746  */
1747  sql = get_sql_delete(rel, pkattnums, pknumatts, tgt_pkattvals);
1748 
1749  /*
1750  * Now we can close the relation.
1751  */
1753 
1754  /*
1755  * And send it
1756  */
1758 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:225
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:232
signed int int32
Definition: c.h:253
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
Definition: c.h:462
#define ACL_SELECT
Definition: parsenodes.h:66
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define PG_GETARG_TEXT_P(n)
Definition: fmgr.h:269
Definition: c.h:434
Datum dblink_build_sql_insert ( PG_FUNCTION_ARGS  )

Definition at line 1614 of file dblink.c.

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg(), ERROR, get_rel_from_relname(), get_sql_insert(), get_text_array_contents(), PG_GETARG_ARRAYTYPE_P, PG_GETARG_INT32, PG_GETARG_POINTER, PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

1615 {
1616  text *relname_text = PG_GETARG_TEXT_P(0);
1617  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1618  int32 pknumatts_arg = PG_GETARG_INT32(2);
1619  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1620  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1621  Relation rel;
1622  int *pkattnums;
1623  int pknumatts;
1624  char **src_pkattvals;
1625  char **tgt_pkattvals;
1626  int src_nitems;
1627  int tgt_nitems;
1628  char *sql;
1629 
1630  /*
1631  * Open target relation.
1632  */
1633  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1634 
1635  /*
1636  * Process pkattnums argument.
1637  */
1638  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1639  &pkattnums, &pknumatts);
1640 
1641  /*
1642  * Source array is made up of key values that will be used to locate the
1643  * tuple of interest from the local system.
1644  */
1645  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1646 
1647  /*
1648  * There should be one source array key value for each key attnum
1649  */
1650  if (src_nitems != pknumatts)
1651  ereport(ERROR,
1652  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1653  errmsg("source key array length must match number of key " \
1654  "attributes")));
1655 
1656  /*
1657  * Target array is made up of key values that will be used to build the
1658  * SQL string for use on the remote system.
1659  */
1660  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1661 
1662  /*
1663  * There should be one target array key value for each key attnum
1664  */
1665  if (tgt_nitems != pknumatts)
1666  ereport(ERROR,
1667  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1668  errmsg("target key array length must match number of key " \
1669  "attributes")));
1670 
1671  /*
1672  * Prep work is finally done. Go get the SQL string.
1673  */
1674  sql = get_sql_insert(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1675 
1676  /*
1677  * Now we can close the relation.
1678  */
1680 
1681  /*
1682  * And send it
1683  */
1685 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:225
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:232
signed int int32
Definition: c.h:253
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
Definition: c.h:462
#define ACL_SELECT
Definition: parsenodes.h:66
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define PG_GETARG_TEXT_P(n)
Definition: fmgr.h:269
Definition: c.h:434
Datum dblink_build_sql_update ( PG_FUNCTION_ARGS  )

Definition at line 1782 of file dblink.c.

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg(), ERROR, get_rel_from_relname(), get_sql_update(), get_text_array_contents(), PG_GETARG_ARRAYTYPE_P, PG_GETARG_INT32, PG_GETARG_POINTER, PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

1783 {
1784  text *relname_text = PG_GETARG_TEXT_P(0);
1785  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1786  int32 pknumatts_arg = PG_GETARG_INT32(2);
1787  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1788  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1789  Relation rel;
1790  int *pkattnums;
1791  int pknumatts;
1792  char **src_pkattvals;
1793  char **tgt_pkattvals;
1794  int src_nitems;
1795  int tgt_nitems;
1796  char *sql;
1797 
1798  /*
1799  * Open target relation.
1800  */
1801  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1802 
1803  /*
1804  * Process pkattnums argument.
1805  */
1806  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1807  &pkattnums, &pknumatts);
1808 
1809  /*
1810  * Source array is made up of key values that will be used to locate the
1811  * tuple of interest from the local system.
1812  */
1813  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1814 
1815  /*
1816  * There should be one source array key value for each key attnum
1817  */
1818  if (src_nitems != pknumatts)
1819  ereport(ERROR,
1820  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1821  errmsg("source key array length must match number of key " \
1822  "attributes")));
1823 
1824  /*
1825  * Target array is made up of key values that will be used to build the
1826  * SQL string for use on the remote system.
1827  */
1828  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1829 
1830  /*
1831  * There should be one target array key value for each key attnum
1832  */
1833  if (tgt_nitems != pknumatts)
1834  ereport(ERROR,
1835  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1836  errmsg("target key array length must match number of key " \
1837  "attributes")));
1838 
1839  /*
1840  * Prep work is finally done. Go get the SQL string.
1841  */
1842  sql = get_sql_update(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1843 
1844  /*
1845  * Now we can close the relation.
1846  */
1848 
1849  /*
1850  * And send it
1851  */
1853 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:225
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:232
signed int int32
Definition: c.h:253
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:244
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
Definition: c.h:462
#define ACL_SELECT
Definition: parsenodes.h:66
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define PG_GETARG_TEXT_P(n)
Definition: fmgr.h:269
Definition: c.h:434
Datum dblink_cancel_query ( PG_FUNCTION_ARGS  )

Definition at line 1324 of file dblink.c.

References conn, cstring_to_text(), DBLINK_GET_NAMED_CONN, DBLINK_INIT, NULL, PG_RETURN_TEXT_P, PQcancel(), PQfreeCancel(), and PQgetCancel().

1325 {
1326  int res = 0;
1327  char *conname = NULL;
1328  PGconn *conn = NULL;
1329  remoteConn *rconn = NULL;
1330  PGcancel *cancel;
1331  char errbuf[256];
1332 
1333  DBLINK_INIT;
1335  cancel = PQgetCancel(conn);
1336 
1337  res = PQcancel(cancel, errbuf, 256);
1338  PQfreeCancel(cancel);
1339 
1340  if (res == 1)
1342  else
1344 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:3661
PGconn * conn
Definition: streamutil.c:45
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:3638
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:3793
Datum dblink_close ( PG_FUNCTION_ARGS  )

Definition at line 446 of file dblink.c.

References appendStringInfo(), BOOLOID, buf, conn, remoteConn::conn, cstring_to_text(), StringInfoData::data, DBLINK_CONN_NOT_AVAIL, DBLINK_INIT, dblink_res_error(), DBLINK_RES_INTERNALERROR, FALSE, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), remoteConn::newXactForCursor, NULL, remoteConn::openCursorCount, pconn, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), and text_to_cstring().

447 {
448  PGconn *conn = NULL;
449  PGresult *res = NULL;
450  char *curname = NULL;
451  char *conname = NULL;
453  char *msg;
454  remoteConn *rconn = NULL;
455  bool fail = true; /* default to backward compatible behavior */
456 
457  DBLINK_INIT;
458  initStringInfo(&buf);
459 
460  if (PG_NARGS() == 1)
461  {
462  /* text */
463  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
464  rconn = pconn;
465  }
466  else if (PG_NARGS() == 2)
467  {
468  /* might be text,text or text,bool */
469  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
470  {
471  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
472  fail = PG_GETARG_BOOL(1);
473  rconn = pconn;
474  }
475  else
476  {
477  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
478  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
479  rconn = getConnectionByName(conname);
480  }
481  }
482  if (PG_NARGS() == 3)
483  {
484  /* text,text,bool */
485  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
486  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
487  fail = PG_GETARG_BOOL(2);
488  rconn = getConnectionByName(conname);
489  }
490 
491  if (!rconn || !rconn->conn)
493  else
494  conn = rconn->conn;
495 
496  appendStringInfo(&buf, "CLOSE %s", curname);
497 
498  /* close the cursor */
499  res = PQexec(conn, buf.data);
500  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
501  {
502  dblink_res_error(conn, conname, res, "could not close cursor", fail);
504  }
505 
506  PQclear(res);
507 
508  /* if we started a transaction, decrement cursor count */
509  if (rconn->newXactForCursor)
510  {
511  (rconn->openCursorCount)--;
512 
513  /* if count is zero, commit the transaction */
514  if (rconn->openCursorCount == 0)
515  {
516  rconn->newXactForCursor = FALSE;
517 
518  res = PQexec(conn, "COMMIT");
519  if (PQresultStatus(res) != PGRES_COMMAND_OK)
520  DBLINK_RES_INTERNALERROR("commit error");
521  PQclear(res);
522  }
523  }
524 
526 }
int openCursorCount
Definition: dblink.c:71
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:230
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define FALSE
Definition: c.h:218
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2220
PGconn * conn
Definition: streamutil.c:45
static char * buf
Definition: pg_test_fsync.c:65
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
bool newXactForCursor
Definition: dblink.c:72
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
#define BOOLOID
Definition: pg_type.h:288
char * text_to_cstring(const text *t)
Definition: varlena.c:184
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 247 of file dblink.c.

References conn, remoteConn::conn, CONNECTION_BAD, connstr, createNewConnection(), cstring_to_text(), dblink_connstr_check(), DBLINK_INIT, dblink_security_check(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_connect_string(), GetDatabaseEncoding(), GetDatabaseEncodingName(), MemoryContextAlloc(), NULL, pfree(), PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PQclientEncoding(), PQconnectdb(), PQerrorMessage(), PQfinish(), PQsetClientEncoding(), PQstatus(), pstrdup(), text_to_cstring(), and TopMemoryContext.

248 {
249  char *conname_or_str = NULL;
250  char *connstr = NULL;
251  char *connname = NULL;
252  char *msg;
253  PGconn *conn = NULL;
254  remoteConn *rconn = NULL;
255 
256  DBLINK_INIT;
257 
258  if (PG_NARGS() == 2)
259  {
260  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
261  connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
262  }
263  else if (PG_NARGS() == 1)
264  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
265 
266  if (connname)
268  sizeof(remoteConn));
269 
270  /* first check for valid foreign data server */
271  connstr = get_connect_string(conname_or_str);
272  if (connstr == NULL)
273  connstr = conname_or_str;
274 
275  /* check password in connection string if not superuser */
276  dblink_connstr_check(connstr);
277  conn = PQconnectdb(connstr);
278 
279  if (PQstatus(conn) == CONNECTION_BAD)
280  {
281  msg = pstrdup(PQerrorMessage(conn));
282  PQfinish(conn);
283  if (rconn)
284  pfree(rconn);
285 
286  ereport(ERROR,
287  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
288  errmsg("could not establish connection"),
289  errdetail_internal("%s", msg)));
290  }
291 
292  /* check password actually used if not superuser */
293  dblink_security_check(conn, rconn);
294 
295  /* attempt to set client encoding to match server encoding, if needed */
296  if (PQclientEncoding(conn) != GetDatabaseEncoding())
298 
299  if (connname)
300  {
301  rconn->conn = conn;
302  createNewConnection(connname, rconn);
303  }
304  else
305  pconn->conn = conn;
306 
308 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
char * pstrdup(const char *in)
Definition: mcxt.c:1165
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6020
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:45
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6028
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1021
#define PG_NARGS()
Definition: fmgr.h:160
char * text_to_cstring(const text *t)
Definition: varlena.c:184
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:749
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:5907
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:527
static char * connstr
Definition: pg_dumpall.c:67
static void dblink_connstr_check ( const char *  connstr)
static

Definition at line 2637 of file dblink.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, _PQconninfoOption::keyword, NULL, options, PQconninfoFree(), PQconninfoParse(), superuser(), and _PQconninfoOption::val.

Referenced by dblink_connect().

2638 {
2639  if (!superuser())
2640  {
2643  bool connstr_gives_password = false;
2644 
2645  options = PQconninfoParse(connstr, NULL);
2646  if (options)
2647  {
2648  for (option = options; option->keyword != NULL; option++)
2649  {
2650  if (strcmp(option->keyword, "password") == 0)
2651  {
2652  if (option->val != NULL && option->val[0] != '\0')
2653  {
2654  connstr_gives_password = true;
2655  break;
2656  }
2657  }
2658  }
2659  PQconninfoFree(options);
2660  }
2661 
2662  if (!connstr_gives_password)
2663  ereport(ERROR,
2664  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2665  errmsg("password is required"),
2666  errdetail("Non-superusers must provide a password in the connection string.")));
2667  }
2668 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:4604
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5810
#define ereport(elevel, rest)
Definition: elog.h:122
static char ** options
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * connstr
Definition: pg_dumpall.c:67
Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1863 of file dblink.c.

References current_query(), and PG_RETURN_DATUM.

1864 {
1865  /* This is now just an alias for the built-in function current_query() */
1866  PG_RETURN_DATUM(current_query(fcinfo));
1867 }
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:193
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:297
Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 315 of file dblink.c.

References conn, remoteConn::conn, cstring_to_text(), DBLINK_CONN_NOT_AVAIL, DBLINK_INIT, deleteConnection(), getConnectionByName(), NULL, pfree(), PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PQfinish(), and text_to_cstring().

316 {
317  char *conname = NULL;
318  remoteConn *rconn = NULL;
319  PGconn *conn = NULL;
320 
321  DBLINK_INIT;
322 
323  if (PG_NARGS() == 1)
324  {
325  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
326  rconn = getConnectionByName(conname);
327  if (rconn)
328  conn = rconn->conn;
329  }
330  else
331  conn = pconn->conn;
332 
333  if (!conn)
335 
336  PQfinish(conn);
337  if (rconn)
338  {
339  deleteConnection(conname);
340  pfree(rconn);
341  }
342  else
343  pconn->conn = NULL;
344 
346 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
void pfree(void *pointer)
Definition: mcxt.c:992
PGconn * conn
Definition: streamutil.c:45
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
char * text_to_cstring(const text *t)
Definition: varlena.c:184
Datum dblink_error_message ( PG_FUNCTION_ARGS  )

Definition at line 1359 of file dblink.c.

References conn, cstring_to_text(), DBLINK_GET_NAMED_CONN, DBLINK_INIT, NULL, PG_RETURN_TEXT_P, and PQerrorMessage().

1360 {
1361  char *msg;
1362  char *conname = NULL;
1363  PGconn *conn = NULL;
1364  remoteConn *rconn = NULL;
1365 
1366  DBLINK_INIT;
1368 
1369  msg = PQerrorMessage(conn);
1370  if (msg == NULL || msg[0] == '\0')
1372  else
1374 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
PGconn * conn
Definition: streamutil.c:45
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
Datum dblink_exec ( PG_FUNCTION_ARGS  )

Definition at line 1381 of file dblink.c.

References BOOLOID, conn, remoteConn::conn, connstr, cstring_to_text(), DBLINK_CONN_NOT_AVAIL, DBLINK_GET_CONN, DBLINK_INIT, dblink_res_error(), elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), NULL, PG_CATCH, PG_END_TRY, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RE_THROW, PG_RETURN_TEXT_P, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQexec(), PQfinish(), PQresultStatus(), and text_to_cstring().

1382 {
1383  text *volatile sql_cmd_status = NULL;
1384  PGconn *volatile conn = NULL;
1385  volatile bool freeconn = false;
1386 
1387  DBLINK_INIT;
1388 
1389  PG_TRY();
1390  {
1391  char *msg;
1392  PGresult *res = NULL;
1393  char *connstr = NULL;
1394  char *sql = NULL;
1395  char *conname = NULL;
1396  remoteConn *rconn = NULL;
1397  bool fail = true; /* default to backward compatible behavior */
1398 
1399  if (PG_NARGS() == 3)
1400  {
1401  /* must be text,text,bool */
1404  fail = PG_GETARG_BOOL(2);
1405  }
1406  else if (PG_NARGS() == 2)
1407  {
1408  /* might be text,text or text,bool */
1409  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1410  {
1411  conn = pconn->conn;
1413  fail = PG_GETARG_BOOL(1);
1414  }
1415  else
1416  {
1419  }
1420  }
1421  else if (PG_NARGS() == 1)
1422  {
1423  /* must be single text argument */
1424  conn = pconn->conn;
1426  }
1427  else
1428  /* shouldn't happen */
1429  elog(ERROR, "wrong number of arguments");
1430 
1431  if (!conn)
1433 
1434  res = PQexec(conn, sql);
1435  if (!res ||
1436  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1438  {
1439  dblink_res_error(conn, conname, res,
1440  "could not execute command", fail);
1441 
1442  /*
1443  * and save a copy of the command status string to return as our
1444  * result tuple
1445  */
1446  sql_cmd_status = cstring_to_text("ERROR");
1447  }
1448  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1449  {
1450  /*
1451  * and save a copy of the command status string to return as our
1452  * result tuple
1453  */
1454  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1455  PQclear(res);
1456  }
1457  else
1458  {
1459  PQclear(res);
1460  ereport(ERROR,
1461  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1462  errmsg("statement returning results not allowed")));
1463  }
1464  }
1465  PG_CATCH();
1466  {
1467  /* if needed, close the connection to the database */
1468  if (freeconn)
1469  PQfinish(conn);
1470  PG_RE_THROW();
1471  }
1472  PG_END_TRY();
1473 
1474  /* if needed, close the connection to the database */
1475  if (freeconn)
1476  PQfinish(conn);
1477 
1478  PG_RETURN_TEXT_P(sql_cmd_status);
1479 }
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:230
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2220
PGconn * conn
Definition: streamutil.c:45
#define ereport(elevel, rest)
Definition: elog.h:122
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:2944
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
#define PG_CATCH()
Definition: elog.h:293
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
#define PG_RE_THROW()
Definition: elog.h:314
#define BOOLOID
Definition: pg_type.h:288
char * text_to_cstring(const text *t)
Definition: varlena.c:184
int errmsg(const char *fmt,...)
Definition: elog.c:797
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
Definition: c.h:434
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
static char * connstr
Definition: pg_dumpall.c:67
Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 1961 of file dblink.c.

References appendStringInfo(), buf, StringInfoData::data, DefElem::defname, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, initStringInfo(), is_valid_dblink_option(), _PQconninfoOption::keyword, StringInfoData::len, lfirst, NULL, PG_GETARG_DATUM, PG_GETARG_OID, PG_RETURN_VOID, PQconndefaults(), and untransformRelOptions().

1962 {
1963  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
1964  Oid context = PG_GETARG_OID(1);
1965  ListCell *cell;
1966 
1967  static const PQconninfoOption *options = NULL;
1968 
1969  /*
1970  * Get list of valid libpq options.
1971  *
1972  * To avoid unnecessary work, we get the list once and use it throughout
1973  * the lifetime of this backend process. We don't need to care about
1974  * memory context issues, because PQconndefaults allocates with malloc.
1975  */
1976  if (!options)
1977  {
1978  options = PQconndefaults();
1979  if (!options) /* assume reason for failure is OOM */
1980  ereport(ERROR,
1981  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
1982  errmsg("out of memory"),
1983  errdetail("could not get libpq's default connection options")));
1984  }
1985 
1986  /* Validate each supplied option. */
1987  foreach(cell, options_list)
1988  {
1989  DefElem *def = (DefElem *) lfirst(cell);
1990 
1991  if (!is_valid_dblink_option(options, def->defname, context))
1992  {
1993  /*
1994  * Unknown option, or invalid option for the context specified, so
1995  * complain about it. Provide a hint with list of valid options
1996  * for the context.
1997  */
1999  const PQconninfoOption *opt;
2000 
2001  initStringInfo(&buf);
2002  for (opt = options; opt->keyword; opt++)
2003  {
2004  if (is_valid_dblink_option(options, opt->keyword, context))
2005  appendStringInfo(&buf, "%s%s",
2006  (buf.len > 0) ? ", " : "",
2007  opt->keyword);
2008  }
2009  ereport(ERROR,
2010  (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
2011  errmsg("invalid option \"%s\"", def->defname),
2012  errhint("Valid options in this context are: %s",
2013  buf.data)));
2014  }
2015  }
2016 
2017  PG_RETURN_VOID();
2018 }
int errhint(const char *fmt,...)
Definition: elog.c:987
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:224
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:65
#define PG_GETARG_OID(n)
Definition: fmgr.h:231
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
List * untransformRelOptions(Datum options)
Definition: reloptions.c:861
#define PG_RETURN_VOID()
Definition: fmgr.h:293
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1108
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:675
Definition: pg_list.h:45
Datum dblink_fetch ( PG_FUNCTION_ARGS  )

Definition at line 533 of file dblink.c.

References appendStringInfo(), BOOLOID, buf, conn, remoteConn::conn, StringInfoData::data, DBLINK_CONN_NOT_AVAIL, DBLINK_INIT, dblink_res_error(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), materializeResult(), NULL, PG_GETARG_BOOL, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_NARGS, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQexec(), PQresultStatus(), prepTuplestoreResult(), and text_to_cstring().

534 {
535  PGresult *res = NULL;
536  char *conname = NULL;
537  remoteConn *rconn = NULL;
538  PGconn *conn = NULL;
540  char *curname = NULL;
541  int howmany = 0;
542  bool fail = true; /* default to backward compatible */
543 
544  prepTuplestoreResult(fcinfo);
545 
546  DBLINK_INIT;
547 
548  if (PG_NARGS() == 4)
549  {
550  /* text,text,int,bool */
551  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
552  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
553  howmany = PG_GETARG_INT32(2);
554  fail = PG_GETARG_BOOL(3);
555 
556  rconn = getConnectionByName(conname);
557  if (rconn)
558  conn = rconn->conn;
559  }
560  else if (PG_NARGS() == 3)
561  {
562  /* text,text,int or text,int,bool */
563  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
564  {
565  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
566  howmany = PG_GETARG_INT32(1);
567  fail = PG_GETARG_BOOL(2);
568  conn = pconn->conn;
569  }
570  else
571  {
572  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
573  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
574  howmany = PG_GETARG_INT32(2);
575 
576  rconn = getConnectionByName(conname);
577  if (rconn)
578  conn = rconn->conn;
579  }
580  }
581  else if (PG_NARGS() == 2)
582  {
583  /* text,int */
584  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
585  howmany = PG_GETARG_INT32(1);
586  conn = pconn->conn;
587  }
588 
589  if (!conn)
591 
592  initStringInfo(&buf);
593  appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
594 
595  /*
596  * Try to execute the query. Note that since libpq uses malloc, the
597  * PGresult will be long-lived even though we are still in a short-lived
598  * memory context.
599  */
600  res = PQexec(conn, buf.data);
601  if (!res ||
602  (PQresultStatus(res) != PGRES_COMMAND_OK &&
604  {
605  dblink_res_error(conn, conname, res,
606  "could not fetch from cursor", fail);
607  return (Datum) 0;
608  }
609  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
610  {
611  /* cursor does not exist - closed already or bad name */
612  PQclear(res);
613  ereport(ERROR,
614  (errcode(ERRCODE_INVALID_CURSOR_NAME),
615  errmsg("cursor \"%s\" does not exist", curname)));
616  }
617 
618  materializeResult(fcinfo, conn, res);
619  return (Datum) 0;
620 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:225
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:230
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2220
PGconn * conn
Definition: streamutil.c:45
static char * buf
Definition: pg_test_fsync.c:65
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
uintptr_t Datum
Definition: postgres.h:374
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
#define BOOLOID
Definition: pg_type.h:288
char * text_to_cstring(const text *t)
Definition: varlena.c:184
int errmsg(const char *fmt,...)
Definition: elog.c:797
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1263 of file dblink.c.

References accumArrayResult(), CStringGetTextDatum, CurrentMemoryContext, hash_seq_init(), hash_seq_search(), makeArrayResult(), remoteConnHashEnt::name, NULL, PG_RETURN_ARRAYTYPE_P, PG_RETURN_NULL, status(), and TEXTOID.

1264 {
1266  remoteConnHashEnt *hentry;
1267  ArrayBuildState *astate = NULL;
1268 
1269  if (remoteConnHash)
1270  {
1271  hash_seq_init(&status, remoteConnHash);
1272  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1273  {
1274  /* stash away current value */
1275  astate = accumArrayResult(astate,
1276  CStringGetTextDatum(hentry->name),
1277  false, TEXTOID, CurrentMemoryContext);
1278  }
1279  }
1280 
1281  if (astate)
1284  else
1285  PG_RETURN_NULL();
1286 }
#define TEXTOID
Definition: pg_type.h:324
char name[NAMEDATALEN]
Definition: dblink.c:142
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:246
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5055
#define NULL
Definition: c.h:226
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1353
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1343
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:4991
#define CStringGetTextDatum(s)
Definition: builtins.h:90
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
#define PG_RETURN_NULL()
Definition: fmgr.h:289
Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

Definition at line 1881 of file dblink.c.

References pgNotify::be_pid, conn, remoteConn::conn, CreateTemplateTupleDesc(), CStringGetTextDatum, DBLINK_GET_NAMED_CONN, DBLINK_INIT, DBLINK_NOTIFY_COLS, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, pgNotify::extra, Int32GetDatum, INT4OID, MemoryContextSwitchTo(), NULL, PG_NARGS, PQconsumeInput(), PQfreemem(), PQnotifies(), prepTuplestoreResult(), pgNotify::relname, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, TEXTOID, TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

1882 {
1883  char *conname = NULL;
1884  PGconn *conn = NULL;
1885  remoteConn *rconn = NULL;
1886  PGnotify *notify;
1887  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1888  TupleDesc tupdesc;
1889  Tuplestorestate *tupstore;
1890  MemoryContext per_query_ctx;
1891  MemoryContext oldcontext;
1892 
1893  prepTuplestoreResult(fcinfo);
1894 
1895  DBLINK_INIT;
1896  if (PG_NARGS() == 1)
1898  else
1899  conn = pconn->conn;
1900 
1901  /* create the tuplestore in per-query memory */
1902  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1903  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1904 
1905  tupdesc = CreateTemplateTupleDesc(DBLINK_NOTIFY_COLS, false);
1906  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1907  TEXTOID, -1, 0);
1908  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1909  INT4OID, -1, 0);
1910  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1911  TEXTOID, -1, 0);
1912 
1913  tupstore = tuplestore_begin_heap(true, false, work_mem);
1914  rsinfo->setResult = tupstore;
1915  rsinfo->setDesc = tupdesc;
1916 
1917  MemoryContextSwitchTo(oldcontext);
1918 
1919  PQconsumeInput(conn);
1920  while ((notify = PQnotifies(conn)) != NULL)
1921  {
1923  bool nulls[DBLINK_NOTIFY_COLS];
1924 
1925  memset(values, 0, sizeof(values));
1926  memset(nulls, 0, sizeof(nulls));
1927 
1928  if (notify->relname != NULL)
1929  values[0] = CStringGetTextDatum(notify->relname);
1930  else
1931  nulls[0] = true;
1932 
1933  values[1] = Int32GetDatum(notify->be_pid);
1934 
1935  if (notify->extra != NULL)
1936  values[2] = CStringGetTextDatum(notify->extra);
1937  else
1938  nulls[2] = true;
1939 
1940  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1941 
1942  PQfreemem(notify);
1943  PQconsumeInput(conn);
1944  }
1945 
1946  /* clean up and return the tuplestore */
1947  tuplestore_donestoring(tupstore);
1948 
1949  return (Datum) 0;
1950 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:735
char * extra
Definition: libpq-fe.h:165
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2193
#define TEXTOID
Definition: pg_type.h:324
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define INT4OID
Definition: pg_type.h:316
PGconn * conn
Definition: dblink.c:70
PGconn * conn
Definition: streamutil.c:45
int be_pid
Definition: libpq-fe.h:164
char * relname
Definition: libpq-fe.h:163
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:493
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:316
uintptr_t Datum
Definition: postgres.h:374
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1631
int work_mem
Definition: globals.c:112
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:133
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
Tuplestorestate * setResult
Definition: execnodes.h:204
static Datum values[MAXATTR]
Definition: bootstrap.c:162
ExprContext * econtext
Definition: execnodes.h:197
#define Int32GetDatum(X)
Definition: postgres.h:487
TupleDesc setDesc
Definition: execnodes.h:205
#define CStringGetTextDatum(s)
Definition: builtins.h:90
int16 AttrNumber
Definition: attnum.h:21
void PQfreemem(void *ptr)
Definition: fe-exec.c:3200
Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1490 of file dblink.c.

References AccessShareLock, ACL_SELECT, FuncCallContext::attinmeta, BuildTupleFromCStrings(), FuncCallContext::call_cntr, CreateTemplateTupleDesc(), get_pkey_attnames(), get_rel_from_relname(), HeapTupleGetDatum, INT4OID, FuncCallContext::max_calls, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NULL, palloc(), PG_GETARG_TEXT_P, psprintf(), relation_close(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), FuncCallContext::user_fctx, and values.

1491 {
1492  int16 numatts;
1493  char **results;
1494  FuncCallContext *funcctx;
1495  int32 call_cntr;
1496  int32 max_calls;
1497  AttInMetadata *attinmeta;
1498  MemoryContext oldcontext;
1499 
1500  /* stuff done only on the first call of the function */
1501  if (SRF_IS_FIRSTCALL())
1502  {
1503  Relation rel;
1504  TupleDesc tupdesc;
1505 
1506  /* create a function context for cross-call persistence */
1507  funcctx = SRF_FIRSTCALL_INIT();
1508 
1509  /*
1510  * switch to memory context appropriate for multiple function calls
1511  */
1512  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1513 
1514  /* open target relation */
1516 
1517  /* get the array of attnums */
1518  results = get_pkey_attnames(rel, &numatts);
1519 
1521 
1522  /*
1523  * need a tuple descriptor representing one INT and one TEXT column
1524  */
1525  tupdesc = CreateTemplateTupleDesc(2, false);
1526  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
1527  INT4OID, -1, 0);
1528  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
1529  TEXTOID, -1, 0);
1530 
1531  /*
1532  * Generate attribute metadata needed later to produce tuples from raw
1533  * C strings
1534  */
1535  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1536  funcctx->attinmeta = attinmeta;
1537 
1538  if ((results != NULL) && (numatts > 0))
1539  {
1540  funcctx->max_calls = numatts;
1541 
1542  /* got results, keep track of them */
1543  funcctx->user_fctx = results;
1544  }
1545  else
1546  {
1547  /* fast track when no results */
1548  MemoryContextSwitchTo(oldcontext);
1549  SRF_RETURN_DONE(funcctx);
1550  }
1551 
1552  MemoryContextSwitchTo(oldcontext);
1553  }
1554 
1555  /* stuff done on every call of the function */
1556  funcctx = SRF_PERCALL_SETUP();
1557 
1558  /*
1559  * initialize per-call variables
1560  */
1561  call_cntr = funcctx->call_cntr;
1562  max_calls = funcctx->max_calls;
1563 
1564  results = (char **) funcctx->user_fctx;
1565  attinmeta = funcctx->attinmeta;
1566 
1567  if (call_cntr < max_calls) /* do when there is more left to send */
1568  {
1569  char **values;
1570  HeapTuple tuple;
1571  Datum result;
1572 
1573  values = (char **) palloc(2 * sizeof(char *));
1574  values[0] = psprintf("%d", call_cntr + 1);
1575  values[1] = results[call_cntr];
1576 
1577  /* build the tuple */
1578  tuple = BuildTupleFromCStrings(attinmeta, values);
1579 
1580  /* make the tuple into a datum */
1581  result = HeapTupleGetDatum(tuple);
1582 
1583  SRF_RETURN_NEXT(funcctx, result);
1584  }
1585  else
1586  {
1587  /* do when there is no more left */
1588  SRF_RETURN_DONE(funcctx);
1589  }
1590 }
uint64 call_cntr
Definition: funcapi.h:65
signed short int16
Definition: c.h:252
#define TEXTOID
Definition: pg_type.h:324
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:285
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define INT4OID
Definition: pg_type.h:316
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:289
signed int int32
Definition: c.h:253
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1115
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:291
AttInMetadata * attinmeta
Definition: funcapi.h:99
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:493
uintptr_t Datum
Definition: postgres.h:374
#define ACL_SELECT
Definition: parsenodes.h:66
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1068
#define NULL
Definition: c.h:226
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:109
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:222
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void * user_fctx
Definition: funcapi.h:90
void * palloc(Size size)
Definition: mcxt.c:891
#define PG_GETARG_TEXT_P(n)
Definition: fmgr.h:269
int16 AttrNumber
Definition: attnum.h:21
uint64 max_calls
Definition: funcapi.h:74
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:309
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:287
Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 661 of file dblink.c.

References dblink_record_internal().

662 {
663  return dblink_record_internal(fcinfo, true);
664 }
Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1298 of file dblink.c.

References conn, DBLINK_GET_NAMED_CONN, DBLINK_INIT, NULL, PG_RETURN_INT32, PQconsumeInput(), and PQisBusy().

1299 {
1300  char *conname = NULL;
1301  PGconn *conn = NULL;
1302  remoteConn *rconn = NULL;
1303 
1304  DBLINK_INIT;
1306 
1307  PQconsumeInput(conn);
1308  PG_RETURN_INT32(PQisBusy(conn));
1309 }
#define PG_RETURN_INT32(x)
Definition: fmgr.h:298
PGconn * conn
Definition: streamutil.c:45
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1631
#define NULL
Definition: c.h:226
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1681
Datum dblink_open ( PG_FUNCTION_ARGS  )

Definition at line 353 of file dblink.c.

References appendStringInfo(), BOOLOID, buf, conn, remoteConn::conn, cstring_to_text(), StringInfoData::data, DBLINK_CONN_NOT_AVAIL, DBLINK_INIT, dblink_res_error(), DBLINK_RES_INTERNALERROR, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), remoteConn::newXactForCursor, NULL, remoteConn::openCursorCount, pconn, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), PQTRANS_IDLE, PQtransactionStatus(), text_to_cstring(), and TRUE.

354 {
355  char *msg;
356  PGresult *res = NULL;
357  PGconn *conn = NULL;
358  char *curname = NULL;
359  char *sql = NULL;
360  char *conname = NULL;
362  remoteConn *rconn = NULL;
363  bool fail = true; /* default to backward compatible behavior */
364 
365  DBLINK_INIT;
366  initStringInfo(&buf);
367 
368  if (PG_NARGS() == 2)
369  {
370  /* text,text */
371  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
373  rconn = pconn;
374  }
375  else if (PG_NARGS() == 3)
376  {
377  /* might be text,text,text or text,text,bool */
378  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
379  {
380  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
382  fail = PG_GETARG_BOOL(2);
383  rconn = pconn;
384  }
385  else
386  {
387  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
388  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
390  rconn = getConnectionByName(conname);
391  }
392  }
393  else if (PG_NARGS() == 4)
394  {
395  /* text,text,text,bool */
396  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
397  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
399  fail = PG_GETARG_BOOL(3);
400  rconn = getConnectionByName(conname);
401  }
402 
403  if (!rconn || !rconn->conn)
405  else
406  conn = rconn->conn;
407 
408  /* If we are not in a transaction, start one */
409  if (PQtransactionStatus(conn) == PQTRANS_IDLE)
410  {
411  res = PQexec(conn, "BEGIN");
412  if (PQresultStatus(res) != PGRES_COMMAND_OK)
413  DBLINK_RES_INTERNALERROR("begin error");
414  PQclear(res);
415  rconn->newXactForCursor = TRUE;
416 
417  /*
418  * Since transaction state was IDLE, we force cursor count to
419  * initially be 0. This is needed as a previous ABORT might have wiped
420  * out our transaction without maintaining the cursor count for us.
421  */
422  rconn->openCursorCount = 0;
423  }
424 
425  /* if we started a transaction, increment cursor count */
426  if (rconn->newXactForCursor)
427  (rconn->openCursorCount)++;
428 
429  appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
430  res = PQexec(conn, buf.data);
431  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
432  {
433  dblink_res_error(conn, conname, res, "could not open cursor", fail);
435  }
436 
437  PQclear(res);
439 }
int openCursorCount
Definition: dblink.c:71
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:230
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2220
PGconn * conn
Definition: streamutil.c:45
static char * buf
Definition: pg_test_fsync.c:65
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:5915
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
bool newXactForCursor
Definition: dblink.c:72
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:314
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
#define BOOLOID
Definition: pg_type.h:288
char * text_to_cstring(const text *t)
Definition: varlena.c:184
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
#define TRUE
Definition: c.h:214
Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 627 of file dblink.c.

References dblink_record_internal().

628 {
629  return dblink_record_internal(fcinfo, false);
630 }
static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 667 of file dblink.c.

References BOOLOID, conn, remoteConn::conn, connstr, DBLINK_CONN_NOT_AVAIL, DBLINK_GET_CONN, DBLINK_GET_NAMED_CONN, DBLINK_INIT, dblink_res_error(), elog, ERROR, FunctionCallInfoData::flinfo, get_fn_expr_argtype(), materializeQueryResult(), materializeResult(), NULL, PG_CATCH, PG_END_TRY, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RE_THROW, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQfinish(), PQgetResult(), PQresultStatus(), prepTuplestoreResult(), and text_to_cstring().

Referenced by dblink_get_result(), and dblink_record().

668 {
669  PGconn *volatile conn = NULL;
670  volatile bool freeconn = false;
671 
672  prepTuplestoreResult(fcinfo);
673 
674  DBLINK_INIT;
675 
676  PG_TRY();
677  {
678  char *msg;
679  char *connstr = NULL;
680  char *sql = NULL;
681  char *conname = NULL;
682  remoteConn *rconn = NULL;
683  bool fail = true; /* default to backward compatible */
684 
685  if (!is_async)
686  {
687  if (PG_NARGS() == 3)
688  {
689  /* text,text,bool */
692  fail = PG_GETARG_BOOL(2);
693  }
694  else if (PG_NARGS() == 2)
695  {
696  /* text,text or text,bool */
697  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
698  {
699  conn = pconn->conn;
701  fail = PG_GETARG_BOOL(1);
702  }
703  else
704  {
707  }
708  }
709  else if (PG_NARGS() == 1)
710  {
711  /* text */
712  conn = pconn->conn;
714  }
715  else
716  /* shouldn't happen */
717  elog(ERROR, "wrong number of arguments");
718  }
719  else /* is_async */
720  {
721  /* get async result */
722  if (PG_NARGS() == 2)
723  {
724  /* text,bool */
726  fail = PG_GETARG_BOOL(1);
727  }
728  else if (PG_NARGS() == 1)
729  {
730  /* text */
732  }
733  else
734  /* shouldn't happen */
735  elog(ERROR, "wrong number of arguments");
736  }
737 
738  if (!conn)
740 
741  if (!is_async)
742  {
743  /* synchronous query, use efficient tuple collection method */
744  materializeQueryResult(fcinfo, conn, conname, sql, fail);
745  }
746  else
747  {
748  /* async result retrieval, do it the old way */
749  PGresult *res = PQgetResult(conn);
750 
751  /* NULL means we're all done with the async results */
752  if (res)
753  {
754  if (PQresultStatus(res) != PGRES_COMMAND_OK &&
756  {
757  dblink_res_error(conn, conname, res,
758  "could not execute query", fail);
759  /* if fail isn't set, we'll return an empty query result */
760  }
761  else
762  {
763  materializeResult(fcinfo, conn, res);
764  }
765  }
766  }
767  }
768  PG_CATCH();
769  {
770  /* if needed, close the connection to the database */
771  if (freeconn)
772  PQfinish(conn);
773  PG_RE_THROW();
774  }
775  PG_END_TRY();
776 
777  /* if needed, close the connection to the database */
778  if (freeconn)
779  PQfinish(conn);
780 
781  return (Datum) 0;
782 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:230
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
PGconn * conn
Definition: dblink.c:70
FmgrInfo * flinfo
Definition: fmgr.h:71
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2220
PGconn * conn
Definition: streamutil.c:45
uintptr_t Datum
Definition: postgres.h:374
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
#define PG_RE_THROW()
Definition: elog.h:314
#define BOOLOID
Definition: pg_type.h:288
char * text_to_cstring(const text *t)
Definition: varlena.c:184
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
#define PG_END_TRY()
Definition: elog.h:300
static char * connstr
Definition: pg_dumpall.c:67
static void dblink_res_error ( PGconn conn,
const char *  conname,
PGresult res,
const char *  dblink_context_msg,
bool  fail 
)
static

Definition at line 2671 of file dblink.c.

References ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, MAKE_SQLSTATE, NOTICE, NULL, PG_DIAG_CONTEXT, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SQLSTATE, PQclear(), PQerrorMessage(), PQresultErrorField(), and xpstrdup.

Referenced by dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), and materializeQueryResult().

2673 {
2674  int level;
2675  char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2676  char *pg_diag_message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2677  char *pg_diag_message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2678  char *pg_diag_message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2679  char *pg_diag_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2680  int sqlstate;
2681  char *message_primary;
2682  char *message_detail;
2683  char *message_hint;
2684  char *message_context;
2685  const char *dblink_context_conname = "unnamed";
2686 
2687  if (fail)
2688  level = ERROR;
2689  else
2690  level = NOTICE;
2691 
2692  if (pg_diag_sqlstate)
2693  sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2694  pg_diag_sqlstate[1],
2695  pg_diag_sqlstate[2],
2696  pg_diag_sqlstate[3],
2697  pg_diag_sqlstate[4]);
2698  else
2699  sqlstate = ERRCODE_CONNECTION_FAILURE;
2700 
2701  xpstrdup(message_primary, pg_diag_message_primary);
2702  xpstrdup(message_detail, pg_diag_message_detail);
2703  xpstrdup(message_hint, pg_diag_message_hint);
2704  xpstrdup(message_context, pg_diag_context);
2705 
2706  /*
2707  * If we don't get a message from the PGresult, try the PGconn. This
2708  * is needed because for connection-level failures, PQexec may just
2709  * return NULL, not a PGresult at all.
2710  */
2711  if (message_primary == NULL)
2712  message_primary = PQerrorMessage(conn);
2713 
2714  if (res)
2715  PQclear(res);
2716 
2717  if (conname)
2718  dblink_context_conname = conname;
2719 
2720  ereport(level,
2721  (errcode(sqlstate),
2722  message_primary ? errmsg_internal("%s", message_primary) :
2723  errmsg("could not obtain message string for remote error"),
2724  message_detail ? errdetail_internal("%s", message_detail) : 0,
2725  message_hint ? errhint("%s", message_hint) : 0,
2726  message_context ? errcontext("%s", message_context) : 0,
2727  errcontext("Error occurred on dblink connection named \"%s\": %s.",
2728  dblink_context_conname, dblink_context_msg)));
2729 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
int errhint(const char *fmt,...)
Definition: elog.c:987
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:54
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:55
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:62
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:53
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:56
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NOTICE
Definition: elog.h:37
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2658
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define errcontext
Definition: elog.h:164
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:60
static void dblink_security_check ( PGconn conn,
remoteConn rconn 
)
static

Definition at line 2611 of file dblink.c.

References ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, pfree(), PQconnectionUsedPassword(), PQfinish(), and superuser().

Referenced by dblink_connect().

2612 {
2613  if (!superuser())
2614  {
2615  if (!PQconnectionUsedPassword(conn))
2616  {
2617  PQfinish(conn);
2618  if (rconn)
2619  pfree(rconn);
2620 
2621  ereport(ERROR,
2622  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2623  errmsg("password is required"),
2624  errdetail("Non-superuser cannot connect if the server does not request a password."),
2625  errhint("Target server's authentication method must be changed.")));
2626  }
2627  }
2628 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
bool superuser(void)
Definition: superuser.c:47
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6009
int errmsg(const char *fmt,...)
Definition: elog.c:797
Datum dblink_send_query ( PG_FUNCTION_ARGS  )

Definition at line 634 of file dblink.c.

References conn, DBLINK_GET_NAMED_CONN, elog, ERROR, NOTICE, NULL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_INT32, PQerrorMessage(), PQsendQuery(), and text_to_cstring().

635 {
636  char *conname = NULL;
637  PGconn *conn = NULL;
638  char *sql = NULL;
639  remoteConn *rconn = NULL;
640  int retval;
641 
642  if (PG_NARGS() == 2)
643  {
646  }
647  else
648  /* shouldn't happen */
649  elog(ERROR, "wrong number of arguments");
650 
651  /* async query send */
652  retval = PQsendQuery(conn, sql);
653  if (retval != 1)
654  elog(NOTICE, "could not send query: %s", PQerrorMessage(conn));
655 
656  PG_RETURN_INT32(retval);
657 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
#define PG_RETURN_INT32(x)
Definition: fmgr.h:298
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:45
#define NOTICE
Definition: elog.h:37
#define NULL
Definition: c.h:226
#define PG_NARGS()
Definition: fmgr.h:160
char * text_to_cstring(const text *t)
Definition: varlena.c:184
#define elog
Definition: elog.h:219
static void deleteConnection ( const char *  name)
static

Definition at line 2589 of file dblink.c.

References createConnHash(), ereport, errcode(), errmsg(), ERROR, HASH_REMOVE, hash_search(), pstrdup(), and truncate_identifier().

Referenced by dblink_disconnect().

2590 {
2591  remoteConnHashEnt *hentry;
2592  bool found;
2593  char *key;
2594 
2595  if (!remoteConnHash)
2597 
2598  key = pstrdup(name);
2599  truncate_identifier(key, strlen(key), false);
2601  key, HASH_REMOVE, &found);
2602 
2603  if (!hentry)
2604  ereport(ERROR,
2605  (errcode(ERRCODE_UNDEFINED_OBJECT),
2606  errmsg("undefined connection name")));
2607 
2608 }
char * pstrdup(const char *in)
Definition: mcxt.c:1165
int errcode(int sqlerrcode)
Definition: elog.c:575
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * escape_param_str ( const char *  from)
static

Definition at line 2823 of file dblink.c.

References appendStringInfoChar(), buf, StringInfoData::data, and makeStringInfo().

Referenced by get_connect_string().

2824 {
2825  const char *cp;
2827 
2828  for (cp = str; *cp; cp++)
2829  {
2830  if (*cp == '\\' || *cp == '\'')
2831  appendStringInfoChar(buf, '\\');
2832  appendStringInfoChar(buf, *cp);
2833  }
2834 
2835  return buf->data;
2836 }
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
static char * buf
Definition: pg_test_fsync.c:65
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:201
static char * generate_relation_name ( Relation  rel)
static

Definition at line 2511 of file dblink.c.

References get_namespace_name(), NULL, quote_qualified_identifier(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, and RelationIsVisible().

Referenced by get_sql_delete(), get_sql_insert(), get_sql_update(), and get_tuple_of_interest().

2512 {
2513  char *nspname;
2514  char *result;
2515 
2516  /* Qualify the name if not visible in search path */
2518  nspname = NULL;
2519  else
2520  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2521 
2522  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2523 
2524  return result;
2525 }
Form_pg_class rd_rel
Definition: rel.h:113
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define RelationGetRelationName(relation)
Definition: rel.h:433
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10061
#define NULL
Definition: c.h:226
bool RelationIsVisible(Oid relid)
Definition: namespace.c:681
#define RelationGetRelid(relation)
Definition: rel.h:413
static int get_attnum_pk_pos ( int *  pkattnums,
int  pknumatts,
int  key 
)
static

Definition at line 2361 of file dblink.c.

References i.

Referenced by get_sql_insert(), and get_sql_update().

2362 {
2363  int i;
2364 
2365  /*
2366  * Not likely a long list anyway, so just scan for the value
2367  */
2368  for (i = 0; i < pknumatts; i++)
2369  if (key == pkattnums[i])
2370  return i;
2371 
2372  return -1;
2373 }
int i
static char * get_connect_string ( const char *  servername)
static

Definition at line 2735 of file dblink.c.

References ACL_KIND_FOREIGN_SERVER, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, appendStringInfo(), DefElem::arg, buf, StringInfoData::data, DefElem::defname, ereport, errcode(), errdetail(), errmsg(), ERROR, escape_param_str(), ForeignServer::fdwid, ForeignDataWrapperRelationId, ForeignServerRelationId, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), GetUserMapping(), is_valid_dblink_option(), lfirst, makeStringInfo(), NULL, ForeignDataWrapper::options, ForeignServer::options, UserMapping::options, pg_foreign_server_aclcheck(), PQconndefaults(), pstrdup(), ForeignServer::serverid, ForeignServer::servername, strVal, truncate_identifier(), and UserMappingRelationId.

Referenced by dblink_connect().

2736 {
2737  ForeignServer *foreign_server = NULL;
2738  UserMapping *user_mapping;
2739  ListCell *cell;
2741  ForeignDataWrapper *fdw;
2742  AclResult aclresult;
2743  char *srvname;
2744 
2745  static const PQconninfoOption *options = NULL;
2746 
2747  /*
2748  * Get list of valid libpq options.
2749  *
2750  * To avoid unnecessary work, we get the list once and use it throughout
2751  * the lifetime of this backend process. We don't need to care about
2752  * memory context issues, because PQconndefaults allocates with malloc.
2753  */
2754  if (!options)
2755  {
2756  options = PQconndefaults();
2757  if (!options) /* assume reason for failure is OOM */
2758  ereport(ERROR,
2759  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2760  errmsg("out of memory"),
2761  errdetail("could not get libpq's default connection options")));
2762  }
2763 
2764  /* first gather the server connstr options */
2765  srvname = pstrdup(servername);
2766  truncate_identifier(srvname, strlen(srvname), false);
2767  foreign_server = GetForeignServerByName(srvname, true);
2768 
2769  if (foreign_server)
2770  {
2771  Oid serverid = foreign_server->serverid;
2772  Oid fdwid = foreign_server->fdwid;
2773  Oid userid = GetUserId();
2774 
2775  user_mapping = GetUserMapping(userid, serverid);
2776  fdw = GetForeignDataWrapper(fdwid);
2777 
2778  /* Check permissions, user must have usage on the server. */
2779  aclresult = pg_foreign_server_aclcheck(serverid, userid, ACL_USAGE);
2780  if (aclresult != ACLCHECK_OK)
2781  aclcheck_error(aclresult, ACL_KIND_FOREIGN_SERVER, foreign_server->servername);
2782 
2783  foreach(cell, fdw->options)
2784  {
2785  DefElem *def = lfirst(cell);
2786 
2788  appendStringInfo(buf, "%s='%s' ", def->defname,
2789  escape_param_str(strVal(def->arg)));
2790  }
2791 
2792  foreach(cell, foreign_server->options)
2793  {
2794  DefElem *def = lfirst(cell);
2795 
2797  appendStringInfo(buf, "%s='%s' ", def->defname,
2798  escape_param_str(strVal(def->arg)));
2799  }
2800 
2801  foreach(cell, user_mapping->options)
2802  {
2803 
2804  DefElem *def = lfirst(cell);
2805 
2807  appendStringInfo(buf, "%s='%s' ", def->defname,
2808  escape_param_str(strVal(def->arg)));
2809  }
2810 
2811  return buf->data;
2812  }
2813  else
2814  return NULL;
2815 }
Oid GetUserId(void)
Definition: miscinit.c:283
char * pstrdup(const char *in)
Definition: mcxt.c:1165
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ERROR
Definition: elog.h:43
AclResult pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4497
static char * buf
Definition: pg_test_fsync.c:65
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
int errdetail(const char *fmt,...)
Definition: elog.c:873
List * options
Definition: foreign.h:61
#define ACL_USAGE
Definition: parsenodes.h:73
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:148
#define ereport(elevel, rest)
Definition: elog.h:122
Node * arg
Definition: parsenodes.h:676
List * options
Definition: foreign.h:42
AclResult
Definition: acl.h:170
#define ForeignServerRelationId
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1108
#define ForeignDataWrapperRelationId
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define UserMappingRelationId
char * servername
Definition: foreign.h:50
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:166
char * defname
Definition: parsenodes.h:675
List * options
Definition: foreign.h:53
Oid serverid
Definition: foreign.h:47
static char ** get_pkey_attnames ( Relation  rel,
int16 numatts 
)
static

Definition at line 2033 of file dblink.c.

References AccessShareLock, Anum_pg_index_indrelid, BTEqualStrategyNumber, GETSTRUCT, heap_close, heap_open(), HeapTupleIsValid, i, IndexIndrelidIndexId, IndexRelationId, NULL, ObjectIdGetDatum, palloc(), RelationData::rd_att, RelationGetRelid, ScanKeyInit(), SPI_fname(), systable_beginscan(), systable_endscan(), and systable_getnext().

Referenced by dblink_get_pkey().

2034 {
2035  Relation indexRelation;
2036  ScanKeyData skey;
2037  SysScanDesc scan;
2038  HeapTuple indexTuple;
2039  int i;
2040  char **result = NULL;
2041  TupleDesc tupdesc;
2042 
2043  /* initialize numatts to 0 in case no primary key exists */
2044  *numatts = 0;
2045 
2046  tupdesc = rel->rd_att;
2047 
2048  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2049  indexRelation = heap_open(IndexRelationId, AccessShareLock);
2050  ScanKeyInit(&skey,
2052  BTEqualStrategyNumber, F_OIDEQ,
2054 
2055  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2056  NULL, 1, &skey);
2057 
2058  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2059  {
2060  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2061 
2062  /* we're only interested if it is the primary key */
2063  if (index->indisprimary)
2064  {
2065  *numatts = index->indnatts;
2066  if (*numatts > 0)
2067  {
2068  result = (char **) palloc(*numatts * sizeof(char *));
2069 
2070  for (i = 0; i < *numatts; i++)
2071  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2072  }
2073  break;
2074  }
2075  }
2076 
2077  systable_endscan(scan);
2078  heap_close(indexRelation, AccessShareLock);
2079 
2080  return result;
2081 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:493
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define IndexRelationId
Definition: pg_index.h:29
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:322
#define Anum_pg_index_indrelid
Definition: pg_index.h:75
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:781
Definition: type.h:90
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:410
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
TupleDesc rd_att
Definition: rel.h:114
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
void * palloc(Size size)
Definition: mcxt.c:891
int i
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:413
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define IndexIndrelidIndexId
Definition: indexing.h:162
static Relation get_rel_from_relname ( text relname_text,
LOCKMODE  lockmode,
AclMode  aclmode 
)
static

Definition at line 2486 of file dblink.c.

References ACL_KIND_CLASS, aclcheck_error(), ACLCHECK_OK, GetUserId(), heap_openrv(), makeRangeVarFromNameList(), pg_class_aclcheck(), RelationGetRelationName, RelationGetRelid, and textToQualifiedNameList().

Referenced by dblink_build_sql_delete(), dblink_build_sql_insert(), dblink_build_sql_update(), and dblink_get_pkey().

2487 {
2488  RangeVar *relvar;
2489  Relation rel;
2490  AclResult aclresult;
2491 
2492  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2493  rel = heap_openrv(relvar, lockmode);
2494 
2495  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2496  aclmode);
2497  if (aclresult != ACLCHECK_OK)
2498  aclcheck_error(aclresult, ACL_KIND_CLASS,
2500 
2501  return rel;
2502 }
Oid GetUserId(void)
Definition: miscinit.c:283
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:2857
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
#define RelationGetRelationName(relation)
Definition: rel.h:433
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3071
AclResult
Definition: acl.h:170
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1315
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4397
#define RelationGetRelid(relation)
Definition: rel.h:413
static char * get_sql_delete ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  tgt_pkattvals 
)
static

Definition at line 2222 of file dblink.c.

References appendStringInfo(), appendStringInfoString(), tupleDesc::attrs, buf, StringInfoData::data, generate_relation_name(), i, initStringInfo(), NameStr, NULL, quote_ident_cstr(), quote_literal_cstr(), and RelationData::rd_att.

Referenced by dblink_build_sql_delete().

2223 {
2224  char *relname;
2225  TupleDesc tupdesc;
2227  int i;
2228 
2229  initStringInfo(&buf);
2230 
2231  /* get relation name including any needed schema prefix and quoting */
2232  relname = generate_relation_name(rel);
2233 
2234  tupdesc = rel->rd_att;
2235 
2236  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2237  for (i = 0; i < pknumatts; i++)
2238  {
2239  int pkattnum = pkattnums[i];
2240 
2241  if (i > 0)
2242  appendStringInfoString(&buf, " AND ");
2243 
2245  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2246 
2247  if (tgt_pkattvals[i] != NULL)
2248  appendStringInfo(&buf, " = %s",
2249  quote_literal_cstr(tgt_pkattvals[i]));
2250  else
2251  appendStringInfoString(&buf, " IS NULL");
2252  }
2253 
2254  return (buf.data);
2255 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
Form_pg_attribute * attrs
Definition: tupdesc.h:74
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static char * buf
Definition: pg_test_fsync.c:65
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
TupleDesc rd_att
Definition: rel.h:114
#define NULL
Definition: c.h:226
int i
#define NameStr(name)
Definition: c.h:494
static char * get_sql_insert ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals,
char **  tgt_pkattvals 
)
static

Definition at line 2144 of file dblink.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), tupleDesc::attrs, buf, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), get_attnum_pk_pos(), get_tuple_of_interest(), i, initStringInfo(), NameStr, tupleDesc::natts, NULL, pfree(), pstrdup(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, SPI_getvalue(), and val.

Referenced by dblink_build_sql_insert().

2145 {
2146  char *relname;
2147  HeapTuple tuple;
2148  TupleDesc tupdesc;
2149  int natts;
2151  char *val;
2152  int key;
2153  int i;
2154  bool needComma;
2155 
2156  initStringInfo(&buf);
2157 
2158  /* get relation name including any needed schema prefix and quoting */
2159  relname = generate_relation_name(rel);
2160 
2161  tupdesc = rel->rd_att;
2162  natts = tupdesc->natts;
2163 
2164  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2165  if (!tuple)
2166  ereport(ERROR,
2167  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2168  errmsg("source row not found")));
2169 
2170  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2171 
2172  needComma = false;
2173  for (i = 0; i < natts; i++)
2174  {
2175  if (tupdesc->attrs[i]->attisdropped)
2176  continue;
2177 
2178  if (needComma)
2179  appendStringInfoChar(&buf, ',');
2180 
2182  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2183  needComma = true;
2184  }
2185 
2186  appendStringInfoString(&buf, ") VALUES(");
2187 
2188  /*
2189  * Note: i is physical column number (counting from 0).
2190  */
2191  needComma = false;
2192  for (i = 0; i < natts; i++)
2193  {
2194  if (tupdesc->attrs[i]->attisdropped)
2195  continue;
2196 
2197  if (needComma)
2198  appendStringInfoChar(&buf, ',');
2199 
2200  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2201 
2202  if (key >= 0)
2203  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2204  else
2205  val = SPI_getvalue(tuple, tupdesc, i + 1);
2206 
2207  if (val != NULL)
2208  {
2210  pfree(val);
2211  }
2212  else
2213  appendStringInfoString(&buf, "NULL");
2214  needComma = true;
2215  }
2216  appendStringInfoChar(&buf, ')');
2217 
2218  return (buf.data);
2219 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
char * pstrdup(const char *in)
Definition: mcxt.c:1165
Form_pg_attribute * attrs
Definition: tupdesc.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:73
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:803
void pfree(void *pointer)
Definition: mcxt.c:992
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static char * buf
Definition: pg_test_fsync.c:65
#define ereport(elevel, rest)
Definition: elog.h:122
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:201
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
TupleDesc rd_att
Definition: rel.h:114
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:494
long val
Definition: informix.c:689
static char * get_sql_update ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals,
char **  tgt_pkattvals 
)
static

Definition at line 2258 of file dblink.c.

References appendStringInfo(), appendStringInfoString(), tupleDesc::attrs, buf, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), get_attnum_pk_pos(), get_tuple_of_interest(), i, initStringInfo(), NameStr, tupleDesc::natts, NULL, pfree(), pstrdup(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, SPI_getvalue(), and val.

Referenced by dblink_build_sql_update().

2259 {
2260  char *relname;
2261  HeapTuple tuple;
2262  TupleDesc tupdesc;
2263  int natts;
2265  char *val;
2266  int key;
2267  int i;
2268  bool needComma;
2269 
2270  initStringInfo(&buf);
2271 
2272  /* get relation name including any needed schema prefix and quoting */
2273  relname = generate_relation_name(rel);
2274 
2275  tupdesc = rel->rd_att;
2276  natts = tupdesc->natts;
2277 
2278  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2279  if (!tuple)
2280  ereport(ERROR,
2281  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2282  errmsg("source row not found")));
2283 
2284  appendStringInfo(&buf, "UPDATE %s SET ", relname);
2285 
2286  /*
2287  * Note: i is physical column number (counting from 0).
2288  */
2289  needComma = false;
2290  for (i = 0; i < natts; i++)
2291  {
2292  if (tupdesc->attrs[i]->attisdropped)
2293  continue;
2294 
2295  if (needComma)
2296  appendStringInfoString(&buf, ", ");
2297 
2298  appendStringInfo(&buf, "%s = ",
2299  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2300 
2301  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2302 
2303  if (key >= 0)
2304  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2305  else
2306  val = SPI_getvalue(tuple, tupdesc, i + 1);
2307 
2308  if (val != NULL)
2309  {
2311  pfree(val);
2312  }
2313  else
2314  appendStringInfoString(&buf, "NULL");
2315  needComma = true;
2316  }
2317 
2318  appendStringInfoString(&buf, " WHERE ");
2319 
2320  for (i = 0; i < pknumatts; i++)
2321  {
2322  int pkattnum = pkattnums[i];
2323 
2324  if (i > 0)
2325  appendStringInfoString(&buf, " AND ");
2326 
2328  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2329 
2330  val = tgt_pkattvals[i];
2331 
2332  if (val != NULL)
2333  appendStringInfo(&buf, " = %s", quote_literal_cstr(val));
2334  else
2335  appendStringInfoString(&buf, " IS NULL");
2336  }
2337 
2338  return (buf.data);
2339 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
char * pstrdup(const char *in)
Definition: mcxt.c:1165
Form_pg_attribute * attrs
Definition: tupdesc.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:73
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:803
void pfree(void *pointer)
Definition: mcxt.c:992
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static char * buf
Definition: pg_test_fsync.c:65
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
TupleDesc rd_att
Definition: rel.h:114
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:494
long val
Definition: informix.c:689
static char ** get_text_array_contents ( ArrayType array,
int *  numitems 
)
static

Definition at line 2088 of file dblink.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, ARR_NULLBITMAP, ArrayGetNItems(), Assert, att_addlength_pointer, att_align_nominal, get_typlenbyvalalign(), i, NULL, palloc(), PointerGetDatum, TextDatumGetCString, TEXTOID, and values.

Referenced by dblink_build_sql_delete(), dblink_build_sql_insert(), and dblink_build_sql_update().

2089 {
2090  int ndim = ARR_NDIM(array);
2091  int *dims = ARR_DIMS(array);
2092  int nitems;
2093  int16 typlen;
2094  bool typbyval;
2095  char typalign;
2096  char **values;
2097  char *ptr;
2098  bits8 *bitmap;
2099  int bitmask;
2100  int i;
2101 
2102  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2103 
2104  *numitems = nitems = ArrayGetNItems(ndim, dims);
2105 
2107  &typlen, &typbyval, &typalign);
2108 
2109  values = (char **) palloc(nitems * sizeof(char *));
2110 
2111  ptr = ARR_DATA_PTR(array);
2112  bitmap = ARR_NULLBITMAP(array);
2113  bitmask = 1;
2114 
2115  for (i = 0; i < nitems; i++)
2116  {
2117  if (bitmap && (*bitmap & bitmask) == 0)
2118  {
2119  values[i] = NULL;
2120  }
2121  else
2122  {
2123  values[i] = TextDatumGetCString(PointerGetDatum(ptr));
2124  ptr = att_addlength_pointer(ptr, typlen, ptr);
2125  ptr = (char *) att_align_nominal(ptr, typalign);
2126  }
2127 
2128  /* advance bitmap pointer if any */
2129  if (bitmap)
2130  {
2131  bitmask <<= 1;
2132  if (bitmask == 0x100)
2133  {
2134  bitmap++;
2135  bitmask = 1;
2136  }
2137  }
2138  }
2139 
2140  return values;
2141 }
signed short int16
Definition: c.h:252
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:144
#define TEXTOID
Definition: pg_type.h:324
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:1989
#define PointerGetDatum(X)
Definition: postgres.h:564
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:275
#define ARR_DATA_PTR(a)
Definition: array.h:303
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:172
uint8 bits8
Definition: c.h:272
#define TextDatumGetCString(d)
Definition: builtins.h:91
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define ARR_NDIM(a)
Definition: array.h:271
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void * palloc(Size size)
Definition: mcxt.c:891
int i
#define ARR_ELEMTYPE(a)
Definition: array.h:273
#define ARR_NULLBITMAP(a)
Definition: array.h:281
static HeapTuple get_tuple_of_interest ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals 
)
static

Definition at line 2376 of file dblink.c.

References appendStringInfo(), appendStringInfoString(), tupleDesc::attrs, buf, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), i, initStringInfo(), NameStr, tupleDesc::natts, NULL, pfree(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, SPI_connect(), SPI_copytuple(), SPI_exec(), SPI_finish(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, and SPITupleTable::vals.

Referenced by get_sql_insert(), and get_sql_update().

2377 {
2378  char *relname;
2379  TupleDesc tupdesc;
2380  int natts;
2382  int ret;
2383  HeapTuple tuple;
2384  int i;
2385 
2386  /*
2387  * Connect to SPI manager
2388  */
2389  if ((ret = SPI_connect()) < 0)
2390  /* internal error */
2391  elog(ERROR, "SPI connect failure - returned %d", ret);
2392 
2393  initStringInfo(&buf);
2394 
2395  /* get relation name including any needed schema prefix and quoting */
2396  relname = generate_relation_name(rel);
2397 
2398  tupdesc = rel->rd_att;
2399  natts = tupdesc->natts;
2400 
2401  /*
2402  * Build sql statement to look up tuple of interest, ie, the one matching
2403  * src_pkattvals. We used to use "SELECT *" here, but it's simpler to
2404  * generate a result tuple that matches the table's physical structure,
2405  * with NULLs for any dropped columns. Otherwise we have to deal with two
2406  * different tupdescs and everything's very confusing.
2407  */
2408  appendStringInfoString(&buf, "SELECT ");
2409 
2410  for (i = 0; i < natts; i++)
2411  {
2412  if (i > 0)
2413  appendStringInfoString(&buf, ", ");
2414 
2415  if (tupdesc->attrs[i]->attisdropped)
2416  appendStringInfoString(&buf, "NULL");
2417  else
2419  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2420  }
2421 
2422  appendStringInfo(&buf, " FROM %s WHERE ", relname);
2423 
2424  for (i = 0; i < pknumatts; i++)
2425  {
2426  int pkattnum = pkattnums[i];
2427 
2428  if (i > 0)
2429  appendStringInfoString(&buf, " AND ");
2430 
2432  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2433 
2434  if (src_pkattvals[i] != NULL)
2435  appendStringInfo(&buf, " = %s",
2436  quote_literal_cstr(src_pkattvals[i]));
2437  else
2438  appendStringInfoString(&buf, " IS NULL");
2439  }
2440 
2441  /*
2442  * Retrieve the desired tuple
2443  */
2444  ret = SPI_exec(buf.data, 0);
2445  pfree(buf.data);
2446 
2447  /*
2448  * Only allow one qualifying tuple
2449  */
2450  if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
2451  ereport(ERROR,
2452  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2453  errmsg("source criteria matched more than one record")));
2454 
2455  else if (ret == SPI_OK_SELECT && SPI_processed == 1)
2456  {
2457  SPITupleTable *tuptable = SPI_tuptable;
2458 
2459  tuple = SPI_copytuple(tuptable->vals[0]);
2460  SPI_finish();
2461 
2462  return tuple;
2463  }
2464  else
2465  {
2466  /*
2467  * no qualifying tuples
2468  */
2469  SPI_finish();
2470 
2471  return NULL;
2472  }
2473 
2474  /*
2475  * never reached, but keep compiler quiet
2476  */
2477  return NULL;
2478 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:147
Form_pg_attribute * attrs
Definition: tupdesc.h:74
SPITupleTable * SPI_tuptable
Definition: spi.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTuple SPI_copytuple(HeapTuple tuple)
Definition: spi.c:630
HeapTuple * vals
Definition: spi.h:27
int natts
Definition: tupdesc.h:73
uint64 SPI_processed
Definition: spi.c:39
void pfree(void *pointer)
Definition: mcxt.c:992
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
#define ERROR
Definition: elog.h:43
int SPI_exec(const char *src, long tcount)
Definition: spi.c:331
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static char * buf
Definition: pg_test_fsync.c:65
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
TupleDesc rd_att
Definition: rel.h:114
#define SPI_OK_SELECT
Definition: spi.h:51
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:494
#define elog
Definition: elog.h:219
static remoteConn * getConnectionByName ( const char *  name)
static

Definition at line 2529 of file dblink.c.

References createConnHash(), HASH_FIND, hash_search(), NULL, pstrdup(), remoteConnHashEnt::rconn, and truncate_identifier().

Referenced by dblink_close(), dblink_disconnect(), dblink_fetch(), and dblink_open().

2530 {
2531  remoteConnHashEnt *hentry;
2532  char *key;
2533 
2534  if (!remoteConnHash)
2536 
2537  key = pstrdup(name);
2538  truncate_identifier(key, strlen(key), false);
2540  key, HASH_FIND, NULL);
2541 
2542  if (hentry)
2543  return (hentry->rconn);
2544 
2545  return (NULL);
2546 }
char * pstrdup(const char *in)
Definition: mcxt.c:1165
remoteConn * rconn
Definition: dblink.c:143
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
#define NULL
Definition: c.h:226
const char * name
Definition: encode.c:521
static bool is_valid_dblink_option ( const PQconninfoOption options,
const char *  option,
Oid  context 
)
static

Definition at line 2925 of file dblink.c.

References _PQconninfoOption::dispchar, ForeignServerRelationId, _PQconninfoOption::keyword, NULL, and UserMappingRelationId.

Referenced by dblink_fdw_validator(), and get_connect_string().

2927 {
2928  const PQconninfoOption *opt;
2929 
2930  /* Look up the option in libpq result */
2931  for (opt = options; opt->keyword; opt++)
2932  {
2933  if (strcmp(opt->keyword, option) == 0)
2934  break;
2935  }
2936  if (opt->keyword == NULL)
2937  return false;
2938 
2939  /* Disallow debug options (particularly "replication") */
2940  if (strchr(opt->dispchar, 'D'))
2941  return false;
2942 
2943  /* Disallow "client_encoding" */
2944  if (strcmp(opt->keyword, "client_encoding") == 0)
2945  return false;
2946 
2947  /*
2948  * If the option is "user" or marked secure, it should be specified only
2949  * in USER MAPPING. Others should be specified only in SERVER.
2950  */
2951  if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
2952  {
2953  if (context != UserMappingRelationId)
2954  return false;
2955  }
2956  else
2957  {
2958  if (context != ForeignServerRelationId)
2959  return false;
2960  }
2961 
2962  return true;
2963 }
#define ForeignServerRelationId
#define NULL
Definition: c.h:226
#define UserMappingRelationId
static void materializeQueryResult ( FunctionCallInfo  fcinfo,
PGconn conn,
const char *  conname,
const char *  sql,
bool  fail 
)
static

Definition at line 965 of file dblink.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Assert, BuildTupleFromCStrings(), CreateTemplateTupleDesc(), CurrentMemoryContext, dblink_res_error(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, MemoryContextDelete(), MemoryContextSwitchTo(), NULL, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQgetResult(), PQresultStatus(), FunctionCallInfoData::resultinfo, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, storeQueryResult(), TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_puttuple(), values, and work_mem.

Referenced by dblink_record_internal().

970 {
971  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
972  PGresult *volatile res = NULL;
973  volatile storeInfo sinfo;
974 
975  /* prepTuplestoreResult must have been called previously */
976  Assert(rsinfo->returnMode == SFRM_Materialize);
977 
978  /* initialize storeInfo to empty */
979  memset((void *) &sinfo, 0, sizeof(sinfo));
980  sinfo.fcinfo = fcinfo;
981 
982  PG_TRY();
983  {
984  /* Create short-lived memory context for data conversions */
985  sinfo.tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
986  "dblink temporary context",
988 
989  /* execute query, collecting any tuples into the tuplestore */
990  res = storeQueryResult(&sinfo, conn, sql);
991 
992  if (!res ||
993  (PQresultStatus(res) != PGRES_COMMAND_OK &&
995  {
996  /*
997  * dblink_res_error will clear the passed PGresult, so we need
998  * this ugly dance to avoid doing so twice during error exit
999  */
1000  PGresult *res1 = res;
1001 
1002  res = NULL;
1003  dblink_res_error(conn, conname, res1,
1004  "could not execute query", fail);
1005  /* if fail isn't set, we'll return an empty query result */
1006  }
1007  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1008  {
1009  /*
1010  * storeRow didn't get called, so we need to convert the command
1011  * status string to a tuple manually
1012  */
1013  TupleDesc tupdesc;
1014  AttInMetadata *attinmeta;
1015  Tuplestorestate *tupstore;
1016  HeapTuple tuple;
1017  char *values[1];
1018  MemoryContext oldcontext;
1019 
1020  /*
1021  * need a tuple descriptor representing one TEXT column to return
1022  * the command status string as our result tuple
1023  */
1024  tupdesc = CreateTemplateTupleDesc(1, false);
1025  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1026  TEXTOID, -1, 0);
1027  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1028 
1029  oldcontext = MemoryContextSwitchTo(
1030  rsinfo->econtext->ecxt_per_query_memory);
1031  tupstore = tuplestore_begin_heap(true, false, work_mem);
1032  rsinfo->setResult = tupstore;
1033  rsinfo->setDesc = tupdesc;
1034  MemoryContextSwitchTo(oldcontext);
1035 
1036  values[0] = PQcmdStatus(res);
1037 
1038  /* build the tuple and put it into the tuplestore. */
1039  tuple = BuildTupleFromCStrings(attinmeta, values);
1040  tuplestore_puttuple(tupstore, tuple);
1041 
1042  PQclear(res);
1043  res = NULL;
1044  }
1045  else
1046  {
1048  /* storeRow should have created a tuplestore */
1049  Assert(rsinfo->setResult != NULL);
1050 
1051  PQclear(res);
1052  res = NULL;
1053  }
1054 
1055  /* clean up data conversion short-lived memory context */
1056  if (sinfo.tmpcontext != NULL)
1057  MemoryContextDelete(sinfo.tmpcontext);
1058  sinfo.tmpcontext = NULL;
1059 
1060  PQclear(sinfo.last_res);
1061  sinfo.last_res = NULL;
1062  PQclear(sinfo.cur_res);
1063  sinfo.cur_res = NULL;
1064  }
1065  PG_CATCH();
1066  {
1067  /* be sure to release any libpq result we collected */
1068  PQclear(res);
1069  PQclear(sinfo.last_res);
1070  PQclear(sinfo.cur_res);
1071  /* and clear out any pending data in libpq */
1072  while ((res = PQgetResult(conn)) != NULL)
1073  PQclear(res);
1074  PG_RE_THROW();
1075  }
1076  PG_END_TRY();
1077 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define TEXTOID
Definition: pg_type.h:324
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1115
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:715
fmNodePtr resultinfo
Definition: fmgr.h:73
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:493
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:316
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:2944
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1068
int work_mem
Definition: globals.c:112
void PQclear(PGresult *res)
Definition: fe-exec.c:650
SetFunctionReturnMode returnMode
Definition: execnodes.h:201
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define PG_RE_THROW()
Definition: elog.h:314
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:133
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
Tuplestorestate * setResult
Definition: execnodes.h:204
static Datum values[MAXATTR]
Definition: bootstrap.c:162
ExprContext * econtext
Definition: execnodes.h:197
TupleDesc setDesc
Definition: execnodes.h:205
#define PG_TRY()
Definition: elog.h:284
int16 AttrNumber
Definition: attnum.h:21
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
#define PG_END_TRY()
Definition: elog.h:300
static void materializeResult ( FunctionCallInfo  fcinfo,
PGconn conn,
PGresult res 
)
static

Definition at line 819 of file dblink.c.

References applyRemoteGucs(), Assert, BuildTupleFromCStrings(), CreateTemplateTupleDesc(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, get_call_result_type(), i, MemoryContextSwitchTo(), tupleDesc::natts, NULL, palloc(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), restoreLocalGucs(), FunctionCallInfoData::resultinfo, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, values, and work_mem.

Referenced by dblink_fetch(), and dblink_record_internal().

820 {
821  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
822 
823  /* prepTuplestoreResult must have been called previously */
824  Assert(rsinfo->returnMode == SFRM_Materialize);
825 
826  PG_TRY();
827  {
828  TupleDesc tupdesc;
829  bool is_sql_cmd;
830  int ntuples;
831  int nfields;
832 
833  if (PQresultStatus(res) == PGRES_COMMAND_OK)
834  {
835  is_sql_cmd = true;
836 
837  /*
838  * need a tuple descriptor representing one TEXT column to return
839  * the command status string as our result tuple
840  */
841  tupdesc = CreateTemplateTupleDesc(1, false);
842  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
843  TEXTOID, -1, 0);
844  ntuples = 1;
845  nfields = 1;
846  }
847  else
848  {
850 
851  is_sql_cmd = false;
852 
853  /* get a tuple descriptor for our result type */
854  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
855  {
856  case TYPEFUNC_COMPOSITE:
857  /* success */
858  break;
859  case TYPEFUNC_RECORD:
860  /* failed to determine actual type of RECORD */
861  ereport(ERROR,
862  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
863  errmsg("function returning record called in context "
864  "that cannot accept type record")));
865  break;
866  default:
867  /* result type isn't composite */
868  elog(ERROR, "return type must be a row type");
869  break;
870  }
871 
872  /* make sure we have a persistent copy of the tupdesc */
873  tupdesc = CreateTupleDescCopy(tupdesc);
874  ntuples = PQntuples(res);
875  nfields = PQnfields(res);
876  }
877 
878  /*
879  * check result and tuple descriptor have the same number of columns
880  */
881  if (nfields != tupdesc->natts)
882  ereport(ERROR,
883  (errcode(ERRCODE_DATATYPE_MISMATCH),
884  errmsg("remote query result rowtype does not match "
885  "the specified FROM clause rowtype")));
886 
887  if (ntuples > 0)
888  {
889  AttInMetadata *attinmeta;
890  int nestlevel = -1;
891  Tuplestorestate *tupstore;
892  MemoryContext oldcontext;
893  int row;
894  char **values;
895 
896  attinmeta = TupleDescGetAttInMetadata(tupdesc);
897 
898  /* Set GUCs to ensure we read GUC-sensitive data types correctly */
899  if (!is_sql_cmd)
900  nestlevel = applyRemoteGucs(conn);
901 
902  oldcontext = MemoryContextSwitchTo(
904  tupstore = tuplestore_begin_heap(true, false, work_mem);
905  rsinfo->setResult = tupstore;
906  rsinfo->setDesc = tupdesc;
907  MemoryContextSwitchTo(oldcontext);
908 
909  values = (char **) palloc(nfields * sizeof(char *));
910 
911  /* put all tuples into the tuplestore */
912  for (row = 0; row < ntuples; row++)
913  {
914  HeapTuple tuple;
915 
916  if (!is_sql_cmd)
917  {
918  int i;
919 
920  for (i = 0; i < nfields; i++)
921  {
922  if (PQgetisnull(res, row, i))
923  values[i] = NULL;
924  else
925  values[i] = PQgetvalue(res, row, i);
926  }
927  }
928  else
929  {
930  values[0] = PQcmdStatus(res);
931  }
932 
933  /* build the tuple and put it into the tuplestore. */
934  tuple = BuildTupleFromCStrings(attinmeta, values);
935  tuplestore_puttuple(tupstore, tuple);
936  }
937 
938  /* clean up GUC settings, if we changed any */
939  restoreLocalGucs(nestlevel);
940 
941  /* clean up and return the tuplestore */
942  tuplestore_donestoring(tupstore);
943  }
944 
945  PQclear(res);
946  }
947  PG_CATCH();
948  {
949  /* be sure to release the libpq result */
950  PQclear(res);
951  PG_RE_THROW();
952  }
953  PG_END_TRY();
954 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2681
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:141
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
#define TEXTOID
Definition: pg_type.h:324
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
int natts
Definition: tupdesc.h:73
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1115
#define ERROR
Definition: elog.h:43
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:715
fmNodePtr resultinfo
Definition: fmgr.h:73
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:493
#define ereport(elevel, rest)
Definition: elog.h:122
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:316
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:2944
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1068
int work_mem
Definition: globals.c:112
void PQclear(PGresult *res)
Definition: fe-exec.c:650
SetFunctionReturnMode returnMode
Definition: execnodes.h:201
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define PG_RE_THROW()
Definition: elog.h:314
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:133
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
Tuplestorestate * setResult
Definition: execnodes.h:204
static Datum values[MAXATTR]
Definition: bootstrap.c:162
ExprContext * econtext
Definition: execnodes.h:197
TupleDesc setDesc
Definition: execnodes.h:205
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3092
#define PG_TRY()
Definition: elog.h:284
int16 AttrNumber
Definition: attnum.h:21
#define PG_END_TRY()
Definition: elog.h:300
PG_FUNCTION_INFO_V1 ( dblink_connect  )
PG_FUNCTION_INFO_V1 ( dblink_disconnect  )
PG_FUNCTION_INFO_V1 ( dblink_open  )
PG_FUNCTION_INFO_V1 ( dblink_close  )
PG_FUNCTION_INFO_V1 ( dblink_fetch  )
PG_FUNCTION_INFO_V1 ( dblink_record  )
PG_FUNCTION_INFO_V1 ( dblink_send_query  )
PG_FUNCTION_INFO_V1 ( dblink_get_result  )
PG_FUNCTION_INFO_V1 ( dblink_get_connections  )
PG_FUNCTION_INFO_V1 ( dblink_is_busy  )
PG_FUNCTION_INFO_V1 ( dblink_cancel_query  )
PG_FUNCTION_INFO_V1 ( dblink_error_message  )
PG_FUNCTION_INFO_V1 ( dblink_exec  )
PG_FUNCTION_INFO_V1 ( dblink_get_pkey  )
PG_FUNCTION_INFO_V1 ( dblink_build_sql_insert  )
PG_FUNCTION_INFO_V1 ( dblink_build_sql_delete  )
PG_FUNCTION_INFO_V1 ( dblink_build_sql_update  )
PG_FUNCTION_INFO_V1 ( dblink_current_query  )
PG_FUNCTION_INFO_V1 ( dblink_get_notify  )
PG_FUNCTION_INFO_V1 ( dblink_fdw_validator  )
static void prepTuplestoreResult ( FunctionCallInfo  fcinfo)
static

Definition at line 791 of file dblink.c.

References ReturnSetInfo::allowedModes, ereport, errcode(), errmsg(), ERROR, IsA, NULL, FunctionCallInfoData::resultinfo, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, and SFRM_Materialize.

Referenced by dblink_fetch(), dblink_get_notify(), and dblink_record_internal().

792 {
793  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
794 
795  /* check to see if query supports us returning a tuplestore */
796  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
797  ereport(ERROR,
798  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
799  errmsg("set-valued function called in context that cannot accept a set")));
800  if (!(rsinfo->allowedModes & SFRM_Materialize))
801  ereport(ERROR,
802  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
803  errmsg("materialize mode required, but it is not allowed in this context")));
804 
805  /* let the executor know we're sending back a tuplestore */
806  rsinfo->returnMode = SFRM_Materialize;
807 
808  /* caller must fill these to return a non-empty result */
809  rsinfo->setResult = NULL;
810  rsinfo->setDesc = NULL;
811 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
fmNodePtr resultinfo
Definition: fmgr.h:73
#define ereport(elevel, rest)
Definition: elog.h:122
int allowedModes
Definition: execnodes.h:199
SetFunctionReturnMode returnMode
Definition: execnodes.h:201
#define NULL
Definition: c.h:226
Tuplestorestate * setResult
Definition: execnodes.h:204
TupleDesc setDesc
Definition: execnodes.h:205
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * quote_ident_cstr ( char *  rawstr)
static

Definition at line 2346 of file dblink.c.

References cstring_to_text(), DatumGetTextP, DirectFunctionCall1, PointerGetDatum, quote_ident(), and text_to_cstring().

Referenced by get_sql_delete(), get_sql_insert(), get_sql_update(), and get_tuple_of_interest().

2347 {
2348  text *rawstr_text;
2349  text *result_text;
2350  char *result;
2351 
2352  rawstr_text = cstring_to_text(rawstr);
2354  PointerGetDatum(rawstr_text)));
2355  result = text_to_cstring(result_text);
2356 
2357  return result;
2358 }
#define PointerGetDatum(X)
Definition: postgres.h:564
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:555
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:24
text * cstring_to_text(const char *s)
Definition: varlena.c:151
#define DatumGetTextP(X)
Definition: fmgr.h:248
char * text_to_cstring(const text *t)
Definition: varlena.c:184
Definition: c.h:434
static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3028 of file dblink.c.

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

3029 {
3030  /* Do nothing if no new nestlevel was created */
3031  if (nestlevel > 0)
3032  AtEOXact_GUC(true, nestlevel);
3033 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5040
static PGresult * storeQueryResult ( volatile storeInfo sinfo,
PGconn conn,
const char *  sql 
)
static

Definition at line 1083 of file dblink.c.

References applyRemoteGucs(), CHECK_FOR_INTERRUPTS, storeInfo::cur_res, elog, ERROR, storeInfo::last_res, NULL, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQgetResult(), PQresultStatus(), PQsendQuery(), PQsetSingleRowMode(), restoreLocalGucs(), and storeRow().

Referenced by materializeQueryResult().

1084 {
1085  bool first = true;
1086  int nestlevel = -1;
1087  PGresult *res;
1088 
1089  if (!PQsendQuery(conn, sql))
1090  elog(ERROR, "could not send query: %s", PQerrorMessage(conn));
1091 
1092  if (!PQsetSingleRowMode(conn)) /* shouldn't fail */
1093  elog(ERROR, "failed to set single-row mode for dblink query");
1094 
1095  for (;;)
1096  {
1098 
1099  sinfo->cur_res = PQgetResult(conn);
1100  if (!sinfo->cur_res)
1101  break;
1102 
1103  if (PQresultStatus(sinfo->cur_res) == PGRES_SINGLE_TUPLE)
1104  {
1105  /* got one row from possibly-bigger resultset */
1106 
1107  /*
1108  * Set GUCs to ensure we read GUC-sensitive data types correctly.
1109  * We shouldn't do this until we have a row in hand, to ensure
1110  * libpq has seen any earlier ParameterStatus protocol messages.
1111  */
1112  if (first && nestlevel < 0)
1113  nestlevel = applyRemoteGucs(conn);
1114 
1115  storeRow(sinfo, sinfo->cur_res, first);
1116 
1117  PQclear(sinfo->cur_res);
1118  sinfo->cur_res = NULL;
1119  first = false;
1120  }
1121  else
1122  {
1123  /* if empty resultset, fill tuplestore header */
1124  if (first && PQresultStatus(sinfo->cur_res) == PGRES_TUPLES_OK)
1125  storeRow(sinfo, sinfo->cur_res, first);
1126 
1127  /* store completed result at last_res */
1128  PQclear(sinfo->last_res);
1129  sinfo->last_res = sinfo->cur_res;
1130  sinfo->cur_res = NULL;
1131  first = true;
1132  }
1133  }
1134 
1135  /* clean up GUC settings, if we changed any */
1136  restoreLocalGucs(nestlevel);
1137 
1138  /* return last_res */
1139  res = sinfo->last_res;
1140  sinfo->last_res = NULL;
1141  return res;
1142 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
#define ERROR
Definition: elog.h:43
int PQsetSingleRowMode(PGconn *conn)
Definition: fe-exec.c:1604
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:226
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define elog
Definition: elog.h:219
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
static void storeRow ( volatile storeInfo sinfo,
PGresult res,
bool  first 
)
static

Definition at line 1151 of file dblink.c.

References Assert, storeInfo::attinmeta, BuildTupleFromCStrings(), CreateTupleDescCopy(), storeInfo::cstrs, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, storeInfo::fcinfo, get_call_result_type(), i, MemoryContextReset(), MemoryContextSwitchTo(), NULL, palloc(), pfree(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), FunctionCallInfoData::resultinfo, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, storeInfo::tmpcontext, TupleDescGetAttInMetadata(), storeInfo::tuplestore, tuplestore_begin_heap(), tuplestore_end(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, and work_mem.

Referenced by storeQueryResult().

1152 {
1153  int nfields = PQnfields(res);
1154  HeapTuple tuple;
1155  int i;
1156  MemoryContext oldcontext;
1157 
1158  if (first)
1159  {
1160  /* Prepare for new result set */
1161  ReturnSetInfo *rsinfo = (ReturnSetInfo *) sinfo->fcinfo->resultinfo;
1162  TupleDesc tupdesc;
1163 
1164  /*
1165  * It's possible to get more than one result set if the query string
1166  * contained multiple SQL commands. In that case, we follow PQexec's
1167  * traditional behavior of throwing away all but the last result.
1168  */
1169  if (sinfo->tuplestore)
1170  tuplestore_end(sinfo->tuplestore);
1171  sinfo->tuplestore = NULL;
1172 
1173  /* get a tuple descriptor for our result type */
1174  switch (get_call_result_type(sinfo->fcinfo, NULL, &tupdesc))
1175  {
1176  case TYPEFUNC_COMPOSITE:
1177  /* success */
1178  break;
1179  case TYPEFUNC_RECORD:
1180  /* failed to determine actual type of RECORD */
1181  ereport(ERROR,
1182  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1183  errmsg("function returning record called in context "
1184  "that cannot accept type record")));
1185  break;
1186  default:
1187  /* result type isn't composite */
1188  elog(ERROR, "return type must be a row type");
1189  break;
1190  }
1191 
1192  /* make sure we have a persistent copy of the tupdesc */
1193  tupdesc = CreateTupleDescCopy(tupdesc);
1194 
1195  /* check result and tuple descriptor have the same number of columns */
1196  if (nfields != tupdesc->natts)
1197  ereport(ERROR,
1198  (errcode(ERRCODE_DATATYPE_MISMATCH),
1199  errmsg("remote query result rowtype does not match "
1200  "the specified FROM clause rowtype")));
1201 
1202  /* Prepare attinmeta for later data conversions */
1203  sinfo->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1204 
1205  /* Create a new, empty tuplestore */
1206  oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1207  sinfo->tuplestore = tuplestore_begin_heap(true, false, work_mem);
1208  rsinfo->setResult = sinfo->tuplestore;
1209  rsinfo->setDesc = tupdesc;
1210  MemoryContextSwitchTo(oldcontext);
1211 
1212  /* Done if empty resultset */
1213  if (PQntuples(res) == 0)
1214  return;
1215 
1216  /*
1217  * Set up sufficiently-wide string pointers array; this won't change
1218  * in size so it's easy to preallocate.
1219  */
1220  if (sinfo->cstrs)
1221  pfree(sinfo->cstrs);
1222  sinfo->cstrs = (char **) palloc(nfields * sizeof(char *));
1223  }
1224 
1225  /* Should have a single-row result if we get here */
1226  Assert(PQntuples(res) == 1);
1227 
1228  /*
1229  * Do the following work in a temp context that we reset after each tuple.
1230  * This cleans up not only the data we have direct access to, but any
1231  * cruft the I/O functions might leak.
1232  */
1233  oldcontext = MemoryContextSwitchTo(sinfo->tmpcontext);
1234 
1235  /*
1236  * Fill cstrs with null-terminated strings of column values.
1237  */
1238  for (i = 0; i < nfields; i++)
1239  {
1240  if (PQgetisnull(res, 0, i))
1241  sinfo->cstrs[i] = NULL;
1242  else
1243  sinfo->cstrs[i] = PQgetvalue(res, 0, i);
1244  }
1245 
1246  /* Convert row to a tuple, and add it to the tuplestore */
1247  tuple = BuildTupleFromCStrings(sinfo->attinmeta, sinfo->cstrs);
1248 
1249  tuplestore_puttuple(sinfo->tuplestore, tuple);
1250 
1251  /* Clean up */
1252  MemoryContextSwitchTo(oldcontext);
1253  MemoryContextReset(sinfo->tmpcontext);
1254 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2681
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:141
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1115
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:715
#define ereport(elevel, rest)
Definition: elog.h:122
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:316
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1068
int work_mem
Definition: globals.c:112
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:450
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:133
Tuplestorestate * setResult
Definition: execnodes.h:204
ExprContext * econtext
Definition: execnodes.h:197
TupleDesc setDesc
Definition: execnodes.h:205
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3092
static void validate_pkattnums ( Relation  rel,
int2vector pkattnums_arg,
int32  pknumatts_arg,
int **  pkattnums,
int *  pknumatts 
)
static

Definition at line 2854 of file dblink.c.

References tupleDesc::attrs, int2vector::dim1, ereport, errcode(), errmsg(), ERROR, i, Min, tupleDesc::natts, palloc(), RelationData::rd_att, and int2vector::values.

Referenced by dblink_build_sql_delete(), dblink_build_sql_insert(), and dblink_build_sql_update().

2857 {
2858  TupleDesc tupdesc = rel->rd_att;
2859  int natts = tupdesc->natts;
2860  int i;
2861 
2862  /* Don't take more array elements than there are */
2863  pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2864 
2865  /* Must have at least one pk attnum selected */
2866  if (pknumatts_arg <= 0)
2867  ereport(ERROR,
2868  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2869  errmsg("number of key attributes must be > 0")));
2870 
2871  /* Allocate output array */
2872  *pkattnums = (int *) palloc(pknumatts_arg * sizeof(int));
2873  *pknumatts = pknumatts_arg;
2874 
2875  /* Validate attnums and convert to internal form */
2876  for (i = 0; i < pknumatts_arg; i++)
2877  {
2878  int pkattnum = pkattnums_arg->values[i];
2879  int lnum;
2880  int j;
2881 
2882  /* Can throw error immediately if out of range */
2883  if (pkattnum <= 0 || pkattnum > natts)
2884  ereport(ERROR,
2885  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2886  errmsg("invalid attribute number %d", pkattnum)));
2887 
2888  /* Identify which physical column has this logical number */
2889  lnum = 0;
2890  for (j = 0; j < natts; j++)
2891  {
2892  /* dropped columns don't count */
2893  if (tupdesc->attrs[j]->attisdropped)
2894  continue;
2895 
2896  if (++lnum == pkattnum)
2897  break;
2898  }
2899 
2900  if (j < natts)
2901  (*pkattnums)[i] = j;
2902  else
2903  ereport(ERROR,
2904  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2905  errmsg("invalid attribute number %d", pkattnum)));
2906  }
2907 }
#define Min(x, y)
Definition: c.h:801
Form_pg_attribute * attrs
Definition: tupdesc.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:73
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int dim1
Definition: c.h:468
TupleDesc rd_att
Definition: rel.h:114
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:470
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i

Variable Documentation

remoteConn* pconn = NULL
static

Definition at line 130 of file dblink.c.

Referenced by dblink_close(), and dblink_open().

PG_MODULE_MAGIC

Definition at line 66 of file dblink.c.

HTAB* remoteConnHash = NULL
static

Definition at line 131 of file dblink.c.