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 1879 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 2989 of file dblink.c.

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

Referenced by materializeResult(), and storeQueryResult().

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

Definition at line 2558 of file dblink.c.

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

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

2559 {
2560  HASHCTL ctl;
2561 
2562  ctl.keysize = NAMEDATALEN;
2563  ctl.entrysize = sizeof(remoteConnHashEnt);
2564 
2565  return hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
2566 }
#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:316
Size keysize
Definition: hsearch.h:72
static void createNewConnection ( const char *  name,
remoteConn rconn 
)
static

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

2570 {
2571  remoteConnHashEnt *hentry;
2572  bool found;
2573  char *key;
2574 
2575  if (!remoteConnHash)
2577 
2578  key = pstrdup(name);
2579  truncate_identifier(key, strlen(key), true);
2580  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2581  HASH_ENTER, &found);
2582 
2583  if (found)
2584  {
2585  PQfinish(rconn->conn);
2586  pfree(rconn);
2587 
2588  ereport(ERROR,
2590  errmsg("duplicate connection name")));
2591  }
2592 
2593  hentry->rconn = rconn;
2594  strlcpy(hentry->name, name, sizeof(hentry->name));
2595 }
char * pstrdup(const char *in)
Definition: mcxt.c:1076
remoteConn * rconn
Definition: dblink.c:141
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3630
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
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:949
#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:33
Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

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

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

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

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

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

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

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

1332 {
1333  int res;
1334  PGconn *conn;
1335  PGcancel *cancel;
1336  char errbuf[256];
1337 
1338  dblink_init();
1340  cancel = PQgetCancel(conn);
1341 
1342  res = PQcancel(cancel, errbuf, 256);
1343  PQfreeCancel(cancel);
1344 
1345  if (res == 1)
1347  else
1349 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:3774
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: streamutil.c:49
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:3751
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
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:3906
Datum dblink_close ( PG_FUNCTION_ARGS  )

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

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

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

256 {
257  char *conname_or_str = NULL;
258  char *connstr = NULL;
259  char *connname = NULL;
260  char *msg;
261  PGconn *conn = NULL;
262  remoteConn *rconn = NULL;
263 
264  dblink_init();
265 
266  if (PG_NARGS() == 2)
267  {
268  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
269  connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
270  }
271  else if (PG_NARGS() == 1)
272  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
273 
274  if (connname)
276  sizeof(remoteConn));
277 
278  /* first check for valid foreign data server */
279  connstr = get_connect_string(conname_or_str);
280  if (connstr == NULL)
281  connstr = conname_or_str;
282 
283  /* check password in connection string if not superuser */
284  dblink_connstr_check(connstr);
285  conn = PQconnectdb(connstr);
286 
287  if (PQstatus(conn) == CONNECTION_BAD)
288  {
289  msg = pchomp(PQerrorMessage(conn));
290  PQfinish(conn);
291  if (rconn)
292  pfree(rconn);
293 
294  ereport(ERROR,
295  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
296  errmsg("could not establish connection"),
297  errdetail_internal("%s", msg)));
298  }
299 
300  /* check password actually used if not superuser */
301  dblink_security_check(conn, rconn);
302 
303  /* attempt to set client encoding to match server encoding, if needed */
304  if (PQclientEncoding(conn) != GetDatabaseEncoding())
306 
307  if (connname)
308  {
309  rconn->conn = conn;
310  createNewConnection(connname, rconn);
311  }
312  else
313  {
314  if (pconn->conn)
315  PQfinish(pconn->conn);
316  pconn->conn = conn;
317  }
318 
320 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3630
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6157
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:1100
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:49
#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:6165
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
text * cstring_to_text(const char *s)
Definition: varlena.c:149
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:706
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6044
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:585
static char * connstr
Definition: pg_dumpall.c:64
static void dblink_connstr_check ( const char *  connstr)
static

Definition at line 2646 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

2647 {
2648  if (!superuser())
2649  {
2652  bool connstr_gives_password = false;
2653 
2654  options = PQconninfoParse(connstr, NULL);
2655  if (options)
2656  {
2657  for (option = options; option->keyword != NULL; option++)
2658  {
2659  if (strcmp(option->keyword, "password") == 0)
2660  {
2661  if (option->val != NULL && option->val[0] != '\0')
2662  {
2663  connstr_gives_password = true;
2664  break;
2665  }
2666  }
2667  }
2668  PQconninfoFree(options);
2669  }
2670 
2671  if (!connstr_gives_password)
2672  ereport(ERROR,
2673  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2674  errmsg("password is required"),
2675  errdetail("Non-superusers must provide a password in the connection string.")));
2676  }
2677 }
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:4717
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5947
#define ereport(elevel, rest)
Definition: elog.h:122
static char ** options
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 1865 of file dblink.c.

References current_query(), and PG_RETURN_DATUM.

1866 {
1867  /* This is now just an alias for the built-in function current_query() */
1868  PG_RETURN_DATUM(current_query(fcinfo));
1869 }
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 327 of file dblink.c.

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

