PostgreSQL Source Code  git master
dblink.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/table.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 "libpq-fe.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 1924 of file dblink.c.

Referenced by dblink_get_notify().

◆ NUMCONN

#define NUMCONN   16

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

3064 {
3065  static const char *const GUCsAffectingIO[] = {
3066  "DateStyle",
3067  "IntervalStyle"
3068  };
3069 
3070  int nestlevel = -1;
3071  int i;
3072 
3073  for (i = 0; i < lengthof(GUCsAffectingIO); i++)
3074  {
3075  const char *gucName = GUCsAffectingIO[i];
3076  const char *remoteVal = PQparameterStatus(conn, gucName);
3077  const char *localVal;
3078 
3079  /*
3080  * If the remote server is pre-8.4, it won't have IntervalStyle, but
3081  * that's okay because its output format won't be ambiguous. So just
3082  * skip the GUC if we don't get a value for it. (We might eventually
3083  * need more complicated logic with remote-version checks here.)
3084  */
3085  if (remoteVal == NULL)
3086  continue;
3087 
3088  /*
3089  * Avoid GUC-setting overhead if the remote and local GUCs already
3090  * have the same value.
3091  */
3092  localVal = GetConfigOption(gucName, false, false);
3093  Assert(localVal != NULL);
3094 
3095  if (strcmp(remoteVal, localVal) == 0)
3096  continue;
3097 
3098  /* Create new GUC nest level if we didn't already */
3099  if (nestlevel < 0)
3100  nestlevel = NewGUCNestLevel();
3101 
3102  /* Apply the option (this will throw error on failure) */
3103  (void) set_config_option(gucName, remoteVal,
3105  GUC_ACTION_SAVE, true, 0, false);
3106  }
3107 
3108  return nestlevel;
3109 }
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6700
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:8126
#define lengthof(array)
Definition: c.h:734
#define Assert(condition)
Definition: c.h:804
int NewGUCNestLevel(void)
Definition: guc.c:6220
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:7311

◆ createConnHash()

static HTAB * createConnHash ( void  )
static

Definition at line 2603 of file dblink.c.

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

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

2604 {
2605  HASHCTL ctl;
2606 
2607  ctl.keysize = NAMEDATALEN;
2608  ctl.entrysize = sizeof(remoteConnHashEnt);
2609 
2610  return hash_create("Remote Con hash", NUMCONN, &ctl,
2612 }
#define HASH_ELEM
Definition: hsearch.h:95
Size entrysize
Definition: hsearch.h:76
#define NAMEDATALEN
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
Size keysize
Definition: hsearch.h:75
#define HASH_STRINGS
Definition: hsearch.h:96

◆ createNewConnection()

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

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

Referenced by dblink_connect().

2616 {
2617  remoteConnHashEnt *hentry;
2618  bool found;
2619  char *key;
2620 
2621  if (!remoteConnHash)
2623 
2624  key = pstrdup(name);
2625  truncate_identifier(key, strlen(key), true);
2626  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2627  HASH_ENTER, &found);
2628 
2629  if (found)
2630  {
2631  PQfinish(rconn->conn);
2633  pfree(rconn);
2634 
2635  ereport(ERROR,
2637  errmsg("duplicate connection name")));
2638  }
2639 
2640  hentry->rconn = rconn;
2641  strlcpy(hentry->name, name, sizeof(hentry->name));
2642 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
remoteConn * rconn
Definition: dblink.c:140
int errcode(int sqlerrcode)
Definition: elog.c:698
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
char name[NAMEDATALEN]
Definition: dblink.c:139
PGconn * conn
Definition: dblink.c:67
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * name
Definition: encode.c:515
void ReleaseExternalFD(void)
Definition: fd.c:1148
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

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

1756 {
1757  text *relname_text = PG_GETARG_TEXT_PP(0);
1758  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1759  int32 pknumatts_arg = PG_GETARG_INT32(2);
1760  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1761  Relation rel;
1762  int *pkattnums;
1763  int pknumatts;
1764  char **tgt_pkattvals;
1765  int tgt_nitems;
1766  char *sql;
1767 
1768  /*
1769  * Open target relation.
1770  */
1771  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1772 
1773  /*
1774  * Process pkattnums argument.
1775  */
1776  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1777  &pkattnums, &pknumatts);
1778 
1779  /*
1780  * Target array is made up of key values that will be used to build the
1781  * SQL string for use on the remote system.
1782  */
1783  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1784 
1785  /*
1786  * There should be one target array key value for each key attnum
1787  */
1788  if (tgt_nitems != pknumatts)
1789  ereport(ERROR,
1790  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1791  errmsg("target key array length must match number of key attributes")));
1792 
1793  /*
1794  * Prep work is finally done. Go get the SQL string.
1795  */
1796  sql = get_sql_delete(rel, pkattnums, pknumatts, tgt_pkattvals);
1797 
1798  /*
1799  * Now we can close the relation.
1800  */
1802 
1803  /*
1804  * And send it
1805  */
1807 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
signed int int32
Definition: c.h:429
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ERROR
Definition: elog.h:46
Definition: c.h:649
#define ACL_SELECT
Definition: parsenodes.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: c.h:621

◆ dblink_build_sql_insert()

Datum dblink_build_sql_insert ( PG_FUNCTION_ARGS  )

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

1667 {
1668  text *relname_text = PG_GETARG_TEXT_PP(0);
1669  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1670  int32 pknumatts_arg = PG_GETARG_INT32(2);
1671  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1672  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1673  Relation rel;
1674  int *pkattnums;
1675  int pknumatts;
1676  char **src_pkattvals;
1677  char **tgt_pkattvals;
1678  int src_nitems;
1679  int tgt_nitems;
1680  char *sql;
1681 
1682  /*
1683  * Open target relation.
1684  */
1685  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1686 
1687  /*
1688  * Process pkattnums argument.
1689  */
1690  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1691  &pkattnums, &pknumatts);
1692 
1693  /*
1694  * Source array is made up of key values that will be used to locate the
1695  * tuple of interest from the local system.
1696  */
1697  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1698 
1699  /*
1700  * There should be one source array key value for each key attnum
1701  */
1702  if (src_nitems != pknumatts)
1703  ereport(ERROR,
1704  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1705  errmsg("source key array length must match number of key attributes")));
1706 
1707  /*
1708  * Target array is made up of key values that will be used to build the
1709  * SQL string for use on the remote system.
1710  */
1711  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1712 
1713  /*
1714  * There should be one target array key value for each key attnum
1715  */
1716  if (tgt_nitems != pknumatts)
1717  ereport(ERROR,
1718  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1719  errmsg("target key array length must match number of key attributes")));
1720 
1721  /*
1722  * Prep work is finally done. Go get the SQL string.
1723  */
1724  sql = get_sql_insert(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1725 
1726  /*
1727  * Now we can close the relation.
1728  */
1730 
1731  /*
1732  * And send it
1733  */
1735 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
signed int int32
Definition: c.h:429
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ERROR
Definition: elog.h:46
Definition: c.h:649
#define ACL_SELECT
Definition: parsenodes.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: c.h:621

◆ dblink_build_sql_update()

Datum dblink_build_sql_update ( PG_FUNCTION_ARGS  )

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

1832 {
1833  text *relname_text = PG_GETARG_TEXT_PP(0);
1834  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1835  int32 pknumatts_arg = PG_GETARG_INT32(2);
1836  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1837  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1838  Relation rel;
1839  int *pkattnums;
1840  int pknumatts;
1841  char **src_pkattvals;
1842  char **tgt_pkattvals;
1843  int src_nitems;
1844  int tgt_nitems;
1845  char *sql;
1846 
1847  /*
1848  * Open target relation.
1849  */
1850  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1851 
1852  /*
1853  * Process pkattnums argument.
1854  */
1855  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1856  &pkattnums, &pknumatts);
1857 
1858  /*
1859  * Source array is made up of key values that will be used to locate the
1860  * tuple of interest from the local system.
1861  */
1862  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1863 
1864  /*
1865  * There should be one source array key value for each key attnum
1866  */
1867  if (src_nitems != pknumatts)
1868  ereport(ERROR,
1869  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1870  errmsg("source key array length must match number of key attributes")));
1871 
1872  /*
1873  * Target array is made up of key values that will be used to build the
1874  * SQL string for use on the remote system.
1875  */
1876  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1877 
1878  /*
1879  * There should be one target array key value for each key attnum
1880  */
1881  if (tgt_nitems != pknumatts)
1882  ereport(ERROR,
1883  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1884  errmsg("target key array length must match number of key attributes")));
1885 
1886  /*
1887  * Prep work is finally done. Go get the SQL string.
1888  */
1889  sql = get_sql_update(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1890 
1891  /*
1892  * Now we can close the relation.
1893  */
1895 
1896  /*
1897  * And send it
1898  */
1900 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
signed int int32
Definition: c.h:429
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:256
#define ERROR
Definition: elog.h:46
Definition: c.h:649
#define ACL_SELECT
Definition: parsenodes.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: c.h:621

◆ dblink_cancel_query()

Datum dblink_cancel_query ( PG_FUNCTION_ARGS  )

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

1384 {
1385  int res;
1386  PGconn *conn;
1387  PGcancel *cancel;
1388  char errbuf[256];
1389 
1390  dblink_init();
1392  cancel = PQgetCancel(conn);
1393 
1394  res = PQcancel(cancel, errbuf, 256);
1395  PQfreeCancel(cancel);
1396 
1397  if (res == 1)
1399  else
1401 }
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4373
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: streamutil.c:54
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4350
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
char * text_to_cstring(const text *t)
Definition: varlena.c:223
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4505

◆ dblink_close()

Datum dblink_close ( PG_FUNCTION_ARGS  )

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

518 {
519  PGconn *conn;
520  PGresult *res = NULL;
521  char *curname = NULL;
522  char *conname = NULL;
524  remoteConn *rconn = NULL;
525  bool fail = true; /* default to backward compatible behavior */
526 
527  dblink_init();
528  initStringInfo(&buf);
529 
530  if (PG_NARGS() == 1)
531  {
532  /* text */
533  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
534  rconn = pconn;
535  }
536  else if (PG_NARGS() == 2)
537  {
538  /* might be text,text or text,bool */
539  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
540  {
541  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
542  fail = PG_GETARG_BOOL(1);
543  rconn = pconn;
544  }
545  else
546  {
547  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
548  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
549  rconn = getConnectionByName(conname);
550  }
551  }
552  if (PG_NARGS() == 3)
553  {
554  /* text,text,bool */
555  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
556  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
557  fail = PG_GETARG_BOOL(2);
558  rconn = getConnectionByName(conname);
559  }
560 
561  if (!rconn || !rconn->conn)
562  dblink_conn_not_avail(conname);
563 
564  conn = rconn->conn;
565 
566  appendStringInfo(&buf, "CLOSE %s", curname);
567 
568  /* close the cursor */
569  res = PQexec(conn, buf.data);
570  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
571  {
572  dblink_res_error(conn, conname, res, fail,
573  "while closing cursor \"%s\"", curname);
575  }
576 
577  PQclear(res);
578 
579  /* if we started a transaction, decrement cursor count */
580  if (rconn->newXactForCursor)
581  {
582  (rconn->openCursorCount)--;
583 
584  /* if count is zero, commit the transaction */
585  if (rconn->openCursorCount == 0)
586  {
587  rconn->newXactForCursor = false;
588 
589  res = PQexec(conn, "COMMIT");
590  if (PQresultStatus(res) != PGRES_COMMAND_OK)
591  dblink_res_internalerror(conn, res, "commit error");
592  PQclear(res);
593  }
594  }
595 
597 }
int openCursorCount
Definition: dblink.c:68
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1800
PGconn * conn
Definition: streamutil.c:54
static char * buf
Definition: pg_test_fsync.c:68
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
bool newXactForCursor
Definition: dblink.c:69
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2142

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 280 of file dblink.c.

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

Referenced by dblink_init().

281 {
282  char *conname_or_str = NULL;
283  char *connstr = NULL;
284  char *connname = NULL;
285  char *msg;
286  PGconn *conn = NULL;
287  remoteConn *rconn = NULL;
288 
289  dblink_init();
290 
291  if (PG_NARGS() == 2)
292  {
293  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
294  connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
295  }
296  else if (PG_NARGS() == 1)
297  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
298 
299  if (connname)
300  {
302  sizeof(remoteConn));
303  rconn->conn = NULL;
304  rconn->openCursorCount = 0;
305  rconn->newXactForCursor = false;
306  }
307 
308  /* first check for valid foreign data server */
309  connstr = get_connect_string(conname_or_str);
310  if (connstr == NULL)
311  connstr = conname_or_str;
312 
313  /* check password in connection string if not superuser */
314  dblink_connstr_check(connstr);
315 
316  /*
317  * We must obey fd.c's limit on non-virtual file descriptors. Assume that
318  * a PGconn represents one long-lived FD. (Doing this here also ensures
319  * that VFDs are closed if needed to make room.)
320  */
321  if (!AcquireExternalFD())
322  {
323 #ifndef WIN32 /* can't write #if within ereport() macro */
324  ereport(ERROR,
325  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
326  errmsg("could not establish connection"),
327  errdetail("There are too many open files on the local server."),
328  errhint("Raise the server's max_files_per_process and/or \"ulimit -n\" limits.")));
329 #else
330  ereport(ERROR,
331  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
332  errmsg("could not establish connection"),
333  errdetail("There are too many open files on the local server."),
334  errhint("Raise the server's max_files_per_process setting.")));
335 #endif
336  }
337 
338  /* OK to make connection */
339  conn = PQconnectdb(connstr);
340 
341  if (PQstatus(conn) == CONNECTION_BAD)
342  {
343  msg = pchomp(PQerrorMessage(conn));
344  PQfinish(conn);
346  if (rconn)
347  pfree(rconn);
348 
349  ereport(ERROR,
350  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
351  errmsg("could not establish connection"),
352  errdetail_internal("%s", msg)));
353  }
354 
355  /* check password actually used if not superuser */
356  dblink_security_check(conn, rconn);
357 
358  /* attempt to set client encoding to match server encoding, if needed */
359  if (PQclientEncoding(conn) != GetDatabaseEncoding())
361 
362  if (connname)
363  {
364  rconn->conn = conn;
365  createNewConnection(connname, rconn);
366  }
367  else
368  {
369  if (pconn->conn)
370  {
371  PQfinish(pconn->conn);
373  }
374  pconn->conn = conn;
375  }
376 
378 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
int openCursorCount
Definition: dblink.c:68
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6804
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
char * pchomp(const char *in)
Definition: mcxt.c:1327
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
PGconn * conn
Definition: streamutil.c:54
int errdetail(const char *fmt,...)
Definition: elog.c:1042
MemoryContext TopMemoryContext
Definition: mcxt.c:48
bool newXactForCursor
Definition: dblink.c:69
int GetDatabaseEncoding(void)
Definition: mbutils.c:1210
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6812
bool AcquireExternalFD(void)
Definition: fd.c:1095
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1216
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
void ReleaseExternalFD(void)
Definition: fd.c:1148
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6682
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:718
static char * connstr
Definition: pg_dumpall.c:62

