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/relation.h"
#include "access/reloptions.h"
#include "access/table.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/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 1880 of file dblink.c.

Referenced by dblink_get_notify().

◆ NUMCONN

#define NUMCONN   16

Definition at line 146 of file dblink.c.

Referenced by createConnHash().

Typedef Documentation

◆ remoteConn

typedef struct remoteConn remoteConn

◆ remoteConnHashEnt

◆ storeInfo

typedef struct storeInfo storeInfo

Function Documentation

◆ applyRemoteGucs()

static int applyRemoteGucs ( PGconn conn)
static

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

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

◆ createConnHash()

static HTAB * createConnHash ( void  )
static

Definition at line 2559 of file dblink.c.

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

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

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

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

Referenced by dblink_connect().

2571 {
2572  remoteConnHashEnt *hentry;
2573  bool found;
2574  char *key;
2575 
2576  if (!remoteConnHash)
2578 
2579  key = pstrdup(name);
2580  truncate_identifier(key, strlen(key), true);
2581  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2582  HASH_ENTER, &found);
2583 
2584  if (found)
2585  {
2586  PQfinish(rconn->conn);
2587  pfree(rconn);
2588 
2589  ereport(ERROR,
2591  errmsg("duplicate connection name")));
2592  }
2593 
2594  hentry->rconn = rconn;
2595  strlcpy(hentry->name, name, sizeof(hentry->name));
2596 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
remoteConn * rconn
Definition: dblink.c:142
int errcode(int sqlerrcode)
Definition: elog.c:570
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4121
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
char name[NAMEDATALEN]
Definition: dblink.c:141
PGconn * conn
Definition: dblink.c:69
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
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:784
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

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

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

◆ dblink_build_sql_insert()

Datum dblink_build_sql_insert ( PG_FUNCTION_ARGS  )

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

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

◆ dblink_build_sql_update()

Datum dblink_build_sql_update ( PG_FUNCTION_ARGS  )

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

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

◆ dblink_cancel_query()

Datum dblink_cancel_query ( PG_FUNCTION_ARGS  )

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

