PostgreSQL Source Code  git master
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 *indnkeyatts)
 
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, bool fail, const char *fmt,...) pg_attribute_printf(5
 
static void 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

◆ DBLINK_NOTIFY_COLS

#define DBLINK_NOTIFY_COLS   3

Definition at line 1881 of file dblink.c.

Referenced by dblink_get_notify().

◆ NUMCONN

#define NUMCONN   16

Definition at line 145 of file dblink.c.

Referenced by createConnHash().

Typedef Documentation

◆ remoteConn

◆ remoteConnHashEnt

◆ storeInfo

Function Documentation

◆ applyRemoteGucs()

static int applyRemoteGucs ( PGconn conn)
static

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

3018 {
3019  static const char *const GUCsAffectingIO[] = {
3020  "DateStyle",
3021  "IntervalStyle"
3022  };
3023 
3024  int nestlevel = -1;
3025  int i;
3026 
3027  for (i = 0; i < lengthof(GUCsAffectingIO); i++)
3028  {
3029  const char *gucName = GUCsAffectingIO[i];
3030  const char *remoteVal = PQparameterStatus(conn, gucName);
3031  const char *localVal;
3032 
3033  /*
3034  * If the remote server is pre-8.4, it won't have IntervalStyle, but
3035  * that's okay because its output format won't be ambiguous. So just
3036  * skip the GUC if we don't get a value for it. (We might eventually
3037  * need more complicated logic with remote-version checks here.)
3038  */
3039  if (remoteVal == NULL)
3040  continue;
3041 
3042  /*
3043  * Avoid GUC-setting overhead if the remote and local GUCs already
3044  * have the same value.
3045  */
3046  localVal = GetConfigOption(gucName, false, false);
3047  Assert(localVal != NULL);
3048 
3049  if (strcmp(remoteVal, localVal) == 0)
3050  continue;
3051 
3052  /* Create new GUC nest level if we didn't already */
3053  if (nestlevel < 0)
3054  nestlevel = NewGUCNestLevel();
3055 
3056  /* Apply the option (this will throw error on failure) */
3057  (void) set_config_option(gucName, remoteVal,
3059  GUC_ACTION_SAVE, true, 0, false);
3060  }
3061 
3062  return nestlevel;
3063 }
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
Definition: guc.c:6931
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6081
#define lengthof(array)
Definition: c.h:629
#define Assert(condition)
Definition: c.h:699
int NewGUCNestLevel(void)
Definition: guc.c:5298
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:6142

◆ createConnHash()

static HTAB * createConnHash ( void  )
static

Definition at line 2560 of file dblink.c.

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

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

2561 {
2562  HASHCTL ctl;
2563 
2564  ctl.keysize = NAMEDATALEN;
2565  ctl.entrysize = sizeof(remoteConnHashEnt);
2566 
2567  return hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
2568 }
#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

◆ createNewConnection()

static void createNewConnection ( const char *  name,
remoteConn rconn 
)
static

Definition at line 2571 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, remoteConnHash, strlcpy(), and truncate_identifier().

Referenced by dblink_connect().

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

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1709 of file dblink.c.

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

Referenced by dblink_build_sql_insert().

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

◆ dblink_build_sql_insert()

Datum dblink_build_sql_insert ( PG_FUNCTION_ARGS  )

Definition at line 1618 of file dblink.c.

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

Referenced by dblink_get_pkey().

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

◆ dblink_build_sql_update()

Datum dblink_build_sql_update ( PG_FUNCTION_ARGS  )

Definition at line 1786 of file dblink.c.

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

Referenced by dblink_build_sql_delete().

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

◆ dblink_cancel_query()

Datum dblink_cancel_query ( PG_FUNCTION_ARGS  )

Definition at line 1333 of file dblink.c.

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

Referenced by dblink_is_busy().

1334 {
1335  int res;
1336  PGconn *conn;
1337  PGcancel *cancel;
1338  char errbuf[256];
1339 
1340  dblink_init();
1342  cancel = PQgetCancel(conn);
1343 
1344  res = PQcancel(cancel, errbuf, 256);
1345  PQfreeCancel(cancel);
1346 
1347  if (res == 1)
1349  else
1351 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:3782
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
PGconn * conn
Definition: streamutil.c:55
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:3759
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:336
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:3914

◆ dblink_close()

Datum dblink_close ( PG_FUNCTION_ARGS  )

Definition at line 458 of file dblink.c.

References appendStringInfo(), buf, remoteConn::conn, cstring_to_text(), StringInfoData::data, dblink_fetch(), dblink_init(), dblink_res_error(), get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), remoteConn::newXactForCursor, remoteConn::openCursorCount, pconn, PG_FUNCTION_INFO_V1(), PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), and text_to_cstring().

Referenced by dblink_open().

