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 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 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)
 
static char * xpstrdup (const char *in)
 
static void pg_attribute_noreturn ()
 
static void dblink_get_conn (char *conname_or_str, PGconn *volatile *conn_p, char **conname_p, volatile bool *freeconn_p)
 
static PGconndblink_get_named_conn (const char *conname)
 
static void dblink_init (void)
 
 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_NOTIFY_COLS   3

Definition at line 1874 of file dblink.c.

Referenced by dblink_get_notify().

#define NUMCONN   16

Definition at line 145 of file dblink.c.

Referenced by createConnHash().

Typedef Documentation

Function Documentation

static int applyRemoteGucs ( PGconn conn)
static

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

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

Definition at line 2544 of file dblink.c.

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

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

2545 {
2546  HASHCTL ctl;
2547 
2548  ctl.keysize = NAMEDATALEN;
2549  ctl.entrysize = sizeof(remoteConnHashEnt);
2550 
2551  return hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
2552 }
#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 2555 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().

2556 {
2557  remoteConnHashEnt *hentry;
2558  bool found;
2559  char *key;
2560 
2561  if (!remoteConnHash)
2563 
2564  key = pstrdup(name);
2565  truncate_identifier(key, strlen(key), true);
2566  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2567  HASH_ENTER, &found);
2568 
2569  if (found)
2570  {
2571  PQfinish(rconn->conn);
2572  pfree(rconn);
2573 
2574  ereport(ERROR,
2576  errmsg("duplicate connection name")));
2577  }
2578 
2579  hentry->rconn = rconn;
2580  strlcpy(hentry->name, name, sizeof(hentry->name));
2581 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
remoteConn * rconn
Definition: dblink.c:141
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
char name[NAMEDATALEN]
Definition: dblink.c:140
PGconn * conn
Definition: dblink.c:68
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
void pfree(void *pointer)
Definition: mcxt.c:950
#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:31
Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1702 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_PP, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

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

Definition at line 1611 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_PP, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

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

Definition at line 1779 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_PP, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

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

Definition at line 1326 of file dblink.c.

References conn, cstring_to_text(), dblink_get_named_conn(), dblink_init(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PQcancel(), PQfreeCancel(), PQgetCancel(), and text_to_cstring().

1327 {
1328  int res;
1329  PGconn *conn;
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:3712
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: streamutil.c:42
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:3689
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:330
text * cstring_to_text(const char *s)
Definition: varlena.c:149
char * text_to_cstring(const text *t)
Definition: varlena.c:182
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:3844
Datum dblink_close ( PG_FUNCTION_ARGS  )

Definition at line 452 of file dblink.c.

References appendStringInfo(), BOOLOID, buf, conn, remoteConn::conn, cstring_to_text(), StringInfoData::data, dblink_init(), dblink_res_error(), 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().

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

Definition at line 250 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, pchomp(), pfree(), PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PQclientEncoding(), PQconnectdb(), PQerrorMessage(), PQfinish(), PQsetClientEncoding(), PQstatus(), text_to_cstring(), and TopMemoryContext.

251 {
252  char *conname_or_str = NULL;
253  char *connstr = NULL;
254  char *connname = NULL;
255  char *msg;
256  PGconn *conn = NULL;
257  remoteConn *rconn = NULL;
258 
259  dblink_init();
260 
261  if (PG_NARGS() == 2)
262  {
263  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
264  connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
265  }
266  else if (PG_NARGS() == 1)
267  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
268 
269  if (connname)
271  sizeof(remoteConn));
272 
273  /* first check for valid foreign data server */
274  connstr = get_connect_string(conname_or_str);
275  if (connstr == NULL)
276  connstr = conname_or_str;
277 
278  /* check password in connection string if not superuser */
279  dblink_connstr_check(connstr);
280  conn = PQconnectdb(connstr);
281 
282  if (PQstatus(conn) == CONNECTION_BAD)
283  {
284  msg = pchomp(PQerrorMessage(conn));
285  PQfinish(conn);
286  if (rconn)
287  pfree(rconn);
288 
289  ereport(ERROR,
290  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
291  errmsg("could not establish connection"),
292  errdetail_internal("%s", msg)));
293  }
294 
295  /* check password actually used if not superuser */
296  dblink_security_check(conn, rconn);
297 
298  /* attempt to set client encoding to match server encoding, if needed */
299  if (PQclientEncoding(conn) != GetDatabaseEncoding())
301 
302  if (connname)
303  {
304  rconn->conn = conn;
305  createNewConnection(connname, rconn);
306  }
307  else
308  {
309  if (pconn->conn)
310  PQfinish(pconn->conn);
311  pconn->conn = conn;
312  }
313 
315 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6071
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
char * pchomp(const char *in)
Definition: mcxt.c:1101
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:42
#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:6079
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:330
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define NULL
Definition: c.h:229
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1021
#define PG_NARGS()
Definition: fmgr.h:168
char * text_to_cstring(const text *t)
Definition: varlena.c:182
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:5958
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:526
static char * connstr
Definition: pg_dumpall.c:64
static void dblink_connstr_check ( const char *  connstr)
static

Definition at line 2632 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

2633 {
2634  if (!superuser())
2635  {
2638  bool connstr_gives_password = false;
2639 
2640  options = PQconninfoParse(connstr, NULL);
2641  if (options)
2642  {
2643  for (option = options; option->keyword != NULL; option++)
2644  {
2645  if (strcmp(option->keyword, "password") == 0)
2646  {
2647  if (option->val != NULL && option->val[0] != '\0')
2648  {
2649  connstr_gives_password = true;
2650  break;
2651  }
2652  }
2653  }
2654  PQconninfoFree(options);
2655  }
2656 
2657  if (!connstr_gives_password)
2658  ereport(ERROR,
2659  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2660  errmsg("password is required"),
2661  errdetail("Non-superusers must provide a password in the connection string.")));
2662  }
2663 }
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:4655
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5861
#define ereport(elevel, rest)
Definition: elog.h:122
static char ** options
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * connstr
Definition: pg_dumpall.c:64
Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1860 of file dblink.c.

References current_query(), and PG_RETURN_DATUM.

1861 {
1862  /* This is now just an alias for the built-in function current_query() */
1863  PG_RETURN_DATUM(current_query(fcinfo));
1864 }
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:191
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:313
Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 322 of file dblink.c.

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