1333 {
1334  int res;
1335  PGconn *conn;
1336  PGcancel *cancel;
1337  char errbuf[256];
1338 
1339  dblink_init();
1341  cancel = PQgetCancel(conn);
1342 
1343  res = PQcancel(cancel, errbuf, 256);
1344  PQfreeCancel(cancel);
1345 
1346  if (res == 1)
1348  else
1350 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4265
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: streamutil.c:56
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4242
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
text * cstring_to_text(const char *s)
Definition: varlena.c:171
char * text_to_cstring(const text *t)
Definition: varlena.c:204
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4397

◆ dblink_close()

Datum dblink_close ( PG_FUNCTION_ARGS  )

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

460 {
461  PGconn *conn;
462  PGresult *res = NULL;
463  char *curname = NULL;
464  char *conname = NULL;
466  remoteConn *rconn = NULL;
467  bool fail = true; /* default to backward compatible behavior */
468 
469  dblink_init();
470  initStringInfo(&buf);
471 
472  if (PG_NARGS() == 1)
473  {
474  /* text */
475  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
476  rconn = pconn;
477  }
478  else if (PG_NARGS() == 2)
479  {
480  /* might be text,text or text,bool */
481  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
482  {
483  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
484  fail = PG_GETARG_BOOL(1);
485  rconn = pconn;
486  }
487  else
488  {
489  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
490  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
491  rconn = getConnectionByName(conname);
492  }
493  }
494  if (PG_NARGS() == 3)
495  {
496  /* text,text,bool */
497  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
498  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
499  fail = PG_GETARG_BOOL(2);
500  rconn = getConnectionByName(conname);
501  }
502 
503  if (!rconn || !rconn->conn)
504  dblink_conn_not_avail(conname);
505 
506  conn = rconn->conn;
507 
508  appendStringInfo(&buf, "CLOSE %s", curname);
509 
510  /* close the cursor */
511  res = PQexec(conn, buf.data);
512  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
513  {
514  dblink_res_error(conn, conname, res, fail,
515  "while closing cursor \"%s\"", curname);
517  }
518 
519  PQclear(res);
520 
521  /* if we started a transaction, decrement cursor count */
522  if (rconn->newXactForCursor)
523  {
524  (rconn->openCursorCount)--;
525 
526  /* if count is zero, commit the transaction */
527  if (rconn->openCursorCount == 0)
528  {
529  rconn->newXactForCursor = false;
530 
531  res = PQexec(conn, "COMMIT");
532  if (PQresultStatus(res) != PGRES_COMMAND_OK)
533  dblink_res_internalerror(conn, res, "commit error");
534  PQclear(res);
535  }
536  }
537 
539 }
int openCursorCount
Definition: dblink.c:70
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:269
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2693
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: dblink.c:69
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1817
PGconn * conn
Definition: streamutil.c:56
static char * buf
Definition: pg_test_fsync.c:68
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
bool newXactForCursor
Definition: dblink.c:71
void PQclear(PGresult *res)
Definition: fe-exec.c:695
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
text * cstring_to_text(const char *s)
Definition: varlena.c:171
#define PG_NARGS()
Definition: fmgr.h:198
char * text_to_cstring(const text *t)
Definition: varlena.c:204
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1940

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

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

257 {
258  char *conname_or_str = NULL;
259  char *connstr = NULL;
260  char *connname = NULL;
261  char *msg;
262  PGconn *conn = NULL;
263  remoteConn *rconn = NULL;
264 
265  dblink_init();
266 
267  if (PG_NARGS() == 2)
268  {
269  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
270  connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
271  }
272  else if (PG_NARGS() == 1)
273  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
274 
275  if (connname)
277  sizeof(remoteConn));
278 
279  /* first check for valid foreign data server */
280  connstr = get_connect_string(conname_or_str);
281  if (connstr == NULL)
282  connstr = conname_or_str;
283 
284  /* check password in connection string if not superuser */
285  dblink_connstr_check(connstr);
286  conn = PQconnectdb(connstr);
287 
288  if (PQstatus(conn) == CONNECTION_BAD)
289  {
290  msg = pchomp(PQerrorMessage(conn));
291  PQfinish(conn);
292  if (rconn)
293  pfree(rconn);
294 
295  ereport(ERROR,
296  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
297  errmsg("could not establish connection"),
298  errdetail_internal("%s", msg)));
299  }
300 
301  /* check password actually used if not superuser */
302  dblink_security_check(conn, rconn);
303 
304  /* attempt to set client encoding to match server encoding, if needed */
305  if (PQclientEncoding(conn) != GetDatabaseEncoding())
307 
308  if (connname)
309  {
310  rconn->conn = conn;
311  createNewConnection(connname, rconn);
312  }
313  else
314  {
315  if (pconn->conn)
316  PQfinish(pconn->conn);
317  pconn->conn = conn;
318  }
319 
321 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6619
int errcode(int sqlerrcode)
Definition: elog.c:570
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4121
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6679
int errdetail_internal(const char *fmt,...)
Definition: elog.c:887
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: dblink.c:69
char * pchomp(const char *in)
Definition: mcxt.c:1214
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:56
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int GetDatabaseEncoding(void)
Definition: mbutils.c:1046
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6687
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
text * cstring_to_text(const char *s)
Definition: varlena.c:171
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1052
#define PG_NARGS()
Definition: fmgr.h:198
char * text_to_cstring(const text *t)
Definition: varlena.c:204
int errmsg(const char *fmt,...)
Definition: elog.c:784
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6566
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:678
static char * connstr
Definition: pg_dumpall.c:62

◆ dblink_connstr_check()

static void dblink_connstr_check ( const char *  connstr)
static

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