328 {
329  char *conname = NULL;
330  remoteConn *rconn = NULL;
331  PGconn *conn = NULL;
332 
333  dblink_init();
334 
335  if (PG_NARGS() == 1)
336  {
337  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
338  rconn = getConnectionByName(conname);
339  if (rconn)
340  conn = rconn->conn;
341  }
342  else
343  conn = pconn->conn;
344 
345  if (!conn)
346  dblink_conn_not_avail(conname);
347 
348  PQfinish(conn);
349  if (rconn)
350  {
351  deleteConnection(conname);
352  pfree(rconn);
353  }
354  else
355  pconn->conn = NULL;
356 
358 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3630
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: dblink.c:68
void pfree(void *pointer)
Definition: mcxt.c:949
PGconn * conn
Definition: streamutil.c:49
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#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 1364 of file dblink.c.

References conn, cstring_to_text(), dblink_get_named_conn(), dblink_init(), pchomp(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PQerrorMessage(), and text_to_cstring().

1365 {
1366  char *msg;
1367  PGconn *conn;
1368 
1369  dblink_init();
1371 
1372  msg = PQerrorMessage(conn);
1373  if (msg == NULL || msg[0] == '\0')
1375  else
1377 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
char * pchomp(const char *in)
Definition: mcxt.c:1100
PGconn * conn
Definition: streamutil.c:49
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
text * cstring_to_text(const char *s)
Definition: varlena.c:149
char * text_to_cstring(const text *t)
Definition: varlena.c:182
Datum dblink_exec ( PG_FUNCTION_ARGS  )

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

1385 {
1386  text *volatile sql_cmd_status = NULL;
1387  PGconn *volatile conn = NULL;
1388  volatile bool freeconn = false;
1389 
1390  dblink_init();
1391 
1392  PG_TRY();
1393  {
1394  PGresult *res = NULL;
1395  char *sql = NULL;
1396  char *conname = NULL;
1397  bool fail = true; /* default to backward compatible behavior */
1398 
1399  if (PG_NARGS() == 3)
1400  {
1401  /* must be text,text,bool */
1402  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1404  fail = PG_GETARG_BOOL(2);
1405  dblink_get_conn(conname, &conn, &conname, &freeconn);
1406  }
1407  else if (PG_NARGS() == 2)
1408  {
1409  /* might be text,text or text,bool */
1410  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1411  {
1413  fail = PG_GETARG_BOOL(1);
1414  conn = pconn->conn;
1415  }
1416  else
1417  {
1418  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1420  dblink_get_conn(conname, &conn, &conname, &freeconn);
1421  }
1422  }
1423  else if (PG_NARGS() == 1)
1424  {
1425  /* must be single text argument */
1426  conn = pconn->conn;
1428  }
1429  else
1430  /* shouldn't happen */
1431  elog(ERROR, "wrong number of arguments");
1432 
1433  if (!conn)
1434  dblink_conn_not_avail(conname);
1435 
1436  res = PQexec(conn, sql);
1437  if (!res ||
1438  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1440  {
1441  dblink_res_error(conn, conname, res,
1442  "could not execute command", fail);
1443 
1444  /*
1445  * and save a copy of the command status string to return as our
1446  * result tuple
1447  */
1448  sql_cmd_status = cstring_to_text("ERROR");
1449  }
1450  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1451  {
1452  /*
1453  * and save a copy of the command status string to return as our
1454  * result tuple
1455  */
1456  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1457  PQclear(res);
1458  }
1459  else
1460  {
1461  PQclear(res);
1462  ereport(ERROR,
1463  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1464  errmsg("statement returning results not allowed")));
1465  }
1466  }
1467  PG_CATCH();
1468  {
1469  /* if needed, close the connection to the database */
1470  if (freeconn)
1471  PQfinish(conn);
1472  PG_RE_THROW();
1473  }
1474  PG_END_TRY();
1475 
1476  /* if needed, close the connection to the database */
1477  if (freeconn)
1478  PQfinish(conn);
1479 
1480  PG_RETURN_TEXT_P(sql_cmd_status);
1481 }
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3630
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:239
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#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:49
#define ereport(elevel, rest)
Definition: elog.h:122
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:2995
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
#define PG_CATCH()
Definition: elog.h:293
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#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:1897
Definition: c.h:433
#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 1961 of file dblink.c.

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

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

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

544 {
545  PGresult *res = NULL;
546  char *conname = NULL;
547  remoteConn *rconn = NULL;
548  PGconn *conn = NULL;
550  char *curname = NULL;
551  int howmany = 0;
552  bool fail = true; /* default to backward compatible */
553 
554  prepTuplestoreResult(fcinfo);
555 
556  dblink_init();
557 
558  if (PG_NARGS() == 4)
559  {
560  /* text,text,int,bool */
561  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
562  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
563  howmany = PG_GETARG_INT32(2);
564  fail = PG_GETARG_BOOL(3);
565 
566  rconn = getConnectionByName(conname);
567  if (rconn)
568  conn = rconn->conn;
569  }
570  else if (PG_NARGS() == 3)
571  {
572  /* text,text,int or text,int,bool */
573  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
574  {
575  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
576  howmany = PG_GETARG_INT32(1);
577  fail = PG_GETARG_BOOL(2);
578  conn = pconn->conn;
579  }
580  else
581  {
582  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
583  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
584  howmany = PG_GETARG_INT32(2);
585 
586  rconn = getConnectionByName(conname);
587  if (rconn)
588  conn = rconn->conn;
589  }
590  }
591  else if (PG_NARGS() == 2)
592  {
593  /* text,int */
594  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
595  howmany = PG_GETARG_INT32(1);
596  conn = pconn->conn;
597  }
598 
599  if (!conn)
600  dblink_conn_not_avail(conname);
601 
602  initStringInfo(&buf);
603  appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
604 
605  /*
606  * Try to execute the query. Note that since libpq uses malloc, the
607  * PGresult will be long-lived even though we are still in a short-lived
608  * memory context.
609  */
610  res = PQexec(conn, buf.data);
611  if (!res ||
612  (PQresultStatus(res) != PGRES_COMMAND_OK &&
614  {
615  dblink_res_error(conn, conname, res,
616  "could not fetch from cursor", fail);
617  return (Datum) 0;
618  }
619  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
620  {
621  /* cursor does not exist - closed already or bad name */
622  PQclear(res);
623  ereport(ERROR,
624  (errcode(ERRCODE_INVALID_CURSOR_NAME),
625  errmsg("cursor \"%s\" does not exist", curname)));
626  }
627 
628  materializeResult(fcinfo, conn, res);
629  return (Datum) 0;
630 }
#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:2647
#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:78
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1909
PGconn * conn
Definition: streamutil.c:49
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
uintptr_t Datum
Definition: postgres.h:372
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#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:1897
static void dblink_get_conn ( char *  conname_or_str,
PGconn *volatile *  conn_p,
char **  conname_p,
volatile bool freeconn_p 
)
static

Definition at line 181 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(), pchomp(), PQclientEncoding(), PQconnectdb(), PQerrorMessage(), PQfinish(), PQsetClientEncoding(), and PQstatus().

Referenced by dblink_exec(), and dblink_record_internal().

183 {
184  remoteConn *rconn = getConnectionByName(conname_or_str);
185  PGconn *conn;
186  char *conname;
187  bool freeconn;
188 
189  if (rconn)
190  {
191  conn = rconn->conn;
192  conname = conname_or_str;
193  freeconn = false;
194  }
195  else
196  {
197  const char *connstr;
198 
199  connstr = get_connect_string(conname_or_str);
200  if (connstr == NULL)
201  connstr = conname_or_str;
202  dblink_connstr_check(connstr);
203  conn = PQconnectdb(connstr);
204  if (PQstatus(conn) == CONNECTION_BAD)
205  {
206  char *msg = pchomp(PQerrorMessage(conn));
207 
208  PQfinish(conn);
209  ereport(ERROR,
210  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
211  errmsg("could not establish connection"),
212  errdetail_internal("%s", msg)));
213  }
214  dblink_security_check(conn, rconn);
215  if (PQclientEncoding(conn) != GetDatabaseEncoding())
217  freeconn = true;
218  conname = NULL;
219  }
220 
221  *conn_p = conn;
222  *conname_p = conname;
223  *freeconn_p = freeconn;
224 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3630
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6157
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
PGconn * conn
Definition: dblink.c:68
char * pchomp(const char *in)
Definition: mcxt.c:1100
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:49
#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:6165
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:6044
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:585
static char * connstr
Definition: pg_dumpall.c:64
Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1272 of file dblink.c.

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

1273 {
1275  remoteConnHashEnt *hentry;
1276  ArrayBuildState *astate = NULL;
1277 
1278  if (remoteConnHash)
1279  {
1280  hash_seq_init(&status, remoteConnHash);
1281  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1282  {
1283  /* stash away current value */
1284  astate = accumArrayResult(astate,
1285  CStringGetTextDatum(hentry->name),
1286  false, TEXTOID, CurrentMemoryContext);
1287  }
1288  }
1289 
1290  if (astate)
1293  else
1294  PG_RETURN_NULL();
1295 }
#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:5133
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1385
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1375
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5069
#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 227 of file dblink.c.

References remoteConn::conn, and getConnectionByName().

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

228 {
229  remoteConn *rconn = getConnectionByName(conname);
230 
231  if (rconn)
232  return rconn->conn;
233 
234  dblink_conn_not_avail(conname);
235  return NULL; /* keep compiler quiet */
236 }
PGconn * conn
Definition: dblink.c:68
Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

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

1884 {
1885  PGconn *conn;
1886  PGnotify *notify;
1887  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1888  TupleDesc tupdesc;
1889  Tuplestorestate *tupstore;
1890  MemoryContext per_query_ctx;
1891  MemoryContext oldcontext;
1892 
1893  prepTuplestoreResult(fcinfo);
1894 
1895  dblink_init();
1896  if (PG_NARGS() == 1)
1898  else
1899  conn = pconn->conn;
1900 
1901  /* create the tuplestore in per-query memory */
1902  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1903  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1904 
1905  tupdesc = CreateTemplateTupleDesc(DBLINK_NOTIFY_COLS, false);
1906  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1907  TEXTOID, -1, 0);
1908  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1909  INT4OID, -1, 0);
1910  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1911  TEXTOID, -1, 0);
1912 
1913  tupstore = tuplestore_begin_heap(true, false, work_mem);
1914  rsinfo->setResult = tupstore;
1915  rsinfo->setDesc = tupdesc;
1916 
1917  MemoryContextSwitchTo(oldcontext);
1918 
1919  PQconsumeInput(conn);
1920  while ((notify = PQnotifies(conn)) != NULL)
1921  {
1923  bool nulls[DBLINK_NOTIFY_COLS];
1924 
1925  memset(values, 0, sizeof(values));
1926  memset(nulls, 0, sizeof(nulls));
1927 
1928  if (notify->relname != NULL)
1929  values[0] = CStringGetTextDatum(notify->relname);
1930  else
1931  nulls[0] = true;
1932 
1933  values[1] = Int32GetDatum(notify->be_pid);
1934 
1935  if (notify->extra != NULL)
1936  values[2] = CStringGetTextDatum(notify->extra);
1937  else
1938  nulls[2] = true;
1939 
1940  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1941 
1942  PQfreemem(notify);
1943  PQconsumeInput(conn);
1944  }
1945 
1946  /* clean up and return the tuplestore */
1947  tuplestore_donestoring(tupstore);
1948 
1949  return (Datum) 0;
1950 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
char * extra
Definition: libpq-fe.h:165
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2244
#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:49
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:505
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:372
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1682
int work_mem
Definition: globals.c:113
#define PG_NARGS()
Definition: fmgr.h:168
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:43
Tuplestorestate * setResult
Definition: execnodes.h:273
static Datum values[MAXATTR]
Definition: bootstrap.c:164
char * text_to_cstring(const text *t)
Definition: varlena.c:182
ExprContext * econtext
Definition: execnodes.h:266
#define Int32GetDatum(X)
Definition: postgres.h:485
TupleDesc setDesc
Definition: execnodes.h:274
#define CStringGetTextDatum(s)
Definition: builtins.h:91
int16 AttrNumber
Definition: attnum.h:21
void PQfreemem(void *ptr)
Definition: fe-exec.c:3251
Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

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

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

References dblink_record_internal().

670 {
671  return dblink_record_internal(fcinfo, true);
672 }
static void dblink_init ( void  )
static

Definition at line 239 of file dblink.c.

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

240 {
241  if (!pconn)
242  {
244  pconn->conn = NULL;
245  pconn->openCursorCount = 0;
247  }
248 }
int openCursorCount
Definition: dblink.c:69
PGconn * conn
Definition: dblink.c:68
#define FALSE
Definition: c.h:219
MemoryContext TopMemoryContext
Definition: mcxt.c:43
bool newXactForCursor
Definition: dblink.c:70
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:706
Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

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

1308 {
1309  PGconn *conn;
1310 
1311  dblink_init();
1313 
1314  PQconsumeInput(conn);
1315  PG_RETURN_INT32(PQisBusy(conn));
1316 }
#define PG_RETURN_INT32(x)
Definition: fmgr.h:314
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
PGconn * conn
Definition: streamutil.c:49
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1682
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1732
char * text_to_cstring(const text *t)
Definition: varlena.c:182
Datum dblink_open ( PG_FUNCTION_ARGS  )

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

366 {
367  PGresult *res = NULL;
368  PGconn *conn;
369  char *curname = NULL;
370  char *sql = NULL;
371  char *conname = NULL;
373  remoteConn *rconn = NULL;
374  bool fail = true; /* default to backward compatible behavior */
375 
376  dblink_init();
377  initStringInfo(&buf);
378 
379  if (PG_NARGS() == 2)
380  {
381  /* text,text */
382  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
384  rconn = pconn;
385  }
386  else if (PG_NARGS() == 3)
387  {
388  /* might be text,text,text or text,text,bool */
389  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
390  {
391  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
393  fail = PG_GETARG_BOOL(2);
394  rconn = pconn;
395  }
396  else
397  {
398  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
399  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
401  rconn = getConnectionByName(conname);
402  }
403  }
404  else if (PG_NARGS() == 4)
405  {
406  /* text,text,text,bool */
407  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
408  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
410  fail = PG_GETARG_BOOL(3);
411  rconn = getConnectionByName(conname);
412  }
413 
414  if (!rconn || !rconn->conn)
415  dblink_conn_not_avail(conname);
416 
417  conn = rconn->conn;
418 
419  /* If we are not in a transaction, start one */
420  if (PQtransactionStatus(conn) == PQTRANS_IDLE)
421  {
422  res = PQexec(conn, "BEGIN");
423  if (PQresultStatus(res) != PGRES_COMMAND_OK)
424  dblink_res_internalerror(conn, res, "begin error");
425  PQclear(res);
426  rconn->newXactForCursor = TRUE;
427 
428  /*
429  * Since transaction state was IDLE, we force cursor count to
430  * initially be 0. This is needed as a previous ABORT might have wiped
431  * out our transaction without maintaining the cursor count for us.
432  */
433  rconn->openCursorCount = 0;
434  }
435 
436  /* if we started a transaction, increment cursor count */
437  if (rconn->newXactForCursor)
438  (rconn->openCursorCount)++;
439 
440  appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
441  res = PQexec(conn, buf.data);
442  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
443  {
444  dblink_res_error(conn, conname, res, "could not open cursor", fail);
446  }
447 
448  PQclear(res);
450 }
int openCursorCount
Definition: dblink.c:69
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:239
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#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:78
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1909
PGconn * conn
Definition: streamutil.c:49
static char * buf
Definition: pg_test_fsync.c:67
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6052
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
bool newXactForCursor
Definition: dblink.c:70
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:331
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#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:1897
#define TRUE
Definition: c.h:215
Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 637 of file dblink.c.

References dblink_record_internal().

638 {
639  return dblink_record_internal(fcinfo, false);
640 }
static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

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

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

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

2682 {
2683  int level;
2684  char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2685  char *pg_diag_message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2686  char *pg_diag_message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2687  char *pg_diag_message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2688  char *pg_diag_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2689  int sqlstate;
2690  char *message_primary;
2691  char *message_detail;
2692  char *message_hint;
2693  char *message_context;
2694  const char *dblink_context_conname = "unnamed";
2695 
2696  if (fail)
2697  level = ERROR;
2698  else
2699  level = NOTICE;
2700 
2701  if (pg_diag_sqlstate)
2702  sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2703  pg_diag_sqlstate[1],
2704  pg_diag_sqlstate[2],
2705  pg_diag_sqlstate[3],
2706  pg_diag_sqlstate[4]);
2707  else
2708  sqlstate = ERRCODE_CONNECTION_FAILURE;
2709 
2710  message_primary = xpstrdup(pg_diag_message_primary);
2711  message_detail = xpstrdup(pg_diag_message_detail);
2712  message_hint = xpstrdup(pg_diag_message_hint);
2713  message_context = xpstrdup(pg_diag_context);
2714 
2715  /*
2716  * If we don't get a message from the PGresult, try the PGconn. This is
2717  * needed because for connection-level failures, PQexec may just return
2718  * NULL, not a PGresult at all.
2719  */
2720  if (message_primary == NULL)
2721  message_primary = pchomp(PQerrorMessage(conn));
2722 
2723  if (res)
2724  PQclear(res);
2725 
2726  if (conname)
2727  dblink_context_conname = conname;
2728 
2729  ereport(level,
2730  (errcode(sqlstate),
2731  message_primary ? errmsg_internal("%s", message_primary) :
2732  errmsg("could not obtain message string for remote error"),
2733  message_detail ? errdetail_internal("%s", message_detail) : 0,
2734  message_hint ? errhint("%s", message_hint) : 0,
2735  message_context ? errcontext("%s", message_context) : 0,
2736  errcontext("Error occurred on dblink connection named \"%s\": %s.",
2737  dblink_context_conname, dblink_context_msg)));
2738 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
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:1100
#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:671
#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:2709
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 2620 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

2621 {
2622  if (!superuser())
2623  {
2624  if (!PQconnectionUsedPassword(conn))
2625  {
2626  PQfinish(conn);
2627  if (rconn)
2628  pfree(rconn);
2629 
2630  ereport(ERROR,
2631  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2632  errmsg("password is required"),
2633  errdetail("Non-superuser cannot connect if the server does not request a password."),
2634  errhint("Target server's authentication method must be changed.")));
2635  }
2636  }
2637 }
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:3630
bool superuser(void)
Definition: superuser.c:47
void pfree(void *pointer)
Definition: mcxt.c:949
#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:6146
int errmsg(const char *fmt,...)
Definition: elog.c:797
Datum dblink_send_query ( PG_FUNCTION_ARGS  )

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

645 {
646  PGconn *conn;
647  char *sql;
648  int retval;
649 
650  if (PG_NARGS() == 2)
651  {
654  }
655  else
656  /* shouldn't happen */
657  elog(ERROR, "wrong number of arguments");
658 
659  /* async query send */
660  retval = PQsendQuery(conn, sql);
661  if (retval != 1)
662  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
663 
664  PG_RETURN_INT32(retval);
665 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
#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:1100
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1183
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:49
#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 2598 of file dblink.c.

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

Referenced by dblink_disconnect().

2599 {
2600  remoteConnHashEnt *hentry;
2601  bool found;
2602  char *key;
2603 
2604  if (!remoteConnHash)
2606 
2607  key = pstrdup(name);
2608  truncate_identifier(key, strlen(key), false);
2610  key, HASH_REMOVE, &found);
2611 
2612  if (!hentry)
2613  ereport(ERROR,
2614  (errcode(ERRCODE_UNDEFINED_OBJECT),
2615  errmsg("undefined connection name")));
2616 
2617 }
char * pstrdup(const char *in)
Definition: mcxt.c:1076
int errcode(int sqlerrcode)
Definition: elog.c:575
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
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 2834 of file dblink.c.

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

Referenced by get_connect_string().

2835 {
2836  const char *cp;
2838 
2839  initStringInfo(&buf);
2840 
2841  for (cp = str; *cp; cp++)
2842  {
2843  if (*cp == '\\' || *cp == '\'')
2844  appendStringInfoChar(&buf, '\\');
2845  appendStringInfoChar(&buf, *cp);
2846  }
2847 
2848  return buf.data;
2849 }
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
static char * generate_relation_name ( Relation  rel)
static

Definition at line 2520 of file dblink.c.

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

2521 {
2522  char *nspname;
2523  char *result;
2524 
2525  /* Qualify the name if not visible in search path */
2527  nspname = NULL;
2528  else
2529  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2530 
2531  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2532 
2533  return result;
2534 }
return result
Definition: formatting.c:1633
Form_pg_class rd_rel
Definition: rel.h:114
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#define RelationGetRelationName(relation)
Definition: rel.h:436
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10476
bool RelationIsVisible(Oid relid)
Definition: namespace.c:682
#define RelationGetRelid(relation)
Definition: rel.h:416
static int get_attnum_pk_pos ( int *  pkattnums,
int  pknumatts,
int  key 
)
static

Definition at line 2367 of file dblink.c.

References i.

Referenced by get_sql_insert(), and get_sql_update().

2368 {
2369  int i;
2370 
2371  /*
2372  * Not likely a long list anyway, so just scan for the value
2373  */
2374  for (i = 0; i < pknumatts; i++)
2375  if (key == pkattnums[i])
2376  return i;
2377 
2378  return -1;
2379 }
int i
static char * get_connect_string ( const char *  servername)
static

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

2745 {
2746  ForeignServer *foreign_server = NULL;
2747  UserMapping *user_mapping;
2748  ListCell *cell;
2750  ForeignDataWrapper *fdw;
2751  AclResult aclresult;
2752  char *srvname;
2753 
2754  static const PQconninfoOption *options = NULL;
2755 
2756  initStringInfo(&buf);
2757 
2758  /*
2759  * Get list of valid libpq options.
2760  *
2761  * To avoid unnecessary work, we get the list once and use it throughout
2762  * the lifetime of this backend process. We don't need to care about
2763  * memory context issues, because PQconndefaults allocates with malloc.
2764  */
2765  if (!options)
2766  {
2767  options = PQconndefaults();
2768  if (!options) /* assume reason for failure is OOM */
2769  ereport(ERROR,
2770  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2771  errmsg("out of memory"),
2772  errdetail("could not get libpq's default connection options")));
2773  }
2774 
2775  /* first gather the server connstr options */
2776  srvname = pstrdup(servername);
2777  truncate_identifier(srvname, strlen(srvname), false);
2778  foreign_server = GetForeignServerByName(srvname, true);
2779 
2780  if (foreign_server)
2781  {
2782  Oid serverid = foreign_server->serverid;
2783  Oid fdwid = foreign_server->fdwid;
2784  Oid userid = GetUserId();
2785 
2786  user_mapping = GetUserMapping(userid, serverid);
2787  fdw = GetForeignDataWrapper(fdwid);
2788 
2789  /* Check permissions, user must have usage on the server. */
2790  aclresult = pg_foreign_server_aclcheck(serverid, userid, ACL_USAGE);
2791  if (aclresult != ACLCHECK_OK)
2792  aclcheck_error(aclresult, ACL_KIND_FOREIGN_SERVER, foreign_server->servername);
2793 
2794  foreach(cell, fdw->options)
2795  {
2796  DefElem *def = lfirst(cell);
2797 
2799  appendStringInfo(&buf, "%s='%s' ", def->defname,
2800  escape_param_str(strVal(def->arg)));
2801  }
2802 
2803  foreach(cell, foreign_server->options)
2804  {
2805  DefElem *def = lfirst(cell);
2806 
2808  appendStringInfo(&buf, "%s='%s' ", def->defname,
2809  escape_param_str(strVal(def->arg)));
2810  }
2811 
2812  foreach(cell, user_mapping->options)
2813  {
2814 
2815  DefElem *def = lfirst(cell);
2816 
2818  appendStringInfo(&buf, "%s='%s' ", def->defname,
2819  escape_param_str(strVal(def->arg)));
2820  }
2821 
2822  return buf.data;
2823  }
2824  else
2825  return NULL;
2826 }
Oid GetUserId(void)
Definition: miscinit.c:284
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#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:78
#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:67
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:80
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:720
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
List * options
Definition: foreign.h:42
AclResult
Definition: acl.h:178
#define ForeignServerRelationId
#define lfirst(lc)
Definition: pg_list.h:106
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1224
#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:719
List * options
Definition: foreign.h:53
Oid serverid
Definition: foreign.h:47
static char ** get_pkey_attnames ( Relation  rel,
int16 numatts 
)
static

Definition at line 2033 of file dblink.c.

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

Referenced by dblink_get_pkey().

2034 {
2035  Relation indexRelation;
2036  ScanKeyData skey;
2037  SysScanDesc scan;
2038  HeapTuple indexTuple;
2039  int i;
2040  char **result = NULL;
2041  TupleDesc tupdesc;
2042 
2043  /* initialize numatts to 0 in case no primary key exists */
2044  *numatts = 0;
2045 
2046  tupdesc = rel->rd_att;
2047 
2048  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2049  indexRelation = heap_open(IndexRelationId, AccessShareLock);
2050  ScanKeyInit(&skey,
2052  BTEqualStrategyNumber, F_OIDEQ,
2054 
2055  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2056  NULL, 1, &skey);
2057 
2058  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2059  {
2060  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2061 
2062  /* we're only interested if it is the primary key */
2063  if (index->indisprimary)
2064  {
2065  *numatts = index->indnatts;
2066  if (*numatts > 0)
2067  {
2068  result = (char **) palloc(*numatts * sizeof(char *));
2069 
2070  for (i = 0; i < *numatts; i++)
2071  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2072  }
2073  break;
2074  }
2075  }
2076 
2077  systable_endscan(scan);
2078  heap_close(indexRelation, AccessShareLock);
2079 
2080  return result;
2081 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c: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:1633
#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:784
Definition: type.h:89
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:1290
TupleDesc rd_att
Definition: rel.h:115
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void * palloc(Size size)
Definition: mcxt.c:848
int i
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:416
#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 2495 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().

2496 {
2497  RangeVar *relvar;
2498  Relation rel;
2499  AclResult aclresult;
2500 
2501  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2502  rel = heap_openrv(relvar, lockmode);
2503 
2504  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2505  aclmode);
2506  if (aclresult != ACLCHECK_OK)
2507  aclcheck_error(aclresult, ACL_KIND_CLASS,
2509 
2510  return rel;
2511 }
Oid GetUserId(void)
Definition: miscinit.c:284
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3023
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RelationGetRelationName(relation)
Definition: rel.h:436
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3202
AclResult
Definition: acl.h:178
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
#define RelationGetRelid(relation)
Definition: rel.h:416
static char * get_sql_delete ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  tgt_pkattvals 
)
static

Definition at line 2224 of file dblink.c.

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

Referenced by dblink_build_sql_delete().

2225 {
2226  char *relname;
2227  TupleDesc tupdesc;
2229  int i;
2230 
2231  initStringInfo(&buf);
2232 
2233  /* get relation name including any needed schema prefix and quoting */
2234  relname = generate_relation_name(rel);
2235 
2236  tupdesc = rel->rd_att;
2237 
2238  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2239  for (i = 0; i < pknumatts; i++)
2240  {
2241  int pkattnum = pkattnums[i];
2242  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2243 
2244  if (i > 0)
2245  appendStringInfoString(&buf, " AND ");
2246 
2248  quote_ident_cstr(NameStr(attr->attname)));
2249 
2250  if (tgt_pkattvals[i] != NULL)
2251  appendStringInfo(&buf, " = %s",
2252  quote_literal_cstr(tgt_pkattvals[i]));
2253  else
2254  appendStringInfoString(&buf, " IS NULL");
2255  }
2256 
2257  return buf.data;
2258 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:67
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
TupleDesc rd_att
Definition: rel.h:115
int i
#define NameStr(name)
Definition: c.h:493
static char * get_sql_insert ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals,
char **  tgt_pkattvals 
)
static