459 {
460  PGconn *conn;
461  PGresult *res = NULL;
462  char *curname = NULL;
463  char *conname = NULL;
465  remoteConn *rconn = NULL;
466  bool fail = true; /* default to backward compatible behavior */
467 
468  dblink_init();
469  initStringInfo(&buf);
470 
471  if (PG_NARGS() == 1)
472  {
473  /* text */
474  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
475  rconn = pconn;
476  }
477  else if (PG_NARGS() == 2)
478  {
479  /* might be text,text or text,bool */
480  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
481  {
482  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
483  fail = PG_GETARG_BOOL(1);
484  rconn = pconn;
485  }
486  else
487  {
488  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
489  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
490  rconn = getConnectionByName(conname);
491  }
492  }
493  if (PG_NARGS() == 3)
494  {
495  /* text,text,bool */
496  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
497  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
498  fail = PG_GETARG_BOOL(2);
499  rconn = getConnectionByName(conname);
500  }
501 
502  if (!rconn || !rconn->conn)
503  dblink_conn_not_avail(conname);
504 
505  conn = rconn->conn;
506 
507  appendStringInfo(&buf, "CLOSE %s", curname);
508 
509  /* close the cursor */
510  res = PQexec(conn, buf.data);
511  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
512  {
513  dblink_res_error(conn, conname, res, fail,
514  "while closing cursor \"%s\"", curname);
516  }
517 
518  PQclear(res);
519 
520  /* if we started a transaction, decrement cursor count */
521  if (rconn->newXactForCursor)
522  {
523  (rconn->openCursorCount)--;
524 
525  /* if count is zero, commit the transaction */
526  if (rconn->openCursorCount == 0)
527  {
528  rconn->newXactForCursor = false;
529 
530  res = PQexec(conn, "COMMIT");
531  if (PQresultStatus(res) != PGRES_COMMAND_OK)
532  dblink_res_internalerror(conn, res, "commit error");
533  PQclear(res);
534  }
535  }
536 
538 }
int openCursorCount
Definition: dblink.c:69
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:244
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
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:1995
PGconn * conn
Definition: streamutil.c:55
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:336
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define PG_NARGS()
Definition: fmgr.h:173
char * text_to_cstring(const text *t)
Definition: varlena.c:182
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 255 of file dblink.c.

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

Referenced by dblink_init().

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:6116
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3638
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6176
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
PGconn * conn
Definition: dblink.c:68
char * pchomp(const char *in)
Definition: mcxt.c:1189
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:55
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int GetDatabaseEncoding(void)
Definition: mbutils.c:1004
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6184
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:336
text * cstring_to_text(const char *s)
Definition: varlena.c:149
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1010
#define PG_NARGS()
Definition: fmgr.h:173
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:771
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6063
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:592
static char * connstr
Definition: pg_dumpall.c:59

◆ dblink_connstr_check()

static void dblink_connstr_check ( const char *  connstr)
static

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

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

◆ dblink_current_query()

Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1867 of file dblink.c.

References current_query(), and PG_RETURN_DATUM.

Referenced by dblink_build_sql_update().

1868 {
1869  /* This is now just an alias for the built-in function current_query() */
1870  PG_RETURN_DATUM(current_query(fcinfo));
1871 }
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:192
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:318

◆ dblink_disconnect()

Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 327 of file dblink.c.

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

Referenced by dblink_connect().

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:3638
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
PGconn * conn
Definition: dblink.c:68
void pfree(void *pointer)
Definition: mcxt.c:1031
PGconn * conn
Definition: streamutil.c:55
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:336
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define PG_NARGS()
Definition: fmgr.h:173
char * text_to_cstring(const text *t)
Definition: varlena.c:182

◆ dblink_error_message()

Datum dblink_error_message ( PG_FUNCTION_ARGS  )

Definition at line 1366 of file dblink.c.