2648 {
2649  if (!superuser())
2650  {
2653  bool connstr_gives_password = false;
2654 
2655  options = PQconninfoParse(connstr, NULL);
2656  if (options)
2657  {
2658  for (option = options; option->keyword != NULL; option++)
2659  {
2660  if (strcmp(option->keyword, "password") == 0)
2661  {
2662  if (option->val != NULL && option->val[0] != '\0')
2663  {
2664  connstr_gives_password = true;
2665  break;
2666  }
2667  }
2668  }
2669  PQconninfoFree(options);
2670  }
2671 
2672  if (!connstr_gives_password)
2673  ereport(ERROR,
2674  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2675  errmsg("password is required"),
2676  errdetail("Non-superusers must provide a password in the connection string.")));
2677  }
2678 }
int errcode(int sqlerrcode)
Definition: elog.c:570
bool superuser(void)
Definition: superuser.c:47
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5221
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6451
#define ereport(elevel, rest)
Definition: elog.h:141
static char ** options
int errmsg(const char *fmt,...)
Definition: elog.c:784
static char * connstr
Definition: pg_dumpall.c:62

◆ dblink_current_query()

Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1866 of file dblink.c.

References current_query(), and PG_RETURN_DATUM.

Referenced by dblink_build_sql_update().

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

◆ dblink_disconnect()

Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

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