Definition at line 2144 of file dblink.c.

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

Referenced by dblink_build_sql_insert().

2145 {
2146  char *relname;
2147  HeapTuple tuple;
2148  TupleDesc tupdesc;
2149  int natts;
2151  char *val;
2152  int key;
2153  int i;
2154  bool needComma;
2155 
2156  initStringInfo(&buf);
2157 
2158  /* get relation name including any needed schema prefix and quoting */
2159  relname = generate_relation_name(rel);
2160 
2161  tupdesc = rel->rd_att;
2162  natts = tupdesc->natts;
2163 
2164  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2165  if (!tuple)
2166  ereport(ERROR,
2167  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2168  errmsg("source row not found")));
2169 
2170  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2171 
2172  needComma = false;
2173  for (i = 0; i < natts; i++)
2174  {
2175  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2176 
2177  if (att->attisdropped)
2178  continue;
2179 
2180  if (needComma)
2181  appendStringInfoChar(&buf, ',');
2182 
2184  quote_ident_cstr(NameStr(att->attname)));
2185  needComma = true;
2186  }
2187 
2188  appendStringInfoString(&buf, ") VALUES(");
2189 
2190  /*
2191  * Note: i is physical column number (counting from 0).
2192  */
2193  needComma = false;
2194  for (i = 0; i < natts; i++)
2195  {
2196  if (TupleDescAttr(tupdesc, i)->attisdropped)
2197  continue;
2198 
2199  if (needComma)
2200  appendStringInfoChar(&buf, ',');
2201 
2202  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2203 
2204  if (key >= 0)
2205  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2206  else
2207  val = SPI_getvalue(tuple, tupdesc, i + 1);
2208 
2209  if (val != NULL)
2210  {
2212  pfree(val);
2213  }
2214  else
2215  appendStringInfoString(&buf, "NULL");
2216  needComma = true;
2217  }
2218  appendStringInfoChar(&buf, ')');
2219 
2220  return buf.data;
2221 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
char * pstrdup(const char *in)
Definition: mcxt.c:1076
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:806
void pfree(void *pointer)
Definition: mcxt.c:949
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
static char * buf
Definition: pg_test_fsync.c:67
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
TupleDesc rd_att
Definition: rel.h:115
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:493
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 2261 of file dblink.c.

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