References remoteConn::conn, cstring_to_text(), dblink_exec(), dblink_get_named_conn(), dblink_init(), pchomp(), PG_FUNCTION_INFO_V1(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PQerrorMessage(), and text_to_cstring().

Referenced by dblink_cancel_query().

1367 {
1368  char *msg;
1369  PGconn *conn;
1370 
1371  dblink_init();
1373 
1374  msg = PQerrorMessage(conn);
1375  if (msg == NULL || msg[0] == '\0')
1377  else
1379 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
char * pchomp(const char *in)
Definition: mcxt.c:1189
PGconn * conn
Definition: streamutil.c:55
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:336
text * cstring_to_text(const char *s)
Definition: varlena.c:149
char * text_to_cstring(const text *t)
Definition: varlena.c:182

◆ dblink_exec()

Datum dblink_exec ( PG_FUNCTION_ARGS  )

Definition at line 1386 of file dblink.c.

References remoteConn::conn, cstring_to_text(), dblink_get_conn(), dblink_get_pkey(), dblink_init(), dblink_res_error(), elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), pconn, PG_CATCH, PG_END_TRY, PG_FUNCTION_INFO_V1(), 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().

Referenced by dblink_error_message().

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

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

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

Referenced by dblink_get_notify().

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

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

Definition at line 545 of file dblink.c.

References appendStringInfo(), buf, remoteConn::conn, StringInfoData::data, dblink_init(), dblink_record(), dblink_res_error(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), materializeResult(), pconn, PG_FUNCTION_INFO_V1(), 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().

Referenced by dblink_close().

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

◆ dblink_get_conn()

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 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:6116
int errcode(int sqlerrcode)
Definition: elog.c:575
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3638
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6176
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
PGconn * conn
Definition: dblink.c:68
char * pchomp(const char *in)
Definition: mcxt.c:1189
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:55
#define ereport(elevel, rest)
Definition: elog.h:122
int GetDatabaseEncoding(void)
Definition: mbutils.c:1004
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6184
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1010
int errmsg(const char *fmt,...)
Definition: elog.c:797
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6063
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:592
static char * connstr
Definition: pg_dumpall.c:59

◆ dblink_get_connections()

Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1274 of file dblink.c.

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

Referenced by storeRow().

1275 {
1277  remoteConnHashEnt *hentry;
1278  ArrayBuildState *astate = NULL;
1279 
1280  if (remoteConnHash)
1281  {
1282  hash_seq_init(&status, remoteConnHash);
1283  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1284  {
1285  /* stash away current value */
1286  astate = accumArrayResult(astate,
1287  CStringGetTextDatum(hentry->name),
1288  false, TEXTOID, CurrentMemoryContext);
1289  }
1290  }
1291 
1292  if (astate)
1295  else
1296  PG_RETURN_NULL();
1297 }
char name[NAMEDATALEN]
Definition: dblink.c:140
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:250
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5106
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1389
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1379
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5042
#define CStringGetTextDatum(s)
Definition: builtins.h:95
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
#define PG_RETURN_NULL()
Definition: fmgr.h:310

◆ dblink_get_named_conn()

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

◆ dblink_get_notify()

Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

Definition at line 1885 of file dblink.c.

References pgNotify::be_pid, remoteConn::conn, CreateTemplateTupleDesc(), CStringGetTextDatum, dblink_fdw_validator(), dblink_get_named_conn(), dblink_init(), DBLINK_NOTIFY_COLS, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, pgNotify::extra, Int32GetDatum, MemoryContextSwitchTo(), pconn, PG_FUNCTION_INFO_V1(), PG_GETARG_TEXT_PP, PG_NARGS, PQconsumeInput(), PQfreemem(), PQnotifies(), prepTuplestoreResult(), pgNotify::relname, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, text_to_cstring(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

1886 {
1887  PGconn *conn;
1888  PGnotify *notify;
1889  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1890  TupleDesc tupdesc;
1891  Tuplestorestate *tupstore;
1892  MemoryContext per_query_ctx;
1893  MemoryContext oldcontext;
1894 
1895  prepTuplestoreResult(fcinfo);
1896 
1897  dblink_init();
1898  if (PG_NARGS() == 1)
1900  else
1901  conn = pconn->conn;
1902 
1903  /* create the tuplestore in per-query memory */
1904  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1905  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1906 
1907  tupdesc = CreateTemplateTupleDesc(DBLINK_NOTIFY_COLS, false);
1908  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1909  TEXTOID, -1, 0);
1910  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1911  INT4OID, -1, 0);
1912  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1913  TEXTOID, -1, 0);
1914 
1915  tupstore = tuplestore_begin_heap(true, false, work_mem);
1916  rsinfo->setResult = tupstore;
1917  rsinfo->setDesc = tupdesc;
1918 
1919  MemoryContextSwitchTo(oldcontext);
1920 
1921  PQconsumeInput(conn);
1922  while ((notify = PQnotifies(conn)) != NULL)
1923  {
1925  bool nulls[DBLINK_NOTIFY_COLS];
1926 
1927  memset(values, 0, sizeof(values));
1928  memset(nulls, 0, sizeof(nulls));
1929 
1930  if (notify->relname != NULL)
1931  values[0] = CStringGetTextDatum(notify->relname);
1932  else
1933  nulls[0] = true;
1934 
1935  values[1] = Int32GetDatum(notify->be_pid);
1936 
1937  if (notify->extra != NULL)
1938  values[2] = CStringGetTextDatum(notify->extra);
1939  else
1940  nulls[2] = true;
1941 
1942  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1943 
1944  PQfreemem(notify);
1945  PQconsumeInput(conn);
1946  }
1947 
1948  /* clean up and return the tuplestore */
1949  tuplestore_donestoring(tupstore);
1950 
1951  return (Datum) 0;
1952 }
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 tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
PGconn * conn
Definition: dblink.c:68
PGconn * conn
Definition: streamutil.c:55
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:600
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:367
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1682
int work_mem
Definition: globals.c:122
#define PG_NARGS()
Definition: fmgr.h:173
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:225
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:45
Tuplestorestate * setResult
Definition: execnodes.h:302
static Datum values[MAXATTR]
Definition: bootstrap.c:164
char * text_to_cstring(const text *t)
Definition: varlena.c:182
ExprContext * econtext
Definition: execnodes.h:295
#define Int32GetDatum(X)
Definition: postgres.h:464
TupleDesc setDesc
Definition: execnodes.h:303
#define CStringGetTextDatum(s)
Definition: builtins.h:95
int16 AttrNumber
Definition: attnum.h:21
void PQfreemem(void *ptr)
Definition: fe-exec.c:3251

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1494 of file dblink.c.

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

Referenced by dblink_exec().

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

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 671 of file dblink.c.

References dblink_record_internal().

Referenced by dblink_send_query().

672 {
673  return dblink_record_internal(fcinfo, true);
674 }

◆ dblink_init()

static void dblink_init ( void  )
static

Definition at line 239 of file dblink.c.

References remoteConn::conn, dblink_connect(), MemoryContextAlloc(), remoteConn::newXactForCursor, remoteConn::openCursorCount, pconn, PG_FUNCTION_INFO_V1(), 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;
246  pconn->newXactForCursor = false;
247  }
248 }
int openCursorCount
Definition: dblink.c:69
PGconn * conn
Definition: dblink.c:68
MemoryContext TopMemoryContext
Definition: mcxt.c:44
bool newXactForCursor
Definition: dblink.c:70
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1309 of file dblink.c.

References remoteConn::conn, dblink_cancel_query(), dblink_get_named_conn(), dblink_init(), PG_FUNCTION_INFO_V1(), PG_GETARG_TEXT_PP, PG_RETURN_INT32, PQconsumeInput(), PQisBusy(), and text_to_cstring().

Referenced by dblink_get_connections().

1310 {
1311  PGconn *conn;
1312 
1313  dblink_init();
1315 
1316  PQconsumeInput(conn);
1317  PG_RETURN_INT32(PQisBusy(conn));
1318 }
#define PG_RETURN_INT32(x)
Definition: fmgr.h:319
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
PGconn * conn
Definition: streamutil.c:55
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

◆ dblink_open()

Datum dblink_open ( PG_FUNCTION_ARGS  )

Definition at line 365 of file dblink.c.

References appendStringInfo(), buf, remoteConn::conn, cstring_to_text(), StringInfoData::data, dblink_close(), dblink_init(), dblink_res_error(), get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), remoteConn::newXactForCursor, remoteConn::openCursorCount, pconn, PG_FUNCTION_INFO_V1(), PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PGRES_COMMAND_OK, PQclear(), PQexec(), PQresultStatus(), PQTRANS_IDLE, PQtransactionStatus(), and text_to_cstring().