329 {
330  char *conname = NULL;
331  remoteConn *rconn = NULL;
332  PGconn *conn = NULL;
333 
334  dblink_init();
335 
336  if (PG_NARGS() == 1)
337  {
338  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
339  rconn = getConnectionByName(conname);
340  if (rconn)
341  conn = rconn->conn;
342  }
343  else
344  conn = pconn->conn;
345 
346  if (!conn)
347  dblink_conn_not_avail(conname);
348 
349  PQfinish(conn);
350  if (rconn)
351  {
352  deleteConnection(conname);
353  pfree(rconn);
354  }
355  else
356  pconn->conn = NULL;
357 
359 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4121
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: dblink.c:69
void pfree(void *pointer)
Definition: mcxt.c:1056
PGconn * conn
Definition: streamutil.c:56
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
text * cstring_to_text(const char *s)
Definition: varlena.c:171
#define PG_NARGS()
Definition: fmgr.h:198
char * text_to_cstring(const text *t)
Definition: varlena.c:204

◆ dblink_error_message()

Datum dblink_error_message ( PG_FUNCTION_ARGS  )

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

1366 {
1367  char *msg;
1368  PGconn *conn;
1369 
1370  dblink_init();
1372 
1373  msg = PQerrorMessage(conn);
1374  if (msg == NULL || msg[0] == '\0')
1376  else
1378 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6619
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
char * pchomp(const char *in)
Definition: mcxt.c:1214
PGconn * conn
Definition: streamutil.c:56
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
text * cstring_to_text(const char *s)
Definition: varlena.c:171
char * text_to_cstring(const text *t)
Definition: varlena.c:204

◆ dblink_exec()

Datum dblink_exec ( PG_FUNCTION_ARGS  )

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

1386 {
1387  text *volatile sql_cmd_status = NULL;
1388  PGconn *volatile conn = NULL;
1389  volatile bool freeconn = false;
1390 
1391  dblink_init();
1392 
1393  PG_TRY();
1394  {
1395  PGresult *res = NULL;
1396  char *sql = NULL;
1397  char *conname = NULL;
1398  bool fail = true; /* default to backward compatible behavior */
1399 
1400  if (PG_NARGS() == 3)
1401  {
1402  /* must be text,text,bool */
1403  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1405  fail = PG_GETARG_BOOL(2);
1406  dblink_get_conn(conname, &conn, &conname, &freeconn);
1407  }
1408  else if (PG_NARGS() == 2)
1409  {
1410  /* might be text,text or text,bool */
1411  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1412  {
1414  fail = PG_GETARG_BOOL(1);
1415  conn = pconn->conn;
1416  }
1417  else
1418  {
1419  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1421  dblink_get_conn(conname, &conn, &conname, &freeconn);
1422  }
1423  }
1424  else if (PG_NARGS() == 1)
1425  {
1426  /* must be single text argument */
1427  conn = pconn->conn;
1429  }
1430  else
1431  /* shouldn't happen */
1432  elog(ERROR, "wrong number of arguments");
1433 
1434  if (!conn)
1435  dblink_conn_not_avail(conname);
1436 
1437  res = PQexec(conn, sql);
1438  if (!res ||
1439  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1441  {
1442  dblink_res_error(conn, conname, res, fail,
1443  "while executing command");
1444 
1445  /*
1446  * and save a copy of the command status string to return as our
1447  * result tuple
1448  */
1449  sql_cmd_status = cstring_to_text("ERROR");
1450  }
1451  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1452  {
1453  /*
1454  * and save a copy of the command status string to return as our
1455  * result tuple
1456  */
1457  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1458  PQclear(res);
1459  }
1460  else
1461  {
1462  PQclear(res);
1463  ereport(ERROR,
1464  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1465  errmsg("statement returning results not allowed")));
1466  }
1467  }
1468  PG_CATCH();
1469  {
1470  /* if needed, close the connection to the database */
1471  if (freeconn)
1472  PQfinish(conn);
1473  PG_RE_THROW();
1474  }
1475  PG_END_TRY();
1476 
1477  /* if needed, close the connection to the database */
1478  if (freeconn)
1479  PQfinish(conn);
1480 
1481  PG_RETURN_TEXT_P(sql_cmd_status);
1482 }
int errcode(int sqlerrcode)
Definition: elog.c:570
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4121
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:269
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2693
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: dblink.c:69
#define ERROR
Definition: elog.h:43
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1817
PGconn * conn
Definition: streamutil.c:56
#define ereport(elevel, rest)
Definition: elog.h:141
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3041
void PQclear(PGresult *res)
Definition: fe-exec.c:695
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
#define PG_CATCH()
Definition: elog.h:310
text * cstring_to_text(const char *s)
Definition: varlena.c:171
#define PG_NARGS()
Definition: fmgr.h:198
#define PG_RE_THROW()
Definition: elog.h:331
char * text_to_cstring(const text *t)
Definition: varlena.c:204
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1940
Definition: c.h:549
#define PG_TRY()
Definition: elog.h:301
#define PG_END_TRY()
Definition: elog.h:317

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

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

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

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

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

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

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

184 {
185  remoteConn *rconn = getConnectionByName(conname_or_str);
186  PGconn *conn;
187  char *conname;
188  bool freeconn;
189 
190  if (rconn)
191  {
192  conn = rconn->conn;
193  conname = conname_or_str;
194  freeconn = false;
195  }
196  else
197  {
198  const char *connstr;
199 
200  connstr = get_connect_string(conname_or_str);
201  if (connstr == NULL)
202  connstr = conname_or_str;
203  dblink_connstr_check(connstr);
204  conn = PQconnectdb(connstr);
205  if (PQstatus(conn) == CONNECTION_BAD)
206  {
207  char *msg = pchomp(PQerrorMessage(conn));
208 
209  PQfinish(conn);
210  ereport(ERROR,
211  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
212  errmsg("could not establish connection"),
213  errdetail_internal("%s", msg)));
214  }
215  dblink_security_check(conn, rconn);
216  if (PQclientEncoding(conn) != GetDatabaseEncoding())
218  freeconn = true;
219  conname = NULL;
220  }
221 
222  *conn_p = conn;
223  *conname_p = conname;
224  *freeconn_p = freeconn;
225 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6619
int errcode(int sqlerrcode)
Definition: elog.c:570
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4121
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6679
int errdetail_internal(const char *fmt,...)
Definition: elog.c:887
PGconn * conn
Definition: dblink.c:69
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:56
#define ereport(elevel, rest)
Definition: elog.h:141
int GetDatabaseEncoding(void)
Definition: mbutils.c:1046
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6687
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1052
int errmsg(const char *fmt,...)
Definition: elog.c:784
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6566
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:678
static char * connstr
Definition: pg_dumpall.c:62

◆ dblink_get_connections()

Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

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

1274 {
1276  remoteConnHashEnt *hentry;
1277  ArrayBuildState *astate = NULL;
1278 
1279  if (remoteConnHash)
1280  {
1281  hash_seq_init(&status, remoteConnHash);
1282  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1283  {
1284  /* stash away current value */
1285  astate = accumArrayResult(astate,
1286  CStringGetTextDatum(hentry->name),
1287  false, TEXTOID, CurrentMemoryContext);
1288  }
1289  }
1290 
1291  if (astate)
1294  else
1295  PG_RETURN_NULL();
1296 }
char name[NAMEDATALEN]
Definition: dblink.c:141
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:253
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5117
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:5053
#define CStringGetTextDatum(s)
Definition: builtins.h:83
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define PG_RETURN_NULL()
Definition: fmgr.h:335

◆ dblink_get_named_conn()

static PGconn* dblink_get_named_conn ( const char *  conname)
static

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

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

◆ dblink_get_notify()

Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

Definition at line 1884 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(), and work_mem.

1885 {
1886  PGconn *conn;
1887  PGnotify *notify;
1888  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1889  TupleDesc tupdesc;
1890  Tuplestorestate *tupstore;
1891  MemoryContext per_query_ctx;
1892  MemoryContext oldcontext;
1893 
1894  prepTuplestoreResult(fcinfo);
1895 
1896  dblink_init();
1897  if (PG_NARGS() == 1)
1899  else
1900  conn = pconn->conn;
1901 
1902  /* create the tuplestore in per-query memory */
1903  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1904  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1905 
1907  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1908  TEXTOID, -1, 0);
1909  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1910  INT4OID, -1, 0);
1911  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1912  TEXTOID, -1, 0);
1913 
1914  tupstore = tuplestore_begin_heap(true, false, work_mem);
1915  rsinfo->setResult = tupstore;
1916  rsinfo->setDesc = tupdesc;
1917 
1918  MemoryContextSwitchTo(oldcontext);
1919 
1920  PQconsumeInput(conn);
1921  while ((notify = PQnotifies(conn)) != NULL)
1922  {
1924  bool nulls[DBLINK_NOTIFY_COLS];
1925 
1926  memset(values, 0, sizeof(values));
1927  memset(nulls, 0, sizeof(nulls));
1928 
1929  if (notify->relname != NULL)
1930  values[0] = CStringGetTextDatum(notify->relname);
1931  else
1932  nulls[0] = true;
1933 
1934  values[1] = Int32GetDatum(notify->be_pid);
1935 
1936  if (notify->extra != NULL)
1937  values[2] = CStringGetTextDatum(notify->extra);
1938  else
1939  nulls[2] = true;
1940 
1941  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1942 
1943  PQfreemem(notify);
1944  PQconsumeInput(conn);
1945  }
1946 
1947  /* clean up and return the tuplestore */
1948  tuplestore_donestoring(tupstore);
1949 
1950  return (Datum) 0;
1951 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
char * extra
Definition: libpq-fe.h:168
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2290
#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:303
PGconn * conn
Definition: dblink.c:69
PGconn * conn
Definition: streamutil.c:56
int be_pid
Definition: libpq-fe.h:167
char * relname
Definition: libpq-fe.h:166
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
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:1705
int work_mem
Definition: globals.c:121
#define PG_NARGS()
Definition: fmgr.h:198
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:231
Tuplestorestate * setResult
Definition: execnodes.h:308
static Datum values[MAXATTR]
Definition: bootstrap.c:167
char * text_to_cstring(const text *t)
Definition: varlena.c:204
ExprContext * econtext
Definition: execnodes.h:301
#define Int32GetDatum(X)
Definition: postgres.h:479
TupleDesc setDesc
Definition: execnodes.h:309
#define CStringGetTextDatum(s)
Definition: builtins.h:83
int16 AttrNumber
Definition: attnum.h:21
void PQfreemem(void *ptr)
Definition: fe-exec.c:3297

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

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

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

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 672 of file dblink.c.