◆ dblink_connstr_check()

static void dblink_connstr_check ( const char *  connstr)
static

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

2695 {
2696  if (!superuser())
2697  {
2700  bool connstr_gives_password = false;
2701 
2702  options = PQconninfoParse(connstr, NULL);
2703  if (options)
2704  {
2705  for (option = options; option->keyword != NULL; option++)
2706  {
2707  if (strcmp(option->keyword, "password") == 0)
2708  {
2709  if (option->val != NULL && option->val[0] != '\0')
2710  {
2711  connstr_gives_password = true;
2712  break;
2713  }
2714  }
2715  }
2716  PQconninfoFree(options);
2717  }
2718 
2719  if (!connstr_gives_password)
2720  ereport(ERROR,
2721  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2722  errmsg("password is required"),
2723  errdetail("Non-superusers must provide a password in the connection string.")));
2724  }
2725 }
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5328
#define ERROR
Definition: elog.h:46
int errdetail(const char *fmt,...)
Definition: elog.c:1042
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6563
static char ** options
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
static char * connstr
Definition: pg_dumpall.c:62

◆ dblink_current_query()

Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1910 of file dblink.c.

References current_query(), and PG_RETURN_DATUM.

Referenced by dblink_build_sql_update().

1911 {
1912  /* This is now just an alias for the built-in function current_query() */
1913  PG_RETURN_DATUM(current_query(fcinfo));
1914 }
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:190
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353

◆ dblink_disconnect()

Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 385 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(), ReleaseExternalFD(), and text_to_cstring().

Referenced by dblink_connect().