Referenced by dblink_disconnect().

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, fail,
445  "while opening cursor \"%s\"", curname);
447  }
448 
449  PQclear(res);
451 }
int openCursorCount
Definition: dblink.c:69
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:244
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
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:1995
PGconn * conn
Definition: streamutil.c:55
static char * buf
Definition: pg_test_fsync.c:67
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6071
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:336
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define PG_NARGS()
Definition: fmgr.h:173
char * text_to_cstring(const text *t)
Definition: varlena.c:182
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897

◆ dblink_record()

Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 639 of file dblink.c.

References dblink_record_internal(), dblink_send_query(), and PG_FUNCTION_INFO_V1().

Referenced by dblink_fetch().

640 {
641  return dblink_record_internal(fcinfo, false);
642 }

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 677 of file dblink.c.

References remoteConn::conn, dblink_get_conn(), dblink_get_named_conn(), dblink_init(), dblink_res_error(), elog, ERROR, FunctionCallInfoData::flinfo, get_fn_expr_argtype(), materializeQueryResult(), materializeResult(), pconn, 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().

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

◆ dblink_res_error()

static void dblink_res_error ( PGconn conn,
const char *  conname,
PGresult res,
bool  fail,
const char *  fmt,
  ... 
)
static

Definition at line 2690 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(), vsnprintf(), and xpstrdup().

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

2692 {
2693  int level;
2694  char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2695  char *pg_diag_message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2696  char *pg_diag_message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2697  char *pg_diag_message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2698  char *pg_diag_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2699  int sqlstate;
2700  char *message_primary;
2701  char *message_detail;
2702  char *message_hint;
2703  char *message_context;
2704  va_list ap;
2705  char dblink_context_msg[512];
2706 
2707  if (fail)
2708  level = ERROR;
2709  else
2710  level = NOTICE;
2711 
2712  if (pg_diag_sqlstate)
2713  sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2714  pg_diag_sqlstate[1],
2715  pg_diag_sqlstate[2],
2716  pg_diag_sqlstate[3],
2717  pg_diag_sqlstate[4]);
2718  else
2719  sqlstate = ERRCODE_CONNECTION_FAILURE;
2720 
2721  message_primary = xpstrdup(pg_diag_message_primary);
2722  message_detail = xpstrdup(pg_diag_message_detail);
2723  message_hint = xpstrdup(pg_diag_message_hint);
2724  message_context = xpstrdup(pg_diag_context);
2725 
2726  /*
2727  * If we don't get a message from the PGresult, try the PGconn. This is
2728  * needed because for connection-level failures, PQexec may just return
2729  * NULL, not a PGresult at all.
2730  */
2731  if (message_primary == NULL)
2732  message_primary = pchomp(PQerrorMessage(conn));
2733 
2734  /*
2735  * Now that we've copied all the data we need out of the PGresult, it's
2736  * safe to free it. We must do this to avoid PGresult leakage. We're
2737  * leaking all the strings too, but those are in palloc'd memory that will
2738  * get cleaned up eventually.
2739  */
2740  if (res)
2741  PQclear(res);
2742 
2743  /*
2744  * Format the basic errcontext string. Below, we'll add on something
2745  * about the connection name. That's a violation of the translatability
2746  * guidelines about constructing error messages out of parts, but since
2747  * there's no translation support for dblink, there's no need to worry
2748  * about that (yet).
2749  */
2750  va_start(ap, fmt);
2751  vsnprintf(dblink_context_msg, sizeof(dblink_context_msg), fmt, ap);
2752  va_end(ap);
2753 
2754  ereport(level,
2755  (errcode(sqlstate),
2756  message_primary ? errmsg_internal("%s", message_primary) :
2757  errmsg("could not obtain message string for remote error"),
2758  message_detail ? errdetail_internal("%s", message_detail) : 0,
2759  message_hint ? errhint("%s", message_hint) : 0,
2760  message_context ? (errcontext("%s", message_context)) : 0,
2761  conname ?
2762  (errcontext("%s on dblink connection named \"%s\"",
2763  dblink_context_msg, conname)) :
2764  (errcontext("%s on unnamed dblink connection",
2765  dblink_context_msg))));
2766 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
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
int int vsnprintf(char *str, size_t count, const char *fmt, va_list args)
char * pchomp(const char *in)
Definition: mcxt.c:1189
#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

◆ dblink_security_check()

static void dblink_security_check ( PGconn conn,
remoteConn rconn 
)
static

Definition at line 2622 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

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

◆ dblink_send_query()

Datum dblink_send_query ( PG_FUNCTION_ARGS  )

Definition at line 646 of file dblink.c.

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

Referenced by dblink_record().