323 {
324  char *conname = NULL;
325  remoteConn *rconn = NULL;
326  PGconn *conn = NULL;
327 
328  dblink_init();
329 
330  if (PG_NARGS() == 1)
331  {
332  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
333  rconn = getConnectionByName(conname);
334  if (rconn)
335  conn = rconn->conn;
336  }
337  else
338  conn = pconn->conn;
339 
340  if (!conn)
341  dblink_conn_not_avail(conname);
342 
343  PQfinish(conn);
344  if (rconn)
345  {
346  deleteConnection(conname);
347  pfree(rconn);
348  }
349  else
350  pconn->conn = NULL;
351 
353 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
void pfree(void *pointer)
Definition: mcxt.c:950
PGconn * conn
Definition: streamutil.c:42
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:330
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:168
char * text_to_cstring(const text *t)
Definition: varlena.c:182
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, pchomp(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PQerrorMessage(), and text_to_cstring().

1360 {
1361  char *msg;
1362  PGconn *conn;
1363 
1364  dblink_init();
1366 
1367  msg = PQerrorMessage(conn);
1368  if (msg == NULL || msg[0] == '\0')
1370  else
1372 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
char * pchomp(const char *in)
Definition: mcxt.c:1101
PGconn * conn
Definition: streamutil.c:42
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:330
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define NULL
Definition: c.h:229
char * text_to_cstring(const text *t)
Definition: varlena.c:182
Datum dblink_exec ( PG_FUNCTION_ARGS  )

Definition at line 1379 of file dblink.c.

References BOOLOID, conn, remoteConn::conn, cstring_to_text(), 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().

1380 {
1381  text *volatile sql_cmd_status = NULL;
1382  PGconn *volatile conn = NULL;
1383  volatile bool freeconn = false;
1384 
1385  dblink_init();
1386 
1387  PG_TRY();
1388  {
1389  PGresult *res = NULL;
1390  char *sql = NULL;
1391  char *conname = NULL;
1392  bool fail = true; /* default to backward compatible behavior */
1393 
1394  if (PG_NARGS() == 3)
1395  {
1396  /* must be text,text,bool */
1397  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1399  fail = PG_GETARG_BOOL(2);
1400  dblink_get_conn(conname, &conn, &conname, &freeconn);
1401  }
1402  else if (PG_NARGS() == 2)
1403  {
1404  /* might be text,text or text,bool */
1405  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1406  {
1408  fail = PG_GETARG_BOOL(1);
1409  conn = pconn->conn;
1410  }
1411  else
1412  {
1413  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1415  dblink_get_conn(conname, &conn, &conname, &freeconn);
1416  }
1417  }
1418  else if (PG_NARGS() == 1)
1419  {
1420  /* must be single text argument */
1421  conn = pconn->conn;
1423  }
1424  else
1425  /* shouldn't happen */
1426  elog(ERROR, "wrong number of arguments");
1427 
1428  if (!conn)
1429  dblink_conn_not_avail(conname);
1430 
1431  res = PQexec(conn, sql);
1432  if (!res ||
1433  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1435  {
1436  dblink_res_error(conn, conname, res,
1437  "could not execute command", fail);
1438 
1439  /*
1440  * and save a copy of the command status string to return as our
1441  * result tuple
1442  */
1443  sql_cmd_status = cstring_to_text("ERROR");
1444  }
1445  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1446  {
1447  /*
1448  * and save a copy of the command status string to return as our
1449  * result tuple
1450  */
1451  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1452  PQclear(res);
1453  }
1454  else
1455  {
1456  PQclear(res);
1457  ereport(ERROR,
1458  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1459  errmsg("statement returning results not allowed")));
1460  }
1461  }
1462  PG_CATCH();
1463  {
1464  /* if needed, close the connection to the database */
1465  if (freeconn)
1466  PQfinish(conn);
1467  PG_RE_THROW();
1468  }
1469  PG_END_TRY();
1470 
1471  /* if needed, close the connection to the database */
1472  if (freeconn)
1473  PQfinish(conn);
1474 
1475  PG_RETURN_TEXT_P(sql_cmd_status);
1476 }
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:239
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1909
PGconn * conn
Definition: streamutil.c:42
#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:330
#define PG_CATCH()
Definition: elog.h:293
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:168
#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:182
int errmsg(const char *fmt,...)
Definition: elog.c:797
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
Definition: c.h:439
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

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

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

Definition at line 538 of file dblink.c.

References appendStringInfo(), BOOLOID, buf, conn, remoteConn::conn, StringInfoData::data, 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().

539 {
540  PGresult *res = NULL;
541  char *conname = NULL;
542  remoteConn *rconn = NULL;
543  PGconn *conn = NULL;
545  char *curname = NULL;
546  int howmany = 0;
547  bool fail = true; /* default to backward compatible */
548 
549  prepTuplestoreResult(fcinfo);
550 
551  dblink_init();
552 
553  if (PG_NARGS() == 4)
554  {
555  /* text,text,int,bool */
556  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
557  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
558  howmany = PG_GETARG_INT32(2);
559  fail = PG_GETARG_BOOL(3);
560 
561  rconn = getConnectionByName(conname);
562  if (rconn)
563  conn = rconn->conn;
564  }
565  else if (PG_NARGS() == 3)
566  {
567  /* text,text,int or text,int,bool */
568  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
569  {
570  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
571  howmany = PG_GETARG_INT32(1);
572  fail = PG_GETARG_BOOL(2);
573  conn = pconn->conn;
574  }
575  else
576  {
577  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
578  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
579  howmany = PG_GETARG_INT32(2);
580 
581  rconn = getConnectionByName(conname);
582  if (rconn)
583  conn = rconn->conn;
584  }
585  }
586  else if (PG_NARGS() == 2)
587  {
588  /* text,int */
589  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
590  howmany = PG_GETARG_INT32(1);
591  conn = pconn->conn;
592  }
593 
594  if (!conn)
595  dblink_conn_not_avail(conname);
596 
597  initStringInfo(&buf);
598  appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
599 
600  /*
601  * Try to execute the query. Note that since libpq uses malloc, the
602  * PGresult will be long-lived even though we are still in a short-lived
603  * memory context.
604  */
605  res = PQexec(conn, buf.data);
606  if (!res ||
607  (PQresultStatus(res) != PGRES_COMMAND_OK &&
609  {
610  dblink_res_error(conn, conname, res,
611  "could not fetch from cursor", fail);
612  return (Datum) 0;
613  }
614  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
615  {
616  /* cursor does not exist - closed already or bad name */
617  PQclear(res);
618  ereport(ERROR,
619  (errcode(ERRCODE_INVALID_CURSOR_NAME),
620  errmsg("cursor \"%s\" does not exist", curname)));
621  }
622 
623  materializeResult(fcinfo, conn, res);
624  return (Datum) 0;
625 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:234
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:239
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
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:1909
PGconn * conn
Definition: streamutil.c:42
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:372
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:168
#define BOOLOID
Definition: pg_type.h:288
char * text_to_cstring(const text *t)
Definition: varlena.c:182
int errmsg(const char *fmt,...)
Definition: elog.c:797
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
static void dblink_get_conn ( char *  conname_or_str,
PGconn *volatile *  conn_p,
char **  conname_p,
volatile bool freeconn_p 
)
static

Definition at line 178 of file dblink.c.

References conn, remoteConn::conn, CONNECTION_BAD, connstr, dblink_connstr_check(), dblink_security_check(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_connect_string(), getConnectionByName(), GetDatabaseEncoding(), GetDatabaseEncodingName(), NULL, pchomp(), PQclientEncoding(), PQconnectdb(), PQerrorMessage(), PQfinish(), PQsetClientEncoding(), and PQstatus().

Referenced by dblink_exec(), and dblink_record_internal().

180 {
181  remoteConn *rconn = getConnectionByName(conname_or_str);
182  PGconn *conn;
183  char *conname;
184  bool freeconn;
185 
186  if (rconn)
187  {
188  conn = rconn->conn;
189  conname = conname_or_str;
190  freeconn = false;
191  }
192  else
193  {
194  const char *connstr;
195 
196  connstr = get_connect_string(conname_or_str);
197  if (connstr == NULL)
198  connstr = conname_or_str;
199  dblink_connstr_check(connstr);
200  conn = PQconnectdb(connstr);
201  if (PQstatus(conn) == CONNECTION_BAD)
202  {
203  char *msg = pchomp(PQerrorMessage(conn));
204  PQfinish(conn);
205  ereport(ERROR,
206  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
207  errmsg("could not establish connection"),
208  errdetail_internal("%s", msg)));
209  }
210  dblink_security_check(conn, rconn);
211  if (PQclientEncoding(conn) != GetDatabaseEncoding())
213  freeconn = true;
214  conname = NULL;
215  }
216 
217  *conn_p = conn;
218  *conname_p = conname;
219  *freeconn_p = freeconn;
220 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6071
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
PGconn * conn
Definition: dblink.c:68
char * pchomp(const char *in)
Definition: mcxt.c:1101
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:42
#define ereport(elevel, rest)
Definition: elog.h:122
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6079
#define NULL
Definition: c.h:229
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1021
int errmsg(const char *fmt,...)
Definition: elog.c:797
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:5958
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:526
static char * connstr
Definition: pg_dumpall.c:64
Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1267 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.

1268 {
1270  remoteConnHashEnt *hentry;
1271  ArrayBuildState *astate = NULL;
1272 
1273  if (remoteConnHash)
1274  {
1275  hash_seq_init(&status, remoteConnHash);
1276  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1277  {
1278  /* stash away current value */
1279  astate = accumArrayResult(astate,
1280  CStringGetTextDatum(hentry->name),
1281  false, TEXTOID, CurrentMemoryContext);
1282  }
1283  }
1284 
1285  if (astate)
1288  else
1289  PG_RETURN_NULL();
1290 }
#define TEXTOID
Definition: pg_type.h:324
char name[NAMEDATALEN]
Definition: dblink.c:140
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:229
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:91
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
#define PG_RETURN_NULL()
Definition: fmgr.h:305
static PGconn* dblink_get_named_conn ( const char *  conname)
static

Definition at line 223 of file dblink.c.

References remoteConn::conn, getConnectionByName(), and NULL.

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

224 {
225  remoteConn *rconn = getConnectionByName(conname);
226  if (rconn)
227  return rconn->conn;
228 
229  dblink_conn_not_avail(conname);
230  return NULL; /* keep compiler quiet */
231 }
PGconn * conn
Definition: dblink.c:68
#define NULL
Definition: c.h:229
Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

Definition at line 1878 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_GETARG_TEXT_PP, PG_NARGS, PQconsumeInput(), PQfreemem(), PQnotifies(), prepTuplestoreResult(), pgNotify::relname, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, text_to_cstring(), TEXTOID, TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

1879 {
1880  PGconn *conn;
1881  PGnotify *notify;
1882  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1883  TupleDesc tupdesc;
1884  Tuplestorestate *tupstore;
1885  MemoryContext per_query_ctx;
1886  MemoryContext oldcontext;
1887 
1888  prepTuplestoreResult(fcinfo);
1889 
1890  dblink_init();
1891  if (PG_NARGS() == 1)
1893  else
1894  conn = pconn->conn;
1895 
1896  /* create the tuplestore in per-query memory */
1897  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1898  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1899 
1900  tupdesc = CreateTemplateTupleDesc(DBLINK_NOTIFY_COLS, false);
1901  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1902  TEXTOID, -1, 0);
1903  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1904  INT4OID, -1, 0);
1905  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1906  TEXTOID, -1, 0);
1907 
1908  tupstore = tuplestore_begin_heap(true, false, work_mem);
1909  rsinfo->setResult = tupstore;
1910  rsinfo->setDesc = tupdesc;
1911 
1912  MemoryContextSwitchTo(oldcontext);
1913 
1914  PQconsumeInput(conn);
1915  while ((notify = PQnotifies(conn)) != NULL)
1916  {
1918  bool nulls[DBLINK_NOTIFY_COLS];
1919 
1920  memset(values, 0, sizeof(values));
1921  memset(nulls, 0, sizeof(nulls));
1922 
1923  if (notify->relname != NULL)
1924  values[0] = CStringGetTextDatum(notify->relname);
1925  else
1926  nulls[0] = true;
1927 
1928  values[1] = Int32GetDatum(notify->be_pid);
1929 
1930  if (notify->extra != NULL)
1931  values[2] = CStringGetTextDatum(notify->extra);
1932  else
1933  nulls[2] = true;
1934 
1935  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1936 
1937  PQfreemem(notify);
1938  PQconsumeInput(conn);
1939  }
1940 
1941  /* clean up and return the tuplestore */
1942  tuplestore_donestoring(tupstore);
1943 
1944  return (Datum) 0;
1945 }
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
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
PGconn * conn
Definition: streamutil.c:42
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:372
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1631
int work_mem
Definition: globals.c:112
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:168
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:201
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
Tuplestorestate * setResult
Definition: execnodes.h:272
static Datum values[MAXATTR]
Definition: bootstrap.c:162
char * text_to_cstring(const text *t)
Definition: varlena.c:182
ExprContext * econtext
Definition: execnodes.h:265
#define Int32GetDatum(X)
Definition: postgres.h:485
TupleDesc setDesc
Definition: execnodes.h:273
#define CStringGetTextDatum(s)
Definition: builtins.h:91
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 1487 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_PP, psprintf(), relation_close(), result, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), FuncCallContext::user_fctx, and values.

1488 {
1489  int16 numatts;
1490  char **results;
1491  FuncCallContext *funcctx;
1492  int32 call_cntr;
1493  int32 max_calls;
1494  AttInMetadata *attinmeta;
1495  MemoryContext oldcontext;
1496 
1497  /* stuff done only on the first call of the function */
1498  if (SRF_IS_FIRSTCALL())
1499  {
1500  Relation rel;
1501  TupleDesc tupdesc;
1502 
1503  /* create a function context for cross-call persistence */
1504  funcctx = SRF_FIRSTCALL_INIT();
1505 
1506  /*
1507  * switch to memory context appropriate for multiple function calls
1508  */
1509  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1510 
1511  /* open target relation */
1513 
1514  /* get the array of attnums */
1515  results = get_pkey_attnames(rel, &numatts);
1516 
1518 
1519  /*
1520  * need a tuple descriptor representing one INT and one TEXT column
1521  */
1522  tupdesc = CreateTemplateTupleDesc(2, false);
1523  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
1524  INT4OID, -1, 0);
1525  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
1526  TEXTOID, -1, 0);
1527 
1528  /*
1529  * Generate attribute metadata needed later to produce tuples from raw
1530  * C strings
1531  */
1532  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1533  funcctx->attinmeta = attinmeta;
1534 
1535  if ((results != NULL) && (numatts > 0))
1536  {
1537  funcctx->max_calls = numatts;
1538 
1539  /* got results, keep track of them */
1540  funcctx->user_fctx = results;
1541  }
1542  else
1543  {
1544  /* fast track when no results */
1545  MemoryContextSwitchTo(oldcontext);
1546  SRF_RETURN_DONE(funcctx);
1547  }
1548 
1549  MemoryContextSwitchTo(oldcontext);
1550  }
1551 
1552  /* stuff done on every call of the function */
1553  funcctx = SRF_PERCALL_SETUP();
1554 
1555  /*
1556  * initialize per-call variables
1557  */
1558  call_cntr = funcctx->call_cntr;
1559  max_calls = funcctx->max_calls;
1560 
1561  results = (char **) funcctx->user_fctx;
1562  attinmeta = funcctx->attinmeta;
1563 
1564  if (call_cntr < max_calls) /* do when there is more left to send */
1565  {
1566  char **values;
1567  HeapTuple tuple;
1568  Datum result;
1569 
1570  values = (char **) palloc(2 * sizeof(char *));
1571  values[0] = psprintf("%d", call_cntr + 1);
1572  values[1] = results[call_cntr];
1573 
1574  /* build the tuple */
1575  tuple = BuildTupleFromCStrings(attinmeta, values);
1576 
1577  /* make the tuple into a datum */
1578  result = HeapTupleGetDatum(tuple);
1579 
1580  SRF_RETURN_NEXT(funcctx, result);
1581  }
1582  else
1583  {
1584  /* do when there is no more left */
1585  SRF_RETURN_DONE(funcctx);
1586  }
1587 }
uint64 call_cntr
Definition: funcapi.h:65
signed short int16
Definition: c.h:255
#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:1260
return result
Definition: formatting.c:1618
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:289
signed int int32
Definition: c.h:256
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1115
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
#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:372
#define ACL_SELECT
Definition: parsenodes.h:66
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1068
#define NULL
Definition: c.h:229
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:849
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 664 of file dblink.c.

References dblink_record_internal().

665 {
666  return dblink_record_internal(fcinfo, true);
667 }
static void dblink_init ( void  )
static

Definition at line 234 of file dblink.c.

References remoteConn::conn, FALSE, MemoryContextAlloc(), remoteConn::newXactForCursor, NULL, remoteConn::openCursorCount, and TopMemoryContext.

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

235 {
236  if (!pconn)
237  {
239  pconn->conn = NULL;
240  pconn->openCursorCount = 0;
242  }
243 }
int openCursorCount
Definition: dblink.c:69
PGconn * conn
Definition: dblink.c:68
#define FALSE
Definition: c.h:221
MemoryContext TopMemoryContext
Definition: mcxt.c:43
bool newXactForCursor
Definition: dblink.c:70
#define NULL
Definition: c.h:229
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1302 of file dblink.c.

References conn, dblink_get_named_conn(), dblink_init(), PG_GETARG_TEXT_PP, PG_RETURN_INT32, PQconsumeInput(), PQisBusy(), and text_to_cstring().

1303 {
1304  PGconn *conn;
1305 
1306  dblink_init();
1308 
1309  PQconsumeInput(conn);
1310  PG_RETURN_INT32(PQisBusy(conn));
1311 }
#define PG_RETURN_INT32(x)
Definition: fmgr.h:314
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: streamutil.c:42
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1631
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1681
char * text_to_cstring(const text *t)
Definition: varlena.c:182
Datum dblink_open ( PG_FUNCTION_ARGS  )

Definition at line 360 of file dblink.c.

References appendStringInfo(), BOOLOID, buf, conn, remoteConn::conn, cstring_to_text(), StringInfoData::data, dblink_init(), dblink_res_error(), 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.

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

Definition at line 632 of file dblink.c.

References dblink_record_internal().

633 {
634  return dblink_record_internal(fcinfo, false);
635 }
static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 670 of file dblink.c.

References BOOLOID, conn, remoteConn::conn, 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().

671 {
672  PGconn *volatile conn = NULL;
673  volatile bool freeconn = false;
674 
675  prepTuplestoreResult(fcinfo);
676 
677  dblink_init();
678 
679  PG_TRY();
680  {
681  char *sql = NULL;
682  char *conname = 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 */
690  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
692  fail = PG_GETARG_BOOL(2);
693  dblink_get_conn(conname, &conn, &conname, &freeconn);
694  }
695  else if (PG_NARGS() == 2)
696  {
697  /* text,text or text,bool */
698  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
699  {
701  fail = PG_GETARG_BOOL(1);
702  conn = pconn->conn;
703  }
704  else
705  {
706  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
708  dblink_get_conn(conname, &conn, &conname, &freeconn);
709  }
710  }
711  else if (PG_NARGS() == 1)
712  {
713  /* text */
714  conn = pconn->conn;
716  }
717  else
718  /* shouldn't happen */
719  elog(ERROR, "wrong number of arguments");
720  }
721  else /* is_async */
722  {
723  /* get async result */
724  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
725 
726  if (PG_NARGS() == 2)
727  {
728  /* text,bool */
729  fail = PG_GETARG_BOOL(1);
730  conn = dblink_get_named_conn(conname);
731  }
732  else if (PG_NARGS() == 1)
733  {
734  /* text */
735  conn = dblink_get_named_conn(conname);
736  }
737  else
738  /* shouldn't happen */
739  elog(ERROR, "wrong number of arguments");
740  }
741 
742  if (!conn)
743  dblink_conn_not_avail(conname);
744 
745  if (!is_async)
746  {
747  /* synchronous query, use efficient tuple collection method */
748  materializeQueryResult(fcinfo, conn, conname, sql, fail);
749  }
750  else
751  {
752  /* async result retrieval, do it the old way */
753  PGresult *res = PQgetResult(conn);
754 
755  /* NULL means we're all done with the async results */
756  if (res)
757  {
758  if (PQresultStatus(res) != PGRES_COMMAND_OK &&
760  {
761  dblink_res_error(conn, conname, res,
762  "could not execute query", fail);
763  /* if fail isn't set, we'll return an empty query result */
764  }
765  else
766  {
767  materializeResult(fcinfo, conn, res);
768  }
769  }
770  }
771  }
772  PG_CATCH();
773  {
774  /* if needed, close the connection to the database */
775  if (freeconn)
776  PQfinish(conn);
777  PG_RE_THROW();
778  }
779  PG_END_TRY();
780 
781  /* if needed, close the connection to the database */
782  if (freeconn)
783  PQfinish(conn);
784 
785  return (Datum) 0;
786 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:239
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
FmgrInfo * flinfo
Definition: fmgr.h:79
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1909
PGconn * conn
Definition: streamutil.c:42
uintptr_t Datum
Definition: postgres.h:372
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:229
#define PG_NARGS()
Definition: fmgr.h:168
#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:182
#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 void dblink_res_error ( PGconn conn,
const char *  conname,
PGresult res,
const char *  dblink_context_msg,
bool  fail 
)
static