386 {
387  char *conname = NULL;
388  remoteConn *rconn = NULL;
389  PGconn *conn = NULL;
390 
391  dblink_init();
392 
393  if (PG_NARGS() == 1)
394  {
395  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
396  rconn = getConnectionByName(conname);
397  if (rconn)
398  conn = rconn->conn;
399  }
400  else
401  conn = pconn->conn;
402 
403  if (!conn)
404  dblink_conn_not_avail(conname);
405 
406  PQfinish(conn);
408  if (rconn)
409  {
410  deleteConnection(conname);
411  pfree(rconn);
412  }
413  else
414  pconn->conn = NULL;
415 
417 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
void pfree(void *pointer)
Definition: mcxt.c:1169
PGconn * conn
Definition: streamutil.c:54
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
void ReleaseExternalFD(void)
Definition: fd.c:1148

◆ dblink_error_message()

Datum dblink_error_message ( PG_FUNCTION_ARGS  )

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

1417 {
1418  char *msg;
1419  PGconn *conn;
1420 
1421  dblink_init();
1423 
1424  msg = PQerrorMessage(conn);
1425  if (msg == NULL || msg[0] == '\0')
1427  else
1429 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
char * pchomp(const char *in)
Definition: mcxt.c:1327
PGconn * conn
Definition: streamutil.c:54
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
char * text_to_cstring(const text *t)
Definition: varlena.c:223

◆ dblink_exec()

Datum dblink_exec ( PG_FUNCTION_ARGS  )

Definition at line 1436 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_END_TRY, PG_FINALLY, PG_FUNCTION_INFO_V1(), PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQexec(), PQfinish(), PQresultStatus(), ReleaseExternalFD(), and text_to_cstring().

Referenced by dblink_error_message().

1437 {
1438  text *volatile sql_cmd_status = NULL;
1439  PGconn *volatile conn = NULL;
1440  volatile bool freeconn = false;
1441 
1442  dblink_init();
1443 
1444  PG_TRY();
1445  {
1446  PGresult *res = NULL;
1447  char *sql = NULL;
1448  char *conname = NULL;
1449  bool fail = true; /* default to backward compatible behavior */
1450 
1451  if (PG_NARGS() == 3)
1452  {
1453  /* must be text,text,bool */
1454  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1456  fail = PG_GETARG_BOOL(2);
1457  dblink_get_conn(conname, &conn, &conname, &freeconn);
1458  }
1459  else if (PG_NARGS() == 2)
1460  {
1461  /* might be text,text or text,bool */
1462  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1463  {
1465  fail = PG_GETARG_BOOL(1);
1466  conn = pconn->conn;
1467  }
1468  else
1469  {
1470  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1472  dblink_get_conn(conname, &conn, &conname, &freeconn);
1473  }
1474  }
1475  else if (PG_NARGS() == 1)
1476  {
1477  /* must be single text argument */
1478  conn = pconn->conn;
1480  }
1481  else
1482  /* shouldn't happen */
1483  elog(ERROR, "wrong number of arguments");
1484 
1485  if (!conn)
1486  dblink_conn_not_avail(conname);
1487 
1488  res = PQexec(conn, sql);
1489  if (!res ||
1490  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1492  {
1493  dblink_res_error(conn, conname, res, fail,
1494  "while executing command");
1495 
1496  /*
1497  * and save a copy of the command status string to return as our
1498  * result tuple
1499  */
1500  sql_cmd_status = cstring_to_text("ERROR");
1501  }
1502  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1503  {
1504  /*
1505  * and save a copy of the command status string to return as our
1506  * result tuple
1507  */
1508  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1509  PQclear(res);
1510  }
1511  else
1512  {
1513  PQclear(res);
1514  ereport(ERROR,
1515  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1516  errmsg("statement returning results not allowed")));
1517  }
1518  }
1519  PG_FINALLY();
1520  {
1521  /* if needed, close the connection to the database */
1522  if (freeconn)
1523  {
1524  PQfinish(conn);
1526  }
1527  }
1528  PG_END_TRY();
1529 
1530  PG_RETURN_TEXT_P(sql_cmd_status);
1531 }
int errcode(int sqlerrcode)
Definition: elog.c:698
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
#define ERROR
Definition: elog.h:46
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1800
PGconn * conn
Definition: streamutil.c:54
#define PG_FINALLY()
Definition: elog.h:330
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3438
#define ereport(elevel,...)
Definition: elog.h:157
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
void ReleaseExternalFD(void)
Definition: fd.c:1148
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2142
Definition: c.h:621
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

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

2007 {
2008  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
2009  Oid context = PG_GETARG_OID(1);
2010  ListCell *cell;
2011 
2012  static const PQconninfoOption *options = NULL;
2013 
2014  /*
2015  * Get list of valid libpq options.
2016  *
2017  * To avoid unnecessary work, we get the list once and use it throughout
2018  * the lifetime of this backend process. We don't need to care about
2019  * memory context issues, because PQconndefaults allocates with malloc.
2020  */
2021  if (!options)
2022  {
2023  options = PQconndefaults();
2024  if (!options) /* assume reason for failure is OOM */
2025  ereport(ERROR,
2026  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2027  errmsg("out of memory"),
2028  errdetail("Could not get libpq's default connection options.")));
2029  }
2030 
2031  /* Validate each supplied option. */
2032  foreach(cell, options_list)
2033  {
2034  DefElem *def = (DefElem *) lfirst(cell);
2035 
2036  if (!is_valid_dblink_option(options, def->defname, context))
2037  {
2038  /*
2039  * Unknown option, or invalid option for the context specified, so
2040  * complain about it. Provide a hint with list of valid options
2041  * for the context.
2042  */
2044  const PQconninfoOption *opt;
2045 
2046  initStringInfo(&buf);
2047  for (opt = options; opt->keyword; opt++)
2048  {
2049  if (is_valid_dblink_option(options, opt->keyword, context))
2050  appendStringInfo(&buf, "%s%s",
2051  (buf.len > 0) ? ", " : "",
2052  opt->keyword);
2053  }
2054  ereport(ERROR,
2055  (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
2056  errmsg("invalid option \"%s\"", def->defname),
2057  errhint("Valid options in this context are: %s",
2058  buf.data)));
2059  }
2060  }
2061 
2062  PG_RETURN_VOID();
2063 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
static char * buf
Definition: pg_test_fsync.c:68
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
int errdetail(const char *fmt,...)
Definition: elog.c:1042
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1308
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define lfirst(lc)
Definition: pg_list.h:169
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1477
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * defname
Definition: parsenodes.h:746
Definition: pg_list.h:50

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

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

605 {
606  PGresult *res = NULL;
607  char *conname = NULL;
608  remoteConn *rconn = NULL;
609  PGconn *conn = NULL;
611  char *curname = NULL;
612  int howmany = 0;
613  bool fail = true; /* default to backward compatible */
614 
615  prepTuplestoreResult(fcinfo);
616 
617  dblink_init();
618 
619  if (PG_NARGS() == 4)
620  {
621  /* text,text,int,bool */
622  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
623  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
624  howmany = PG_GETARG_INT32(2);
625  fail = PG_GETARG_BOOL(3);
626 
627  rconn = getConnectionByName(conname);
628  if (rconn)
629  conn = rconn->conn;
630  }
631  else if (PG_NARGS() == 3)
632  {
633  /* text,text,int or text,int,bool */
634  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
635  {
636  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
637  howmany = PG_GETARG_INT32(1);
638  fail = PG_GETARG_BOOL(2);
639  conn = pconn->conn;
640  }
641  else
642  {
643  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
644  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
645  howmany = PG_GETARG_INT32(2);
646 
647  rconn = getConnectionByName(conname);
648  if (rconn)
649  conn = rconn->conn;
650  }
651  }
652  else if (PG_NARGS() == 2)
653  {
654  /* text,int */
655  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
656  howmany = PG_GETARG_INT32(1);
657  conn = pconn->conn;
658  }
659 
660  if (!conn)
661  dblink_conn_not_avail(conname);
662 
663  initStringInfo(&buf);
664  appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
665 
666  /*
667  * Try to execute the query. Note that since libpq uses malloc, the
668  * PGresult will be long-lived even though we are still in a short-lived
669  * memory context.
670  */
671  res = PQexec(conn, buf.data);
672  if (!res ||
673  (PQresultStatus(res) != PGRES_COMMAND_OK &&
675  {
676  dblink_res_error(conn, conname, res, fail,
677  "while fetching from cursor \"%s\"", curname);
678  return (Datum) 0;
679  }
680  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
681  {
682  /* cursor does not exist - closed already or bad name */
683  PQclear(res);
684  ereport(ERROR,
685  (errcode(ERRCODE_INVALID_CURSOR_NAME),
686  errmsg("cursor \"%s\" does not exist", curname)));
687  }
688 
689  materializeResult(fcinfo, conn, res);
690  return (Datum) 0;
691 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1800
PGconn * conn
Definition: streamutil.c:54
static char * buf
Definition: pg_test_fsync.c:68
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
int errmsg(const char *fmt,...)
Definition: elog.c:909
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2142

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

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

Referenced by dblink_exec(), and dblink_record_internal().

182 {
183  remoteConn *rconn = getConnectionByName(conname_or_str);
184  PGconn *conn;
185  char *conname;
186  bool freeconn;
187 
188  if (rconn)
189  {
190  conn = rconn->conn;
191  conname = conname_or_str;
192  freeconn = false;
193  }
194  else
195  {
196  const char *connstr;
197 
198  connstr = get_connect_string(conname_or_str);
199  if (connstr == NULL)
200  connstr = conname_or_str;
201  dblink_connstr_check(connstr);
202 
203  /*
204  * We must obey fd.c's limit on non-virtual file descriptors. Assume
205  * that a PGconn represents one long-lived FD. (Doing this here also
206  * ensures that VFDs are closed if needed to make room.)
207  */
208  if (!AcquireExternalFD())
209  {
210 #ifndef WIN32 /* can't write #if within ereport() macro */
211  ereport(ERROR,
212  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
213  errmsg("could not establish connection"),
214  errdetail("There are too many open files on the local server."),
215  errhint("Raise the server's max_files_per_process and/or \"ulimit -n\" limits.")));
216 #else
217  ereport(ERROR,
218  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
219  errmsg("could not establish connection"),
220  errdetail("There are too many open files on the local server."),
221  errhint("Raise the server's max_files_per_process setting.")));
222 #endif
223  }
224 
225  /* OK to make connection */
226  conn = PQconnectdb(connstr);
227 
228  if (PQstatus(conn) == CONNECTION_BAD)
229  {
230  char *msg = pchomp(PQerrorMessage(conn));
231 
232  PQfinish(conn);
234  ereport(ERROR,
235  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
236  errmsg("could not establish connection"),
237  errdetail_internal("%s", msg)));
238  }
239  dblink_security_check(conn, rconn);
240  if (PQclientEncoding(conn) != GetDatabaseEncoding())
242  freeconn = true;
243  conname = NULL;
244  }
245 
246  *conn_p = conn;
247  *conname_p = conname;
248  *freeconn_p = freeconn;
249 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6804
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
PGconn * conn
Definition: dblink.c:67
char * pchomp(const char *in)
Definition: mcxt.c:1327
#define ERROR
Definition: elog.h:46
PGconn * conn
Definition: streamutil.c:54
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int GetDatabaseEncoding(void)
Definition: mbutils.c:1210
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6812
bool AcquireExternalFD(void)
Definition: fd.c:1095
#define ereport(elevel,...)
Definition: elog.h:157
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1216
void ReleaseExternalFD(void)
Definition: fd.c:1148
int errmsg(const char *fmt,...)
Definition: elog.c:909
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6682
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:718
static char * connstr
Definition: pg_dumpall.c:62

◆ dblink_get_connections()

Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

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

1325 {
1327  remoteConnHashEnt *hentry;
1328  ArrayBuildState *astate = NULL;
1329 
1330  if (remoteConnHash)
1331  {
1332  hash_seq_init(&status, remoteConnHash);
1333  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1334  {
1335  /* stash away current value */
1336  astate = accumArrayResult(astate,
1337  CStringGetTextDatum(hentry->name),
1338  false, TEXTOID, CurrentMemoryContext);
1339  }
1340  }
1341 
1342  if (astate)
1345  else
1346  PG_RETURN_NULL();
1347 }
char name[NAMEDATALEN]
Definition: dblink.c:139
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5149
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1436
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1426
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5085
#define CStringGetTextDatum(s)
Definition: builtins.h:82
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define PG_RETURN_NULL()
Definition: fmgr.h:345

◆ dblink_get_named_conn()

static PGconn* dblink_get_named_conn ( const char *  conname)
static

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

253 {
254  remoteConn *rconn = getConnectionByName(conname);
255 
256  if (rconn)
257  return rconn->conn;
258 
259  dblink_conn_not_avail(conname);
260  return NULL; /* keep compiler quiet */
261 }
PGconn * conn
Definition: dblink.c:67

◆ dblink_get_notify()

Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

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

1929 {
1930  PGconn *conn;
1931  PGnotify *notify;
1932  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1933  TupleDesc tupdesc;
1934  Tuplestorestate *tupstore;
1935  MemoryContext per_query_ctx;
1936  MemoryContext oldcontext;
1937 
1938  prepTuplestoreResult(fcinfo);
1939 
1940  dblink_init();
1941  if (PG_NARGS() == 1)
1943  else
1944  conn = pconn->conn;
1945 
1946  /* create the tuplestore in per-query memory */
1947  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1948  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1949 
1951  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1952  TEXTOID, -1, 0);
1953  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1954  INT4OID, -1, 0);
1955  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1956  TEXTOID, -1, 0);
1957 
1958  tupstore = tuplestore_begin_heap(true, false, work_mem);
1959  rsinfo->setResult = tupstore;
1960  rsinfo->setDesc = tupdesc;
1961 
1962  MemoryContextSwitchTo(oldcontext);
1963 
1964  PQconsumeInput(conn);
1965  while ((notify = PQnotifies(conn)) != NULL)
1966  {
1968  bool nulls[DBLINK_NOTIFY_COLS];
1969 
1970  memset(values, 0, sizeof(values));
1971  memset(nulls, 0, sizeof(nulls));
1972 
1973  if (notify->relname != NULL)
1974  values[0] = CStringGetTextDatum(notify->relname);
1975  else
1976  nulls[0] = true;
1977 
1978  values[1] = Int32GetDatum(notify->be_pid);
1979 
1980  if (notify->extra != NULL)
1981  values[2] = CStringGetTextDatum(notify->extra);
1982  else
1983  nulls[2] = true;
1984 
1985  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1986 
1987  PQfreemem(notify);
1988  PQconsumeInput(conn);
1989  }
1990 
1991  /* clean up and return the tuplestore */
1992  tuplestore_donestoring(tupstore);
1993 
1994  return (Datum) 0;
1995 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
char * extra
Definition: libpq-fe.h:180
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2466
#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:309
PGconn * conn
Definition: dblink.c:67
PGconn * conn
Definition: streamutil.c:54
int be_pid
Definition: libpq-fe.h:179
char * relname
Definition: libpq-fe.h:178
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:580
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:411
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1853
int work_mem
Definition: globals.c:124
#define PG_NARGS()
Definition: fmgr.h:203
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:233
Tuplestorestate * setResult
Definition: execnodes.h:310
static Datum values[MAXATTR]
Definition: bootstrap.c:166
char * text_to_cstring(const text *t)
Definition: varlena.c:223
ExprContext * econtext
Definition: execnodes.h:303
#define Int32GetDatum(X)
Definition: postgres.h:523
TupleDesc setDesc
Definition: execnodes.h:311
#define CStringGetTextDatum(s)
Definition: builtins.h:82
int16 AttrNumber
Definition: attnum.h:21
void PQfreemem(void *ptr)
Definition: fe-exec.c:3715

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

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

1543 {
1544  int16 indnkeyatts;
1545  char **results;
1546  FuncCallContext *funcctx;
1547  int32 call_cntr;
1548  int32 max_calls;
1549  AttInMetadata *attinmeta;
1550  MemoryContext oldcontext;
1551 
1552  /* stuff done only on the first call of the function */
1553  if (SRF_IS_FIRSTCALL())
1554  {
1555  Relation rel;
1556  TupleDesc tupdesc;
1557 
1558  /* create a function context for cross-call persistence */
1559  funcctx = SRF_FIRSTCALL_INIT();
1560 
1561  /*
1562  * switch to memory context appropriate for multiple function calls
1563  */
1564  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1565 
1566  /* open target relation */
1568 
1569  /* get the array of attnums */
1570  results = get_pkey_attnames(rel, &indnkeyatts);
1571 
1573 
1574  /*
1575  * need a tuple descriptor representing one INT and one TEXT column
1576  */
1577  tupdesc = CreateTemplateTupleDesc(2);
1578  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
1579  INT4OID, -1, 0);
1580  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
1581  TEXTOID, -1, 0);
1582 
1583  /*
1584  * Generate attribute metadata needed later to produce tuples from raw
1585  * C strings
1586  */
1587  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1588  funcctx->attinmeta = attinmeta;
1589 
1590  if ((results != NULL) && (indnkeyatts > 0))
1591  {
1592  funcctx->max_calls = indnkeyatts;
1593 
1594  /* got results, keep track of them */
1595  funcctx->user_fctx = results;
1596  }
1597  else
1598  {
1599  /* fast track when no results */
1600  MemoryContextSwitchTo(oldcontext);
1601  SRF_RETURN_DONE(funcctx);
1602  }
1603 
1604  MemoryContextSwitchTo(oldcontext);
1605  }
1606 
1607  /* stuff done on every call of the function */
1608  funcctx = SRF_PERCALL_SETUP();
1609 
1610  /*
1611  * initialize per-call variables
1612  */
1613  call_cntr = funcctx->call_cntr;
1614  max_calls = funcctx->max_calls;
1615 
1616  results = (char **) funcctx->user_fctx;
1617  attinmeta = funcctx->attinmeta;
1618 
1619  if (call_cntr < max_calls) /* do when there is more left to send */
1620  {
1621  char **values;
1622  HeapTuple tuple;
1623  Datum result;
1624 
1625  values = (char **) palloc(2 * sizeof(char *));
1626  values[0] = psprintf("%d", call_cntr + 1);
1627  values[1] = results[call_cntr];
1628 
1629  /* build the tuple */
1630  tuple = BuildTupleFromCStrings(attinmeta, values);
1631 
1632  /* make the tuple into a datum */
1633  result = HeapTupleGetDatum(tuple);
1634 
1635  SRF_RETURN_NEXT(funcctx, result);
1636  }
1637  else
1638  {
1639  /* do when there is no more left */
1640  SRF_RETURN_DONE(funcctx);
1641  }
1642 }
uint64 call_cntr
Definition: funcapi.h:65
signed short int16
Definition: c.h:428
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:294
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:298
signed int int32
Definition: c.h:429
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2146
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:300
AttInMetadata * attinmeta
Definition: funcapi.h:91
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:580
uintptr_t Datum
Definition: postgres.h:411
#define ACL_SELECT
Definition: parsenodes.h:83
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
static Datum values[MAXATTR]
Definition: bootstrap.c:166
void * user_fctx
Definition: funcapi.h:82
void * palloc(Size size)
Definition: mcxt.c:1062
int16 AttrNumber
Definition: attnum.h:21
uint64 max_calls
Definition: funcapi.h:74
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:318
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:296

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 730 of file dblink.c.