647 {
648  PGconn *conn;
649  char *sql;
650  int retval;
651 
652  if (PG_NARGS() == 2)
653  {
656  }
657  else
658  /* shouldn't happen */
659  elog(ERROR, "wrong number of arguments");
660 
661  /* async query send */
662  retval = PQsendQuery(conn, sql);
663  if (retval != 1)
664  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
665 
666  PG_RETURN_INT32(retval);
667 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6116
#define PG_RETURN_INT32(x)
Definition: fmgr.h:319
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:278
char * pchomp(const char *in)
Definition: mcxt.c:1189
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1183
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:55
#define NOTICE
Definition: elog.h:37
#define PG_NARGS()
Definition: fmgr.h:173
char * text_to_cstring(const text *t)
Definition: varlena.c:182
#define elog
Definition: elog.h:219

◆ deleteConnection()

static void deleteConnection ( const char *  name)
static

Definition at line 2600 of file dblink.c.

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

Referenced by dblink_disconnect().

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

◆ escape_param_str()

static char * escape_param_str ( const char *  from)
static

Definition at line 2862 of file dblink.c.

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

Referenced by get_connect_string().

2863 {
2864  const char *cp;
2866 
2867  initStringInfo(&buf);
2868 
2869  for (cp = str; *cp; cp++)
2870  {
2871  if (*cp == '\\' || *cp == '\'')
2872  appendStringInfoChar(&buf, '\\');
2873  appendStringInfoChar(&buf, *cp);
2874  }
2875 
2876  return buf.data;
2877 }
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

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

Definition at line 2522 of file dblink.c.

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

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

2523 {
2524  char *nspname;
2525  char *result;
2526 
2527  /* Qualify the name if not visible in search path */
2529  nspname = NULL;
2530  else
2531  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2532 
2533  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2534 
2535  return result;
2536 }
Form_pg_class rd_rel
Definition: rel.h:84
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
#define RelationGetRelationName(relation)
Definition: rel.h:441
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10574
bool RelationIsVisible(Oid relid)
Definition: namespace.c:701
#define RelationGetRelid(relation)
Definition: rel.h:407

◆ get_attnum_pk_pos()

static int get_attnum_pk_pos ( int *  pkattnums,
int  pknumatts,
int  key 
)
static

Definition at line 2369 of file dblink.c.

References i.

Referenced by get_sql_insert(), and get_sql_update().

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

◆ get_connect_string()

static char * get_connect_string ( const char *  servername)
static

Definition at line 2772 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

2773 {
2774  ForeignServer *foreign_server = NULL;
2775  UserMapping *user_mapping;
2776  ListCell *cell;
2778  ForeignDataWrapper *fdw;
2779  AclResult aclresult;
2780  char *srvname;
2781 
2782  static const PQconninfoOption *options = NULL;
2783 
2784  initStringInfo(&buf);
2785 
2786  /*
2787  * Get list of valid libpq options.
2788  *
2789  * To avoid unnecessary work, we get the list once and use it throughout
2790  * the lifetime of this backend process. We don't need to care about
2791  * memory context issues, because PQconndefaults allocates with malloc.
2792  */
2793  if (!options)
2794  {
2795  options = PQconndefaults();
2796  if (!options) /* assume reason for failure is OOM */
2797  ereport(ERROR,
2798  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2799  errmsg("out of memory"),
2800  errdetail("Could not get libpq's default connection options.")));
2801  }
2802 
2803  /* first gather the server connstr options */
2804  srvname = pstrdup(servername);
2805  truncate_identifier(srvname, strlen(srvname), false);
2806  foreign_server = GetForeignServerByName(srvname, true);
2807 
2808  if (foreign_server)
2809  {
2810  Oid serverid = foreign_server->serverid;
2811  Oid fdwid = foreign_server->fdwid;
2812  Oid userid = GetUserId();
2813 
2814  user_mapping = GetUserMapping(userid, serverid);
2815  fdw = GetForeignDataWrapper(fdwid);
2816 
2817  /* Check permissions, user must have usage on the server. */
2818  aclresult = pg_foreign_server_aclcheck(serverid, userid, ACL_USAGE);
2819  if (aclresult != ACLCHECK_OK)
2820  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, foreign_server->servername);
2821 
2822  foreach(cell, fdw->options)
2823  {
2824  DefElem *def = lfirst(cell);
2825 
2826  if (is_valid_dblink_option(options, def->defname, ForeignDataWrapperRelationId))
2827  appendStringInfo(&buf, "%s='%s' ", def->defname,
2828  escape_param_str(strVal(def->arg)));
2829  }
2830 
2831  foreach(cell, foreign_server->options)
2832  {
2833  DefElem *def = lfirst(cell);
2834 
2835  if (is_valid_dblink_option(options, def->defname, ForeignServerRelationId))
2836  appendStringInfo(&buf, "%s='%s' ", def->defname,
2837  escape_param_str(strVal(def->arg)));
2838  }
2839 
2840  foreach(cell, user_mapping->options)
2841  {
2842 
2843  DefElem *def = lfirst(cell);
2844 
2845  if (is_valid_dblink_option(options, def->defname, UserMappingRelationId))
2846  appendStringInfo(&buf, "%s='%s' ", def->defname,
2847  escape_param_str(strVal(def->arg)));
2848  }
2849 
2850  return buf.data;
2851  }
2852  else
2853  return NULL;
2854 }
Oid GetUserId(void)
Definition: miscinit.c:379
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#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
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3349
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:4727
static char * buf
Definition: pg_test_fsync.c:67
int errdetail(const char *fmt,...)
Definition: elog.c:873
List * options
Definition: foreign.h:61
#define ACL_USAGE
Definition: parsenodes.h:82
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:731
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
List * options
Definition: foreign.h:42
AclResult
Definition: acl.h:178
#define lfirst(lc)
Definition: pg_list.h:106
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1230
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * servername
Definition: foreign.h:50
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:166
char * defname
Definition: parsenodes.h:730
List * options
Definition: foreign.h:53
Oid serverid
Definition: foreign.h:47

◆ get_pkey_attnames()

static char ** get_pkey_attnames ( Relation  rel,
int16 indnkeyatts 
)
static

Definition at line 2035 of file dblink.c.

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

Referenced by dblink_get_pkey().