Definition at line 2666 of file dblink.c.

References ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, MAKE_SQLSTATE, NOTICE, NULL, pchomp(), 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().

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

Definition at line 2606 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

2607 {
2608  if (!superuser())
2609  {
2610  if (!PQconnectionUsedPassword(conn))
2611  {
2612  PQfinish(conn);
2613  if (rconn)
2614  pfree(rconn);
2615 
2616  ereport(ERROR,
2617  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2618  errmsg("password is required"),
2619  errdetail("Non-superuser cannot connect if the server does not request a password."),
2620  errhint("Target server's authentication method must be changed.")));
2621  }
2622  }
2623 }
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:3568
bool superuser(void)
Definition: superuser.c:47
void pfree(void *pointer)
Definition: mcxt.c:950
#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:6060
int errmsg(const char *fmt,...)
Definition: elog.c:797
Datum dblink_send_query ( PG_FUNCTION_ARGS  )

Definition at line 639 of file dblink.c.

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

640 {
641  PGconn *conn;
642  char *sql;
643  int retval;
644 
645  if (PG_NARGS() == 2)
646  {
649  }
650  else
651  /* shouldn't happen */
652  elog(ERROR, "wrong number of arguments");
653 
654  /* async query send */
655  retval = PQsendQuery(conn, sql);
656  if (retval != 1)
657  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
658 
659  PG_RETURN_INT32(retval);
660 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
#define PG_RETURN_INT32(x)
Definition: fmgr.h:314
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
char * pchomp(const char *in)
Definition: mcxt.c:1101
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:42
#define NOTICE
Definition: elog.h:37
#define PG_NARGS()
Definition: fmgr.h:168
char * text_to_cstring(const text *t)
Definition: varlena.c:182
#define elog
Definition: elog.h:219
static void deleteConnection ( const char *  name)
static

Definition at line 2584 of file dblink.c.

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

Referenced by dblink_disconnect().

2585 {
2586  remoteConnHashEnt *hentry;
2587  bool found;
2588  char *key;
2589 
2590  if (!remoteConnHash)
2592 
2593  key = pstrdup(name);
2594  truncate_identifier(key, strlen(key), false);
2596  key, HASH_REMOVE, &found);
2597 
2598  if (!hentry)
2599  ereport(ERROR,
2600  (errcode(ERRCODE_UNDEFINED_OBJECT),
2601  errmsg("undefined connection name")));
2602 
2603 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
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 2820 of file dblink.c.

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

Referenced by get_connect_string().

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

Definition at line 2506 of file dblink.c.

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

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

2507 {
2508  char *nspname;
2509  char *result;
2510 
2511  /* Qualify the name if not visible in search path */
2513  nspname = NULL;
2514  else
2515  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2516 
2517  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2518 
2519  return result;
2520 }
return result
Definition: formatting.c:1618
Form_pg_class rd_rel
Definition: rel.h:114
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define RelationGetRelationName(relation)
Definition: rel.h:437
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10271
#define NULL
Definition: c.h:229
bool RelationIsVisible(Oid relid)
Definition: namespace.c:681
#define RelationGetRelid(relation)
Definition: rel.h:417
static int get_attnum_pk_pos ( int *  pkattnums,
int  pknumatts,
int  key 
)
static

Definition at line 2356 of file dblink.c.

References i.

Referenced by get_sql_insert(), and get_sql_update().

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

Definition at line 2730 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(), initStringInfo(), is_valid_dblink_option(), lfirst, 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(), and dblink_get_conn().

2731 {
2732  ForeignServer *foreign_server = NULL;
2733  UserMapping *user_mapping;
2734  ListCell *cell;
2736  ForeignDataWrapper *fdw;
2737  AclResult aclresult;
2738  char *srvname;
2739 
2740  static const PQconninfoOption *options = NULL;
2741 
2742  initStringInfo(&buf);
2743 
2744  /*
2745  * Get list of valid libpq options.
2746  *
2747  * To avoid unnecessary work, we get the list once and use it throughout
2748  * the lifetime of this backend process. We don't need to care about
2749  * memory context issues, because PQconndefaults allocates with malloc.
2750  */
2751  if (!options)
2752  {
2753  options = PQconndefaults();
2754  if (!options) /* assume reason for failure is OOM */
2755  ereport(ERROR,
2756  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2757  errmsg("out of memory"),
2758  errdetail("could not get libpq's default connection options")));
2759  }
2760 
2761  /* first gather the server connstr options */
2762  srvname = pstrdup(servername);
2763  truncate_identifier(srvname, strlen(srvname), false);
2764  foreign_server = GetForeignServerByName(srvname, true);
2765 
2766  if (foreign_server)
2767  {
2768  Oid serverid = foreign_server->serverid;
2769  Oid fdwid = foreign_server->fdwid;
2770  Oid userid = GetUserId();
2771 
2772  user_mapping = GetUserMapping(userid, serverid);
2773  fdw = GetForeignDataWrapper(fdwid);
2774 
2775  /* Check permissions, user must have usage on the server. */
2776  aclresult = pg_foreign_server_aclcheck(serverid, userid, ACL_USAGE);
2777  if (aclresult != ACLCHECK_OK)
2778  aclcheck_error(aclresult, ACL_KIND_FOREIGN_SERVER, foreign_server->servername);
2779 
2780  foreach(cell, fdw->options)
2781  {
2782  DefElem *def = lfirst(cell);
2783 
2785  appendStringInfo(&buf, "%s='%s' ", def->defname,
2786  escape_param_str(strVal(def->arg)));
2787  }
2788 
2789  foreach(cell, foreign_server->options)
2790  {
2791  DefElem *def = lfirst(cell);
2792 
2794  appendStringInfo(&buf, "%s='%s' ", def->defname,
2795  escape_param_str(strVal(def->arg)));
2796  }
2797 
2798  foreach(cell, user_mapping->options)
2799  {
2800 
2801  DefElem *def = lfirst(cell);
2802 
2804  appendStringInfo(&buf, "%s='%s' ", def->defname,
2805  escape_param_str(strVal(def->arg)));
2806  }
2807 
2808  return buf.data;
2809  }
2810  else
2811  return NULL;
2812 }
Oid GetUserId(void)
Definition: miscinit.c:283
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#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:4522
static char * buf
Definition: pg_test_fsync.c:65
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
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:709
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
List * options
Definition: foreign.h:42
AclResult
Definition: acl.h:170
#define ForeignServerRelationId
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1107
#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:708
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 2028 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, result, ScanKeyInit(), SPI_fname(), systable_beginscan(), systable_endscan(), and systable_getnext().