References dblink_record_internal().

Referenced by dblink_send_query().

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

◆ dblink_init()

static void dblink_init ( void  )
static

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

241 {
242  if (!pconn)
243  {
245  pconn->conn = NULL;
246  pconn->openCursorCount = 0;
247  pconn->newXactForCursor = false;
248  }
249 }
int openCursorCount
Definition: dblink.c:70
PGconn * conn
Definition: dblink.c:69
MemoryContext TopMemoryContext
Definition: mcxt.c:44
bool newXactForCursor
Definition: dblink.c:71
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

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

1309 {
1310  PGconn *conn;
1311 
1312  dblink_init();
1314 
1315  PQconsumeInput(conn);
1316  PG_RETURN_INT32(PQisBusy(conn));
1317 }
#define PG_RETURN_INT32(x)
Definition: fmgr.h:344
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: streamutil.c:56
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1705
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1755
char * text_to_cstring(const text *t)
Definition: varlena.c:204

◆ dblink_open()

Datum dblink_open ( PG_FUNCTION_ARGS  )

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

367 {
368  PGresult *res = NULL;
369  PGconn *conn;
370  char *curname = NULL;
371  char *sql = NULL;
372  char *conname = NULL;
374  remoteConn *rconn = NULL;
375  bool fail = true; /* default to backward compatible behavior */
376 
377  dblink_init();
378  initStringInfo(&buf);
379 
380  if (PG_NARGS() == 2)
381  {
382  /* text,text */
383  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
385  rconn = pconn;
386  }
387  else if (PG_NARGS() == 3)
388  {
389  /* might be text,text,text or text,text,bool */
390  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
391  {
392  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
394  fail = PG_GETARG_BOOL(2);
395  rconn = pconn;
396  }
397  else
398  {
399  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
400  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
402  rconn = getConnectionByName(conname);
403  }
404  }
405  else if (PG_NARGS() == 4)
406  {
407  /* text,text,text,bool */
408  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
409  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
411  fail = PG_GETARG_BOOL(3);
412  rconn = getConnectionByName(conname);
413  }
414 
415  if (!rconn || !rconn->conn)
416  dblink_conn_not_avail(conname);
417 
418  conn = rconn->conn;
419 
420  /* If we are not in a transaction, start one */
421  if (PQtransactionStatus(conn) == PQTRANS_IDLE)
422  {
423  res = PQexec(conn, "BEGIN");
424  if (PQresultStatus(res) != PGRES_COMMAND_OK)
425  dblink_res_internalerror(conn, res, "begin error");
426  PQclear(res);
427  rconn->newXactForCursor = true;
428 
429  /*
430  * Since transaction state was IDLE, we force cursor count to
431  * initially be 0. This is needed as a previous ABORT might have wiped
432  * out our transaction without maintaining the cursor count for us.
433  */
434  rconn->openCursorCount = 0;
435  }
436 
437  /* if we started a transaction, increment cursor count */
438  if (rconn->newXactForCursor)
439  (rconn->openCursorCount)++;
440 
441  appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
442  res = PQexec(conn, buf.data);
443  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
444  {
445  dblink_res_error(conn, conname, res, fail,
446  "while opening cursor \"%s\"", curname);
448  }
449 
450  PQclear(res);
452 }
int openCursorCount
Definition: dblink.c:70
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:269
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2693
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
PGconn * conn
Definition: dblink.c:69
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1817
PGconn * conn
Definition: streamutil.c:56
static char * buf
Definition: pg_test_fsync.c:68
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6574
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
bool newXactForCursor
Definition: dblink.c:71
void PQclear(PGresult *res)
Definition: fe-exec.c:695
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:361
text * cstring_to_text(const char *s)
Definition: varlena.c:171
#define PG_NARGS()
Definition: fmgr.h:198
char * text_to_cstring(const text *t)
Definition: varlena.c:204
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1940