Referenced by dblink_build_sql_update().

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

Definition at line 2088 of file dblink.c.

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

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

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

References appendStringInfo(), appendStringInfoString(), buf, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), i, initStringInfo(), NameStr, tupleDesc::natts, 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, TupleDescAttr, and SPITupleTable::vals.

Referenced by get_sql_insert(), and get_sql_update().

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

Definition at line 2538 of file dblink.c.

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

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

2539 {
2540  remoteConnHashEnt *hentry;
2541  char *key;
2542 
2543  if (!remoteConnHash)
2545 
2546  key = pstrdup(name);
2547  truncate_identifier(key, strlen(key), false);
2549  key, HASH_FIND, NULL);
2550 
2551  if (hentry)
2552  return hentry->rconn;
2553 
2554  return NULL;
2555 }
char * pstrdup(const char *in)
Definition: mcxt.c:1076
remoteConn * rconn
Definition: dblink.c:141
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
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 2938 of file dblink.c.

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

Referenced by dblink_fdw_validator(), and get_connect_string().

2940 {
2941  const PQconninfoOption *opt;
2942 
2943  /* Look up the option in libpq result */
2944  for (opt = options; opt->keyword; opt++)
2945  {
2946  if (strcmp(opt->keyword, option) == 0)
2947  break;
2948  }
2949  if (opt->keyword == NULL)
2950  return false;
2951 
2952  /* Disallow debug options (particularly "replication") */
2953  if (strchr(opt->dispchar, 'D'))
2954  return false;
2955 
2956  /* Disallow "client_encoding" */
2957  if (strcmp(opt->keyword, "client_encoding") == 0)
2958  return false;
2959 
2960  /*
2961  * If the option is "user" or marked secure, it should be specified only
2962  * in USER MAPPING. Others should be specified only in SERVER.
2963  */
2964  if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
2965  {
2966  if (context != UserMappingRelationId)
2967  return false;
2968  }
2969  else
2970  {
2971  if (context != ForeignServerRelationId)
2972  return false;
2973  }
2974 
2975  return true;
2976 }
#define ForeignServerRelationId
#define UserMappingRelationId
static void materializeQueryResult ( FunctionCallInfo  fcinfo,
PGconn conn,
const char *  conname,
const char *  sql,
bool  fail 
)
static

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

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

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

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

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