Referenced by dblink_get_pkey().

2029 {
2030  Relation indexRelation;
2031  ScanKeyData skey;
2032  SysScanDesc scan;
2033  HeapTuple indexTuple;
2034  int i;
2035  char **result = NULL;
2036  TupleDesc tupdesc;
2037 
2038  /* initialize numatts to 0 in case no primary key exists */
2039  *numatts = 0;
2040 
2041  tupdesc = rel->rd_att;
2042 
2043  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2044  indexRelation = heap_open(IndexRelationId, AccessShareLock);
2045  ScanKeyInit(&skey,
2047  BTEqualStrategyNumber, F_OIDEQ,
2049 
2050  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2051  NULL, 1, &skey);
2052 
2053  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2054  {
2055  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2056 
2057  /* we're only interested if it is the primary key */
2058  if (index->indisprimary)
2059  {
2060  *numatts = index->indnatts;
2061  if (*numatts > 0)
2062  {
2063  result = (char **) palloc(*numatts * sizeof(char *));
2064 
2065  for (i = 0; i < *numatts; i++)
2066  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2067  }
2068  break;
2069  }
2070  }
2071 
2072  systable_endscan(scan);
2073  heap_close(indexRelation, AccessShareLock);
2074 
2075  return result;
2076 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define IndexRelationId
Definition: pg_index.h:29
#define AccessShareLock
Definition: lockdefs.h:36
return result
Definition: formatting.c:1618
#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:328
#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:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
TupleDesc rd_att
Definition: rel.h:115
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void * palloc(Size size)
Definition: mcxt.c:849
int i
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:417
#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 2481 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().

2482 {
2483  RangeVar *relvar;
2484  Relation rel;
2485  AclResult aclresult;
2486 
2487  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2488  rel = heap_openrv(relvar, lockmode);
2489 
2490  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2491  aclmode);
2492  if (aclresult != ACLCHECK_OK)
2493  aclcheck_error(aclresult, ACL_KIND_CLASS,
2495 
2496  return rel;
2497 }
Oid GetUserId(void)
Definition: miscinit.c:283
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:2913
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RelationGetRelationName(relation)
Definition: rel.h:437
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3182
AclResult
Definition: acl.h:170
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1312
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
#define RelationGetRelid(relation)
Definition: rel.h:417
static char * get_sql_delete ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  tgt_pkattvals 
)
static

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