References dblink_record_internal().

Referenced by dblink_send_query().

731 {
732  return dblink_record_internal(fcinfo, true);
733 }

◆ dblink_init()

static void dblink_init ( void  )
static

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

265 {
266  if (!pconn)
267  {
269  pconn->conn = NULL;
270  pconn->openCursorCount = 0;
271  pconn->newXactForCursor = false;
272  }
273 }
int openCursorCount
Definition: dblink.c:68
PGconn * conn
Definition: dblink.c:67
MemoryContext TopMemoryContext
Definition: mcxt.c:48
bool newXactForCursor
Definition: dblink.c:69
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

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

1360 {
1361  PGconn *conn;
1362 
1363  dblink_init();
1365 
1366  PQconsumeInput(conn);
1367  PG_RETURN_INT32(PQisBusy(conn));
1368 }
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: streamutil.c:54
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1853
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:1900
char * text_to_cstring(const text *t)
Definition: varlena.c:223

◆ dblink_open()

Datum dblink_open ( PG_FUNCTION_ARGS  )

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

425 {
426  PGresult *res = NULL;
427  PGconn *conn;
428  char *curname = NULL;
429  char *sql = NULL;
430  char *conname = NULL;
432  remoteConn *rconn = NULL;
433  bool fail = true; /* default to backward compatible behavior */
434 
435  dblink_init();
436  initStringInfo(&buf);
437 
438  if (PG_NARGS() == 2)
439  {
440  /* text,text */
441  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
443  rconn = pconn;
444  }
445  else if (PG_NARGS() == 3)
446  {
447  /* might be text,text,text or text,text,bool */
448  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
449  {
450  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
452  fail = PG_GETARG_BOOL(2);
453  rconn = pconn;
454  }
455  else
456  {
457  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
458  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
460  rconn = getConnectionByName(conname);
461  }
462  }
463  else if (PG_NARGS() == 4)
464  {
465  /* text,text,text,bool */
466  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
467  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
469  fail = PG_GETARG_BOOL(3);
470  rconn = getConnectionByName(conname);
471  }
472 
473  if (!rconn || !rconn->conn)
474  dblink_conn_not_avail(conname);
475 
476  conn = rconn->conn;
477 
478  /* If we are not in a transaction, start one */
479  if (PQtransactionStatus(conn) == PQTRANS_IDLE)
480  {
481  res = PQexec(conn, "BEGIN");
482  if (PQresultStatus(res) != PGRES_COMMAND_OK)
483  dblink_res_internalerror(conn, res, "begin error");
484  PQclear(res);
485  rconn->newXactForCursor = true;
486 
487  /*
488  * Since transaction state was IDLE, we force cursor count to
489  * initially be 0. This is needed as a previous ABORT might have wiped
490  * out our transaction without maintaining the cursor count for us.
491  */
492  rconn->openCursorCount = 0;
493  }
494 
495  /* if we started a transaction, increment cursor count */
496  if (rconn->newXactForCursor)
497  (rconn->openCursorCount)++;
498 
499  appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
500  res = PQexec(conn, buf.data);
501  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
502  {
503  dblink_res_error(conn, conname, res, fail,
504  "while opening cursor \"%s\"", curname);
506  }
507 
508  PQclear(res);
510 }
int openCursorCount
Definition: dblink.c:68
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1800
PGconn * conn
Definition: streamutil.c:54
static char * buf
Definition: pg_test_fsync.c:68
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6690
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
bool newXactForCursor
Definition: dblink.c:69
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
text * cstring_to_text(const char *s)
Definition: varlena.c:190
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2142

◆ dblink_record()

Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 698 of file dblink.c.

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

Referenced by dblink_fetch().

699 {
700  return dblink_record_internal(fcinfo, false);
701 }

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 736 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_END_TRY, PG_FINALLY, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQfinish(), PQgetResult(), PQresultStatus(), prepTuplestoreResult(), ReleaseExternalFD(), and text_to_cstring().

Referenced by dblink_get_result(), and dblink_record().