◆ dblink_record()

Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 640 of file dblink.c.

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

Referenced by dblink_fetch().

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

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 678 of file dblink.c.

References remoteConn::conn, dblink_get_conn(), dblink_get_named_conn(), dblink_init(), dblink_res_error(), elog, ERROR, FunctionCallInfoBaseData::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().

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

◆ dblink_res_error()

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

Definition at line 2689 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(), and dblink_record_internal().

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

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

Referenced by dblink_connect(), and dblink_get_conn().

2622 {
2623  if (!superuser())
2624  {
2625  if (!PQconnectionUsedPassword(conn))
2626  {
2627  PQfinish(conn);
2628  if (rconn)
2629  pfree(rconn);
2630 
2631  ereport(ERROR,
2632  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2633  errmsg("password is required"),
2634  errdetail("Non-superuser cannot connect if the server does not request a password."),
2635  errhint("Target server's authentication method must be changed.")));
2636  }
2637  }
2638 }
int errhint(const char *fmt,...)
Definition: elog.c:974
int errcode(int sqlerrcode)
Definition: elog.c:570
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4121
bool superuser(void)
Definition: superuser.c:47
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6668
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ dblink_send_query()

Datum dblink_send_query ( PG_FUNCTION_ARGS  )

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

648 {
649  PGconn *conn;
650  char *sql;
651  int retval;
652 
653  if (PG_NARGS() == 2)
654  {
657  }
658  else
659  /* shouldn't happen */
660  elog(ERROR, "wrong number of arguments");
661 
662  /* async query send */
663  retval = PQsendQuery(conn, sql);
664  if (retval != 1)
665  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
666 
667  PG_RETURN_INT32(retval);
668 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6619
#define PG_RETURN_INT32(x)
Definition: fmgr.h:344
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
char * pchomp(const char *in)
Definition: mcxt.c:1214
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1235
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:56
#define NOTICE
Definition: elog.h:37
#define PG_NARGS()
Definition: fmgr.h:198
char * text_to_cstring(const text *t)
Definition: varlena.c:204
#define elog(elevel,...)
Definition: elog.h:226

◆ deleteConnection()

static void deleteConnection ( const char *  name)
static

Definition at line 2599 of file dblink.c.

References createConnHash(), ereport, errcode(), errmsg(), ERROR, HASH_REMOVE, hash_search(), sort-test::key, pstrdup(), remoteConnHash, and truncate_identifier().

Referenced by dblink_disconnect().

2600 {
2601  remoteConnHashEnt *hentry;
2602  bool found;
2603  char *key;
2604 
2605  if (!remoteConnHash)
2607 
2608  key = pstrdup(name);
2609  truncate_identifier(key, strlen(key), false);
2611  key, HASH_REMOVE, &found);
2612 
2613  if (!hentry)
2614  ereport(ERROR,
2615  (errcode(ERRCODE_UNDEFINED_OBJECT),
2616  errmsg("undefined connection name")));
2617 
2618 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
int errcode(int sqlerrcode)
Definition: elog.c:570
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:141
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ escape_param_str()

static char * escape_param_str ( const char *  from)
static

Definition at line 2861 of file dblink.c.

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

Referenced by get_connect_string().

2862 {
2863  const char *cp;
2865 
2866  initStringInfo(&buf);
2867 
2868  for (cp = str; *cp; cp++)
2869  {
2870  if (*cp == '\\' || *cp == '\'')
2871  appendStringInfoChar(&buf, '\\');
2872  appendStringInfoChar(&buf, *cp);
2873  }
2874 
2875  return buf.data;
2876 }
static char * buf
Definition: pg_test_fsync.c:68
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:175
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

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

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

◆ get_attnum_pk_pos()

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

Definition at line 2368 of file dblink.c.

References i.

Referenced by get_sql_insert(), and get_sql_update().

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

◆ get_connect_string()

static char * get_connect_string ( const char *  servername)
static

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

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

◆ get_pkey_attnames()

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

Definition at line 2034 of file dblink.c.

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

Referenced by dblink_get_pkey().

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

◆ get_rel_from_relname()

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

Definition at line 2496 of file dblink.c.

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

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

2497 {
2498  RangeVar *relvar;
2499  Relation rel;
2500  AclResult aclresult;
2501 
2502  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2503  rel = table_openrv(relvar, lockmode);
2504 
2505  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2506  aclmode);
2507  if (aclresult != ACLCHECK_OK)
2508  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2510 
2511  return rel;
2512 }
Oid GetUserId(void)
Definition: miscinit.c:380
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3054
Form_pg_class rd_rel
Definition: rel.h:83
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define RelationGetRelationName(relation)
Definition: rel.h:453
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3586
AclResult
Definition: acl.h:177
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:68
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4631
ObjectType get_relkind_objtype(char relkind)
#define RelationGetRelid(relation)
Definition: rel.h:419