2218 {
2219  char *relname;
2220  TupleDesc tupdesc;
2222  int i;
2223 
2224  initStringInfo(&buf);
2225 
2226  /* get relation name including any needed schema prefix and quoting */
2227  relname = generate_relation_name(rel);
2228 
2229  tupdesc = rel->rd_att;
2230 
2231  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2232  for (i = 0; i < pknumatts; i++)
2233  {
2234  int pkattnum = pkattnums[i];
2235 
2236  if (i > 0)
2237  appendStringInfoString(&buf, " AND ");
2238 
2240  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2241 
2242  if (tgt_pkattvals[i] != NULL)
2243  appendStringInfo(&buf, " = %s",
2244  quote_literal_cstr(tgt_pkattvals[i]));
2245  else
2246  appendStringInfoString(&buf, " IS NULL");
2247  }
2248 
2249  return (buf.data);
2250 }
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:115
#define NULL
Definition: c.h:229
int i
#define NameStr(name)
Definition: c.h:499
static char * get_sql_insert ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals,
char **  tgt_pkattvals 
)
static

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

2140 {
2141  char *relname;
2142  HeapTuple tuple;
2143  TupleDesc tupdesc;
2144  int natts;
2146  char *val;
2147  int key;
2148  int i;
2149  bool needComma;
2150 
2151  initStringInfo(&buf);
2152 
2153  /* get relation name including any needed schema prefix and quoting */
2154  relname = generate_relation_name(rel);
2155 
2156  tupdesc = rel->rd_att;
2157  natts = tupdesc->natts;
2158 
2159  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2160  if (!tuple)
2161  ereport(ERROR,
2162  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2163  errmsg("source row not found")));
2164 
2165  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2166 
2167  needComma = false;
2168  for (i = 0; i < natts; i++)
2169  {
2170  if (tupdesc->attrs[i]->attisdropped)
2171  continue;
2172 
2173  if (needComma)
2174  appendStringInfoChar(&buf, ',');
2175 
2177  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2178  needComma = true;
2179  }
2180 
2181  appendStringInfoString(&buf, ") VALUES(");
2182 
2183  /*
2184  * Note: i is physical column number (counting from 0).
2185  */
2186  needComma = false;
2187  for (i = 0; i < natts; i++)
2188  {
2189  if (tupdesc->attrs[i]->attisdropped)
2190  continue;
2191 
2192  if (needComma)
2193  appendStringInfoChar(&buf, ',');
2194 
2195  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2196 
2197  if (key >= 0)
2198  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2199  else
2200  val = SPI_getvalue(tuple, tupdesc, i + 1);
2201 
2202  if (val != NULL)
2203  {
2205  pfree(val);
2206  }
2207  else
2208  appendStringInfoString(&buf, "NULL");
2209  needComma = true;
2210  }
2211  appendStringInfoChar(&buf, ')');
2212 
2213  return (buf.data);
2214 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
char * pstrdup(const char *in)
Definition: mcxt.c:1077
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:950
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:115
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:499
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 2253 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().