737 {
738  PGconn *volatile conn = NULL;
739  volatile bool freeconn = false;
740 
741  prepTuplestoreResult(fcinfo);
742 
743  dblink_init();
744 
745  PG_TRY();
746  {
747  char *sql = NULL;
748  char *conname = NULL;
749  bool fail = true; /* default to backward compatible */
750 
751  if (!is_async)
752  {
753  if (PG_NARGS() == 3)
754  {
755  /* text,text,bool */
756  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
758  fail = PG_GETARG_BOOL(2);
759  dblink_get_conn(conname, &conn, &conname, &freeconn);
760  }
761  else if (PG_NARGS() == 2)
762  {
763  /* text,text or text,bool */
764  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
765  {
767  fail = PG_GETARG_BOOL(1);
768  conn = pconn->conn;
769  }
770  else
771  {
772  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
774  dblink_get_conn(conname, &conn, &conname, &freeconn);
775  }
776  }
777  else if (PG_NARGS() == 1)
778  {
779  /* text */
780  conn = pconn->conn;
782  }
783  else
784  /* shouldn't happen */
785  elog(ERROR, "wrong number of arguments");
786  }
787  else /* is_async */
788  {
789  /* get async result */
790  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
791 
792  if (PG_NARGS() == 2)
793  {
794  /* text,bool */
795  fail = PG_GETARG_BOOL(1);
796  conn = dblink_get_named_conn(conname);
797  }
798  else if (PG_NARGS() == 1)
799  {
800  /* text */
801  conn = dblink_get_named_conn(conname);
802  }
803  else
804  /* shouldn't happen */
805  elog(ERROR, "wrong number of arguments");
806  }
807 
808  if (!conn)
809  dblink_conn_not_avail(conname);
810 
811  if (!is_async)
812  {
813  /* synchronous query, use efficient tuple collection method */
814  materializeQueryResult(fcinfo, conn, conname, sql, fail);
815  }
816  else
817  {
818  /* async result retrieval, do it the old way */
819  PGresult *res = PQgetResult(conn);
820 
821  /* NULL means we're all done with the async results */
822  if (res)
823  {
824  if (PQresultStatus(res) != PGRES_COMMAND_OK &&
826  {
827  dblink_res_error(conn, conname, res, fail,
828  "while executing query");
829  /* if fail isn't set, we'll return an empty query result */
830  }
831  else
832  {
833  materializeResult(fcinfo, conn, res);
834  }
835  }
836  }
837  }
838  PG_FINALLY();
839  {
840  /* if needed, close the connection to the database */
841  if (freeconn)
842  {
843  PQfinish(conn);
845  }
846  }
847  PG_END_TRY();
848 
849  return (Datum) 0;
850 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
PGconn * conn
Definition: dblink.c:67
#define ERROR
Definition: elog.h:46
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1800
PGconn * conn
Definition: streamutil.c:54
#define PG_FINALLY()
Definition: elog.h:330
uintptr_t Datum
Definition: postgres.h:411
FmgrInfo * flinfo
Definition: fmgr.h:87
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
void ReleaseExternalFD(void)
Definition: fd.c:1148
#define elog(elevel,...)
Definition: elog.h:232
#define PG_TRY()
Definition: elog.h:313
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1927
#define PG_END_TRY()
Definition: elog.h:338

◆ dblink_res_error()

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

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

2738 {
2739  int level;
2740  char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2741  char *pg_diag_message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2742  char *pg_diag_message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2743  char *pg_diag_message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2744  char *pg_diag_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2745  int sqlstate;
2746  char *message_primary;
2747  char *message_detail;
2748  char *message_hint;
2749  char *message_context;
2750  va_list ap;
2751  char dblink_context_msg[512];
2752 
2753  if (fail)
2754  level = ERROR;
2755  else
2756  level = NOTICE;
2757 
2758  if (pg_diag_sqlstate)
2759  sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2760  pg_diag_sqlstate[1],
2761  pg_diag_sqlstate[2],
2762  pg_diag_sqlstate[3],
2763  pg_diag_sqlstate[4]);
2764  else
2765  sqlstate = ERRCODE_CONNECTION_FAILURE;
2766 
2767  message_primary = xpstrdup(pg_diag_message_primary);
2768  message_detail = xpstrdup(pg_diag_message_detail);
2769  message_hint = xpstrdup(pg_diag_message_hint);
2770  message_context = xpstrdup(pg_diag_context);
2771 
2772  /*
2773  * If we don't get a message from the PGresult, try the PGconn. This is
2774  * needed because for connection-level failures, PQexec may just return
2775  * NULL, not a PGresult at all.
2776  */
2777  if (message_primary == NULL)
2778  message_primary = pchomp(PQerrorMessage(conn));
2779 
2780  /*
2781  * Now that we've copied all the data we need out of the PGresult, it's
2782  * safe to free it. We must do this to avoid PGresult leakage. We're
2783  * leaking all the strings too, but those are in palloc'd memory that will
2784  * get cleaned up eventually.
2785  */
2786  if (res)
2787  PQclear(res);
2788 
2789  /*
2790  * Format the basic errcontext string. Below, we'll add on something
2791  * about the connection name. That's a violation of the translatability
2792  * guidelines about constructing error messages out of parts, but since
2793  * there's no translation support for dblink, there's no need to worry
2794  * about that (yet).
2795  */
2796  va_start(ap, fmt);
2797  vsnprintf(dblink_context_msg, sizeof(dblink_context_msg), fmt, ap);
2798  va_end(ap);
2799 
2800  ereport(level,
2801  (errcode(sqlstate),
2802  message_primary ? errmsg_internal("%s", message_primary) :
2803  errmsg("could not obtain message string for remote error"),
2804  message_detail ? errdetail_internal("%s", message_detail) : 0,
2805  message_hint ? errhint("%s", message_hint) : 0,
2806  message_context ? (errcontext("%s", message_context)) : 0,
2807  conname ?
2808  (errcontext("%s on dblink connection named \"%s\"",
2809  dblink_context_msg, conname)) :
2810  (errcontext("%s on unnamed dblink connection",
2811  dblink_context_msg))));
2812 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
int errhint(const char *fmt,...)
Definition: elog.c:1156
#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:64
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
char * pchomp(const char *in)
Definition: mcxt.c:1327
#define ERROR
Definition: elog.h:46
#define vsnprintf
Definition: port.h:215
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define ereport(elevel,...)
Definition: elog.h:157
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define NOTICE
Definition: elog.h:37
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3152
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define errcontext
Definition: elog.h:204
#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 2667 of file dblink.c.

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

Referenced by dblink_connect(), and dblink_get_conn().

2668 {
2669  if (!superuser())
2670  {
2671  if (!PQconnectionUsedPassword(conn))
2672  {
2673  PQfinish(conn);
2675  if (rconn)
2676  pfree(rconn);
2677 
2678  ereport(ERROR,
2679  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2680  errmsg("password is required"),
2681  errdetail("Non-superuser cannot connect if the server does not request a password."),
2682  errhint("Target server's authentication method must be changed.")));
2683  }
2684  }
2685 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4229
bool superuser(void)
Definition: superuser.c:46
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define ereport(elevel,...)
Definition: elog.h:157
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6793
void ReleaseExternalFD(void)
Definition: fd.c:1148
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ dblink_send_query()

Datum dblink_send_query ( PG_FUNCTION_ARGS  )

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

706 {
707  PGconn *conn;
708  char *sql;
709  int retval;
710 
711  if (PG_NARGS() == 2)
712  {
715  }
716  else
717  /* shouldn't happen */
718  elog(ERROR, "wrong number of arguments");
719 
720  /* async query send */
721  retval = PQsendQuery(conn, sql);
722  if (retval != 1)
723  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
724 
725  PG_RETURN_INT32(retval);
726 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
char * pchomp(const char *in)
Definition: mcxt.c:1327
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1279
#define ERROR
Definition: elog.h:46
PGconn * conn
Definition: streamutil.c:54
#define NOTICE
Definition: elog.h:37
#define PG_NARGS()
Definition: fmgr.h:203
char * text_to_cstring(const text *t)
Definition: varlena.c:223
#define elog(elevel,...)
Definition: elog.h:232

◆ deleteConnection()

static void deleteConnection ( const char *  name)
static

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

2646 {
2647  remoteConnHashEnt *hentry;
2648  bool found;
2649  char *key;
2650 
2651  if (!remoteConnHash)
2653 
2654  key = pstrdup(name);
2655  truncate_identifier(key, strlen(key), false);
2657  key, HASH_REMOVE, &found);
2658 
2659  if (!hentry)
2660  ereport(ERROR,
2661  (errcode(ERRCODE_UNDEFINED_OBJECT),
2662  errmsg("undefined connection name")));
2663 
2664 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ escape_param_str()

static char * escape_param_str ( const char *  from)
static

Definition at line 2908 of file dblink.c.

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

Referenced by get_connect_string().

2909 {
2910  const char *cp;
2912 
2913  initStringInfo(&buf);
2914 
2915  for (cp = str; *cp; cp++)
2916  {
2917  if (*cp == '\\' || *cp == '\'')
2918  appendStringInfoChar(&buf, '\\');
2919  appendStringInfoChar(&buf, *cp);
2920  }
2921 
2922  return buf.data;
2923 }
static char * buf
Definition: pg_test_fsync.c:68
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

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

2566 {
2567  char *nspname;
2568  char *result;
2569 
2570  /* Qualify the name if not visible in search path */
2572  nspname = NULL;
2573  else
2574  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2575 
2576  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2577 
2578  return result;
2579 }
Form_pg_class rd_rel
Definition: rel.h:110
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define RelationGetRelationName(relation)
Definition: rel.h:506
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11407
bool RelationIsVisible(Oid relid)
Definition: namespace.c:708
#define RelationGetRelid(relation)
Definition: rel.h:472

◆ get_attnum_pk_pos()

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

Definition at line 2412 of file dblink.c.

References i.

Referenced by get_sql_insert(), and get_sql_update().

2413 {
2414  int i;
2415 
2416  /*
2417  * Not likely a long list anyway, so just scan for the value
2418  */
2419  for (i = 0; i < pknumatts; i++)
2420  if (key == pkattnums[i])
2421  return i;
2422 
2423  return -1;
2424 }
int i

◆ get_connect_string()

static char * get_connect_string ( const char *  servername)
static

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

2819 {
2820  ForeignServer *foreign_server = NULL;
2821  UserMapping *user_mapping;
2822  ListCell *cell;
2824  ForeignDataWrapper *fdw;
2825  AclResult aclresult;
2826  char *srvname;
2827 
2828  static const PQconninfoOption *options = NULL;
2829 
2830  initStringInfo(&buf);
2831 
2832  /*
2833  * Get list of valid libpq options.
2834  *
2835  * To avoid unnecessary work, we get the list once and use it throughout
2836  * the lifetime of this backend process. We don't need to care about
2837  * memory context issues, because PQconndefaults allocates with malloc.
2838  */
2839  if (!options)
2840  {
2841  options = PQconndefaults();
2842  if (!options) /* assume reason for failure is OOM */
2843  ereport(ERROR,
2844  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2845  errmsg("out of memory"),
2846  errdetail("Could not get libpq's default connection options.")));
2847  }
2848 
2849  /* first gather the server connstr options */
2850  srvname = pstrdup(servername);
2851  truncate_identifier(srvname, strlen(srvname), false);
2852  foreign_server = GetForeignServerByName(srvname, true);
2853 
2854  if (foreign_server)
2855  {
2856  Oid serverid = foreign_server->serverid;
2857  Oid fdwid = foreign_server->fdwid;
2858  Oid userid = GetUserId();
2859 
2860  user_mapping = GetUserMapping(userid, serverid);
2861  fdw = GetForeignDataWrapper(fdwid);
2862 
2863  /* Check permissions, user must have usage on the server. */
2864  aclresult = pg_foreign_server_aclcheck(serverid, userid, ACL_USAGE);
2865  if (aclresult != ACLCHECK_OK)
2866  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, foreign_server->servername);
2867 
2868  foreach(cell, fdw->options)
2869  {
2870  DefElem *def = lfirst(cell);
2871 
2872  if (is_valid_dblink_option(options, def->defname, ForeignDataWrapperRelationId))
2873  appendStringInfo(&buf, "%s='%s' ", def->defname,
2874  escape_param_str(strVal(def->arg)));
2875  }
2876 
2877  foreach(cell, foreign_server->options)
2878  {
2879  DefElem *def = lfirst(cell);
2880 
2881  if (is_valid_dblink_option(options, def->defname, ForeignServerRelationId))
2882  appendStringInfo(&buf, "%s='%s' ", def->defname,
2883  escape_param_str(strVal(def->arg)));
2884  }
2885 
2886  foreach(cell, user_mapping->options)
2887  {
2888 
2889  DefElem *def = lfirst(cell);
2890 
2891  if (is_valid_dblink_option(options, def->defname, UserMappingRelationId))
2892  appendStringInfo(&buf, "%s='%s' ", def->defname,
2893  escape_param_str(strVal(def->arg)));
2894  }
2895 
2896  return buf.data;
2897  }
2898  else
2899  return NULL;
2900 }
Oid GetUserId(void)
Definition: miscinit.c:478
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:35
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
AclResult pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4799
static char * buf
Definition: pg_test_fsync.c:68
int errdetail(const char *fmt,...)
Definition: elog.c:1042
List * options
Definition: foreign.h:50
#define ACL_USAGE
Definition: parsenodes.h:90
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:180
Node * arg
Definition: parsenodes.h:747
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
List * options
Definition: foreign.h:31
AclResult
Definition: acl.h:177
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1477
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * servername
Definition: foreign.h:39
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:198
char * defname
Definition: parsenodes.h:746
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 2078 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().

2079 {
2080  Relation indexRelation;
2081  ScanKeyData skey;
2082  SysScanDesc scan;
2083  HeapTuple indexTuple;
2084  int i;
2085  char **result = NULL;
2086  TupleDesc tupdesc;
2087 
2088  /* initialize indnkeyatts to 0 in case no primary key exists */
2089  *indnkeyatts = 0;
2090 
2091  tupdesc = rel->rd_att;
2092 
2093  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2094  indexRelation = table_open(IndexRelationId, AccessShareLock);
2095  ScanKeyInit(&skey,
2096  Anum_pg_index_indrelid,
2097  BTEqualStrategyNumber, F_OIDEQ,
2099 
2100  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2101  NULL, 1, &skey);
2102 
2103  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2104  {
2105  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2106 
2107  /* we're only interested if it is the primary key */
2108  if (index->indisprimary)
2109  {
2110  *indnkeyatts = index->indnkeyatts;
2111  if (*indnkeyatts > 0)
2112  {
2113  result = (char **) palloc(*indnkeyatts * sizeof(char *));
2114 
2115  for (i = 0; i < *indnkeyatts; i++)
2116  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2117  }
2118  break;
2119  }
2120  }
2121 
2122  systable_endscan(scan);
2123  table_close(indexRelation, AccessShareLock);
2124 
2125  return result;
2126 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define AccessShareLock
Definition: lockdefs.h:36
#define IndexIndrelidIndexId
Definition: pg_index.h:72
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:1094
Definition: type.h:89
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
TupleDesc rd_att
Definition: rel.h:111
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void * palloc(Size size)
Definition: mcxt.c:1062
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:472
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ get_rel_from_relname()

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

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

2541 {
2542  RangeVar *relvar;
2543  Relation rel;
2544  AclResult aclresult;
2545 
2546  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2547  rel = table_openrv(relvar, lockmode);
2548 
2549  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2550  aclmode);
2551  if (aclresult != ACLCHECK_OK)
2552  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2554 
2555  return rel;
2556 }
Oid GetUserId(void)
Definition: miscinit.c:478
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3061
Form_pg_class rd_rel
Definition: rel.h:110
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define RelationGetRelationName(relation)
Definition: rel.h:506
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3695
AclResult
Definition: acl.h:177
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4685
ObjectType get_relkind_objtype(char relkind)
#define RelationGetRelid(relation)
Definition: rel.h:472

◆ get_sql_delete()

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

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

2270 {
2271  char *relname;
2272  TupleDesc tupdesc;
2274  int i;
2275 
2276  initStringInfo(&buf);
2277 
2278  /* get relation name including any needed schema prefix and quoting */
2279  relname = generate_relation_name(rel);
2280 
2281  tupdesc = rel->rd_att;
2282 
2283  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2284  for (i = 0; i < pknumatts; i++)
2285  {
2286  int pkattnum = pkattnums[i];
2287  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2288 
2289  if (i > 0)
2290  appendStringInfoString(&buf, " AND ");
2291 
2293  quote_ident_cstr(NameStr(attr->attname)));
2294 
2295  if (tgt_pkattvals[i] != NULL)
2296  appendStringInfo(&buf, " = %s",
2297  quote_literal_cstr(tgt_pkattvals[i]));
2298  else
2299  appendStringInfoString(&buf, " IS NULL");
2300  }
2301 
2302  return buf.data;
2303 }
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:38
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
TupleDesc rd_att
Definition: rel.h:111
int i
#define NameStr(name)
Definition: c.h:681