158 {
159  char *msg = pchomp(PQerrorMessage(conn));
160 
161  if (res)
162  PQclear(res);
163  elog(ERROR, "%s: %s", p2, msg);
164 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
char * pchomp(const char *in)
Definition: mcxt.c:1100
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:49
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#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 800 of file dblink.c.

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

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

801 {
802  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
803 
804  /* check to see if query supports us returning a tuplestore */
805  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
806  ereport(ERROR,
807  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
808  errmsg("set-valued function called in context that cannot accept a set")));
809  if (!(rsinfo->allowedModes & SFRM_Materialize))
810  ereport(ERROR,
811  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
812  errmsg("materialize mode required, but it is not allowed in this context")));
813 
814  /* let the executor know we're sending back a tuplestore */
815  rsinfo->returnMode = SFRM_Materialize;
816 
817  /* caller must fill these to return a non-empty result */
818  rsinfo->setResult = NULL;
819  rsinfo->setDesc = NULL;
820 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
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:268
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
Tuplestorestate * setResult
Definition: execnodes.h:273
TupleDesc setDesc
Definition: execnodes.h:274
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * quote_ident_cstr ( char *  rawstr)
static

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

2353 {
2354  text *rawstr_text;
2355  text *result_text;
2356  char *result;
2357 
2358  rawstr_text = cstring_to_text(rawstr);
2360  PointerGetDatum(rawstr_text)));
2361  result = text_to_cstring(result_text);
2362 
2363  return result;
2364 }
#define PointerGetDatum(X)
Definition: postgres.h:562
#define DatumGetTextPP(X)
Definition: fmgr.h:256
return result
Definition: formatting.c:1633
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
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:433
static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3041 of file dblink.c.

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