2254 {
2255  char *relname;
2256  HeapTuple tuple;
2257  TupleDesc tupdesc;
2258  int natts;
2260  char *val;
2261  int key;
2262  int i;
2263  bool needComma;
2264 
2265  initStringInfo(&buf);
2266 
2267  /* get relation name including any needed schema prefix and quoting */
2268  relname = generate_relation_name(rel);
2269 
2270  tupdesc = rel->rd_att;
2271  natts = tupdesc->natts;
2272 
2273  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2274  if (!tuple)
2275  ereport(ERROR,
2276  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2277  errmsg("source row not found")));
2278 
2279  appendStringInfo(&buf, "UPDATE %s SET ", relname);
2280 
2281  /*
2282  * Note: i is physical column number (counting from 0).
2283  */
2284  needComma = false;
2285  for (i = 0; i < natts; i++)
2286  {
2287  if (tupdesc->attrs[i]->attisdropped)
2288  continue;
2289 
2290  if (needComma)
2291  appendStringInfoString(&buf, ", ");
2292 
2293  appendStringInfo(&buf, "%s = ",
2294  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2295 
2296  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2297 
2298  if (key >= 0)
2299  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2300  else
2301  val = SPI_getvalue(tuple, tupdesc, i + 1);
2302 
2303  if (val != NULL)
2304  {
2306  pfree(val);
2307  }
2308  else
2309  appendStringInfoString(&buf, "NULL");
2310  needComma = true;
2311  }
2312 
2313  appendStringInfoString(&buf, " WHERE ");
2314 
2315  for (i = 0; i < pknumatts; i++)
2316  {
2317  int pkattnum = pkattnums[i];
2318 
2319  if (i > 0)
2320  appendStringInfoString(&buf, " AND ");
2321 
2323  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2324 
2325  val = tgt_pkattvals[i];
2326 
2327  if (val != NULL)
2328  appendStringInfo(&buf, " = %s", quote_literal_cstr(val));
2329  else
2330  appendStringInfoString(&buf, " IS NULL");
2331  }
2332 
2333  return (buf.data);
2334 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
char * pstrdup(const char *in)
Definition: mcxt.c:1077
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:950
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:115
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:499
long val
Definition: informix.c:689
static char ** get_text_array_contents ( ArrayType array,
int *  numitems 
)
static

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

2084 {
2085  int ndim = ARR_NDIM(array);
2086  int *dims = ARR_DIMS(array);
2087  int nitems;
2088  int16 typlen;
2089  bool typbyval;
2090  char typalign;
2091  char **values;
2092  char *ptr;
2093  bits8 *bitmap;
2094  int bitmask;
2095  int i;
2096 
2097  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2098 
2099  *numitems = nitems = ArrayGetNItems(ndim, dims);
2100 
2102  &typlen, &typbyval, &typalign);
2103 
2104  values = (char **) palloc(nitems * sizeof(char *));
2105 
2106  ptr = ARR_DATA_PTR(array);
2107  bitmap = ARR_NULLBITMAP(array);
2108  bitmask = 1;
2109 
2110  for (i = 0; i < nitems; i++)
2111  {
2112  if (bitmap && (*bitmap & bitmask) == 0)
2113  {
2114  values[i] = NULL;
2115  }
2116  else
2117  {
2118  values[i] = TextDatumGetCString(PointerGetDatum(ptr));
2119  ptr = att_addlength_pointer(ptr, typlen, ptr);
2120  ptr = (char *) att_align_nominal(ptr, typalign);
2121  }
2122 
2123  /* advance bitmap pointer if any */
2124  if (bitmap)
2125  {
2126  bitmask <<= 1;
2127  if (bitmask == 0x100)
2128  {
2129  bitmap++;
2130  bitmask = 1;
2131  }
2132  }
2133  }
2134 
2135  return values;
2136 }
signed short int16
Definition: c.h:255
#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:562
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:275
#define TextDatumGetCString(d)
Definition: builtins.h:92
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define ARR_NDIM(a)
Definition: array.h:271
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void * palloc(Size size)
Definition: mcxt.c:849
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 2371 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().

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

Definition at line 2524 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(), dblink_get_conn(), dblink_get_named_conn(), and dblink_open().

2525 {
2526  remoteConnHashEnt *hentry;
2527  char *key;
2528 
2529  if (!remoteConnHash)
2531 
2532  key = pstrdup(name);
2533  truncate_identifier(key, strlen(key), false);
2535  key, HASH_FIND, NULL);
2536 
2537  if (hentry)
2538  return (hentry->rconn);
2539 
2540  return (NULL);
2541 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
remoteConn * rconn
Definition: dblink.c:141
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:229
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 2924 of file dblink.c.

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