2036 {
2037  Relation indexRelation;
2038  ScanKeyData skey;
2039  SysScanDesc scan;
2040  HeapTuple indexTuple;
2041  int i;
2042  char **result = NULL;
2043  TupleDesc tupdesc;
2044 
2045  /* initialize indnkeyatts to 0 in case no primary key exists */
2046  *indnkeyatts = 0;
2047 
2048  tupdesc = rel->rd_att;
2049 
2050  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2051  indexRelation = heap_open(IndexRelationId, AccessShareLock);
2052  ScanKeyInit(&skey,
2053  Anum_pg_index_indrelid,
2054  BTEqualStrategyNumber, F_OIDEQ,
2056 
2057  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2058  NULL, 1, &skey);
2059 
2060  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2061  {
2062  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2063 
2064  /* we're only interested if it is the primary key */
2065  if (index->indisprimary)
2066  {
2067  *indnkeyatts = index->indnkeyatts;
2068  if (*indnkeyatts > 0)
2069  {
2070  result = (char **) palloc(*indnkeyatts * sizeof(char *));
2071 
2072  for (i = 0; i < *indnkeyatts; i++)
2073  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2074  }
2075  break;
2076  }
2077  }
2078 
2079  systable_endscan(scan);
2080  heap_close(indexRelation, AccessShareLock);
2081 
2082  return result;
2083 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:502
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:331
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:880
Definition: type.h:89
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:419
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
TupleDesc rd_att
Definition: rel.h:85
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void * palloc(Size size)
Definition: mcxt.c:924
int i
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define RelationGetRelid(relation)
Definition: rel.h:407
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define IndexIndrelidIndexId
Definition: indexing.h:163

◆ get_rel_from_relname()

static Relation get_rel_from_relname ( text relname_text,
LOCKMODE  lockmode,
AclMode  aclmode 
)
static

Definition at line 2497 of file dblink.c.

References aclcheck_error(), ACLCHECK_OK, get_relkind_objtype(), GetUserId(), heap_openrv(), makeRangeVarFromNameList(), pg_class_aclcheck(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, and textToQualifiedNameList().

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

2498 {
2499  RangeVar *relvar;
2500  Relation rel;
2501  AclResult aclresult;
2502 
2503  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2504  rel = heap_openrv(relvar, lockmode);
2505 
2506  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2507  aclmode);
2508  if (aclresult != ACLCHECK_OK)
2509  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2511 
2512  return rel;
2513 }
Oid GetUserId(void)
Definition: miscinit.c:379
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3042
Form_pg_class rd_rel
Definition: rel.h:84
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3349
#define RelationGetRelationName(relation)
Definition: rel.h:441
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3232
AclResult
Definition: acl.h:178
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1323
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4627
ObjectType get_relkind_objtype(char relkind)
#define RelationGetRelid(relation)
Definition: rel.h:407

◆ get_sql_delete()

static char * get_sql_delete ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  tgt_pkattvals 
)
static

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

2227 {
2228  char *relname;
2229  TupleDesc tupdesc;
2231  int i;
2232 
2233  initStringInfo(&buf);
2234 
2235  /* get relation name including any needed schema prefix and quoting */
2236  relname = generate_relation_name(rel);
2237 
2238  tupdesc = rel->rd_att;
2239 
2240  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2241  for (i = 0; i < pknumatts; i++)
2242  {
2243  int pkattnum = pkattnums[i];
2244  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2245 
2246  if (i > 0)
2247  appendStringInfoString(&buf, " AND ");
2248 
2250  quote_ident_cstr(NameStr(attr->attname)));
2251 
2252  if (tgt_pkattvals[i] != NULL)
2253  appendStringInfo(&buf, " = %s",
2254  quote_literal_cstr(tgt_pkattvals[i]));
2255  else
2256  appendStringInfoString(&buf, " IS NULL");
2257  }
2258 
2259  return buf.data;
2260 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
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:197
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
TupleDesc rd_att
Definition: rel.h:85
int i
#define NameStr(name)
Definition: c.h:576

◆ get_sql_insert()

static char * get_sql_insert ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals,
char **  tgt_pkattvals 
)
static

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

2147 {
2148  char *relname;
2149  HeapTuple tuple;
2150  TupleDesc tupdesc;
2151  int natts;
2153  char *val;
2154  int key;
2155  int i;
2156  bool needComma;
2157 
2158  initStringInfo(&buf);
2159 
2160  /* get relation name including any needed schema prefix and quoting */
2161  relname = generate_relation_name(rel);
2162 
2163  tupdesc = rel->rd_att;
2164  natts = tupdesc->natts;
2165 
2166  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2167  if (!tuple)
2168  ereport(ERROR,
2169  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2170  errmsg("source row not found")));
2171 
2172  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2173 
2174  needComma = false;
2175  for (i = 0; i < natts; i++)
2176  {
2177  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2178 
2179  if (att->attisdropped)
2180  continue;
2181 
2182  if (needComma)
2183  appendStringInfoChar(&buf, ',');
2184 
2186  quote_ident_cstr(NameStr(att->attname)));
2187  needComma = true;
2188  }
2189 
2190  appendStringInfoString(&buf, ") VALUES(");
2191 
2192  /*
2193  * Note: i is physical column number (counting from 0).
2194  */
2195  needComma = false;
2196  for (i = 0; i < natts; i++)
2197  {
2198  if (TupleDescAttr(tupdesc, i)->attisdropped)
2199  continue;
2200 
2201  if (needComma)
2202  appendStringInfoChar(&buf, ',');
2203 
2204  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2205 
2206  if (key >= 0)
2207  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2208  else
2209  val = SPI_getvalue(tuple, tupdesc, i + 1);
2210 
2211  if (val != NULL)
2212  {
2214  pfree(val);
2215  }
2216  else
2217  appendStringInfoString(&buf, "NULL");
2218  needComma = true;
2219  }
2220  appendStringInfoChar(&buf, ')');
2221 
2222  return buf.data;
2223 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:82
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:902
void pfree(void *pointer)
Definition: mcxt.c:1031
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:197
#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:85
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:576
long val
Definition: informix.c:689

◆ get_sql_update()

static char * get_sql_update ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals,
char **  tgt_pkattvals 
)
static

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

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

◆ get_text_array_contents()

static char ** get_text_array_contents ( ArrayType array,
int *  numitems 
)
static

Definition at line 2090 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, typalign, typbyval, typlen, and values.

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