◆ get_sql_insert()

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

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

2190 {
2191  char *relname;
2192  HeapTuple tuple;
2193  TupleDesc tupdesc;
2194  int natts;
2196  char *val;
2197  int key;
2198  int i;
2199  bool needComma;
2200 
2201  initStringInfo(&buf);
2202 
2203  /* get relation name including any needed schema prefix and quoting */
2204  relname = generate_relation_name(rel);
2205 
2206  tupdesc = rel->rd_att;
2207  natts = tupdesc->natts;
2208 
2209  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2210  if (!tuple)
2211  ereport(ERROR,
2212  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2213  errmsg("source row not found")));
2214 
2215  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2216 
2217  needComma = false;
2218  for (i = 0; i < natts; i++)
2219  {
2220  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2221 
2222  if (att->attisdropped)
2223  continue;
2224 
2225  if (needComma)
2226  appendStringInfoChar(&buf, ',');
2227 
2229  quote_ident_cstr(NameStr(att->attname)));
2230  needComma = true;
2231  }
2232 
2233  appendStringInfoString(&buf, ") VALUES(");
2234 
2235  /*
2236  * Note: i is physical column number (counting from 0).
2237  */
2238  needComma = false;
2239  for (i = 0; i < natts; i++)
2240  {
2241  if (TupleDescAttr(tupdesc, i)->attisdropped)
2242  continue;
2243 
2244  if (needComma)
2245  appendStringInfoChar(&buf, ',');
2246 
2247  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2248 
2249  if (key >= 0)
2250  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2251  else
2252  val = SPI_getvalue(tuple, tupdesc, i + 1);
2253 
2254  if (val != NULL)
2255  {
2257  pfree(val);
2258  }
2259  else
2260  appendStringInfoString(&buf, "NULL");
2261  needComma = true;
2262  }
2263  appendStringInfoChar(&buf, ')');
2264 
2265  return buf.data;
2266 }
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:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
NameData relname
Definition: pg_class.h:38
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1116
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
TupleDesc rd_att
Definition: rel.h:111
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define NameStr(name)
Definition: c.h:681
long val
Definition: informix.c:664

◆ get_sql_update()

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

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

2307 {
2308  char *relname;
2309  HeapTuple tuple;
2310  TupleDesc tupdesc;
2311  int natts;
2313  char *val;
2314  int key;
2315  int i;
2316  bool needComma;
2317 
2318  initStringInfo(&buf);
2319 
2320  /* get relation name including any needed schema prefix and quoting */
2321  relname = generate_relation_name(rel);
2322 
2323  tupdesc = rel->rd_att;
2324  natts = tupdesc->natts;
2325 
2326  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2327  if (!tuple)
2328  ereport(ERROR,
2329  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2330  errmsg("source row not found")));
2331 
2332  appendStringInfo(&buf, "UPDATE %s SET ", relname);
2333 
2334  /*
2335  * Note: i is physical column number (counting from 0).
2336  */
2337  needComma = false;
2338  for (i = 0; i < natts; i++)
2339  {
2340  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2341 
2342  if (attr->attisdropped)
2343  continue;
2344 
2345  if (needComma)
2346  appendStringInfoString(&buf, ", ");
2347 
2348  appendStringInfo(&buf, "%s = ",
2349  quote_ident_cstr(NameStr(attr->attname)));
2350 
2351  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2352 
2353  if (key >= 0)
2354  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2355  else
2356  val = SPI_getvalue(tuple, tupdesc, i + 1);
2357 
2358  if (val != NULL)
2359  {
2361  pfree(val);
2362  }
2363  else
2364  appendStringInfoString(&buf, "NULL");
2365  needComma = true;
2366  }
2367 
2368  appendStringInfoString(&buf, " WHERE ");
2369 
2370  for (i = 0; i < pknumatts; i++)
2371  {
2372  int pkattnum = pkattnums[i];
2373  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2374 
2375  if (i > 0)
2376  appendStringInfoString(&buf, " AND ");
2377 
2379  quote_ident_cstr(NameStr(attr->attname)));
2380 
2381  val = tgt_pkattvals[i];
2382 
2383  if (val != NULL)
2384  appendStringInfo(&buf, " = %s", quote_literal_cstr(val));
2385  else
2386  appendStringInfoString(&buf, " IS NULL");
2387  }
2388 
2389  return buf.data;
2390 }
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:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
NameData relname
Definition: pg_class.h:38
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1116
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
TupleDesc rd_att
Definition: rel.h:111
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define NameStr(name)
Definition: c.h:681
long val
Definition: informix.c:664

◆ get_text_array_contents()

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

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

2134 {
2135  int ndim = ARR_NDIM(array);
2136  int *dims = ARR_DIMS(array);
2137  int nitems;
2138  int16 typlen;
2139  bool typbyval;
2140  char typalign;
2141  char **values;
2142  char *ptr;
2143  bits8 *bitmap;
2144  int bitmask;
2145  int i;
2146 
2147  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2148 
2149  *numitems = nitems = ArrayGetNItems(ndim, dims);
2150 
2152  &typlen, &typbyval, &typalign);
2153 
2154  values = (char **) palloc(nitems * sizeof(char *));
2155 
2156  ptr = ARR_DATA_PTR(array);
2157  bitmap = ARR_NULLBITMAP(array);
2158  bitmask = 1;
2159 
2160  for (i = 0; i < nitems; i++)
2161  {
2162  if (bitmap && (*bitmap & bitmask) == 0)
2163  {
2164  values[i] = NULL;
2165  }
2166  else
2167  {
2168  values[i] = TextDatumGetCString(PointerGetDatum(ptr));
2169  ptr = att_addlength_pointer(ptr, typlen, ptr);
2170  ptr = (char *) att_align_nominal(ptr, typalign);
2171  }
2172 
2173  /* advance bitmap pointer if any */
2174  if (bitmap)
2175  {
2176  bitmask <<= 1;
2177  if (bitmask == 0x100)
2178  {
2179  bitmap++;
2180  bitmask = 1;
2181  }
2182  }
2183  }
2184 
2185  return values;
2186 }
signed short int16
Definition: c.h:428
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2218
#define PointerGetDatum(X)
Definition: postgres.h:600
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
char typalign
Definition: pg_type.h:176
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:176
uint8 bits8
Definition: c.h:448
#define TextDatumGetCString(d)
Definition: builtins.h:83
#define Assert(condition)
Definition: c.h:804
#define ARR_NDIM(a)
Definition: array.h:283
static Datum values[MAXATTR]
Definition: bootstrap.c:166
void * palloc(Size size)
Definition: mcxt.c:1062
int i
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_NULLBITMAP(a)
Definition: array.h:293

◆ get_tuple_of_interest()

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

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

2428 {
2429  char *relname;
2430  TupleDesc tupdesc;
2431  int natts;
2433  int ret;
2434  HeapTuple tuple;
2435  int i;
2436 
2437  /*
2438  * Connect to SPI manager
2439  */
2440  if ((ret = SPI_connect()) < 0)
2441  /* internal error */
2442  elog(ERROR, "SPI connect failure - returned %d", ret);
2443 
2444  initStringInfo(&buf);
2445 
2446  /* get relation name including any needed schema prefix and quoting */
2447  relname = generate_relation_name(rel);
2448 
2449  tupdesc = rel->rd_att;
2450  natts = tupdesc->natts;
2451 
2452  /*
2453  * Build sql statement to look up tuple of interest, ie, the one matching
2454  * src_pkattvals. We used to use "SELECT *" here, but it's simpler to
2455  * generate a result tuple that matches the table's physical structure,
2456  * with NULLs for any dropped columns. Otherwise we have to deal with two
2457  * different tupdescs and everything's very confusing.
2458  */
2459  appendStringInfoString(&buf, "SELECT ");
2460 
2461  for (i = 0; i < natts; i++)
2462  {
2463  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2464 
2465  if (i > 0)
2466  appendStringInfoString(&buf, ", ");
2467 
2468  if (attr->attisdropped)
2469  appendStringInfoString(&buf, "NULL");
2470  else
2472  quote_ident_cstr(NameStr(attr->attname)));
2473  }
2474 
2475  appendStringInfo(&buf, " FROM %s WHERE ", relname);
2476 
2477  for (i = 0; i < pknumatts; i++)
2478  {
2479  int pkattnum = pkattnums[i];
2480  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2481 
2482  if (i > 0)
2483  appendStringInfoString(&buf, " AND ");
2484 
2486  quote_ident_cstr(NameStr(attr->attname)));
2487 
2488  if (src_pkattvals[i] != NULL)
2489  appendStringInfo(&buf, " = %s",
2490  quote_literal_cstr(src_pkattvals[i]));
2491  else
2492  appendStringInfoString(&buf, " IS NULL");
2493  }
2494 
2495  /*
2496  * Retrieve the desired tuple
2497  */
2498  ret = SPI_exec(buf.data, 0);
2499  pfree(buf.data);
2500 
2501  /*
2502  * Only allow one qualifying tuple
2503  */
2504  if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
2505  ereport(ERROR,
2506  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2507  errmsg("source criteria matched more than one record")));
2508 
2509  else if (ret == SPI_OK_SELECT && SPI_processed == 1)
2510  {
2511  SPITupleTable *tuptable = SPI_tuptable;
2512 
2513  tuple = SPI_copytuple(tuptable->vals[0]);
2514  SPI_finish();
2515 
2516  return tuple;
2517  }
2518  else
2519  {
2520  /*
2521  * no qualifying tuples
2522  */
2523  SPI_finish();
2524 
2525  return NULL;
2526  }
2527 
2528  /*
2529  * never reached, but keep compiler quiet
2530  */
2531  return NULL;
2532 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
int SPI_connect(void)
Definition: spi.c:98
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int SPI_finish(void)
Definition: spi.c:185
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:698
HeapTuple SPI_copytuple(HeapTuple tuple)
Definition: spi.c:943
NameData relname
Definition: pg_class.h:38
HeapTuple * vals
Definition: spi.h:26
uint64 SPI_processed
Definition: spi.c:45
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
int SPI_exec(const char *src, long tcount)
Definition: spi.c:536
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
TupleDesc rd_att
Definition: rel.h:111
#define SPI_OK_SELECT
Definition: spi.h:85
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681