◆ get_sql_delete()

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

Definition at line 2225 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, relname, and TupleDescAttr.

Referenced by dblink_build_sql_delete().

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

◆ get_sql_insert()

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

Definition at line 2145 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(), sort-test::key, NameStr, TupleDescData::natts, pfree(), pstrdup(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, relname, SPI_getvalue(), TupleDescAttr, and val.

Referenced by dblink_build_sql_insert().

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

◆ get_sql_update()

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

Definition at line 2262 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(), sort-test::key, NameStr, TupleDescData::natts, pfree(), pstrdup(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, relname, SPI_getvalue(), TupleDescAttr, and val.

Referenced by dblink_build_sql_update().

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

◆ get_text_array_contents()

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

Definition at line 2089 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, and values.

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

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

◆ get_tuple_of_interest()

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

Definition at line 2383 of file dblink.c.

References appendStringInfo(), appendStringInfoString(), buf, StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), i, initStringInfo(), NameStr, TupleDescData::natts, pfree(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, relname, 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().

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

◆ getConnectionByName()

static remoteConn * getConnectionByName ( const char *  name)
static

Definition at line 2539 of file dblink.c.

References createConnHash(), HASH_FIND, hash_search(), sort-test::key, 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().

2540 {
2541  remoteConnHashEnt *hentry;
2542  char *key;
2543 
2544  if (!remoteConnHash)
2546 
2547  key = pstrdup(name);
2548  truncate_identifier(key, strlen(key), false);
2550  key, HASH_FIND, NULL);
2551 
2552  if (hentry)
2553  return hentry->rconn;
2554 
2555  return NULL;
2556 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
remoteConn * rconn
Definition: dblink.c:142
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 2965 of file dblink.c.

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

Referenced by dblink_fdw_validator(), and get_connect_string().

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

◆ materializeQueryResult()

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

Definition at line 977 of file dblink.c.

References FunctionCallInfoBaseData::resultinfo.

Referenced by dblink_record_internal().

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

◆ materializeResult()

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

Definition at line 831 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(), TupleDescData::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(), FunctionCallInfoBaseData::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().

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

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 157 of file dblink.c.

References elog, ereport, errcode(), errmsg(), ERROR, pchomp(), PQclear(), and PQerrorMessage().

159 {
160  char *msg = pchomp(PQerrorMessage(conn));
161 
162  if (res)
163  PQclear(res);
164  elog(ERROR, "%s: %s", p2, msg);
165 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6619
char * pchomp(const char *in)
Definition: mcxt.c:1214
#define ERROR
Definition: elog.h:43
PGconn * conn
Definition: streamutil.c:56
void PQclear(PGresult *res)
Definition: fe-exec.c:695
#define elog(elevel,...)
Definition: elog.h:226

◆ 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 803 of file dblink.c.

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

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

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

◆ quote_ident_cstr()

static char * quote_ident_cstr ( char *  rawstr)
static

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

2354 {
2355  text *rawstr_text;
2356  text *result_text;
2357  char *result;
2358 
2359  rawstr_text = cstring_to_text(rawstr);
2361  PointerGetDatum(rawstr_text)));
2362  result = text_to_cstring(result_text);
2363 
2364  return result;
2365 }
#define PointerGetDatum(X)
Definition: postgres.h:556
#define DatumGetTextPP(X)
Definition: fmgr.h:286
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:617
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:24
text * cstring_to_text(const char *s)
Definition: varlena.c:171
char * text_to_cstring(const text *t)
Definition: varlena.c:204
Definition: c.h:549

◆ restoreLocalGucs()

static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3068 of file dblink.c.

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

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

◆ storeQueryResult()

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

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

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

◆ storeRow()

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

Definition at line 1161 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(), TupleDescData::natts, palloc(), pfree(), PG_FUNCTION_INFO_V1(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), FunctionCallInfoBaseData::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().

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

◆ validate_pkattnums()

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

Definition at line 2894 of file dblink.c.

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

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

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

◆ xpstrdup()

static char* xpstrdup ( const char *  in)
static

Definition at line 149 of file dblink.c.

References pstrdup().

Referenced by dblink_res_error().

150 {
151  if (in == NULL)
152  return NULL;
153  return pstrdup(in);
154 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186

Variable Documentation

◆ pconn

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 65 of file dblink.c.

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static