3042 {
3043  /* Do nothing if no new nestlevel was created */
3044  if (nestlevel > 0)
3045  AtEOXact_GUC(true, nestlevel);
3046 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5089
static PGresult * storeQueryResult ( volatile storeInfo sinfo,
PGconn conn,
const char *  sql 
)
static

Definition at line 1092 of file dblink.c.

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

Referenced by materializeQueryResult().

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

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

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

Definition at line 2867 of file dblink.c.

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

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

2870 {
2871  TupleDesc tupdesc = rel->rd_att;
2872  int natts = tupdesc->natts;
2873  int i;
2874 
2875  /* Don't take more array elements than there are */
2876  pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2877 
2878  /* Must have at least one pk attnum selected */
2879  if (pknumatts_arg <= 0)
2880  ereport(ERROR,
2881  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2882  errmsg("number of key attributes must be > 0")));
2883 
2884  /* Allocate output array */
2885  *pkattnums = (int *) palloc(pknumatts_arg * sizeof(int));
2886  *pknumatts = pknumatts_arg;
2887 
2888  /* Validate attnums and convert to internal form */
2889  for (i = 0; i < pknumatts_arg; i++)
2890  {
2891  int pkattnum = pkattnums_arg->values[i];
2892  int lnum;
2893  int j;
2894 
2895  /* Can throw error immediately if out of range */
2896  if (pkattnum <= 0 || pkattnum > natts)
2897  ereport(ERROR,
2898  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2899  errmsg("invalid attribute number %d", pkattnum)));
2900 
2901  /* Identify which physical column has this logical number */
2902  lnum = 0;
2903  for (j = 0; j < natts; j++)
2904  {
2905  /* dropped columns don't count */
2906  if (TupleDescAttr(tupdesc, j)->attisdropped)
2907  continue;
2908 
2909  if (++lnum == pkattnum)
2910  break;
2911  }
2912 
2913  if (j < natts)
2914  (*pkattnums)[i] = j;
2915  else
2916  ereport(ERROR,
2917  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2918  errmsg("invalid attribute number %d", pkattnum)));
2919  }
2920 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
#define Min(x, y)
Definition: c.h:795
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:467
TupleDesc rd_att
Definition: rel.h:115
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:469
void * palloc(Size size)
Definition: mcxt.c:848
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 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:1076

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.