◆ getConnectionByName()

static remoteConn * getConnectionByName ( const char *  name)
static

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

2584 {
2585  remoteConnHashEnt *hentry;
2586  char *key;
2587 
2588  if (!remoteConnHash)
2590 
2591  key = pstrdup(name);
2592  truncate_identifier(key, strlen(key), false);
2594  key, HASH_FIND, NULL);
2595 
2596  if (hentry)
2597  return hentry->rconn;
2598 
2599  return NULL;
2600 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
remoteConn * rconn
Definition: dblink.c:140
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
const char * name
Definition: encode.c:515

◆ is_valid_dblink_option()

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

Definition at line 3012 of file dblink.c.

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

Referenced by dblink_fdw_validator(), and get_connect_string().

3014 {
3015  const PQconninfoOption *opt;
3016 
3017  /* Look up the option in libpq result */
3018  for (opt = options; opt->keyword; opt++)
3019  {
3020  if (strcmp(opt->keyword, option) == 0)
3021  break;
3022  }
3023  if (opt->keyword == NULL)
3024  return false;
3025 
3026  /* Disallow debug options (particularly "replication") */
3027  if (strchr(opt->dispchar, 'D'))
3028  return false;
3029 
3030  /* Disallow "client_encoding" */
3031  if (strcmp(opt->keyword, "client_encoding") == 0)
3032  return false;
3033 
3034  /*
3035  * If the option is "user" or marked secure, it should be specified only
3036  * in USER MAPPING. Others should be specified only in SERVER.
3037  */
3038  if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
3039  {
3040  if (context != UserMappingRelationId)
3041  return false;
3042  }
3043  else
3044  {
3045  if (context != ForeignServerRelationId)
3046  return false;
3047  }
3048 
3049  return true;
3050 }

◆ materializeQueryResult()

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

Definition at line 1029 of file dblink.c.

References FunctionCallInfoBaseData::resultinfo.

Referenced by dblink_record_internal().

1034 {
1035  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1036  PGresult *volatile res = NULL;
1037  volatile storeInfo sinfo = {0};
1038 
1039  /* prepTuplestoreResult must have been called previously */
1040  Assert(rsinfo->returnMode == SFRM_Materialize);
1041 
1042  sinfo.fcinfo = fcinfo;
1043 
1044  PG_TRY();
1045  {
1046  /* Create short-lived memory context for data conversions */
1047  sinfo.tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
1048  "dblink temporary context",
1050 
1051  /* execute query, collecting any tuples into the tuplestore */
1052  res = storeQueryResult(&sinfo, conn, sql);
1053 
1054  if (!res ||
1055  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1057  {
1058  /*
1059  * dblink_res_error will clear the passed PGresult, so we need
1060  * this ugly dance to avoid doing so twice during error exit
1061  */
1062  PGresult *res1 = res;
1063 
1064  res = NULL;
1065  dblink_res_error(conn, conname, res1, fail,
1066  "while executing query");
1067  /* if fail isn't set, we'll return an empty query result */
1068  }
1069  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1070  {
1071  /*
1072  * storeRow didn't get called, so we need to convert the command
1073  * status string to a tuple manually
1074  */
1075  TupleDesc tupdesc;
1076  AttInMetadata *attinmeta;
1077  Tuplestorestate *tupstore;
1078  HeapTuple tuple;
1079  char *values[1];
1080  MemoryContext oldcontext;
1081 
1082  /*
1083  * need a tuple descriptor representing one TEXT column to return
1084  * the command status string as our result tuple
1085  */
1086  tupdesc = CreateTemplateTupleDesc(1);
1087  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1088  TEXTOID, -1, 0);
1089  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1090 
1091  oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1092  tupstore = tuplestore_begin_heap(true, false, work_mem);
1093  rsinfo->setResult = tupstore;
1094  rsinfo->setDesc = tupdesc;
1095  MemoryContextSwitchTo(oldcontext);
1096 
1097  values[0] = PQcmdStatus(res);
1098 
1099  /* build the tuple and put it into the tuplestore. */
1100  tuple = BuildTupleFromCStrings(attinmeta, values);
1101  tuplestore_puttuple(tupstore, tuple);
1102 
1103  PQclear(res);
1104  res = NULL;
1105  }
1106  else
1107  {
1109  /* storeRow should have created a tuplestore */
1110  Assert(rsinfo->setResult != NULL);
1111 
1112  PQclear(res);
1113  res = NULL;
1114  }
1115 
1116  /* clean up data conversion short-lived memory context */
1117  if (sinfo.tmpcontext != NULL)
1118  MemoryContextDelete(sinfo.tmpcontext);
1119  sinfo.tmpcontext = NULL;
1120 
1121  PQclear(sinfo.last_res);
1122  sinfo.last_res = NULL;
1123  PQclear(sinfo.cur_res);
1124  sinfo.cur_res = NULL;
1125  }
1126  PG_CATCH();
1127  {
1128  /* be sure to release any libpq result we collected */
1129  PQclear(res);
1130  PQclear(sinfo.last_res);
1131  PQclear(sinfo.cur_res);
1132  /* and clear out any pending data in libpq */
1133  while ((res = PQgetResult(conn)) != NULL)
1134  PQclear(res);
1135  PG_RE_THROW();
1136  }
1137  PG_END_TRY();
1138 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2146
fmNodePtr resultinfo
Definition: fmgr.h:89
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:580
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3438
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
int work_mem
Definition: globals.c:124
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define PG_CATCH()
Definition: elog.h:323
#define Assert(condition)
Definition: c.h:804
#define PG_RE_THROW()
Definition: elog.h:354
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define PG_TRY()
Definition: elog.h:313
int16 AttrNumber
Definition: attnum.h:21
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1927
#define PG_END_TRY()
Definition: elog.h:338

◆ materializeResult()

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

Definition at line 887 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_END_TRY, PG_FINALLY, 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().

888 {
889  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
890 
891  /* prepTuplestoreResult must have been called previously */
892  Assert(rsinfo->returnMode == SFRM_Materialize);
893 
894  PG_TRY();
895  {
896  TupleDesc tupdesc;
897  bool is_sql_cmd;
898  int ntuples;
899  int nfields;
900 
901  if (PQresultStatus(res) == PGRES_COMMAND_OK)
902  {
903  is_sql_cmd = true;
904 
905  /*
906  * need a tuple descriptor representing one TEXT column to return
907  * the command status string as our result tuple
908  */
909  tupdesc = CreateTemplateTupleDesc(1);
910  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
911  TEXTOID, -1, 0);
912  ntuples = 1;
913  nfields = 1;
914  }
915  else
916  {
918 
919  is_sql_cmd = false;
920 
921  /* get a tuple descriptor for our result type */
922  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
923  {
924  case TYPEFUNC_COMPOSITE:
925  /* success */
926  break;
927  case TYPEFUNC_RECORD:
928  /* failed to determine actual type of RECORD */
929  ereport(ERROR,
930  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
931  errmsg("function returning record called in context "
932  "that cannot accept type record")));
933  break;
934  default:
935  /* result type isn't composite */
936  elog(ERROR, "return type must be a row type");
937  break;
938  }
939 
940  /* make sure we have a persistent copy of the tupdesc */
941  tupdesc = CreateTupleDescCopy(tupdesc);
942  ntuples = PQntuples(res);
943  nfields = PQnfields(res);
944  }
945 
946  /*
947  * check result and tuple descriptor have the same number of columns
948  */
949  if (nfields != tupdesc->natts)
950  ereport(ERROR,
951  (errcode(ERRCODE_DATATYPE_MISMATCH),
952  errmsg("remote query result rowtype does not match "
953  "the specified FROM clause rowtype")));
954 
955  if (ntuples > 0)
956  {
957  AttInMetadata *attinmeta;
958  int nestlevel = -1;
959  Tuplestorestate *tupstore;
960  MemoryContext oldcontext;
961  int row;
962  char **values;
963 
964  attinmeta = TupleDescGetAttInMetadata(tupdesc);
965 
966  /* Set GUCs to ensure we read GUC-sensitive data types correctly */
967  if (!is_sql_cmd)
968  nestlevel = applyRemoteGucs(conn);
969 
971  tupstore = tuplestore_begin_heap(true, false, work_mem);
972  rsinfo->setResult = tupstore;
973  rsinfo->setDesc = tupdesc;
974  MemoryContextSwitchTo(oldcontext);
975 
976  values = (char **) palloc(nfields * sizeof(char *));
977 
978  /* put all tuples into the tuplestore */
979  for (row = 0; row < ntuples; row++)
980  {
981  HeapTuple tuple;
982 
983  if (!is_sql_cmd)
984  {
985  int i;
986 
987  for (i = 0; i < nfields; i++)
988  {
989  if (PQgetisnull(res, row, i))
990  values[i] = NULL;
991  else
992  values[i] = PQgetvalue(res, row, i);
993  }
994  }
995  else
996  {
997  values[0] = PQcmdStatus(res);
998  }
999 
1000  /* build the tuple and put it into the tuplestore. */
1001  tuple = BuildTupleFromCStrings(attinmeta, values);
1002  tuplestore_puttuple(tupstore, tuple);
1003  }
1004 
1005  /* clean up GUC settings, if we changed any */
1006  restoreLocalGucs(nestlevel);
1007 
1008  /* clean up and return the tuplestore */
1009  tuplestore_donestoring(tupstore);
1010  }
1011  }
1012  PG_FINALLY();
1013  {
1014  /* be sure to release the libpq result */
1015  PQclear(res);
1016  }
1017  PG_END_TRY();
1018 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3175
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:207
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3561
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3167
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2146
#define ERROR
Definition: elog.h:46
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:580
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
#define PG_FINALLY()
Definition: elog.h:330
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3438
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
int work_mem
Definition: globals.c:124
#define ereport(elevel,...)
Definition: elog.h:157
void PQclear(PGresult *res)
Definition: fe-exec.c:680
SetFunctionReturnMode returnMode
Definition: execnodes.h:307
#define Assert(condition)
Definition: c.h:804
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:233
Tuplestorestate * setResult
Definition: execnodes.h:310
static Datum values[MAXATTR]
Definition: bootstrap.c:166
ExprContext * econtext
Definition: execnodes.h:303
TupleDesc setDesc
Definition: execnodes.h:311
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
int i
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3586
#define PG_TRY()
Definition: elog.h:313
int16 AttrNumber
Definition: attnum.h:21
#define PG_END_TRY()
Definition: elog.h:338

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 155 of file dblink.c.

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