Referenced by dblink_fdw_validator(), and get_connect_string().

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

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

974 {
975  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
976  PGresult *volatile res = NULL;
977  volatile storeInfo sinfo;
978 
979  /* prepTuplestoreResult must have been called previously */
980  Assert(rsinfo->returnMode == SFRM_Materialize);
981 
982  /* initialize storeInfo to empty */
983  memset((void *) &sinfo, 0, sizeof(sinfo));
984  sinfo.fcinfo = fcinfo;
985 
986  PG_TRY();
987  {
988  /* Create short-lived memory context for data conversions */
989  sinfo.tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
990  "dblink temporary context",
992 
993  /* execute query, collecting any tuples into the tuplestore */
994  res = storeQueryResult(&sinfo, conn, sql);
995 
996  if (!res ||
997  (PQresultStatus(res) != PGRES_COMMAND_OK &&
999  {
1000  /*
1001  * dblink_res_error will clear the passed PGresult, so we need
1002  * this ugly dance to avoid doing so twice during error exit
1003  */
1004  PGresult *res1 = res;
1005 
1006  res = NULL;
1007  dblink_res_error(conn, conname, res1,
1008  "could not execute query", fail);
1009  /* if fail isn't set, we'll return an empty query result */
1010  }
1011  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1012  {
1013  /*
1014  * storeRow didn't get called, so we need to convert the command
1015  * status string to a tuple manually
1016  */
1017  TupleDesc tupdesc;
1018  AttInMetadata *attinmeta;
1019  Tuplestorestate *tupstore;
1020  HeapTuple tuple;
1021  char *values[1];
1022  MemoryContext oldcontext;
1023 
1024  /*
1025  * need a tuple descriptor representing one TEXT column to return
1026  * the command status string as our result tuple
1027  */
1028  tupdesc = CreateTemplateTupleDesc(1, false);
1029  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1030  TEXTOID, -1, 0);
1031  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1032 
1033  oldcontext = MemoryContextSwitchTo(
1034  rsinfo->econtext->ecxt_per_query_memory);
1035  tupstore = tuplestore_begin_heap(true, false, work_mem);
1036  rsinfo->setResult = tupstore;
1037  rsinfo->setDesc = tupdesc;
1038  MemoryContextSwitchTo(oldcontext);
1039 
1040  values[0] = PQcmdStatus(res);
1041 
1042  /* build the tuple and put it into the tuplestore. */
1043  tuple = BuildTupleFromCStrings(attinmeta, values);
1044  tuplestore_puttuple(tupstore, tuple);
1045 
1046  PQclear(res);
1047  res = NULL;
1048  }
1049  else
1050  {
1052  /* storeRow should have created a tuplestore */
1053  Assert(rsinfo->setResult != NULL);
1054 
1055  PQclear(res);
1056  res = NULL;
1057  }
1058 
1059  /* clean up data conversion short-lived memory context */
1060  if (sinfo.tmpcontext != NULL)
1061  MemoryContextDelete(sinfo.tmpcontext);
1062  sinfo.tmpcontext = NULL;
1063 
1064  PQclear(sinfo.last_res);
1065  sinfo.last_res = NULL;
1066  PQclear(sinfo.cur_res);
1067  sinfo.cur_res = NULL;
1068  }
1069  PG_CATCH();
1070  {
1071  /* be sure to release any libpq result we collected */
1072  PQclear(res);
1073  PQclear(sinfo.last_res);
1074  PQclear(sinfo.cur_res);
1075  /* and clear out any pending data in libpq */
1076  while ((res = PQgetResult(conn)) != NULL)
1077  PQclear(res);
1078  PG_RE_THROW();
1079  }
1080  PG_END_TRY();
1081 }
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:165
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:715
fmNodePtr resultinfo
Definition: fmgr.h:81
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:322
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:269
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define PG_RE_THROW()
Definition: elog.h:314
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:201
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
Tuplestorestate * setResult
Definition: execnodes.h:272
static Datum values[MAXATTR]
Definition: bootstrap.c:162
ExprContext * econtext
Definition: execnodes.h:265
TupleDesc setDesc
Definition: execnodes.h:273
#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 823 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().

824 {
825  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
826 
827  /* prepTuplestoreResult must have been called previously */
828  Assert(rsinfo->returnMode == SFRM_Materialize);
829 
830  PG_TRY();
831  {
832  TupleDesc tupdesc;
833  bool is_sql_cmd;
834  int ntuples;
835  int nfields;
836 
837  if (PQresultStatus(res) == PGRES_COMMAND_OK)
838  {
839  is_sql_cmd = true;
840 
841  /*
842  * need a tuple descriptor representing one TEXT column to return
843  * the command status string as our result tuple
844  */
845  tupdesc = CreateTemplateTupleDesc(1, false);
846  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
847  TEXTOID, -1, 0);
848  ntuples = 1;
849  nfields = 1;
850  }
851  else
852  {
854 
855  is_sql_cmd = false;
856 
857  /* get a tuple descriptor for our result type */
858  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
859  {
860  case TYPEFUNC_COMPOSITE:
861  /* success */
862  break;
863  case TYPEFUNC_RECORD:
864  /* failed to determine actual type of RECORD */
865  ereport(ERROR,
866  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
867  errmsg("function returning record called in context "
868  "that cannot accept type record")));
869  break;
870  default:
871  /* result type isn't composite */
872  elog(ERROR, "return type must be a row type");
873  break;
874  }
875 
876  /* make sure we have a persistent copy of the tupdesc */
877  tupdesc = CreateTupleDescCopy(tupdesc);
878  ntuples = PQntuples(res);
879  nfields = PQnfields(res);
880  }
881 
882  /*
883  * check result and tuple descriptor have the same number of columns
884  */
885  if (nfields != tupdesc->natts)
886  ereport(ERROR,
887  (errcode(ERRCODE_DATATYPE_MISMATCH),
888  errmsg("remote query result rowtype does not match "
889  "the specified FROM clause rowtype")));
890 
891  if (ntuples > 0)
892  {
893  AttInMetadata *attinmeta;
894  int nestlevel = -1;
895  Tuplestorestate *tupstore;
896  MemoryContext oldcontext;
897  int row;
898  char **values;
899 
900  attinmeta = TupleDescGetAttInMetadata(tupdesc);
901 
902  /* Set GUCs to ensure we read GUC-sensitive data types correctly */
903  if (!is_sql_cmd)
904  nestlevel = applyRemoteGucs(conn);
905 
906  oldcontext = MemoryContextSwitchTo(
908  tupstore = tuplestore_begin_heap(true, false, work_mem);
909  rsinfo->setResult = tupstore;
910  rsinfo->setDesc = tupdesc;
911  MemoryContextSwitchTo(oldcontext);
912 
913  values = (char **) palloc(nfields * sizeof(char *));
914 
915  /* put all tuples into the tuplestore */
916  for (row = 0; row < ntuples; row++)
917  {
918  HeapTuple tuple;
919 
920  if (!is_sql_cmd)
921  {
922  int i;
923 
924  for (i = 0; i < nfields; i++)
925  {
926  if (PQgetisnull(res, row, i))
927  values[i] = NULL;
928  else
929  values[i] = PQgetvalue(res, row, i);
930  }
931  }
932  else
933  {
934  values[0] = PQcmdStatus(res);
935  }
936 
937  /* build the tuple and put it into the tuplestore. */
938  tuple = BuildTupleFromCStrings(attinmeta, values);
939  tuplestore_puttuple(tupstore, tuple);
940  }
941 
942  /* clean up GUC settings, if we changed any */
943  restoreLocalGucs(nestlevel);
944 
945  /* clean up and return the tuplestore */
946  tuplestore_donestoring(tupstore);
947  }
948 
949  PQclear(res);
950  }
951  PG_CATCH();
952  {
953  /* be sure to release the libpq result */
954  PQclear(res);
955  PG_RE_THROW();
956  }
957  PG_END_TRY();
958 }
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:81
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:269
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define PG_RE_THROW()
Definition: elog.h:314
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:201
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
Tuplestorestate * setResult
Definition: execnodes.h:272
static Datum values[MAXATTR]
Definition: bootstrap.c:162
ExprContext * econtext
Definition: execnodes.h:265
TupleDesc setDesc
Definition: execnodes.h:273
void * palloc(Size size)
Definition: mcxt.c:849
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
static void pg_attribute_noreturn ( )
static