2091 {
2092  int ndim = ARR_NDIM(array);
2093  int *dims = ARR_DIMS(array);
2094  int nitems;
2095  int16 typlen;
2096  bool typbyval;
2097  char typalign;
2098  char **values;
2099  char *ptr;
2100  bits8 *bitmap;
2101  int bitmask;
2102  int i;
2103 
2104  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2105 
2106  *numitems = nitems = ArrayGetNItems(ndim, dims);
2107 
2109  &typlen, &typbyval, &typalign);
2110 
2111  values = (char **) palloc(nitems * sizeof(char *));
2112 
2113  ptr = ARR_DATA_PTR(array);
2114  bitmap = ARR_NULLBITMAP(array);
2115  bitmask = 1;
2116 
2117  for (i = 0; i < nitems; i++)
2118  {
2119  if (bitmap && (*bitmap & bitmask) == 0)
2120  {
2121  values[i] = NULL;
2122  }
2123  else
2124  {
2125  values[i] = TextDatumGetCString(PointerGetDatum(ptr));
2126  ptr = att_addlength_pointer(ptr, typlen, ptr);
2127  ptr = (char *) att_align_nominal(ptr, typalign);
2128  }
2129 
2130  /* advance bitmap pointer if any */
2131  if (bitmap)
2132  {
2133  bitmask <<= 1;
2134  if (bitmask == 0x100)
2135  {
2136  bitmap++;
2137  bitmask = 1;
2138  }
2139  }
2140  }
2141 
2142  return values;
2143 }
signed short int16
Definition: c.h:312
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:144
int16 typlen
Definition: pg_type.h:55
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2025
#define PointerGetDatum(X)
Definition: postgres.h:541
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
char typalign
Definition: pg_type.h:167
#define ARR_DIMS(a)
Definition: array.h:279
#define ARR_DATA_PTR(a)
Definition: array.h:307
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:172
uint8 bits8
Definition: c.h:332
#define TextDatumGetCString(d)
Definition: builtins.h:96
#define Assert(condition)
Definition: c.h:699
#define ARR_NDIM(a)
Definition: array.h:275
static Datum values[MAXATTR]
Definition: bootstrap.c:164
void * palloc(Size size)
Definition: mcxt.c:924
int i
#define ARR_ELEMTYPE(a)
Definition: array.h:277
#define ARR_NULLBITMAP(a)
Definition: array.h:285
bool typbyval
Definition: pg_type.h:65

◆ get_tuple_of_interest()

static HeapTuple get_tuple_of_interest ( Relation  rel,
int *  pkattnums,
int  pknumatts,
char **  src_pkattvals 
)
static

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

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

◆ getConnectionByName()

static remoteConn * getConnectionByName ( const char *  name)
static

Definition at line 2540 of file dblink.c.

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

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

2541 {
2542  remoteConnHashEnt *hentry;
2543  char *key;
2544 
2545  if (!remoteConnHash)
2547 
2548  key = pstrdup(name);
2549  truncate_identifier(key, strlen(key), false);
2551  key, HASH_FIND, NULL);
2552 
2553  if (hentry)
2554  return hentry->rconn;
2555 
2556  return NULL;
2557 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
remoteConn * rconn
Definition: dblink.c:141
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
const char * name
Definition: encode.c:521

◆ is_valid_dblink_option()

static bool is_valid_dblink_option ( const PQconninfoOption options,
const char *  option,
Oid  context 
)
static

Definition at line 2966 of file dblink.c.

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

Referenced by dblink_fdw_validator(), and get_connect_string().

2968 {
2969  const PQconninfoOption *opt;
2970 
2971  /* Look up the option in libpq result */
2972  for (opt = options; opt->keyword; opt++)
2973  {
2974  if (strcmp(opt->keyword, option) == 0)
2975  break;
2976  }
2977  if (opt->keyword == NULL)
2978  return false;
2979 
2980  /* Disallow debug options (particularly "replication") */
2981  if (strchr(opt->dispchar, 'D'))
2982  return false;
2983 
2984  /* Disallow "client_encoding" */
2985  if (strcmp(opt->keyword, "client_encoding") == 0)
2986  return false;
2987 
2988  /*
2989  * If the option is "user" or marked secure, it should be specified only
2990  * in USER MAPPING. Others should be specified only in SERVER.
2991  */
2992  if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
2993  {
2994  if (context != UserMappingRelationId)
2995  return false;
2996  }
2997  else
2998  {
2999  if (context != ForeignServerRelationId)
3000  return false;
3001  }
3002 
3003  return true;
3004 }

◆ materializeQueryResult()

static void materializeQueryResult ( FunctionCallInfo  fcinfo,
PGconn conn,
const char *  conname,
const char *  sql,
bool  fail 
)
static