157 {
158  char *msg = pchomp(PQerrorMessage(conn));
159 
160  if (res)
161  PQclear(res);
162  elog(ERROR, "%s: %s", p2, msg);
163 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
char * pchomp(const char *in)
Definition: mcxt.c:1327
#define ERROR
Definition: elog.h:46
PGconn * conn
Definition: streamutil.c:54
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define elog(elevel,...)
Definition: elog.h:232

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

860 {
861  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
862 
863  /* check to see if query supports us returning a tuplestore */
864  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
865  ereport(ERROR,
866  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
867  errmsg("set-valued function called in context that cannot accept a set")));
868  if (!(rsinfo->allowedModes & SFRM_Materialize))
869  ereport(ERROR,
870  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
871  errmsg("materialize mode required, but it is not allowed in this context")));
872 
873  /* let the executor know we're sending back a tuplestore */
874  rsinfo->returnMode = SFRM_Materialize;
875 
876  /* caller must fill these to return a non-empty result */
877  rsinfo->setResult = NULL;
878  rsinfo->setDesc = NULL;
879 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
fmNodePtr resultinfo
Definition: fmgr.h:89
#define ereport(elevel,...)
Definition: elog.h:157
int allowedModes
Definition: execnodes.h:305
SetFunctionReturnMode returnMode
Definition: execnodes.h:307
Tuplestorestate * setResult
Definition: execnodes.h:310
TupleDesc setDesc
Definition: execnodes.h:311
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ quote_ident_cstr()

static char * quote_ident_cstr ( char *  rawstr)
static

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

2398 {
2399  text *rawstr_text;
2400  text *result_text;
2401  char *result;
2402 
2403  rawstr_text = cstring_to_text(rawstr);
2405  PointerGetDatum(rawstr_text)));
2406  result = text_to_cstring(result_text);
2407 
2408  return result;
2409 }
#define PointerGetDatum(X)
Definition: postgres.h:600
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:24
text * cstring_to_text(const char *s)
Definition: varlena.c:190
char * text_to_cstring(const text *t)
Definition: varlena.c:223
Definition: c.h:621

◆ restoreLocalGucs()

static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3115 of file dblink.c.

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

3116 {
3117  /* Do nothing if no new nestlevel was created */
3118  if (nestlevel > 0)
3119  AtEOXact_GUC(true, nestlevel);
3120 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6234

◆ storeQueryResult()

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

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

1145 {
1146  bool first = true;
1147  int nestlevel = -1;
1148  PGresult *res;
1149 
1150  if (!PQsendQuery(conn, sql))
1151  elog(ERROR, "could not send query: %s", pchomp(PQerrorMessage(conn)));
1152 
1153  if (!PQsetSingleRowMode(conn)) /* shouldn't fail */
1154  elog(ERROR, "failed to set single-row mode for dblink query");
1155 
1156  for (;;)
1157  {
1159 
1160  sinfo->cur_res = PQgetResult(conn);
1161  if (!sinfo->cur_res)
1162  break;
1163 
1164  if (PQresultStatus(sinfo->cur_res) == PGRES_SINGLE_TUPLE)
1165  {
1166  /* got one row from possibly-bigger resultset */
1167 
1168  /*
1169  * Set GUCs to ensure we read GUC-sensitive data types correctly.
1170  * We shouldn't do this until we have a row in hand, to ensure
1171  * libpq has seen any earlier ParameterStatus protocol messages.
1172  */
1173  if (first && nestlevel < 0)
1174  nestlevel = applyRemoteGucs(conn);
1175 
1176  storeRow(sinfo, sinfo->cur_res, first);
1177 
1178  PQclear(sinfo->cur_res);
1179  sinfo->cur_res = NULL;
1180  first = false;
1181  }
1182  else
1183  {
1184  /* if empty resultset, fill tuplestore header */
1185  if (first && PQresultStatus(sinfo->cur_res) == PGRES_TUPLES_OK)
1186  storeRow(sinfo, sinfo->cur_res, first);
1187 
1188  /* store completed result at last_res */
1189  PQclear(sinfo->last_res);
1190  sinfo->last_res = sinfo->cur_res;
1191  sinfo->cur_res = NULL;
1192  first = true;
1193  }
1194  }
1195 
1196  /* clean up GUC settings, if we changed any */
1197  restoreLocalGucs(nestlevel);
1198 
1199  /* return last_res */
1200  res = sinfo->last_res;
1201  sinfo->last_res = NULL;
1202  return res;
1203 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6735
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3097
char * pchomp(const char *in)
Definition: mcxt.c:1327
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1279
#define ERROR
Definition: elog.h:46
int PQsetSingleRowMode(PGconn *conn)
Definition: fe-exec.c:1825
void PQclear(PGresult *res)
Definition: fe-exec.c:680
#define elog(elevel,...)
Definition: elog.h:232
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1927

◆ storeRow()

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

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

1213 {
1214  int nfields = PQnfields(res);
1215  HeapTuple tuple;
1216  int i;
1217  MemoryContext oldcontext;
1218 
1219  if (first)
1220  {
1221  /* Prepare for new result set */
1222  ReturnSetInfo *rsinfo = (ReturnSetInfo *) sinfo->fcinfo->resultinfo;
1223  TupleDesc tupdesc;
1224 
1225  /*
1226  * It's possible to get more than one result set if the query string
1227  * contained multiple SQL commands. In that case, we follow PQexec's
1228  * traditional behavior of throwing away all but the last result.
1229  */
1230  if (sinfo->tuplestore)
1231  tuplestore_end(sinfo->tuplestore);
1232  sinfo->tuplestore = NULL;
1233 
1234  /* get a tuple descriptor for our result type */
1235  switch (get_call_result_type(sinfo->fcinfo, NULL, &tupdesc))
1236  {
1237  case TYPEFUNC_COMPOSITE:
1238  /* success */
1239  break;
1240  case TYPEFUNC_RECORD:
1241  /* failed to determine actual type of RECORD */
1242  ereport(ERROR,
1243  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1244  errmsg("function returning record called in context "
1245  "that cannot accept type record")));
1246  break;
1247  default:
1248  /* result type isn't composite */
1249  elog(ERROR, "return type must be a row type");
1250  break;
1251  }
1252 
1253  /* make sure we have a persistent copy of the tupdesc */
1254  tupdesc = CreateTupleDescCopy(tupdesc);
1255 
1256  /* check result and tuple descriptor have the same number of columns */
1257  if (nfields != tupdesc->natts)
1258  ereport(ERROR,
1259  (errcode(ERRCODE_DATATYPE_MISMATCH),
1260  errmsg("remote query result rowtype does not match "
1261  "the specified FROM clause rowtype")));
1262 
1263  /* Prepare attinmeta for later data conversions */
1264  sinfo->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1265 
1266  /* Create a new, empty tuplestore */
1267  oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1268  sinfo->tuplestore = tuplestore_begin_heap(true, false, work_mem);
1269  rsinfo->setResult = sinfo->tuplestore;
1270  rsinfo->setDesc = tupdesc;
1271  MemoryContextSwitchTo(oldcontext);
1272 
1273  /* Done if empty resultset */
1274  if (PQntuples(res) == 0)
1275  return;
1276 
1277  /*
1278  * Set up sufficiently-wide string pointers array; this won't change
1279  * in size so it's easy to preallocate.
1280  */
1281  if (sinfo->cstrs)
1282  pfree(sinfo->cstrs);
1283  sinfo->cstrs = (char **) palloc(nfields * sizeof(char *));
1284  }
1285 
1286  /* Should have a single-row result if we get here */
1287  Assert(PQntuples(res) == 1);
1288 
1289  /*
1290  * Do the following work in a temp context that we reset after each tuple.
1291  * This cleans up not only the data we have direct access to, but any
1292  * cruft the I/O functions might leak.
1293  */
1294  oldcontext = MemoryContextSwitchTo(sinfo->tmpcontext);
1295 
1296  /*
1297  * Fill cstrs with null-terminated strings of column values.
1298  */
1299  for (i = 0; i < nfields; i++)
1300  {
1301  if (PQgetisnull(res, 0, i))
1302  sinfo->cstrs[i] = NULL;
1303  else
1304  sinfo->cstrs[i] = PQgetvalue(res, 0, i);
1305  }
1306 
1307  /* Convert row to a tuple, and add it to the tuplestore */
1308  tuple = BuildTupleFromCStrings(sinfo->attinmeta, sinfo->cstrs);
1309 
1310  tuplestore_puttuple(sinfo->tuplestore, tuple);
1311 
1312  /* Clean up */
1313  MemoryContextSwitchTo(oldcontext);
1314  MemoryContextReset(sinfo->tmpcontext);
1315 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3175
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:207
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3561
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3167
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2146
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
int work_mem
Definition: globals.c:124
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:233
Tuplestorestate * setResult
Definition: execnodes.h:310
ExprContext * econtext
Definition: execnodes.h:303
TupleDesc setDesc
Definition: execnodes.h:311
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
int i
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3586

◆ validate_pkattnums()

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

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

2944 {
2945  TupleDesc tupdesc = rel->rd_att;
2946  int natts = tupdesc->natts;
2947  int i;
2948 
2949  /* Don't take more array elements than there are */
2950  pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2951 
2952  /* Must have at least one pk attnum selected */
2953  if (pknumatts_arg <= 0)
2954  ereport(ERROR,
2955  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2956  errmsg("number of key attributes must be > 0")));
2957 
2958  /* Allocate output array */
2959  *pkattnums = (int *) palloc(pknumatts_arg * sizeof(int));
2960  *pknumatts = pknumatts_arg;
2961 
2962  /* Validate attnums and convert to internal form */
2963  for (i = 0; i < pknumatts_arg; i++)
2964  {
2965  int pkattnum = pkattnums_arg->values[i];
2966  int lnum;
2967  int j;
2968 
2969  /* Can throw error immediately if out of range */
2970  if (pkattnum <= 0 || pkattnum > natts)
2971  ereport(ERROR,
2972  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2973  errmsg("invalid attribute number %d", pkattnum)));
2974 
2975  /* Identify which physical column has this logical number */
2976  lnum = 0;
2977  for (j = 0; j < natts; j++)
2978  {
2979  /* dropped columns don't count */
2980  if (TupleDescAttr(tupdesc, j)->attisdropped)
2981  continue;
2982 
2983  if (++lnum == pkattnum)
2984  break;
2985  }
2986 
2987  if (j < natts)
2988  (*pkattnums)[i] = j;
2989  else
2990  ereport(ERROR,
2991  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2992  errmsg("invalid attribute number %d", pkattnum)));
2993  }
2994 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define Min(x, y)
Definition: c.h:986
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int dim1
Definition: c.h:655
TupleDesc rd_att
Definition: rel.h:111
#define ereport(elevel,...)
Definition: elog.h:157
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:657
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i

◆ xpstrdup()

static char* xpstrdup ( const char *  in)
static

Definition at line 147 of file dblink.c.

References pstrdup().

Referenced by dblink_res_error().

148 {
149  if (in == NULL)
150  return NULL;
151  return pstrdup(in);
152 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299

Variable Documentation

◆ pconn

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 63 of file dblink.c.

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static