Definition at line 155 of file dblink.c.

References elog, ERROR, pchomp(), PQclear(), and PQerrorMessage().

157 {
158  char *msg = pchomp(PQerrorMessage(conn));
159  if (res)
160  PQclear(res);
161  elog(ERROR, "%s: %s", p2, msg);
162 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
char * pchomp(const char *in)
Definition: mcxt.c:1101
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:42
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define elog
Definition: elog.h:219
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 795 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().

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

Definition at line 2341 of file dblink.c.

References cstring_to_text(), DatumGetTextPP, DirectFunctionCall1, PointerGetDatum, quote_ident(), result, and text_to_cstring().

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

2342 {
2343  text *rawstr_text;
2344  text *result_text;
2345  char *result;
2346 
2347  rawstr_text = cstring_to_text(rawstr);
2349  PointerGetDatum(rawstr_text)));
2350  result = text_to_cstring(result_text);
2351 
2352  return result;
2353 }
#define PointerGetDatum(X)
Definition: postgres.h:562
#define DatumGetTextPP(X)
Definition: fmgr.h:256
return result
Definition: formatting.c:1618
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:24
text * cstring_to_text(const char *s)
Definition: varlena.c:149
char * text_to_cstring(const text *t)
Definition: varlena.c:182
Definition: c.h:439
static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3027 of file dblink.c.

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

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

Definition at line 1087 of file dblink.c.

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

Referenced by materializeQueryResult().

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

1156 {
1157  int nfields = PQnfields(res);
1158  HeapTuple tuple;
1159  int i;
1160  MemoryContext oldcontext;
1161 
1162  if (first)
1163  {
1164  /* Prepare for new result set */
1165  ReturnSetInfo *rsinfo = (ReturnSetInfo *) sinfo->fcinfo->resultinfo;
1166  TupleDesc tupdesc;
1167 
1168  /*
1169  * It's possible to get more than one result set if the query string
1170  * contained multiple SQL commands. In that case, we follow PQexec's
1171  * traditional behavior of throwing away all but the last result.
1172  */
1173  if (sinfo->tuplestore)
1174  tuplestore_end(sinfo->tuplestore);
1175  sinfo->tuplestore = NULL;
1176 
1177  /* get a tuple descriptor for our result type */
1178  switch (get_call_result_type(sinfo->fcinfo, NULL, &tupdesc))
1179  {
1180  case TYPEFUNC_COMPOSITE:
1181  /* success */
1182  break;
1183  case TYPEFUNC_RECORD:
1184  /* failed to determine actual type of RECORD */
1185  ereport(ERROR,
1186  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1187  errmsg("function returning record called in context "
1188  "that cannot accept type record")));
1189  break;
1190  default:
1191  /* result type isn't composite */
1192  elog(ERROR, "return type must be a row type");
1193  break;
1194  }
1195 
1196  /* make sure we have a persistent copy of the tupdesc */
1197  tupdesc = CreateTupleDescCopy(tupdesc);
1198 
1199  /* check result and tuple descriptor have the same number of columns */
1200  if (nfields != tupdesc->natts)
1201  ereport(ERROR,
1202  (errcode(ERRCODE_DATATYPE_MISMATCH),
1203  errmsg("remote query result rowtype does not match "
1204  "the specified FROM clause rowtype")));
1205 
1206  /* Prepare attinmeta for later data conversions */
1207  sinfo->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1208 
1209  /* Create a new, empty tuplestore */
1210  oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1211  sinfo->tuplestore = tuplestore_begin_heap(true, false, work_mem);
1212  rsinfo->setResult = sinfo->tuplestore;
1213  rsinfo->setDesc = tupdesc;
1214  MemoryContextSwitchTo(oldcontext);
1215 
1216  /* Done if empty resultset */
1217  if (PQntuples(res) == 0)
1218  return;
1219 
1220  /*
1221  * Set up sufficiently-wide string pointers array; this won't change
1222  * in size so it's easy to preallocate.
1223  */
1224  if (sinfo->cstrs)
1225  pfree(sinfo->cstrs);
1226  sinfo->cstrs = (char **) palloc(nfields * sizeof(char *));
1227  }
1228 
1229  /* Should have a single-row result if we get here */
1230  Assert(PQntuples(res) == 1);
1231 
1232  /*
1233  * Do the following work in a temp context that we reset after each tuple.
1234  * This cleans up not only the data we have direct access to, but any
1235  * cruft the I/O functions might leak.
1236  */
1237  oldcontext = MemoryContextSwitchTo(sinfo->tmpcontext);
1238 
1239  /*
1240  * Fill cstrs with null-terminated strings of column values.
1241  */
1242  for (i = 0; i < nfields; i++)
1243  {
1244  if (PQgetisnull(res, 0, i))
1245  sinfo->cstrs[i] = NULL;
1246  else
1247  sinfo->cstrs[i] = PQgetvalue(res, 0, i);
1248  }
1249 
1250  /* Convert row to a tuple, and add it to the tuplestore */
1251  tuple = BuildTupleFromCStrings(sinfo->attinmeta, sinfo->cstrs);
1252 
1253  tuplestore_puttuple(sinfo->tuplestore, tuple);
1254 
1255  /* Clean up */
1256  MemoryContextSwitchTo(oldcontext);
1257  MemoryContextReset(sinfo->tmpcontext);
1258 }
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:950
#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:229
#define Assert(condition)
Definition: c.h:675
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:450
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:201
Tuplestorestate * setResult
Definition: execnodes.h:272
ExprContext * econtext
Definition: execnodes.h:265
TupleDesc setDesc
Definition: execnodes.h:273
void * palloc(Size size)
Definition: mcxt.c:849
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 2853 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().

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

Definition at line 148 of file dblink.c.

References NULL, and pstrdup().

Referenced by dblink_res_error().

149 {
150  if (in == NULL)
151  return NULL;
152  return pstrdup(in);
153 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define NULL
Definition: c.h:229

Variable Documentation

remoteConn* pconn = NULL
static

Definition at line 128 of file dblink.c.

Referenced by dblink_close(), and dblink_open().

PG_MODULE_MAGIC

Definition at line 64 of file dblink.c.

HTAB* remoteConnHash = NULL
static

Definition at line 129 of file dblink.c.