Definition at line 976 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(), TupleDescGetAttInMetadata(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_puttuple(), values, and work_mem.

Referenced by dblink_record_internal().

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

◆ materializeResult()

static void materializeResult ( FunctionCallInfo  fcinfo,
PGconn conn,
PGresult res 
)
static

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

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

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 156 of file dblink.c.

References elog, ereport, errcode(), errmsg(), 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:6116
char * pchomp(const char *in)
Definition: mcxt.c:1189
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:55
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define elog
Definition: elog.h:219

◆ PG_FUNCTION_INFO_V1() [1/20]

◆ PG_FUNCTION_INFO_V1() [2/20]

PG_FUNCTION_INFO_V1 ( dblink_disconnect  )

◆ PG_FUNCTION_INFO_V1() [3/20]

PG_FUNCTION_INFO_V1 ( dblink_open  )

◆ PG_FUNCTION_INFO_V1() [4/20]

PG_FUNCTION_INFO_V1 ( dblink_close  )

◆ PG_FUNCTION_INFO_V1() [5/20]

PG_FUNCTION_INFO_V1 ( dblink_fetch  )

◆ PG_FUNCTION_INFO_V1() [6/20]

PG_FUNCTION_INFO_V1 ( dblink_record  )

◆ PG_FUNCTION_INFO_V1() [7/20]

PG_FUNCTION_INFO_V1 ( dblink_send_query  )

◆ PG_FUNCTION_INFO_V1() [8/20]

PG_FUNCTION_INFO_V1 ( dblink_get_result  )

◆ PG_FUNCTION_INFO_V1() [9/20]

PG_FUNCTION_INFO_V1 ( dblink_get_connections  )

◆ PG_FUNCTION_INFO_V1() [10/20]

PG_FUNCTION_INFO_V1 ( dblink_is_busy  )

◆ PG_FUNCTION_INFO_V1() [11/20]

PG_FUNCTION_INFO_V1 ( dblink_cancel_query  )

◆ PG_FUNCTION_INFO_V1() [12/20]

PG_FUNCTION_INFO_V1 ( dblink_error_message  )

◆ PG_FUNCTION_INFO_V1() [13/20]

PG_FUNCTION_INFO_V1 ( dblink_exec  )

◆ PG_FUNCTION_INFO_V1() [14/20]

PG_FUNCTION_INFO_V1 ( dblink_get_pkey  )

◆ PG_FUNCTION_INFO_V1() [15/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_insert  )

◆ PG_FUNCTION_INFO_V1() [16/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_delete  )

◆ PG_FUNCTION_INFO_V1() [17/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_update  )

◆ PG_FUNCTION_INFO_V1() [18/20]

PG_FUNCTION_INFO_V1 ( dblink_current_query  )

◆ PG_FUNCTION_INFO_V1() [19/20]

PG_FUNCTION_INFO_V1 ( dblink_get_notify  )

◆ PG_FUNCTION_INFO_V1() [20/20]

PG_FUNCTION_INFO_V1 ( dblink_fdw_validator  )

◆ prepTuplestoreResult()

static void prepTuplestoreResult ( FunctionCallInfo  fcinfo)
static

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

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

◆ quote_ident_cstr()

static char * quote_ident_cstr ( char *  rawstr)
static

Definition at line 2354 of file dblink.c.

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

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

2355 {
2356  text *rawstr_text;
2357  text *result_text;
2358  char *result;
2359 
2360  rawstr_text = cstring_to_text(rawstr);
2362  PointerGetDatum(rawstr_text)));
2363  result = text_to_cstring(result_text);
2364 
2365  return result;
2366 }
#define PointerGetDatum(X)
Definition: postgres.h:541
#define DatumGetTextPP(X)
Definition: fmgr.h:261
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:590
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:516

◆ restoreLocalGucs()

static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3069 of file dblink.c.

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

3070 {
3071  /* Do nothing if no new nestlevel was created */
3072  if (nestlevel > 0)
3073  AtEOXact_GUC(true, nestlevel);
3074 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5312

◆ storeQueryResult()

static PGresult * storeQueryResult ( volatile storeInfo sinfo,
PGconn conn,
const char *  sql 
)
static

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

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

◆ storeRow()

static void storeRow ( volatile storeInfo sinfo,
PGresult res,
bool  first 
)
static

Definition at line 1162 of file dblink.c.

References Assert, storeInfo::attinmeta, BuildTupleFromCStrings(), CreateTupleDescCopy(), storeInfo::cstrs, dblink_get_connections(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, storeInfo::fcinfo, get_call_result_type(), i, MemoryContextReset(), MemoryContextSwitchTo(), palloc(), pfree(), PG_FUNCTION_INFO_V1(), 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().

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

◆ validate_pkattnums()

static void validate_pkattnums ( Relation  rel,
int2vector pkattnums_arg,
int32  pknumatts_arg,
int **  pkattnums,
int *  pknumatts 
)
static

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

2898 {
2899  TupleDesc tupdesc = rel->rd_att;
2900  int natts = tupdesc->natts;
2901  int i;
2902 
2903  /* Don't take more array elements than there are */
2904  pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2905 
2906  /* Must have at least one pk attnum selected */
2907  if (pknumatts_arg <= 0)
2908  ereport(ERROR,
2909  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2910  errmsg("number of key attributes must be > 0")));
2911 
2912  /* Allocate output array */
2913  *pkattnums = (int *) palloc(pknumatts_arg * sizeof(int));
2914  *pknumatts = pknumatts_arg;
2915 
2916  /* Validate attnums and convert to internal form */
2917  for (i = 0; i < pknumatts_arg; i++)
2918  {
2919  int pkattnum = pkattnums_arg->values[i];
2920  int lnum;
2921  int j;
2922 
2923  /* Can throw error immediately if out of range */
2924  if (pkattnum <= 0 || pkattnum > natts)
2925  ereport(ERROR,
2926  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2927  errmsg("invalid attribute number %d", pkattnum)));
2928 
2929  /* Identify which physical column has this logical number */
2930  lnum = 0;
2931  for (j = 0; j < natts; j++)
2932  {
2933  /* dropped columns don't count */
2934  if (TupleDescAttr(tupdesc, j)->attisdropped)
2935  continue;
2936 
2937  if (++lnum == pkattnum)
2938  break;
2939  }
2940 
2941  if (j < natts)
2942  (*pkattnums)[i] = j;
2943  else
2944  ereport(ERROR,
2945  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2946  errmsg("invalid attribute number %d", pkattnum)));
2947  }
2948 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
#define Min(x, y)
Definition: c.h:857
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:82
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int dim1
Definition: c.h:550
TupleDesc rd_att
Definition: rel.h:85
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:552
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i

◆ xpstrdup()

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:1161

Variable Documentation

◆ pconn

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 64 of file dblink.c.

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static