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 "libpq/libpq-be.h"
#include "libpq/libpq-be-fe-helpers.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 "utils/wait_event.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 bool dblink_connstr_has_pw (const char *connstr)
 
static void dblink_security_check (PGconn *conn, remoteConn *rconn, const char *connstr)
 
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 *str)
 
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 () dblink_res_internalerror(PGconn *conn
 
 PQclear (res)
 
 elog (ERROR, "%s: %s", p2, msg)
 
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
 
static uint32 dblink_we_connect = 0
 
static uint32 dblink_we_get_conn = 0
 
static uint32 dblink_we_get_result = 0
 
static void PGresultres
 
static void PGresult const char * p2
 

Macro Definition Documentation

◆ DBLINK_NOTIFY_COLS

#define DBLINK_NOTIFY_COLS   3

Definition at line 1882 of file dblink.c.

◆ NUMCONN

#define NUMCONN   16

Definition at line 153 of file dblink.c.

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

3033 {
3034  static const char *const GUCsAffectingIO[] = {
3035  "DateStyle",
3036  "IntervalStyle"
3037  };
3038 
3039  int nestlevel = -1;
3040  int i;
3041 
3042  for (i = 0; i < lengthof(GUCsAffectingIO); i++)
3043  {
3044  const char *gucName = GUCsAffectingIO[i];
3045  const char *remoteVal = PQparameterStatus(conn, gucName);
3046  const char *localVal;
3047 
3048  /*
3049  * If the remote server is pre-8.4, it won't have IntervalStyle, but
3050  * that's okay because its output format won't be ambiguous. So just
3051  * skip the GUC if we don't get a value for it. (We might eventually
3052  * need more complicated logic with remote-version checks here.)
3053  */
3054  if (remoteVal == NULL)
3055  continue;
3056 
3057  /*
3058  * Avoid GUC-setting overhead if the remote and local GUCs already
3059  * have the same value.
3060  */
3061  localVal = GetConfigOption(gucName, false, false);
3062  Assert(localVal != NULL);
3063 
3064  if (strcmp(remoteVal, localVal) == 0)
3065  continue;
3066 
3067  /* Create new GUC nest level if we didn't already */
3068  if (nestlevel < 0)
3069  nestlevel = NewGUCNestLevel();
3070 
3071  /* Apply the option (this will throw error on failure) */
3072  (void) set_config_option(gucName, remoteVal,
3074  GUC_ACTION_SAVE, true, 0, false);
3075  }
3076 
3077  return nestlevel;
3078 }
#define Assert(condition)
Definition: c.h:812
#define lengthof(array)
Definition: c.h:742
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7155
int NewGUCNestLevel(void)
Definition: guc.c:2235
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4355
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:3342
@ GUC_ACTION_SAVE
Definition: guc.h:201
@ PGC_S_SESSION
Definition: guc.h:122
@ PGC_USERSET
Definition: guc.h:75
int i
Definition: isn.c:72
PGconn * conn
Definition: streamutil.c:53

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

Referenced by materializeResult(), and storeQueryResult().

◆ createConnHash()

static HTAB * createConnHash ( void  )
static

Definition at line 2541 of file dblink.c.

2542 {
2543  HASHCTL ctl;
2544 
2545  ctl.keysize = NAMEDATALEN;
2546  ctl.entrysize = sizeof(remoteConnHashEnt);
2547 
2548  return hash_create("Remote Con hash", NUMCONN, &ctl,
2550 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
#define HASH_STRINGS
Definition: hsearch.h:96
#define HASH_ELEM
Definition: hsearch.h:95
#define NAMEDATALEN
tree ctl
Definition: radixtree.h:1853

References ctl, hash_create(), HASH_ELEM, HASH_STRINGS, NAMEDATALEN, and NUMCONN.

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

◆ createNewConnection()

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

Definition at line 2553 of file dblink.c.

2554 {
2555  remoteConnHashEnt *hentry;
2556  bool found;
2557  char *key;
2558 
2559  if (!remoteConnHash)
2561 
2562  key = pstrdup(name);
2563  truncate_identifier(key, strlen(key), true);
2565  HASH_ENTER, &found);
2566 
2567  if (found)
2568  {
2569  libpqsrv_disconnect(rconn->conn);
2570  pfree(rconn);
2571 
2572  ereport(ERROR,
2574  errmsg("duplicate connection name")));
2575  }
2576 
2577  hentry->rconn = rconn;
2578 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
@ HASH_ENTER
Definition: hsearch.h:114
static void libpqsrv_disconnect(PGconn *conn)
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
remoteConn * rconn
Definition: dblink.c:149
PGconn * conn
Definition: dblink.c:70
const char * name

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

Referenced by dblink_connect().

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1713 of file dblink.c.

1714 {
1715  text *relname_text = PG_GETARG_TEXT_PP(0);
1716  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1717  int32 pknumatts_arg = PG_GETARG_INT32(2);
1718  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1719  Relation rel;
1720  int *pkattnums;
1721  int pknumatts;
1722  char **tgt_pkattvals;
1723  int tgt_nitems;
1724  char *sql;
1725 
1726  /*
1727  * Open target relation.
1728  */
1729  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1730 
1731  /*
1732  * Process pkattnums argument.
1733  */
1734  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1735  &pkattnums, &pknumatts);
1736 
1737  /*
1738  * Target array is made up of key values that will be used to build the
1739  * SQL string for use on the remote system.
1740  */
1741  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1742 
1743  /*
1744  * There should be one target array key value for each key attnum
1745  */
1746  if (tgt_nitems != pknumatts)
1747  ereport(ERROR,
1748  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1749  errmsg("target key array length must match number of key attributes")));
1750 
1751  /*
1752  * Prep work is finally done. Go get the SQL string.
1753  */
1754  sql = get_sql_delete(rel, pkattnums, pknumatts, tgt_pkattvals);
1755 
1756  /*
1757  * Now we can close the relation.
1758  */
1760 
1761  /*
1762  * And send it
1763  */
1765 }
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:263
int32_t int32
Definition: c.h:481
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define AccessShareLock
Definition: lockdefs.h:36
#define ACL_SELECT
Definition: parsenodes.h:77
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Definition: c.h:669
Definition: c.h:641
text * cstring_to_text(const char *s)
Definition: varlena.c:184

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

◆ dblink_build_sql_insert()

Datum dblink_build_sql_insert ( PG_FUNCTION_ARGS  )

Definition at line 1624 of file dblink.c.

1625 {
1626  text *relname_text = PG_GETARG_TEXT_PP(0);
1627  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1628  int32 pknumatts_arg = PG_GETARG_INT32(2);
1629  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1630  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1631  Relation rel;
1632  int *pkattnums;
1633  int pknumatts;
1634  char **src_pkattvals;
1635  char **tgt_pkattvals;
1636  int src_nitems;
1637  int tgt_nitems;
1638  char *sql;
1639 
1640  /*
1641  * Open target relation.
1642  */
1643  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1644 
1645  /*
1646  * Process pkattnums argument.
1647  */
1648  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1649  &pkattnums, &pknumatts);
1650 
1651  /*
1652  * Source array is made up of key values that will be used to locate the
1653  * tuple of interest from the local system.
1654  */
1655  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1656 
1657  /*
1658  * There should be one source array key value for each key attnum
1659  */
1660  if (src_nitems != pknumatts)
1661  ereport(ERROR,
1662  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1663  errmsg("source key array length must match number of key attributes")));
1664 
1665  /*
1666  * Target array is made up of key values that will be used to build the
1667  * SQL string for use on the remote system.
1668  */
1669  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1670 
1671  /*
1672  * There should be one target array key value for each key attnum
1673  */
1674  if (tgt_nitems != pknumatts)
1675  ereport(ERROR,
1676  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1677  errmsg("target key array length must match number of key attributes")));
1678 
1679  /*
1680  * Prep work is finally done. Go get the SQL string.
1681  */
1682  sql = get_sql_insert(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1683 
1684  /*
1685  * Now we can close the relation.
1686  */
1688 
1689  /*
1690  * And send it
1691  */
1693 }

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

◆ dblink_build_sql_update()

Datum dblink_build_sql_update ( PG_FUNCTION_ARGS  )

Definition at line 1789 of file dblink.c.

1790 {
1791  text *relname_text = PG_GETARG_TEXT_PP(0);
1792  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1793  int32 pknumatts_arg = PG_GETARG_INT32(2);
1794  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1795  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1796  Relation rel;
1797  int *pkattnums;
1798  int pknumatts;
1799  char **src_pkattvals;
1800  char **tgt_pkattvals;
1801  int src_nitems;
1802  int tgt_nitems;
1803  char *sql;
1804 
1805  /*
1806  * Open target relation.
1807  */
1808  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1809 
1810  /*
1811  * Process pkattnums argument.
1812  */
1813  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1814  &pkattnums, &pknumatts);
1815 
1816  /*
1817  * Source array is made up of key values that will be used to locate the
1818  * tuple of interest from the local system.
1819  */
1820  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1821 
1822  /*
1823  * There should be one source array key value for each key attnum
1824  */
1825  if (src_nitems != pknumatts)
1826  ereport(ERROR,
1827  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1828  errmsg("source key array length must match number of key attributes")));
1829 
1830  /*
1831  * Target array is made up of key values that will be used to build the
1832  * SQL string for use on the remote system.
1833  */
1834  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1835 
1836  /*
1837  * There should be one target array key value for each key attnum
1838  */
1839  if (tgt_nitems != pknumatts)
1840  ereport(ERROR,
1841  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1842  errmsg("target key array length must match number of key attributes")));
1843 
1844  /*
1845  * Prep work is finally done. Go get the SQL string.
1846  */
1847  sql = get_sql_update(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1848 
1849  /*
1850  * Now we can close the relation.
1851  */
1853 
1854  /*
1855  * And send it
1856  */
1858 }

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

◆ dblink_cancel_query()

Datum dblink_cancel_query ( PG_FUNCTION_ARGS  )

Definition at line 1347 of file dblink.c.

1348 {
1349  PGconn *conn;
1350  const char *msg;
1351  TimestampTz endtime;
1352 
1353  dblink_init();
1356  30000);
1357  msg = libpqsrv_cancel(conn, endtime);
1358  if (msg == NULL)
1359  msg = "OK";
1360 
1362 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
int64 TimestampTz
Definition: timestamp.h:39
static const char * libpqsrv_cancel(PGconn *conn, TimestampTz endtime)
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
char * text_to_cstring(const text *t)
Definition: varlena.c:217

References conn, cstring_to_text(), dblink_get_named_conn(), dblink_init(), GetCurrentTimestamp(), libpqsrv_cancel(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, text_to_cstring(), and TimestampTzPlusMilliseconds.

◆ dblink_close()

Datum dblink_close ( PG_FUNCTION_ARGS  )

Definition at line 486 of file dblink.c.

487 {
488  PGconn *conn;
489  PGresult *res = NULL;
490  char *curname = NULL;
491  char *conname = NULL;
493  remoteConn *rconn = NULL;
494  bool fail = true; /* default to backward compatible behavior */
495 
496  dblink_init();
498 
499  if (PG_NARGS() == 1)
500  {
501  /* text */
502  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
503  rconn = pconn;
504  }
505  else if (PG_NARGS() == 2)
506  {
507  /* might be text,text or text,bool */
508  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
509  {
510  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
511  fail = PG_GETARG_BOOL(1);
512  rconn = pconn;
513  }
514  else
515  {
516  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
517  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
518  rconn = getConnectionByName(conname);
519  }
520  }
521  if (PG_NARGS() == 3)
522  {
523  /* text,text,bool */
524  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
525  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
526  fail = PG_GETARG_BOOL(2);
527  rconn = getConnectionByName(conname);
528  }
529 
530  if (!rconn || !rconn->conn)
531  dblink_conn_not_avail(conname);
532 
533  conn = rconn->conn;
534 
535  appendStringInfo(&buf, "CLOSE %s", curname);
536 
537  /* close the cursor */
540  {
541  dblink_res_error(conn, conname, res, fail,
542  "while closing cursor \"%s\"", curname);
544  }
545 
546  PQclear(res);
547 
548  /* if we started a transaction, decrement cursor count */
549  if (rconn->newXactForCursor)
550  {
551  (rconn->openCursorCount)--;
552 
553  /* if count is zero, commit the transaction */
554  if (rconn->openCursorCount == 0)
555  {
556  rconn->newXactForCursor = false;
557 
560  dblink_res_internalerror(conn, res, "commit error");
561  PQclear(res);
562  }
563  }
564 
566 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1910
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
static PGresult * libpqsrv_exec(PGconn *conn, const char *query, uint32 wait_event_info)
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:120
static char * buf
Definition: pg_test_fsync.c:72
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:94
void initStringInfo(StringInfo str)
Definition: stringinfo.c:56
bool newXactForCursor
Definition: dblink.c:72
int openCursorCount
Definition: dblink.c:71

References appendStringInfo(), buf, remoteConn::conn, conn, cstring_to_text(), dblink_init(), dblink_res_error(), dblink_we_get_result, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), libpqsrv_exec(), remoteConn::newXactForCursor, remoteConn::openCursorCount, pconn, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PGRES_COMMAND_OK, PQclear(), PQresultStatus(), res, and text_to_cstring().

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 272 of file dblink.c.

273 {
274  char *conname_or_str = NULL;
275  char *connstr = NULL;
276  char *connname = NULL;
277  char *msg;
278  PGconn *conn = NULL;
279  remoteConn *rconn = NULL;
280 
281  dblink_init();
282 
283  if (PG_NARGS() == 2)
284  {
285  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
286  connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
287  }
288  else if (PG_NARGS() == 1)
289  conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
290 
291  if (connname)
292  {
294  sizeof(remoteConn));
295  rconn->conn = NULL;
296  rconn->openCursorCount = 0;
297  rconn->newXactForCursor = false;
298  }
299 
300  /* first check for valid foreign data server */
301  connstr = get_connect_string(conname_or_str);
302  if (connstr == NULL)
303  connstr = conname_or_str;
304 
305  /* check password in connection string if not superuser */
307 
308  /* first time, allocate or get the custom wait event */
309  if (dblink_we_connect == 0)
310  dblink_we_connect = WaitEventExtensionNew("DblinkConnect");
311 
312  /* OK to make connection */
314 
315  if (PQstatus(conn) == CONNECTION_BAD)
316  {
317  msg = pchomp(PQerrorMessage(conn));
319  if (rconn)
320  pfree(rconn);
321 
322  ereport(ERROR,
323  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
324  errmsg("could not establish connection"),
325  errdetail_internal("%s", msg)));
326  }
327 
328  /* check password actually used if not superuser */
330 
331  /* attempt to set client encoding to match server encoding, if needed */
334 
335  if (connname)
336  {
337  rconn->conn = conn;
338  createNewConnection(connname, rconn);
339  }
340  else
341  {
342  if (pconn->conn)
344  pconn->conn = conn;
345  }
346 
348 }
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7200
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7137
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7288
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7296
static PGconn * libpqsrv_connect(const char *conninfo, uint32 wait_event_info)
@ CONNECTION_BAD
Definition: libpq-fe.h:82
int GetDatabaseEncoding(void)
Definition: mbutils.c:1261
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1267
char * pchomp(const char *in)
Definition: mcxt.c:1724
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1181
static char * connstr
Definition: pg_dumpall.c:88
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition: wait_event.c:163

References remoteConn::conn, conn, CONNECTION_BAD, connstr, createNewConnection(), cstring_to_text(), dblink_connstr_check(), dblink_init(), dblink_security_check(), dblink_we_connect, ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_connect_string(), GetDatabaseEncoding(), GetDatabaseEncodingName(), libpqsrv_connect(), libpqsrv_disconnect(), MemoryContextAlloc(), remoteConn::newXactForCursor, remoteConn::openCursorCount, pchomp(), pconn, pfree(), PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PQclientEncoding(), PQerrorMessage(), PQsetClientEncoding(), PQstatus(), text_to_cstring(), TopMemoryContext, and WaitEventExtensionNew().

◆ dblink_connstr_check()

static void dblink_connstr_check ( const char *  connstr)
static

Definition at line 2677 of file dblink.c.

2678 {
2679  if (superuser())
2680  return;
2681 
2683  return;
2684 
2685 #ifdef ENABLE_GSS
2687  return;
2688 #endif
2689 
2690  ereport(ERROR,
2691  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2692  errmsg("password or GSSAPI delegated credentials required"),
2693  errdetail("Non-superusers must provide a password in the connection string or send delegated GSSAPI credentials.")));
2694 }
bool be_gssapi_get_delegation(Port *port)
int errdetail(const char *fmt,...)
Definition: elog.c:1203
struct Port * MyProcPort
Definition: globals.c:50
bool superuser(void)
Definition: superuser.c:46

References be_gssapi_get_delegation(), connstr, dblink_connstr_has_pw(), ereport, errcode(), errdetail(), errmsg(), ERROR, MyProcPort, and superuser().

Referenced by dblink_connect(), and dblink_get_conn().

◆ dblink_connstr_has_pw()

static bool dblink_connstr_has_pw ( const char *  connstr)
static

Definition at line 2642 of file dblink.c.

2643 {
2646  bool connstr_gives_password = false;
2647 
2648  options = PQconninfoParse(connstr, NULL);
2649  if (options)
2650  {
2651  for (option = options; option->keyword != NULL; option++)
2652  {
2653  if (strcmp(option->keyword, "password") == 0)
2654  {
2655  if (option->val != NULL && option->val[0] != '\0')
2656  {
2657  connstr_gives_password = true;
2658  break;
2659  }
2660  }
2661  }
2663  }
2664 
2665  return connstr_gives_password;
2666 }
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5739
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7023
static char ** options
int val
Definition: getopt_long.h:21

References connstr, options, PQconninfoFree(), PQconninfoParse(), and option::val.

Referenced by dblink_connstr_check(), and dblink_security_check().

◆ dblink_current_query()

Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1868 of file dblink.c.

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

References current_query(), and PG_RETURN_DATUM.

◆ dblink_disconnect()

Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 355 of file dblink.c.

356 {
357  char *conname = NULL;
358  remoteConn *rconn = NULL;
359  PGconn *conn = NULL;
360 
361  dblink_init();
362 
363  if (PG_NARGS() == 1)
364  {
365  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
366  rconn = getConnectionByName(conname);
367  if (rconn)
368  conn = rconn->conn;
369  }
370  else
371  conn = pconn->conn;
372 
373  if (!conn)
374  dblink_conn_not_avail(conname);
375 
377  if (rconn)
378  {
379  deleteConnection(conname);
380  pfree(rconn);
381  }
382  else
383  pconn->conn = NULL;
384 
386 }

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

◆ dblink_error_message()

Datum dblink_error_message ( PG_FUNCTION_ARGS  )

Definition at line 1377 of file dblink.c.

1378 {
1379  char *msg;
1380  PGconn *conn;
1381 
1382  dblink_init();
1384 
1385  msg = PQerrorMessage(conn);
1386  if (msg == NULL || msg[0] == '\0')
1388  else
1390 }

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

◆ dblink_exec()

Datum dblink_exec ( PG_FUNCTION_ARGS  )

Definition at line 1397 of file dblink.c.

1398 {
1399  text *volatile sql_cmd_status = NULL;
1400  PGconn *volatile conn = NULL;
1401  volatile bool freeconn = false;
1402 
1403  dblink_init();
1404 
1405  PG_TRY();
1406  {
1407  PGresult *res = NULL;
1408  char *sql = NULL;
1409  char *conname = NULL;
1410  bool fail = true; /* default to backward compatible behavior */
1411 
1412  if (PG_NARGS() == 3)
1413  {
1414  /* must be text,text,bool */
1415  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1417  fail = PG_GETARG_BOOL(2);
1418  dblink_get_conn(conname, &conn, &conname, &freeconn);
1419  }
1420  else if (PG_NARGS() == 2)
1421  {
1422  /* might be text,text or text,bool */
1423  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1424  {
1426  fail = PG_GETARG_BOOL(1);
1427  conn = pconn->conn;
1428  }
1429  else
1430  {
1431  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1433  dblink_get_conn(conname, &conn, &conname, &freeconn);
1434  }
1435  }
1436  else if (PG_NARGS() == 1)
1437  {
1438  /* must be single text argument */
1439  conn = pconn->conn;
1441  }
1442  else
1443  /* shouldn't happen */
1444  elog(ERROR, "wrong number of arguments");
1445 
1446  if (!conn)
1447  dblink_conn_not_avail(conname);
1448 
1450  if (!res ||
1453  {
1454  dblink_res_error(conn, conname, res, fail,
1455  "while executing command");
1456 
1457  /*
1458  * and save a copy of the command status string to return as our
1459  * result tuple
1460  */
1461  sql_cmd_status = cstring_to_text("ERROR");
1462  }
1463  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1464  {
1465  /*
1466  * and save a copy of the command status string to return as our
1467  * result tuple
1468  */
1469  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1470  PQclear(res);
1471  }
1472  else
1473  {
1474  PQclear(res);
1475  ereport(ERROR,
1476  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1477  errmsg("statement returning results not allowed")));
1478  }
1479  }
1480  PG_FINALLY();
1481  {
1482  /* if needed, close the connection to the database */
1483  if (freeconn)
1485  }
1486  PG_END_TRY();
1487 
1488  PG_RETURN_TEXT_P(sql_cmd_status);
1489 }
#define PG_TRY(...)
Definition: elog.h:371
#define PG_END_TRY(...)
Definition: elog.h:396
#define PG_FINALLY(...)
Definition: elog.h:388
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3752
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:123

References remoteConn::conn, conn, cstring_to_text(), dblink_get_conn(), dblink_init(), dblink_res_error(), dblink_we_get_result, elog(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), libpqsrv_disconnect(), libpqsrv_exec(), pconn, PG_END_TRY, PG_FINALLY, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQresultStatus(), res, and text_to_cstring().

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 1939 of file dblink.c.

1940 {
1941  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
1942  Oid context = PG_GETARG_OID(1);
1943  ListCell *cell;
1944 
1945  static const PQconninfoOption *options = NULL;
1946 
1947  /*
1948  * Get list of valid libpq options.
1949  *
1950  * To avoid unnecessary work, we get the list once and use it throughout
1951  * the lifetime of this backend process. We don't need to care about
1952  * memory context issues, because PQconndefaults allocates with malloc.
1953  */
1954  if (!options)
1955  {
1956  options = PQconndefaults();
1957  if (!options) /* assume reason for failure is OOM */
1958  ereport(ERROR,
1959  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
1960  errmsg("out of memory"),
1961  errdetail("Could not get libpq's default connection options.")));
1962  }
1963 
1964  /* Validate each supplied option. */
1965  foreach(cell, options_list)
1966  {
1967  DefElem *def = (DefElem *) lfirst(cell);
1968 
1970  {
1971  /*
1972  * Unknown option, or invalid option for the context specified, so
1973  * complain about it. Provide a hint with a valid option that
1974  * looks similar, if there is one.
1975  */
1976  const PQconninfoOption *opt;
1977  const char *closest_match;
1979  bool has_valid_options = false;
1980 
1982  for (opt = options; opt->keyword; opt++)
1983  {
1985  {
1986  has_valid_options = true;
1988  }
1989  }
1990 
1991  closest_match = getClosestMatch(&match_state);
1992  ereport(ERROR,
1993  (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
1994  errmsg("invalid option \"%s\"", def->defname),
1995  has_valid_options ? closest_match ?
1996  errhint("Perhaps you meant the option \"%s\".",
1997  closest_match) : 0 :
1998  errhint("There are no valid options in this context.")));
1999  }
2000  }
2001 
2002  PG_RETURN_VOID();
2003 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1882
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
struct parser_state match_state[5]
#define lfirst(lc)
Definition: pg_list.h:172
unsigned int Oid
Definition: postgres_ext.h:31
tree context
Definition: radixtree.h:1835
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1331
char * defname
Definition: parsenodes.h:817
Definition: pg_list.h:54
const char * getClosestMatch(ClosestMatchState *state)
Definition: varlena.c:6256
void initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
Definition: varlena.c:6201
void updateClosestMatch(ClosestMatchState *state, const char *candidate)
Definition: varlena.c:6221

References context, DefElem::defname, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, getClosestMatch(), initClosestMatch(), is_valid_dblink_option(), _PQconninfoOption::keyword, lfirst, match_state, PG_GETARG_DATUM, PG_GETARG_OID, PG_RETURN_VOID, PQconndefaults(), untransformRelOptions(), and updateClosestMatch().

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

Definition at line 573 of file dblink.c.

574 {
575  PGresult *res = NULL;
576  char *conname = NULL;
577  remoteConn *rconn = NULL;
578  PGconn *conn = NULL;
580  char *curname = NULL;
581  int howmany = 0;
582  bool fail = true; /* default to backward compatible */
583 
584  prepTuplestoreResult(fcinfo);
585 
586  dblink_init();
587 
588  if (PG_NARGS() == 4)
589  {
590  /* text,text,int,bool */
591  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
592  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
593  howmany = PG_GETARG_INT32(2);
594  fail = PG_GETARG_BOOL(3);
595 
596  rconn = getConnectionByName(conname);
597  if (rconn)
598  conn = rconn->conn;
599  }
600  else if (PG_NARGS() == 3)
601  {
602  /* text,text,int or text,int,bool */
603  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
604  {
605  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
606  howmany = PG_GETARG_INT32(1);
607  fail = PG_GETARG_BOOL(2);
608  conn = pconn->conn;
609  }
610  else
611  {
612  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
613  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
614  howmany = PG_GETARG_INT32(2);
615 
616  rconn = getConnectionByName(conname);
617  if (rconn)
618  conn = rconn->conn;
619  }
620  }
621  else if (PG_NARGS() == 2)
622  {
623  /* text,int */
624  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
625  howmany = PG_GETARG_INT32(1);
626  conn = pconn->conn;
627  }
628 
629  if (!conn)
630  dblink_conn_not_avail(conname);
631 
633  appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
634 
635  /*
636  * Try to execute the query. Note that since libpq uses malloc, the
637  * PGresult will be long-lived even though we are still in a short-lived
638  * memory context.
639  */
641  if (!res ||
644  {
645  dblink_res_error(conn, conname, res, fail,
646  "while fetching from cursor \"%s\"", curname);
647  return (Datum) 0;
648  }
649  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
650  {
651  /* cursor does not exist - closed already or bad name */
652  PQclear(res);
653  ereport(ERROR,
654  (errcode(ERRCODE_INVALID_CURSOR_NAME),
655  errmsg("cursor \"%s\" does not exist", curname)));
656  }
657 
658  materializeResult(fcinfo, conn, res);
659  return (Datum) 0;
660 }
uintptr_t Datum
Definition: postgres.h:64

References appendStringInfo(), buf, remoteConn::conn, conn, dblink_init(), dblink_res_error(), dblink_we_get_result, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), libpqsrv_exec(), materializeResult(), pconn, PG_GETARG_BOOL, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_NARGS, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQresultStatus(), prepTuplestoreResult(), res, and text_to_cstring().

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

190 {
191  remoteConn *rconn = getConnectionByName(conname_or_str);
192  PGconn *conn;
193  char *conname;
194  bool freeconn;
195 
196  if (rconn)
197  {
198  conn = rconn->conn;
199  conname = conname_or_str;
200  freeconn = false;
201  }
202  else
203  {
204  const char *connstr;
205 
206  connstr = get_connect_string(conname_or_str);
207  if (connstr == NULL)
208  connstr = conname_or_str;
210 
211  /* first time, allocate or get the custom wait event */
212  if (dblink_we_get_conn == 0)
213  dblink_we_get_conn = WaitEventExtensionNew("DblinkGetConnect");
214 
215  /* OK to make connection */
217 
218  if (PQstatus(conn) == CONNECTION_BAD)
219  {
220  char *msg = pchomp(PQerrorMessage(conn));
221 
223  ereport(ERROR,
224  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
225  errmsg("could not establish connection"),
226  errdetail_internal("%s", msg)));
227  }
231  freeconn = true;
232  conname = NULL;
233  }
234 
235  *conn_p = conn;
236  *conname_p = conname;
237  *freeconn_p = freeconn;
238 }

References remoteConn::conn, conn, CONNECTION_BAD, connstr, dblink_connstr_check(), dblink_security_check(), dblink_we_get_conn, ereport, errcode(), errdetail_internal(), errmsg(), ERROR, get_connect_string(), getConnectionByName(), GetDatabaseEncoding(), GetDatabaseEncodingName(), libpqsrv_connect(), libpqsrv_disconnect(), pchomp(), PQclientEncoding(), PQerrorMessage(), PQsetClientEncoding(), PQstatus(), and WaitEventExtensionNew().

Referenced by dblink_exec(), and dblink_record_internal().

◆ dblink_get_connections()

Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1288 of file dblink.c.

1289 {
1290  HASH_SEQ_STATUS status;
1291  remoteConnHashEnt *hentry;
1292  ArrayBuildState *astate = NULL;
1293 
1294  if (remoteConnHash)
1295  {
1296  hash_seq_init(&status, remoteConnHash);
1297  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1298  {
1299  /* stash away current value */
1300  astate = accumArrayResult(astate,
1301  CStringGetTextDatum(hentry->name),
1302  false, TEXTOID, CurrentMemoryContext);
1303  }
1304  }
1305 
1306  if (astate)
1309  else
1310  PG_RETURN_NULL();
1311 }
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5350
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5420
#define CStringGetTextDatum(s)
Definition: builtins.h:97
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1420
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
#define PG_RETURN_NULL()
Definition: fmgr.h:345
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
char name[NAMEDATALEN]
Definition: dblink.c:148

References accumArrayResult(), CStringGetTextDatum, CurrentMemoryContext, hash_seq_init(), hash_seq_search(), makeArrayResult(), remoteConnHashEnt::name, PG_RETURN_DATUM, PG_RETURN_NULL, and remoteConnHash.

◆ dblink_get_named_conn()

static PGconn* dblink_get_named_conn ( const char *  conname)
static

Definition at line 241 of file dblink.c.

242 {
243  remoteConn *rconn = getConnectionByName(conname);
244 
245  if (rconn)
246  return rconn->conn;
247 
248  dblink_conn_not_avail(conname);
249  return NULL; /* keep compiler quiet */
250 }

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

◆ dblink_get_notify()

Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

Definition at line 1886 of file dblink.c.

1887 {
1888  PGconn *conn;
1889  PGnotify *notify;
1890  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1891 
1892  dblink_init();
1893  if (PG_NARGS() == 1)
1895  else
1896  conn = pconn->conn;
1897 
1898  InitMaterializedSRF(fcinfo, 0);
1899 
1901  while ((notify = PQnotifies(conn)) != NULL)
1902  {
1904  bool nulls[DBLINK_NOTIFY_COLS];
1905 
1906  memset(values, 0, sizeof(values));
1907  memset(nulls, 0, sizeof(nulls));
1908 
1909  if (notify->relname != NULL)
1910  values[0] = CStringGetTextDatum(notify->relname);
1911  else
1912  nulls[0] = true;
1913 
1914  values[1] = Int32GetDatum(notify->be_pid);
1915 
1916  if (notify->extra != NULL)
1917  values[2] = CStringGetTextDatum(notify->extra);
1918  else
1919  nulls[2] = true;
1920 
1921  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1922 
1923  PQfreemem(notify);
1925  }
1926 
1927  return (Datum) 0;
1928 }
static Datum values[MAXATTR]
Definition: bootstrap.c:151
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2667
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1984
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
TupleDesc setDesc
Definition: execnodes.h:343
Tuplestorestate * setResult
Definition: execnodes.h:342
int be_pid
Definition: libpq-fe.h:219
char * relname
Definition: libpq-fe.h:218
char * extra
Definition: libpq-fe.h:220
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784

References pgNotify::be_pid, remoteConn::conn, conn, CStringGetTextDatum, dblink_get_named_conn(), dblink_init(), DBLINK_NOTIFY_COLS, pgNotify::extra, InitMaterializedSRF(), Int32GetDatum(), pconn, PG_GETARG_TEXT_PP, PG_NARGS, PQconsumeInput(), PQfreemem(), PQnotifies(), pgNotify::relname, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, text_to_cstring(), tuplestore_putvalues(), and values.

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1500 of file dblink.c.

1501 {
1502  int16 indnkeyatts;
1503  char **results;
1504  FuncCallContext *funcctx;
1505  int32 call_cntr;
1506  int32 max_calls;
1507  AttInMetadata *attinmeta;
1508  MemoryContext oldcontext;
1509 
1510  /* stuff done only on the first call of the function */
1511  if (SRF_IS_FIRSTCALL())
1512  {
1513  Relation rel;
1514  TupleDesc tupdesc;
1515 
1516  /* create a function context for cross-call persistence */
1517  funcctx = SRF_FIRSTCALL_INIT();
1518 
1519  /*
1520  * switch to memory context appropriate for multiple function calls
1521  */
1522  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1523 
1524  /* open target relation */
1526 
1527  /* get the array of attnums */
1528  results = get_pkey_attnames(rel, &indnkeyatts);
1529 
1531 
1532  /*
1533  * need a tuple descriptor representing one INT and one TEXT column
1534  */
1535  tupdesc = CreateTemplateTupleDesc(2);
1536  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
1537  INT4OID, -1, 0);
1538  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
1539  TEXTOID, -1, 0);
1540 
1541  /*
1542  * Generate attribute metadata needed later to produce tuples from raw
1543  * C strings
1544  */
1545  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1546  funcctx->attinmeta = attinmeta;
1547 
1548  if ((results != NULL) && (indnkeyatts > 0))
1549  {
1550  funcctx->max_calls = indnkeyatts;
1551 
1552  /* got results, keep track of them */
1553  funcctx->user_fctx = results;
1554  }
1555  else
1556  {
1557  /* fast track when no results */
1558  MemoryContextSwitchTo(oldcontext);
1559  SRF_RETURN_DONE(funcctx);
1560  }
1561 
1562  MemoryContextSwitchTo(oldcontext);
1563  }
1564 
1565  /* stuff done on every call of the function */
1566  funcctx = SRF_PERCALL_SETUP();
1567 
1568  /*
1569  * initialize per-call variables
1570  */
1571  call_cntr = funcctx->call_cntr;
1572  max_calls = funcctx->max_calls;
1573 
1574  results = (char **) funcctx->user_fctx;
1575  attinmeta = funcctx->attinmeta;
1576 
1577  if (call_cntr < max_calls) /* do when there is more left to send */
1578  {
1579  char **values;
1580  HeapTuple tuple;
1581  Datum result;
1582 
1583  values = palloc_array(char *, 2);
1584  values[0] = psprintf("%d", call_cntr + 1);
1585  values[1] = results[call_cntr];
1586 
1587  /* build the tuple */
1588  tuple = BuildTupleFromCStrings(attinmeta, values);
1589 
1590  /* make the tuple into a datum */
1591  result = HeapTupleGetDatum(tuple);
1592 
1593  SRF_RETURN_NEXT(funcctx, result);
1594  }
1595  else
1596  {
1597  /* do when there is no more left */
1598  SRF_RETURN_DONE(funcctx);
1599  }
1600 }
int16 AttrNumber
Definition: attnum.h:21
int16_t int16
Definition: c.h:480
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2222
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2173
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
MemoryContextSwitchTo(old_ctx)
void * user_fctx
Definition: funcapi.h:82
uint64 max_calls
Definition: funcapi.h:74
uint64 call_cntr
Definition: funcapi.h:65
AttInMetadata * attinmeta
Definition: funcapi.h:91
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:67
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:651

References AccessShareLock, ACL_SELECT, FuncCallContext::attinmeta, BuildTupleFromCStrings(), FuncCallContext::call_cntr, CreateTemplateTupleDesc(), get_pkey_attnames(), get_rel_from_relname(), HeapTupleGetDatum(), if(), FuncCallContext::max_calls, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, palloc_array, 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.

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 699 of file dblink.c.

700 {
701  return dblink_record_internal(fcinfo, true);
702 }

References dblink_record_internal().

◆ dblink_init()

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1323 of file dblink.c.

1324 {
1325  PGconn *conn;
1326 
1327  dblink_init();
1329 
1332 }
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354

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

◆ dblink_open()

Datum dblink_open ( PG_FUNCTION_ARGS  )

Definition at line 393 of file dblink.c.

394 {
395  PGresult *res = NULL;
396  PGconn *conn;
397  char *curname = NULL;
398  char *sql = NULL;
399  char *conname = NULL;
401  remoteConn *rconn = NULL;
402  bool fail = true; /* default to backward compatible behavior */
403 
404  dblink_init();
406 
407  if (PG_NARGS() == 2)
408  {
409  /* text,text */
410  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
412  rconn = pconn;
413  }
414  else if (PG_NARGS() == 3)
415  {
416  /* might be text,text,text or text,text,bool */
417  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
418  {
419  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
421  fail = PG_GETARG_BOOL(2);
422  rconn = pconn;
423  }
424  else
425  {
426  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
427  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
429  rconn = getConnectionByName(conname);
430  }
431  }
432  else if (PG_NARGS() == 4)
433  {
434  /* text,text,text,bool */
435  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
436  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
438  fail = PG_GETARG_BOOL(3);
439  rconn = getConnectionByName(conname);
440  }
441 
442  if (!rconn || !rconn->conn)
443  dblink_conn_not_avail(conname);
444 
445  conn = rconn->conn;
446 
447  /* If we are not in a transaction, start one */
449  {
452  dblink_res_internalerror(conn, res, "begin error");
453  PQclear(res);
454  rconn->newXactForCursor = true;
455 
456  /*
457  * Since transaction state was IDLE, we force cursor count to
458  * initially be 0. This is needed as a previous ABORT might have wiped
459  * out our transaction without maintaining the cursor count for us.
460  */
461  rconn->openCursorCount = 0;
462  }
463 
464  /* if we started a transaction, increment cursor count */
465  if (rconn->newXactForCursor)
466  (rconn->openCursorCount)++;
467 
468  appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
471  {
472  dblink_res_error(conn, conname, res, fail,
473  "while opening cursor \"%s\"", curname);
475  }
476 
477  PQclear(res);
479 }
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7145
@ PQTRANS_IDLE
Definition: libpq-fe.h:142

References appendStringInfo(), buf, remoteConn::conn, conn, cstring_to_text(), dblink_init(), dblink_res_error(), dblink_we_get_result, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), libpqsrv_exec(), remoteConn::newXactForCursor, remoteConn::openCursorCount, pconn, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_TEXT_P, PGRES_COMMAND_OK, PQclear(), PQresultStatus(), PQTRANS_IDLE, PQtransactionStatus(), res, and text_to_cstring().

◆ dblink_record()

Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 667 of file dblink.c.

668 {
669  return dblink_record_internal(fcinfo, false);
670 }

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 705 of file dblink.c.

706 {
707  PGconn *volatile conn = NULL;
708  volatile bool freeconn = false;
709 
710  prepTuplestoreResult(fcinfo);
711 
712  dblink_init();
713 
714  PG_TRY();
715  {
716  char *sql = NULL;
717  char *conname = NULL;
718  bool fail = true; /* default to backward compatible */
719 
720  if (!is_async)
721  {
722  if (PG_NARGS() == 3)
723  {
724  /* text,text,bool */
725  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
727  fail = PG_GETARG_BOOL(2);
728  dblink_get_conn(conname, &conn, &conname, &freeconn);
729  }
730  else if (PG_NARGS() == 2)
731  {
732  /* text,text or text,bool */
733  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
734  {
736  fail = PG_GETARG_BOOL(1);
737  conn = pconn->conn;
738  }
739  else
740  {
741  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
743  dblink_get_conn(conname, &conn, &conname, &freeconn);
744  }
745  }
746  else if (PG_NARGS() == 1)
747  {
748  /* text */
749  conn = pconn->conn;
751  }
752  else
753  /* shouldn't happen */
754  elog(ERROR, "wrong number of arguments");
755  }
756  else /* is_async */
757  {
758  /* get async result */
759  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
760 
761  if (PG_NARGS() == 2)
762  {
763  /* text,bool */
764  fail = PG_GETARG_BOOL(1);
765  conn = dblink_get_named_conn(conname);
766  }
767  else if (PG_NARGS() == 1)
768  {
769  /* text */
770  conn = dblink_get_named_conn(conname);
771  }
772  else
773  /* shouldn't happen */
774  elog(ERROR, "wrong number of arguments");
775  }
776 
777  if (!conn)
778  dblink_conn_not_avail(conname);
779 
780  if (!is_async)
781  {
782  /* synchronous query, use efficient tuple collection method */
783  materializeQueryResult(fcinfo, conn, conname, sql, fail);
784  }
785  else
786  {
787  /* async result retrieval, do it the old way */
789 
790  /* NULL means we're all done with the async results */
791  if (res)
792  {
795  {
796  dblink_res_error(conn, conname, res, fail,
797  "while executing query");
798  /* if fail isn't set, we'll return an empty query result */
799  }
800  else
801  {
802  materializeResult(fcinfo, conn, res);
803  }
804  }
805  }
806  }
807  PG_FINALLY();
808  {
809  /* if needed, close the connection to the database */
810  if (freeconn)
812  }
813  PG_END_TRY();
814 
815  return (Datum) 0;
816 }
static PGresult * libpqsrv_get_result(PGconn *conn, uint32 wait_event_info)
FmgrInfo * flinfo
Definition: fmgr.h:87

References remoteConn::conn, conn, dblink_get_conn(), dblink_get_named_conn(), dblink_init(), dblink_res_error(), dblink_we_get_result, elog(), ERROR, FunctionCallInfoBaseData::flinfo, get_fn_expr_argtype(), libpqsrv_disconnect(), libpqsrv_get_result(), 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, PQresultStatus(), prepTuplestoreResult(), res, and text_to_cstring().

Referenced by dblink_get_result(), and dblink_record().

◆ dblink_res_error()

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

Definition at line 2705 of file dblink.c.

2707 {
2708  int level;
2709  char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2710  char *pg_diag_message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2711  char *pg_diag_message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2712  char *pg_diag_message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2713  char *pg_diag_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2714  int sqlstate;
2715  char *message_primary;
2716  char *message_detail;
2717  char *message_hint;
2718  char *message_context;
2719  va_list ap;
2720  char dblink_context_msg[512];
2721 
2722  if (fail)
2723  level = ERROR;
2724  else
2725  level = NOTICE;
2726 
2727  if (pg_diag_sqlstate)
2728  sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2729  pg_diag_sqlstate[1],
2730  pg_diag_sqlstate[2],
2731  pg_diag_sqlstate[3],
2732  pg_diag_sqlstate[4]);
2733  else
2734  sqlstate = ERRCODE_CONNECTION_FAILURE;
2735 
2736  message_primary = xpstrdup(pg_diag_message_primary);
2737  message_detail = xpstrdup(pg_diag_message_detail);
2738  message_hint = xpstrdup(pg_diag_message_hint);
2739  message_context = xpstrdup(pg_diag_context);
2740 
2741  /*
2742  * If we don't get a message from the PGresult, try the PGconn. This is
2743  * needed because for connection-level failures, PQgetResult may just
2744  * return NULL, not a PGresult at all.
2745  */
2746  if (message_primary == NULL)
2747  message_primary = pchomp(PQerrorMessage(conn));
2748 
2749  /*
2750  * Now that we've copied all the data we need out of the PGresult, it's
2751  * safe to free it. We must do this to avoid PGresult leakage. We're
2752  * leaking all the strings too, but those are in palloc'd memory that will
2753  * get cleaned up eventually.
2754  */
2755  PQclear(res);
2756 
2757  /*
2758  * Format the basic errcontext string. Below, we'll add on something
2759  * about the connection name. That's a violation of the translatability
2760  * guidelines about constructing error messages out of parts, but since
2761  * there's no translation support for dblink, there's no need to worry
2762  * about that (yet).
2763  */
2764  va_start(ap, fmt);
2765  vsnprintf(dblink_context_msg, sizeof(dblink_context_msg), fmt, ap);
2766  va_end(ap);
2767 
2768  ereport(level,
2769  (errcode(sqlstate),
2770  (message_primary != NULL && message_primary[0] != '\0') ?
2771  errmsg_internal("%s", message_primary) :
2772  errmsg("could not obtain message string for remote error"),
2773  message_detail ? errdetail_internal("%s", message_detail) : 0,
2774  message_hint ? errhint("%s", message_hint) : 0,
2775  message_context ? (errcontext("%s", message_context)) : 0,
2776  conname ?
2777  (errcontext("%s on dblink connection named \"%s\"",
2778  dblink_context_msg, conname)) :
2779  (errcontext("%s on unnamed dblink connection",
2780  dblink_context_msg))));
2781 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
#define errcontext
Definition: elog.h:196
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
#define NOTICE
Definition: elog.h:35
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
static void const char * fmt
va_end(args)
va_start(args, fmt)
#define vsnprintf
Definition: port.h:237
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:59
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:58
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:63

References conn, ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, fmt, 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(), res, va_end(), va_start(), vsnprintf, and xpstrdup().

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

◆ dblink_security_check()

static void dblink_security_check ( PGconn conn,
remoteConn rconn,
const char *  connstr 
)
static

Definition at line 2607 of file dblink.c.

2608 {
2609  /* Superuser bypasses security check */
2610  if (superuser())
2611  return;
2612 
2613  /* If password was used to connect, make sure it was one provided */
2615  return;
2616 
2617 #ifdef ENABLE_GSS
2618  /* If GSSAPI creds used to connect, make sure it was one delegated */
2620  return;
2621 #endif
2622 
2623  /* Otherwise, fail out */
2625  if (rconn)
2626  pfree(rconn);
2627 
2628  ereport(ERROR,
2629  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2630  errmsg("password or GSSAPI delegated credentials required"),
2631  errdetail("Non-superusers may only connect using credentials they provide, eg: password in connection string or delegated GSSAPI credentials"),
2632  errhint("Ensure provided credentials match target server's authentication method.")));
2633 }
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7266
int PQconnectionUsedGSSAPI(const PGconn *conn)
Definition: fe-connect.c:7277

References be_gssapi_get_delegation(), conn, connstr, dblink_connstr_has_pw(), ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, libpqsrv_disconnect(), MyProcPort, pfree(), PQconnectionUsedGSSAPI(), PQconnectionUsedPassword(), and superuser().

Referenced by dblink_connect(), and dblink_get_conn().

◆ dblink_send_query()

Datum dblink_send_query ( PG_FUNCTION_ARGS  )

Definition at line 674 of file dblink.c.

675 {
676  PGconn *conn;
677  char *sql;
678  int retval;
679 
680  if (PG_NARGS() == 2)
681  {
684  }
685  else
686  /* shouldn't happen */
687  elog(ERROR, "wrong number of arguments");
688 
689  /* async query send */
690  retval = PQsendQuery(conn, sql);
691  if (retval != 1)
692  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
693 
694  PG_RETURN_INT32(retval);
695 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1416

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

◆ deleteConnection()

static void deleteConnection ( const char *  name)
static

Definition at line 2581 of file dblink.c.

2582 {
2583  remoteConnHashEnt *hentry;
2584  bool found;
2585  char *key;
2586 
2587  if (!remoteConnHash)
2589 
2590  key = pstrdup(name);
2591  truncate_identifier(key, strlen(key), false);
2593  key, HASH_REMOVE, &found);
2594 
2595  if (!hentry)
2596  ereport(ERROR,
2597  (errcode(ERRCODE_UNDEFINED_OBJECT),
2598  errmsg("undefined connection name")));
2599 }
@ HASH_REMOVE
Definition: hsearch.h:115

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

Referenced by dblink_disconnect().

◆ elog()

◆ escape_param_str()

static char * escape_param_str ( const char *  str)
static

Definition at line 2877 of file dblink.c.

2878 {
2879  const char *cp;
2881 
2882  initStringInfo(&buf);
2883 
2884  for (cp = str; *cp; cp++)
2885  {
2886  if (*cp == '\\' || *cp == '\'')
2887  appendStringInfoChar(&buf, '\\');
2888  appendStringInfoChar(&buf, *cp);
2889  }
2890 
2891  return buf.data;
2892 }
const char * str
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:191

References appendStringInfoChar(), buf, initStringInfo(), and str.

Referenced by get_connect_string().

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

Definition at line 2503 of file dblink.c.

2504 {
2505  char *nspname;
2506  char *result;
2507 
2508  /* Qualify the name if not visible in search path */
2510  nspname = NULL;
2511  else
2512  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2513 
2514  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2515 
2516  return result;
2517 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
bool RelationIsVisible(Oid relid)
Definition: namespace.c:913
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetRelationName(relation)
Definition: rel.h:539
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12952
Form_pg_class rd_rel
Definition: rel.h:111

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

◆ get_attnum_pk_pos()

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

Definition at line 2352 of file dblink.c.

2353 {
2354  int i;
2355 
2356  /*
2357  * Not likely a long list anyway, so just scan for the value
2358  */
2359  for (i = 0; i < pknumatts; i++)
2360  if (key == pkattnums[i])
2361  return i;
2362 
2363  return -1;
2364 }

References i, and sort-test::key.

Referenced by get_sql_insert(), and get_sql_update().

◆ get_connect_string()

static char * get_connect_string ( const char *  servername)
static

Definition at line 2787 of file dblink.c.

2788 {
2789  ForeignServer *foreign_server = NULL;
2790  UserMapping *user_mapping;
2791  ListCell *cell;
2793  ForeignDataWrapper *fdw;
2794  AclResult aclresult;
2795  char *srvname;
2796 
2797  static const PQconninfoOption *options = NULL;
2798 
2799  initStringInfo(&buf);
2800 
2801  /*
2802  * Get list of valid libpq options.
2803  *
2804  * To avoid unnecessary work, we get the list once and use it throughout
2805  * the lifetime of this backend process. We don't need to care about
2806  * memory context issues, because PQconndefaults allocates with malloc.
2807  */
2808  if (!options)
2809  {
2810  options = PQconndefaults();
2811  if (!options) /* assume reason for failure is OOM */
2812  ereport(ERROR,
2813  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2814  errmsg("out of memory"),
2815  errdetail("Could not get libpq's default connection options.")));
2816  }
2817 
2818  /* first gather the server connstr options */
2819  srvname = pstrdup(servername);
2820  truncate_identifier(srvname, strlen(srvname), false);
2821  foreign_server = GetForeignServerByName(srvname, true);
2822 
2823  if (foreign_server)
2824  {
2825  Oid serverid = foreign_server->serverid;
2826  Oid fdwid = foreign_server->fdwid;
2827  Oid userid = GetUserId();
2828 
2829  user_mapping = GetUserMapping(userid, serverid);
2830  fdw = GetForeignDataWrapper(fdwid);
2831 
2832  /* Check permissions, user must have usage on the server. */
2833  aclresult = object_aclcheck(ForeignServerRelationId, serverid, userid, ACL_USAGE);
2834  if (aclresult != ACLCHECK_OK)
2835  aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, foreign_server->servername);
2836 
2837  foreach(cell, fdw->options)
2838  {
2839  DefElem *def = lfirst(cell);
2840 
2841  if (is_valid_dblink_option(options, def->defname, ForeignDataWrapperRelationId))
2842  appendStringInfo(&buf, "%s='%s' ", def->defname,
2843  escape_param_str(strVal(def->arg)));
2844  }
2845 
2846  foreach(cell, foreign_server->options)
2847  {
2848  DefElem *def = lfirst(cell);
2849 
2850  if (is_valid_dblink_option(options, def->defname, ForeignServerRelationId))
2851  appendStringInfo(&buf, "%s='%s' ", def->defname,
2852  escape_param_str(strVal(def->arg)));
2853  }
2854 
2855  foreach(cell, user_mapping->options)
2856  {
2857 
2858  DefElem *def = lfirst(cell);
2859 
2860  if (is_valid_dblink_option(options, def->defname, UserMappingRelationId))
2861  appendStringInfo(&buf, "%s='%s' ", def->defname,
2862  escape_param_str(strVal(def->arg)));
2863  }
2864 
2865  return buf.data;
2866  }
2867  else
2868  return NULL;
2869 }
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2622
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3810
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:37
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:200
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:182
Oid GetUserId(void)
Definition: miscinit.c:524
#define ACL_USAGE
Definition: parsenodes.h:84
@ OBJECT_FOREIGN_SERVER
Definition: parsenodes.h:2285
Node * arg
Definition: parsenodes.h:818
List * options
Definition: foreign.h:31
List * options
Definition: foreign.h:42
char * servername
Definition: foreign.h:39
Oid serverid
Definition: foreign.h:36
List * options
Definition: foreign.h:50
#define strVal(v)
Definition: value.h:82

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

Referenced by dblink_connect(), and dblink_get_conn().

◆ get_pkey_attnames()

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

Definition at line 2018 of file dblink.c.

2019 {
2020  Relation indexRelation;
2021  ScanKeyData skey;
2022  SysScanDesc scan;
2023  HeapTuple indexTuple;
2024  int i;
2025  char **result = NULL;
2026  TupleDesc tupdesc;
2027 
2028  /* initialize indnkeyatts to 0 in case no primary key exists */
2029  *indnkeyatts = 0;
2030 
2031  tupdesc = rel->rd_att;
2032 
2033  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2034  indexRelation = table_open(IndexRelationId, AccessShareLock);
2035  ScanKeyInit(&skey,
2036  Anum_pg_index_indrelid,
2037  BTEqualStrategyNumber, F_OIDEQ,
2039 
2040  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2041  NULL, 1, &skey);
2042 
2043  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2044  {
2045  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2046 
2047  /* we're only interested if it is the primary key */
2048  if (index->indisprimary)
2049  {
2050  *indnkeyatts = index->indnkeyatts;
2051  if (*indnkeyatts > 0)
2052  {
2053  result = palloc_array(char *, *indnkeyatts);
2054 
2055  for (i = 0; i < *indnkeyatts; i++)
2056  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2057  }
2058  break;
2059  }
2060  }
2061 
2062  systable_endscan(scan);
2063  table_close(indexRelation, AccessShareLock);
2064 
2065  return result;
2066 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:606
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:513
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:1198
#define BTEqualStrategyNumber
Definition: stratnum.h:31
TupleDesc rd_att
Definition: rel.h:112
Definition: type.h:96
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

Referenced by dblink_get_pkey().

◆ get_rel_from_relname()

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

Definition at line 2478 of file dblink.c.

2479 {
2480  RangeVar *relvar;
2481  Relation rel;
2482  AclResult aclresult;
2483 
2484  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2485  rel = table_openrv(relvar, lockmode);
2486 
2487  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2488  aclmode);
2489  if (aclresult != ACLCHECK_OK)
2490  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2492 
2493  return rel;
2494 }
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4013
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3554
ObjectType get_relkind_objtype(char relkind)
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3374

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

◆ get_sql_delete()

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

Definition at line 2209 of file dblink.c.

2210 {
2211  char *relname;
2212  TupleDesc tupdesc;
2214  int i;
2215 
2216  initStringInfo(&buf);
2217 
2218  /* get relation name including any needed schema prefix and quoting */
2220 
2221  tupdesc = rel->rd_att;
2222 
2223  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2224  for (i = 0; i < pknumatts; i++)
2225  {
2226  int pkattnum = pkattnums[i];
2227  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2228 
2229  if (i > 0)
2230  appendStringInfoString(&buf, " AND ");
2231 
2233  quote_ident_cstr(NameStr(attr->attname)));
2234 
2235  if (tgt_pkattvals[i] != NULL)
2236  appendStringInfo(&buf, " = %s",
2237  quote_literal_cstr(tgt_pkattvals[i]));
2238  else
2239  appendStringInfoString(&buf, " IS NULL");
2240  }
2241 
2242  return buf.data;
2243 }
#define NameStr(name)
Definition: c.h:700
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
NameData relname
Definition: pg_class.h:38
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:179
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by dblink_build_sql_delete().

◆ get_sql_insert()

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

Definition at line 2129 of file dblink.c.

2130 {
2131  char *relname;
2132  HeapTuple tuple;
2133  TupleDesc tupdesc;
2134  int natts;
2136  char *val;
2137  int key;
2138  int i;
2139  bool needComma;
2140 
2141  initStringInfo(&buf);
2142 
2143  /* get relation name including any needed schema prefix and quoting */
2145 
2146  tupdesc = rel->rd_att;
2147  natts = tupdesc->natts;
2148 
2149  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2150  if (!tuple)
2151  ereport(ERROR,
2152  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2153  errmsg("source row not found")));
2154 
2155  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2156 
2157  needComma = false;
2158  for (i = 0; i < natts; i++)
2159  {
2160  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2161 
2162  if (att->attisdropped)
2163  continue;
2164 
2165  if (needComma)
2166  appendStringInfoChar(&buf, ',');
2167 
2169  quote_ident_cstr(NameStr(att->attname)));
2170  needComma = true;
2171  }
2172 
2173  appendStringInfoString(&buf, ") VALUES(");
2174 
2175  /*
2176  * Note: i is physical column number (counting from 0).
2177  */
2178  needComma = false;
2179  for (i = 0; i < natts; i++)
2180  {
2181  if (TupleDescAttr(tupdesc, i)->attisdropped)
2182  continue;
2183 
2184  if (needComma)
2185  appendStringInfoChar(&buf, ',');
2186 
2187  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2188 
2189  if (key >= 0)
2190  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2191  else
2192  val = SPI_getvalue(tuple, tupdesc, i + 1);
2193 
2194  if (val != NULL)
2195  {
2197  pfree(val);
2198  }
2199  else
2200  appendStringInfoString(&buf, "NULL");
2201  needComma = true;
2202  }
2203  appendStringInfoChar(&buf, ')');
2204 
2205  return buf.data;
2206 }
long val
Definition: informix.c:689
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1220

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, 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().

◆ get_sql_update()

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

Definition at line 2246 of file dblink.c.

2247 {
2248  char *relname;
2249  HeapTuple tuple;
2250  TupleDesc tupdesc;
2251  int natts;
2253  char *val;
2254  int key;
2255  int i;
2256  bool needComma;
2257 
2258  initStringInfo(&buf);
2259 
2260  /* get relation name including any needed schema prefix and quoting */
2262 
2263  tupdesc = rel->rd_att;
2264  natts = tupdesc->natts;
2265 
2266  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2267  if (!tuple)
2268  ereport(ERROR,
2269  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2270  errmsg("source row not found")));
2271 
2272  appendStringInfo(&buf, "UPDATE %s SET ", relname);
2273 
2274  /*
2275  * Note: i is physical column number (counting from 0).
2276  */
2277  needComma = false;
2278  for (i = 0; i < natts; i++)
2279  {
2280  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2281 
2282  if (attr->attisdropped)
2283  continue;
2284 
2285  if (needComma)
2286  appendStringInfoString(&buf, ", ");
2287 
2288  appendStringInfo(&buf, "%s = ",
2289  quote_ident_cstr(NameStr(attr->attname)));
2290 
2291  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2292 
2293  if (key >= 0)
2294  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2295  else
2296  val = SPI_getvalue(tuple, tupdesc, i + 1);
2297 
2298  if (val != NULL)
2299  {
2301  pfree(val);
2302  }
2303  else
2304  appendStringInfoString(&buf, "NULL");
2305  needComma = true;
2306  }
2307 
2308  appendStringInfoString(&buf, " WHERE ");
2309 
2310  for (i = 0; i < pknumatts; i++)
2311  {
2312  int pkattnum = pkattnums[i];
2313  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2314 
2315  if (i > 0)
2316  appendStringInfoString(&buf, " AND ");
2317 
2319  quote_ident_cstr(NameStr(attr->attname)));
2320 
2321  val = tgt_pkattvals[i];
2322 
2323  if (val != NULL)
2325  else
2326  appendStringInfoString(&buf, " IS NULL");
2327  }
2328 
2329  return buf.data;
2330 }

References appendStringInfo(), appendStringInfoString(), buf, 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().

◆ get_text_array_contents()

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

Definition at line 2073 of file dblink.c.

2074 {
2075  int ndim = ARR_NDIM(array);
2076  int *dims = ARR_DIMS(array);
2077  int nitems;
2078  int16 typlen;
2079  bool typbyval;
2080  char typalign;
2081  char **values;
2082  char *ptr;
2083  bits8 *bitmap;
2084  int bitmask;
2085  int i;
2086 
2087  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2088 
2089  *numitems = nitems = ArrayGetNItems(ndim, dims);
2090 
2092  &typlen, &typbyval, &typalign);
2093 
2094  values = palloc_array(char *, nitems);
2095 
2096  ptr = ARR_DATA_PTR(array);
2097  bitmap = ARR_NULLBITMAP(array);
2098  bitmask = 1;
2099 
2100  for (i = 0; i < nitems; i++)
2101  {
2102  if (bitmap && (*bitmap & bitmask) == 0)
2103  {
2104  values[i] = NULL;
2105  }
2106  else
2107  {
2109  ptr = att_addlength_pointer(ptr, typlen, ptr);
2110  ptr = (char *) att_align_nominal(ptr, typalign);
2111  }
2112 
2113  /* advance bitmap pointer if any */
2114  if (bitmap)
2115  {
2116  bitmask <<= 1;
2117  if (bitmask == 0x100)
2118  {
2119  bitmap++;
2120  bitmask = 1;
2121  }
2122  }
2123  }
2124 
2125  return values;
2126 }
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define ARR_NULLBITMAP(a)
Definition: array.h:300
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
#define TextDatumGetCString(d)
Definition: builtins.h:98
uint8 bits8
Definition: c.h:492
#define nitems(x)
Definition: indent.h:31
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2271
char typalign
Definition: pg_type.h:176
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:129
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:157

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

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

◆ get_tuple_of_interest()

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

Definition at line 2367 of file dblink.c.

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

References appendStringInfo(), appendStringInfoString(), buf, 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().

◆ getConnectionByName()

static remoteConn * getConnectionByName ( const char *  name)
static

Definition at line 2521 of file dblink.c.

2522 {
2523  remoteConnHashEnt *hentry;
2524  char *key;
2525 
2526  if (!remoteConnHash)
2528 
2529  key = pstrdup(name);
2530  truncate_identifier(key, strlen(key), false);
2532  key, HASH_FIND, NULL);
2533 
2534  if (hentry)
2535  return hentry->rconn;
2536 
2537  return NULL;
2538 }
@ HASH_FIND
Definition: hsearch.h:113

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

◆ is_valid_dblink_option()

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

Definition at line 2981 of file dblink.c.

2983 {
2984  const PQconninfoOption *opt;
2985 
2986  /* Look up the option in libpq result */
2987  for (opt = options; opt->keyword; opt++)
2988  {
2989  if (strcmp(opt->keyword, option) == 0)
2990  break;
2991  }
2992  if (opt->keyword == NULL)
2993  return false;
2994 
2995  /* Disallow debug options (particularly "replication") */
2996  if (strchr(opt->dispchar, 'D'))
2997  return false;
2998 
2999  /* Disallow "client_encoding" */
3000  if (strcmp(opt->keyword, "client_encoding") == 0)
3001  return false;
3002 
3003  /*
3004  * If the option is "user" or marked secure, it should be specified only
3005  * in USER MAPPING. Others should be specified only in SERVER.
3006  */
3007  if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
3008  {
3009  if (context != UserMappingRelationId)
3010  return false;
3011  }
3012  else
3013  {
3014  if (context != ForeignServerRelationId)
3015  return false;
3016  }
3017 
3018  return true;
3019 }

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

Referenced by dblink_fdw_validator(), and get_connect_string().

◆ materializeQueryResult()

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

Definition at line 992 of file dblink.c.

997 {
998  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
999  PGresult *volatile res = NULL;
1000  volatile storeInfo sinfo = {0};
1001 
1002  /* prepTuplestoreResult must have been called previously */
1003  Assert(rsinfo->returnMode == SFRM_Materialize);
1004 
1005  sinfo.fcinfo = fcinfo;
1006 
1007  PG_TRY();
1008  {
1009  /* Create short-lived memory context for data conversions */
1010  sinfo.tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
1011  "dblink temporary context",
1013 
1014  /* execute query, collecting any tuples into the tuplestore */
1015  res = storeQueryResult(&sinfo, conn, sql);
1016 
1017  if (!res ||
1020  {
1021  /*
1022  * dblink_res_error will clear the passed PGresult, so we need
1023  * this ugly dance to avoid doing so twice during error exit
1024  */
1025  PGresult *res1 = res;
1026 
1027  res = NULL;
1028  dblink_res_error(conn, conname, res1, fail,
1029  "while executing query");
1030  /* if fail isn't set, we'll return an empty query result */
1031  }
1032  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1033  {
1034  /*
1035  * storeRow didn't get called, so we need to convert the command
1036  * status string to a tuple manually
1037  */
1038  TupleDesc tupdesc;
1039  AttInMetadata *attinmeta;
1040  Tuplestorestate *tupstore;
1041  HeapTuple tuple;
1042  char *values[1];
1043  MemoryContext oldcontext;
1044 
1045  /*
1046  * need a tuple descriptor representing one TEXT column to return
1047  * the command status string as our result tuple
1048  */
1049  tupdesc = CreateTemplateTupleDesc(1);
1050  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1051  TEXTOID, -1, 0);
1052  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1053 
1054  oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1055  tupstore = tuplestore_begin_heap(true, false, work_mem);
1056  rsinfo->setResult = tupstore;
1057  rsinfo->setDesc = tupdesc;
1058  MemoryContextSwitchTo(oldcontext);
1059 
1060  values[0] = PQcmdStatus(res);
1061 
1062  /* build the tuple and put it into the tuplestore. */
1063  tuple = BuildTupleFromCStrings(attinmeta, values);
1064  tuplestore_puttuple(tupstore, tuple);
1065 
1066  PQclear(res);
1067  res = NULL;
1068  }
1069  else
1070  {
1072  /* storeRow should have created a tuplestore */
1073  Assert(rsinfo->setResult != NULL);
1074 
1075  PQclear(res);
1076  res = NULL;
1077  }
1078 
1079  /* clean up data conversion short-lived memory context */
1080  if (sinfo.tmpcontext != NULL)
1081  MemoryContextDelete(sinfo.tmpcontext);
1082  sinfo.tmpcontext = NULL;
1083 
1084  PQclear(sinfo.last_res);
1085  sinfo.last_res = NULL;
1086  PQclear(sinfo.cur_res);
1087  sinfo.cur_res = NULL;
1088  }
1089  PG_CATCH();
1090  {
1091  /* be sure to release any libpq result we collected */
1092  PQclear(res);
1093  PQclear(sinfo.last_res);
1094  PQclear(sinfo.cur_res);
1095  /* and clear out any pending data in libpq */
1097  NULL)
1098  PQclear(res);
1099  PG_RE_THROW();
1100  }
1101  PG_END_TRY();
1102 }
#define PG_RE_THROW()
Definition: elog.h:412
#define PG_CATCH(...)
Definition: elog.h:381
@ SFRM_Materialize
Definition: execnodes.h:320
int work_mem
Definition: globals.c:130
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
fmNodePtr resultinfo
Definition: fmgr.h:89
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:330
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:764

References res, and FunctionCallInfoBaseData::resultinfo.

Referenced by dblink_record_internal().

◆ materializeResult()

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

Definition at line 853 of file dblink.c.

854 {
855  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
856 
857  /* prepTuplestoreResult must have been called previously */
858  Assert(rsinfo->returnMode == SFRM_Materialize);
859 
860  PG_TRY();
861  {
862  TupleDesc tupdesc;
863  bool is_sql_cmd;
864  int ntuples;
865  int nfields;
866 
868  {
869  is_sql_cmd = true;
870 
871  /*
872  * need a tuple descriptor representing one TEXT column to return
873  * the command status string as our result tuple
874  */
875  tupdesc = CreateTemplateTupleDesc(1);
876  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
877  TEXTOID, -1, 0);
878  ntuples = 1;
879  nfields = 1;
880  }
881  else
882  {
884 
885  is_sql_cmd = false;
886 
887  /* get a tuple descriptor for our result type */
888  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
889  {
890  case TYPEFUNC_COMPOSITE:
891  /* success */
892  break;
893  case TYPEFUNC_RECORD:
894  /* failed to determine actual type of RECORD */
895  ereport(ERROR,
896  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
897  errmsg("function returning record called in context "
898  "that cannot accept type record")));
899  break;
900  default:
901  /* result type isn't composite */
902  elog(ERROR, "return type must be a row type");
903  break;
904  }
905 
906  /* make sure we have a persistent copy of the tupdesc */
907  tupdesc = CreateTupleDescCopy(tupdesc);
908  ntuples = PQntuples(res);
909  nfields = PQnfields(res);
910  }
911 
912  /*
913  * check result and tuple descriptor have the same number of columns
914  */
915  if (nfields != tupdesc->natts)
916  ereport(ERROR,
917  (errcode(ERRCODE_DATATYPE_MISMATCH),
918  errmsg("remote query result rowtype does not match "
919  "the specified FROM clause rowtype")));
920 
921  if (ntuples > 0)
922  {
923  AttInMetadata *attinmeta;
924  int nestlevel = -1;
925  Tuplestorestate *tupstore;
926  MemoryContext oldcontext;
927  int row;
928  char **values;
929 
930  attinmeta = TupleDescGetAttInMetadata(tupdesc);
931 
932  /* Set GUCs to ensure we read GUC-sensitive data types correctly */
933  if (!is_sql_cmd)
934  nestlevel = applyRemoteGucs(conn);
935 
937  tupstore = tuplestore_begin_heap(true, false, work_mem);
938  rsinfo->setResult = tupstore;
939  rsinfo->setDesc = tupdesc;
940  MemoryContextSwitchTo(oldcontext);
941 
942  values = palloc_array(char *, nfields);
943 
944  /* put all tuples into the tuplestore */
945  for (row = 0; row < ntuples; row++)
946  {
947  HeapTuple tuple;
948 
949  if (!is_sql_cmd)
950  {
951  int i;
952 
953  for (i = 0; i < nfields; i++)
954  {
955  if (PQgetisnull(res, row, i))
956  values[i] = NULL;
957  else
958  values[i] = PQgetvalue(res, row, i);
959  }
960  }
961  else
962  {
963  values[0] = PQcmdStatus(res);
964  }
965 
966  /* build the tuple and put it into the tuplestore. */
967  tuple = BuildTupleFromCStrings(attinmeta, values);
968  tuplestore_puttuple(tupstore, tuple);
969  }
970 
971  /* clean up GUC settings, if we changed any */
972  restoreLocalGucs(nestlevel);
973  }
974  }
975  PG_FINALLY();
976  {
977  /* be sure to release the libpq result */
978  PQclear(res);
979  }
980  PG_END_TRY();
981 }
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3901
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3489
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
@ TYPEFUNC_RECORD
Definition: funcapi.h:151
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:265
SetFunctionReturnMode returnMode
Definition: execnodes.h:339
ExprContext * econtext
Definition: execnodes.h:335
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133

References applyRemoteGucs(), Assert, BuildTupleFromCStrings(), conn, CreateTemplateTupleDesc(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog(), ereport, errcode(), errmsg(), ERROR, get_call_result_type(), i, MemoryContextSwitchTo(), TupleDescData::natts, palloc_array, PG_END_TRY, PG_FINALLY, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQcmdStatus(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), res, restoreLocalGucs(), FunctionCallInfoBaseData::resultinfo, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, TupleDescGetAttInMetadata(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, values, and work_mem.

Referenced by dblink_fetch(), and dblink_record_internal().

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 174 of file dblink.c.

176 {
177  if (conname)
178  ereport(ERROR,
179  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
180  errmsg("connection \"%s\" not available", conname)));
181  else
182  ereport(ERROR,
183  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
184  errmsg("connection not available")));
185 }

References ereport, errcode(), errmsg(), and ERROR.

◆ PG_FUNCTION_INFO_V1() [1/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_delete  )

◆ PG_FUNCTION_INFO_V1() [2/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_insert  )

◆ PG_FUNCTION_INFO_V1() [3/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_update  )

◆ PG_FUNCTION_INFO_V1() [4/20]

PG_FUNCTION_INFO_V1 ( dblink_cancel_query  )

◆ PG_FUNCTION_INFO_V1() [5/20]

PG_FUNCTION_INFO_V1 ( dblink_close  )

◆ PG_FUNCTION_INFO_V1() [6/20]

PG_FUNCTION_INFO_V1 ( dblink_connect  )

◆ PG_FUNCTION_INFO_V1() [7/20]

PG_FUNCTION_INFO_V1 ( dblink_current_query  )

◆ PG_FUNCTION_INFO_V1() [8/20]

PG_FUNCTION_INFO_V1 ( dblink_disconnect  )

◆ PG_FUNCTION_INFO_V1() [9/20]

PG_FUNCTION_INFO_V1 ( dblink_error_message  )

◆ PG_FUNCTION_INFO_V1() [10/20]

PG_FUNCTION_INFO_V1 ( dblink_exec  )

◆ PG_FUNCTION_INFO_V1() [11/20]

PG_FUNCTION_INFO_V1 ( dblink_fdw_validator  )

◆ PG_FUNCTION_INFO_V1() [12/20]

PG_FUNCTION_INFO_V1 ( dblink_fetch  )

◆ PG_FUNCTION_INFO_V1() [13/20]

PG_FUNCTION_INFO_V1 ( dblink_get_connections  )

◆ PG_FUNCTION_INFO_V1() [14/20]

PG_FUNCTION_INFO_V1 ( dblink_get_notify  )

◆ PG_FUNCTION_INFO_V1() [15/20]

PG_FUNCTION_INFO_V1 ( dblink_get_pkey  )

◆ PG_FUNCTION_INFO_V1() [16/20]

PG_FUNCTION_INFO_V1 ( dblink_get_result  )

◆ PG_FUNCTION_INFO_V1() [17/20]

PG_FUNCTION_INFO_V1 ( dblink_is_busy  )

◆ PG_FUNCTION_INFO_V1() [18/20]

PG_FUNCTION_INFO_V1 ( dblink_open  )

◆ PG_FUNCTION_INFO_V1() [19/20]

PG_FUNCTION_INFO_V1 ( dblink_record  )

◆ PG_FUNCTION_INFO_V1() [20/20]

PG_FUNCTION_INFO_V1 ( dblink_send_query  )

◆ PQclear()

PQclear ( res  )

Referenced by _check_database_version(), _doSetSessionAuth(), _printTableAccessMethodNoStorage(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), add_tablespace_footer(), addFooterToPublicationDesc(), advanceConnectionState(), append_depends_on_extension(), appendQualifiedRelation(), BaseBackup(), binary_upgrade_set_type_oids_by_type_oid(), buildMatViewRefreshDependencies(), buildShSecLabels(), check_and_drop_existing_subscriptions(), check_for_connection_status(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_loadable_libraries(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_prepare_conn(), check_publisher(), check_subscriber(), ClearOrSaveResult(), close_cursor(), cluster_all_databases(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), compile_database_list(), compile_relation_list_one_db(), confirm_query_canceled_impl(), connect_database(), ConnectDatabase(), connectDatabase(), connectToServer(), convertTSFunction(), create_cursor(), create_logical_replication_slot(), create_logical_replication_slots(), create_new_objects(), create_publication(), create_subscription(), CreateReplicationSlot(), createViewAsClause(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_res_error(), deallocate_one(), deallocate_query(), describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoleGrants(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), descriptor_free(), discardUntilSync(), do_lo_import(), do_sql_command_end(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), ecpg_autostart_transaction(), ecpg_check_PQresult(), ecpg_process_output(), ECPGdescribe(), ECPGsetcommit(), ECPGtrans(), enable_subscription(), EndDBCopyMode(), exec_command_password(), execute_foreign_modify(), executeCommand(), executeMaintenanceCommand(), executeQueryOrDie(), ExecuteSqlCommand(), ExecuteSqlStatement(), executeStatement(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), finish_lo_xact(), generate_object_name(), get_create_object_cmd(), get_db_infos(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_object_list(), get_primary_sysid(), get_remote_estimate(), get_returning_data(), get_subscription_count(), get_synchronized_snapshot(), get_tablespace_paths(), get_template0_info(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getCopyStart(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getParamDescriptions(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRowDescriptions(), getRules(), GetSlotInformation(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), handleCopyIn(), HandleCopyResult(), HandleEndOfCopyStream(), init_libpq_conn(), initPopulateTable(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_exec(), libpqrcv_identify_system(), libpqrcv_PQexec(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), libpqsrv_get_result_last(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listLargeObjects(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), lockTableForWorker(), lookup_object_oid(), main(), materializeResult(), objectDescription(), old_9_6_invalidate_hash_indexes(), permissionsList(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), pgfdw_report_error(), pgfdw_xact_callback(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresEndDirectModify(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), PQconnectPoll(), PQencryptPasswordConn(), pqEndcopy3(), pqGetErrorNotice3(), PQsetClientEncoding(), prepare_common(), prepare_foreign_modify(), prepareCommand(), process_query_result(), process_queued_fetch_requests(), process_result(), processExtensionTables(), processQueryResult(), readCommandResponse(), ReceiveCopyData(), ReceiveXlogStream(), reindex_all_databases(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), SendQuery(), server_is_in_recovery(), set_frozenxids(), set_locale_and_encoding(), set_replication_progress(), set_restrict_relation_kind(), setup_connection(), setup_publisher(), sql_conn(), sql_exec(), start_lo_xact(), store_returning_result(), storeQueryResult(), StreamLogicalLog(), TableCommandResultHandler(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), try_complete_step(), tryExecuteStatement(), vacuum_all_databases(), vacuum_one_database(), vacuumlo(), and wait_for_connection_state().

◆ prepTuplestoreResult()

static void prepTuplestoreResult ( FunctionCallInfo  fcinfo)
static

Definition at line 825 of file dblink.c.

826 {
827  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
828 
829  /* check to see if query supports us returning a tuplestore */
830  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
831  ereport(ERROR,
832  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
833  errmsg("set-valued function called in context that cannot accept a set")));
834  if (!(rsinfo->allowedModes & SFRM_Materialize))
835  ereport(ERROR,
836  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
837  errmsg("materialize mode required, but it is not allowed in this context")));
838 
839  /* let the executor know we're sending back a tuplestore */
840  rsinfo->returnMode = SFRM_Materialize;
841 
842  /* caller must fill these to return a non-empty result */
843  rsinfo->setResult = NULL;
844  rsinfo->setDesc = NULL;
845 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
int allowedModes
Definition: execnodes.h:337

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

Referenced by dblink_fetch(), and dblink_record_internal().

◆ quote_ident_cstr()

static char * quote_ident_cstr ( char *  rawstr)
static

Definition at line 2337 of file dblink.c.

2338 {
2339  text *rawstr_text;
2340  text *result_text;
2341  char *result;
2342 
2343  rawstr_text = cstring_to_text(rawstr);
2345  PointerGetDatum(rawstr_text)));
2346  result = text_to_cstring(result_text);
2347 
2348  return result;
2349 }
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:641
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:25

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

◆ restoreLocalGucs()

static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3084 of file dblink.c.

3085 {
3086  /* Do nothing if no new nestlevel was created */
3087  if (nestlevel > 0)
3088  AtEOXact_GUC(true, nestlevel);
3089 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2262

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

◆ storeQueryResult()

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

Definition at line 1108 of file dblink.c.

1109 {
1110  bool first = true;
1111  int nestlevel = -1;
1112  PGresult *res;
1113 
1114  if (!PQsendQuery(conn, sql))
1115  elog(ERROR, "could not send query: %s", pchomp(PQerrorMessage(conn)));
1116 
1117  if (!PQsetSingleRowMode(conn)) /* shouldn't fail */
1118  elog(ERROR, "failed to set single-row mode for dblink query");
1119 
1120  for (;;)
1121  {
1123 
1124  sinfo->cur_res = libpqsrv_get_result(conn, dblink_we_get_result);
1125  if (!sinfo->cur_res)
1126  break;
1127 
1128  if (PQresultStatus(sinfo->cur_res) == PGRES_SINGLE_TUPLE)
1129  {
1130  /* got one row from possibly-bigger resultset */
1131 
1132  /*
1133  * Set GUCs to ensure we read GUC-sensitive data types correctly.
1134  * We shouldn't do this until we have a row in hand, to ensure
1135  * libpq has seen any earlier ParameterStatus protocol messages.
1136  */
1137  if (first && nestlevel < 0)
1138  nestlevel = applyRemoteGucs(conn);
1139 
1140  storeRow(sinfo, sinfo->cur_res, first);
1141 
1142  PQclear(sinfo->cur_res);
1143  sinfo->cur_res = NULL;
1144  first = false;
1145  }
1146  else
1147  {
1148  /* if empty resultset, fill tuplestore header */
1149  if (first && PQresultStatus(sinfo->cur_res) == PGRES_TUPLES_OK)
1150  storeRow(sinfo, sinfo->cur_res, first);
1151 
1152  /* store completed result at last_res */
1153  PQclear(sinfo->last_res);
1154  sinfo->last_res = sinfo->cur_res;
1155  sinfo->cur_res = NULL;
1156  first = true;
1157  }
1158  }
1159 
1160  /* clean up GUC settings, if we changed any */
1161  restoreLocalGucs(nestlevel);
1162 
1163  /* return last_res */
1164  res = sinfo->last_res;
1165  sinfo->last_res = NULL;
1166  return res;
1167 }
int PQsetSingleRowMode(PGconn *conn)
Definition: fe-exec.c:1948
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:133
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122

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

◆ storeRow()

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

Definition at line 1176 of file dblink.c.

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

References Assert, storeInfo::attinmeta, BuildTupleFromCStrings(), CreateTupleDescCopy(), storeInfo::cstrs, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog(), ereport, errcode(), errmsg(), ERROR, storeInfo::fcinfo, get_call_result_type(), i, if(), MemoryContextReset(), MemoryContextSwitchTo(), TupleDescData::natts, palloc_array, pfree(), PQgetisnull(), PQgetvalue(), PQnfields(), PQntuples(), res, 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().

◆ validate_pkattnums()

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

Definition at line 2910 of file dblink.c.

2913 {
2914  TupleDesc tupdesc = rel->rd_att;
2915  int natts = tupdesc->natts;
2916  int i;
2917 
2918  /* Don't take more array elements than there are */
2919  pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2920 
2921  /* Must have at least one pk attnum selected */
2922  if (pknumatts_arg <= 0)
2923  ereport(ERROR,
2924  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2925  errmsg("number of key attributes must be > 0")));
2926 
2927  /* Allocate output array */
2928  *pkattnums = palloc_array(int, pknumatts_arg);
2929  *pknumatts = pknumatts_arg;
2930 
2931  /* Validate attnums and convert to internal form */
2932  for (i = 0; i < pknumatts_arg; i++)
2933  {
2934  int pkattnum = pkattnums_arg->values[i];
2935  int lnum;
2936  int j;
2937 
2938  /* Can throw error immediately if out of range */
2939  if (pkattnum <= 0 || pkattnum > natts)
2940  ereport(ERROR,
2941  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2942  errmsg("invalid attribute number %d", pkattnum)));
2943 
2944  /* Identify which physical column has this logical number */
2945  lnum = 0;
2946  for (j = 0; j < natts; j++)
2947  {
2948  /* dropped columns don't count */
2949  if (TupleDescAttr(tupdesc, j)->attisdropped)
2950  continue;
2951 
2952  if (++lnum == pkattnum)
2953  break;
2954  }
2955 
2956  if (j < natts)
2957  (*pkattnums)[i] = j;
2958  else
2959  ereport(ERROR,
2960  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2961  errmsg("invalid attribute number %d", pkattnum)));
2962  }
2963 }
#define Min(x, y)
Definition: c.h:958
int j
Definition: isn.c:73
int dim1
Definition: c.h:674
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:676

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

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

◆ xpstrdup()

static char* xpstrdup ( const char *  in)
static

Definition at line 156 of file dblink.c.

157 {
158  if (in == NULL)
159  return NULL;
160  return pstrdup(in);
161 }

References pstrdup().

Referenced by dblink_res_error().

Variable Documentation

◆ dblink_we_connect

uint32 dblink_we_connect = 0
static

Definition at line 135 of file dblink.c.

Referenced by dblink_connect().

◆ dblink_we_get_conn

uint32 dblink_we_get_conn = 0
static

Definition at line 136 of file dblink.c.

Referenced by dblink_get_conn().

◆ dblink_we_get_result

uint32 dblink_we_get_result = 0
static

◆ p2

◆ pconn

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 66 of file dblink.c.

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static

◆ res

void PGresult* res

Definition at line 165 of file dblink.c.

Referenced by _bt_binsrch_posting(), _bt_checkkeys(), _bt_merge_arrays(), _check_database_version(), _doSetSessionAuth(), _int_contains(), _intbig_alloc(), _lca(), _lt_q_regex(), _ltq_regex(), _ltree_consistent(), _ltree_isparent(), _ltree_risparent(), _ltxtq_exec(), _pgp_read_public_key(), _printTableAccessMethodNoStorage(), _ReadByte(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), _SPI_execute_plan(), _SPI_pquery(), _tarAddFile(), _tarReadRaw(), _tocEntryRequired(), addFooterToPublicationDesc(), addItemPointersToLeafTuple(), advance_windowaggregate(), advance_windowaggregate_base(), advanceConnectionState(), analyze_row_processor(), anybit_typmodout(), anychar_typmodout(), append_depends_on_extension(), appendBoolResult(), appendQualifiedRelation(), appendReloptionsArrayAH(), BaseBackup(), bf_check_supported_key_len(), binary_decode(), binary_encode(), binary_upgrade_set_type_oids_by_type_oid(), blgetbitmap(), BloomFormTuple(), bn_to_mpi(), btgettuple(), btproperty(), buildFreshLeafTuple(), buildMatViewRefreshDependencies(), buildShSecLabels(), byteaSetBit(), byteaSetByte(), calc_key_id(), calc_rank(), calc_rank_and(), calc_rank_or(), cash_div_float8(), cash_mi_cash(), cash_mul_float8(), cash_mul_int64(), cash_pl_cash(), cash_words(), cfb_process(), check_and_drop_existing_subscriptions(), check_field_number(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_is_install_user(), check_key_cksum(), check_key_sha1(), check_loadable_libraries(), check_locale(), check_locale_name(), check_new_cluster_logical_replication_slots(), check_new_cluster_subscription_configuration(), check_old_cluster_subscription_state(), check_param_number(), check_prepare_conn(), check_publications(), check_publications_origin(), check_publisher(), check_subscriber(), check_tuple_field_number(), checkcondition_str(), CheckForBufferLeaks(), clean_NOT_intree(), clean_stopword_intree(), close_cursor(), cmp_list_len_contents_asc(), cmpEntries(), cmpTheLexeme(), cnt_sml(), coerceJsonFuncExpr(), collectBinaryUpgradeClassOids(), collectComments(), collectMatchesForHeapRow(), collectRoleNames(), collectSecLabels(), collectSequences(), combo_decrypt(), combo_encrypt(), compareItems(), compareJsonbContainers(), comparePairs(), CompareTSQ(), compareWORD(), compile_database_list(), compile_relation_list_one_db(), ConditionalLockDatabaseObject(), ConditionalLockRelation(), ConditionalLockRelationOid(), ConditionalLockSharedObject(), confirm_query_canceled_impl(), connect_database(), contain_context_dependent_node_walker(), convert_charset(), convert_network_to_scalar(), convertToJsonb(), convertTSFunction(), copy_crlf(), copy_messages(), copy_table(), CopyLimitPrintoutLength(), copyTSLexeme(), cpstrdup(), create_cursor(), create_logical_replication_slot(), create_publication(), create_secmsg(), create_subscription(), createPQExpBuffer(), CreateReplicationSlot(), createViewAsClause(), crlf_process(), cube_cmp(), cube_contained(), cube_contains(), cube_eq(), cube_ge(), cube_gt(), cube_le(), cube_lt(), cube_ne(), cube_overlap(), cube_union(), datetime_to_char_body(), datumCopy(), datumIsEqual(), dblink_close(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), dblink_res_error(), deallocate_query(), decompose_code(), decrypt_elgamal(), decrypt_internal(), decrypt_key(), decrypt_read(), decrypt_rsa(), defaultNoticeReceiver(), describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), describeRoleGrants(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), determineNotNullFlags(), DetermineTimeZoneOffsetInternal(), dintdict_lexize(), discardUntilSync(), dispell_lexize(), do_field(), do_header(), do_lo_import(), do_sql_command_end(), do_watch(), downcase_convert(), drop_existing_subscriptions(), drop_failover_replication_slots(), drop_publication(), drop_replication_slot(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dsimple_lexize(), dsnowball_lexize(), dsynonym_lexize(), dump_lo_buf(), dumpAgg(), dumpBaseType(), dumpCollation(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDatabases(), dumpDomain(), dumpEnumType(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpRangeType(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSequence(), dumpSequenceData(), dumpStatisticsExt(), dumpTable(), dumpTableAttach(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTablespaces(), dumpTSConfig(), dumpTSDictionary(), dumpUserConfig(), dumpUserMappings(), duplicate_numeric(), dxsyn_lexize(), ecpg_build_compat_sqlda(), ecpg_build_native_sqlda(), ecpg_get_data(), ecpg_process_output(), ecpg_set_compat_sqlda(), ecpg_set_native_sqlda(), ECPGdescribe(), ECPGtrans(), emitShSecLabels(), enable_subscription(), encrypt_and_write_elgamal(), encrypt_and_write_rsa(), encrypt_init(), encrypt_internal(), encrypt_process(), EndDBCopyMode(), evalStandardFunc(), exec_command_password(), ExecEvalJsonConstructor(), ExecEvalJsonIsPredicate(), ExecEvalStepOp(), execute_foreign_modify(), execute_jsp_gin_node(), executeAnyItem(), executeBinaryArithmExpr(), executeBoolItem(), executeCommand(), executeDateTimeMethod(), executeItemOptUnwrapResult(), executeItemOptUnwrapResultNoThrow(), executeItemOptUnwrapTarget(), executeJsonPath(), executeKeyValueMethod(), executeMaintenanceCommand(), executeNestedBoolItem(), executePredicate(), executeQuery(), ExecuteSqlCommand(), ExecuteSqlQuery(), ExecuteSqlQueryForSingleRow(), ExecuteSqlStatement(), executeStatement(), expand_dbname_patterns(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fail_lo_xact(), fetch_more_data(), fetch_remote_table_info(), fetch_table_list(), finalize_windowaggregate(), find_among(), find_among_b(), find_next_mcelem(), find_provider(), find_window_run_conditions(), FindConflictTuple(), findTheLexeme(), finish_lo_xact(), float4_numeric(), float8_numeric(), g_cube_consistent(), g_int_union(), g_intbig_compress(), gbt_date_penalty(), gbt_datekey_cmp(), gbt_intvkey_cmp(), gbt_macad8key_cmp(), gbt_macadkey_cmp(), gbt_time_penalty(), gbt_timekey_cmp(), gbt_tskey_cmp(), gbt_uuidkey_cmp(), gbt_var_penalty(), gbt_vsrt_cmp(), gen_ossl_decrypt(), gen_ossl_encrypt(), generate_object_name(), generate_series_numeric_support(), get_create_object_cmd(), get_db_infos(), get_distance(), get_hex(), get_jsonb_path_all(), get_language_name(), get_loadable_libraries(), get_next_possible_free_pg_type_oid(), get_parallel_object_list(), get_primary_sysid(), get_remote_estimate(), get_subscription_count(), get_subscription_list(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getArrayIndex(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getDatumCopy(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getKeyJsonValueFromContainer(), GetLastImportantRecPtr(), getLOs(), getNamespaces(), getNextNearest(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), GetPrivateRefCountEntry(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), GetSubscriptionRelations(), getSubscriptions(), getSubscriptionTables(), getTableAttrs(), GetTableInfo(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), ghstore_alloc(), ghstore_compress(), ghstore_consistent(), gin_btree_compare_prefix(), gin_consistent_hstore(), gin_consistent_jsonb(), gin_consistent_jsonb_path(), gin_enum_cmp(), gin_numeric_cmp(), gin_trgm_consistent(), gin_trgm_triconsistent(), gin_triconsistent_jsonb(), gin_triconsistent_jsonb_path(), gin_tsquery_consistent(), gin_tsquery_triconsistent(), ginarrayconsistent(), ginarraytriconsistent(), ginCombineData(), ginint4_consistent(), ginint4_queryextract(), gintuple_get_attrnum(), gintuple_get_key(), gist_ischild(), gist_tqcmp(), gistFormTuple(), gistproperty(), gistSplit(), gtrgm_alloc(), gtrgm_compress(), gtrgm_consistent(), gtrgm_distance(), gtsvector_alloc(), gtsvector_compress(), handleCopyIn(), handleCopyOut(), HandleCopyStream(), HandleEndOfCopyStream(), HandleParallelApplyMessages(), HandleParallelMessages(), hashgetbitmap(), hashgettuple(), heap_lock_tuple(), heap_prune_satisfies_vacuum(), heapam_tuple_satisfies_snapshot(), HeapTupleSatisfiesNonVacuumable(), HeapTupleSatisfiesVacuum(), hemdist(), hstore_cmp(), hstore_contains(), hstore_defined(), hstore_each(), hstore_eq(), hstore_exists_all(), hstore_exists_any(), hstore_ge(), hstore_gt(), hstore_le(), hstore_lt(), hstore_ne(), hstore_to_jsonb(), hstore_to_jsonb_loose(), hstoreUniquePairs(), indexam_property(), indexOfColumn(), inetmi(), init_compress(), init_encdata_packet(), init_libpq_conn(), init_litdata_packet(), init_s2k_key(), initPopulateTable(), inner_subltree(), insertStatEntry(), int64_div_fast_to_numeric(), int64_to_numeric(), internal_read_key(), interval_to_char(), intervaltypmodout(), is_visible_fxid(), IteratorConcat(), itsdir(), join_tsqueries(), json_parse_manifest_incremental_chunk(), jsonb_cmp(), jsonb_concat(), jsonb_delete(), jsonb_delete_array(), jsonb_delete_idx(), jsonb_delete_path(), jsonb_eq(), jsonb_ge(), jsonb_get_element(), jsonb_gt(), jsonb_insert(), jsonb_le(), jsonb_lt(), jsonb_ne(), jsonb_path_exists_internal(), jsonb_set(), jsonb_set_element(), jsonb_strip_nulls(), JsonbExtractScalar(), JsonbValueToJsonb(), JsonItemFromDatum(), JsonPathExists(), jsonPathFromCstring(), JsonPathQuery(), JsonPathValue(), JsonTableResetRowPattern(), keyGetItem(), lca(), lca_inner(), lengthCompareJsonbPair(), LexizeExec(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtendedStats(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listLargeObjects(), listOneExtensionContents(), listOperatorClasses(), listOperatorFamilies(), listOpFamilyFunctions(), listOpFamilyOperators(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_close(), lo_creat(), lo_create(), lo_initialize(), lo_lseek(), lo_lseek64(), lo_open(), lo_read(), lo_tell(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_unlink(), lo_write(), locale_date_order(), LockRelation(), LockRelationId(), LockRelationOid(), lockTableForWorker(), logicalrep_pa_worker_count(), logicalrep_sync_worker_count(), logicalrep_worker_find(), logicalrep_workers_find(), LogicalRepSyncTableStart(), lookup_object_oid(), LPLRemoveHead(), lquery_in(), lquery_recv(), lquery_send(), lseg_inside_poly(), lt_q_regex(), ltq_regex(), ltree_cmp(), ltree_compare(), ltree_consistent(), ltree_eq(), ltree_ge(), ltree_gt(), ltree_in(), ltree_isparent(), ltree_le(), ltree_lt(), ltree_ne(), ltree_recv(), ltree_risparent(), ltree_send(), ltree_strncasecmp(), ltxtq_in(), ltxtq_recv(), mac8_2_uint64(), mac_2_uint64(), macaddr_abbrev_convert(), main(), make_attrmap(), make_tuple_from_result_row(), makeDefElem(), makeDefElemExtended(), makeStringInfo(), makeSublist(), matchIdSubst(), materializeQueryResult(), materializeResult(), mb_strchr(), mdc_finish(), mdc_flush(), mdc_init(), mdcbuf_finish(), mdcbuf_read(), mdcbuf_refill(), minimal_error_message(), network_abbrev_convert(), NewPrivateRefCountEntry(), newTParserPosition(), NINormalizeWord(), nlevel(), numeric_abs(), numeric_add(), numeric_add_opt_error(), numeric_ceil(), numeric_div(), numeric_div_opt_error(), numeric_div_trunc(), numeric_exp(), numeric_fac(), numeric_floor(), numeric_gcd(), numeric_in(), numeric_inc(), numeric_lcm(), numeric_ln(), numeric_log(), numeric_mod(), numeric_mod_opt_error(), numeric_mul(), numeric_mul_opt_error(), numeric_poly_stddev_pop(), numeric_poly_stddev_samp(), numeric_poly_sum(), numeric_poly_var_pop(), numeric_poly_var_samp(), numeric_power(), numeric_recv(), numeric_round(), numeric_sqrt(), numeric_stddev_internal(), numeric_stddev_pop(), numeric_stddev_samp(), numeric_sub(), numeric_sub_opt_error(), numeric_trim_scale(), numeric_trunc(), numeric_uminus(), numeric_var_pop(), numeric_var_samp(), numerictypmodout(), objectDescription(), oid_dist(), old_9_6_invalidate_hash_indexes(), optimize_window_clauses(), p_ishost(), p_isURLPath(), parse_args(), parse_compressed_data(), parse_literal_data(), parse_symenc_data(), parse_symenc_mdc_data(), parse_symenc_sesskey(), permissionsList(), pg_add_s16_overflow(), pg_add_s32_overflow(), pg_add_s64_overflow(), pg_add_u16_overflow(), pg_add_u32_overflow(), pg_add_u64_overflow(), pg_advisory_unlock_int4(), pg_advisory_unlock_int8(), pg_advisory_unlock_shared_int4(), pg_advisory_unlock_shared_int8(), pg_armor(), pg_atomic_fetch_add_u32_impl(), pg_crypt(), pg_dearmor(), pg_decrypt(), pg_decrypt_iv(), pg_digest(), pg_encrypt(), pg_encrypt_iv(), pg_get_constraintdef(), pg_get_constraintdef_ext(), pg_get_indexdef(), pg_get_indexdef_ext(), pg_get_line_append(), pg_get_partkeydef(), pg_get_ruledef(), pg_get_ruledef_ext(), pg_get_statisticsobjdef(), pg_get_statisticsobjdef_columns(), pg_get_triggerdef(), pg_get_triggerdef_ext(), pg_get_viewdef(), pg_get_viewdef_ext(), pg_get_viewdef_name(), pg_get_viewdef_name_ext(), pg_get_viewdef_wrap(), pg_hmac(), pg_lsn_mii(), pg_lsn_pli(), pg_mul_s16_overflow(), pg_mul_s32_overflow(), pg_mul_s64_overflow(), pg_mul_u16_overflow(), pg_mul_u32_overflow(), pg_mul_u64_overflow(), pg_neg_u16_overflow(), pg_neg_u32_overflow(), pg_neg_u64_overflow(), pg_random_bytes(), pg_SASL_continue(), pg_strong_random(), pg_sub_s16_overflow(), pg_sub_s32_overflow(), pg_sub_s64_overflow(), pg_try_advisory_lock_int4(), pg_try_advisory_lock_int8(), pg_try_advisory_lock_shared_int4(), pg_try_advisory_lock_shared_int8(), pg_try_advisory_xact_lock_int4(), pg_try_advisory_xact_lock_int8(), pg_try_advisory_xact_lock_shared_int4(), pg_try_advisory_xact_lock_shared_int8(), pgconn_bio_ctrl(), pgconn_bio_method(), pgconn_bio_read(), pgconn_bio_write(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), pgfdw_report_error(), pgfdw_xact_callback(), pgp_armor_decode(), pgp_armor_encode(), pgp_armor_headers(), pgp_cfb_create(), pgp_create_pkt_reader(), pgp_create_pkt_writer(), pgp_decrypt(), pgp_elgamal_decrypt(), pgp_elgamal_encrypt(), pgp_encrypt(), pgp_expect_packet_end(), pgp_get_keyid(), pgp_key_id_w(), pgp_load_cipher(), pgp_load_digest(), pgp_mpi_create(), pgp_mpi_read(), pgp_mpi_write(), pgp_parse_pkt_hdr(), pgp_parse_pubenc_sesskey(), pgp_pub_decrypt_bytea(), pgp_pub_decrypt_text(), pgp_pub_encrypt_bytea(), pgp_pub_encrypt_text(), pgp_rsa_decrypt(), pgp_rsa_encrypt(), pgp_s2k_fill(), pgp_s2k_process(), pgp_s2k_read(), pgp_set_pubkey(), pgp_skip_packet(), pgp_sym_decrypt_bytea(), pgp_sym_decrypt_text(), pgp_sym_encrypt_bytea(), pgp_sym_encrypt_text(), pgp_write_pubenc_sesskey(), pgwin32_bind(), pgwin32_listen(), pgwin32_putenv(), pgwin32_setenv(), pgwin32_unsetenv(), pgxml_result_to_text(), pkt_stream_flush(), pkt_stream_process(), pktreader_pull(), populate_domain(), populate_record(), populate_scalar(), port_bio_ctrl(), port_bio_read(), port_bio_write(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresGetAnalyzeInfoForForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqAddTuple(), PQbinaryTuples(), pqBuildErrorMessage3(), PQchangePassword(), PQclear(), PQcmdStatus(), PQcmdTuples(), PQconnectPoll(), PQdisplayTuples(), PQencryptPasswordConn(), PQfformat(), PQfireResultCreateEvents(), PQfmod(), PQfname(), PQfnumber(), PQfsize(), PQftable(), PQftablecol(), PQftype(), pqGetErrorNotice3(), PQgetisnull(), PQgetlength(), PQgetResult(), PQgetvalue(), pqInternalNotice(), PQnfields(), PQnparams(), PQntuples(), PQoidStatus(), PQoidValue(), PQparamtype(), pqPrepareAsyncResult(), PQprint(), PQprintTuples(), PQresultAlloc(), pqResultAlloc(), PQresultErrorField(), PQresultErrorMessage(), PQresultMemorySize(), PQresultStatus(), pqResultStrdup(), PQresultVerboseErrorMessage(), pqRowProcessor(), pqSaveMessageField(), PQsetClientEncoding(), PQsetResultAttrs(), pqSetResultError(), PQsetvalue(), prepare_foreign_modify(), prepareCommand(), PrintManyTest(), PrintResultInCrosstab(), printResultSet(), PrintString(), printTypmod(), process_data_packets(), process_data_type_check(), process_extension_updates(), process_incompat_polymorphics(), process_isn_and_int8_passing_mismatch(), process_loadable_libraries(), process_old_cluster_logical_slot_infos(), process_old_sub_state_check(), process_query_result(), process_queued_fetch_requests(), process_rel_infos(), process_result(), process_secret_key(), process_user_defined_encoding_conversions(), process_user_defined_postfix_ops(), process_with_oids_check(), processExtensionTables(), PSQLexec(), PSQLexecWatch(), pullf_create(), pullf_read(), pullf_read_fixed(), pullf_read_max(), pushf_create(), pushf_create_mbuf_writer(), pushf_flush(), pushf_write(), pushJsonbValue(), px_find_cipher(), px_find_combo(), px_find_digest(), px_find_hmac(), qsortCompareItemPointers(), QTNodeCompare(), quote_postgres(), random_numeric(), read_pubenc_keyid(), read_pubkey_keyid(), readCommandResponse(), readDatum(), ReadEndOfStreamingResult(), ReadInt(), readTimeLineHistory(), reap_child(), ReceiveCopyData(), ReceiveXlogStream(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), ReleaseManyTestResource(), ReleaseString(), ReplicationSlotDropAtPubNode(), ReservePrivateRefCountEntry(), ResOwnerPrintBufferIO(), ResOwnerPrintBufferPin(), ResOwnerPrintCatCache(), ResOwnerPrintCatCacheList(), ResOwnerPrintDSM(), ResOwnerPrintFile(), ResOwnerPrintRelCache(), ResOwnerPrintTupleDesc(), ResOwnerReleaseBufferIO(), ResOwnerReleaseBufferPin(), ResOwnerReleaseCachedPlan(), ResOwnerReleaseCatCache(), ResOwnerReleaseCatCacheList(), ResOwnerReleaseCryptoHash(), ResOwnerReleaseDSM(), ResOwnerReleaseFile(), ResOwnerReleaseHMAC(), ResOwnerReleaseJitContext(), ResOwnerReleaseOSSLCipher(), ResOwnerReleaseOSSLDigest(), ResOwnerReleaseRelation(), ResOwnerReleaseSnapshot(), ResOwnerReleaseTupleDesc(), ResOwnerReleaseWaitEventSet(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_crypt_des(), run_crypt_md5(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), runShellCommand(), sampler_random_fract(), server_is_in_recovery(), set_arg(), set_replication_progress(), set_restrict_relation_kind(), setNewTmpRes(), setPath(), setup_publisher(), shm_mq_receive(), shm_mq_sendv(), should_processing_continue(), should_refetch_tuple(), show_binary_results(), silly_cmp_tsvector(), similarity(), similarity_dist(), similarity_op(), socket_flush(), socket_flush_if_writable(), socket_putmessage_noblock(), SortAndUniqItems(), spg_quad_leaf_consistent(), spg_range_quad_leaf_consistent(), spg_text_inner_consistent(), spg_text_leaf_consistent(), spgist_name_inner_consistent(), spgist_name_leaf_consistent(), spgproperty(), SPI_execute(), SPI_execute_extended(), SPI_execute_plan(), SPI_execute_plan_extended(), SPI_execute_plan_with_paramlist(), SPI_execute_snapshot(), SPI_execute_with_args(), SPI_finish(), SPI_fnumber(), SPI_register_relation(), SPI_unregister_relation(), sql_conn(), sql_exec(), sqlda_common_total_size(), sqlda_compat_empty_size(), sqlda_compat_total_size(), sqlda_native_empty_size(), sqlda_native_total_size(), start_lo_xact(), store_returning_result(), storeQueryResult(), storeRow(), StreamLogicalLog(), strict_word_similarity(), strict_word_similarity_commutator_op(), strict_word_similarity_dist_commutator_op(), strict_word_similarity_dist_op(), strict_word_similarity_op(), stringlist_to_identifierstr(), strip_trailing_ws(), subltree(), subpath(), sv2cstr(), symencrypt_sesskey(), synchronize_slots(), TableCommandResultHandler(), tarRead(), tarWrite(), test_disallowed_in_pipeline(), test_indoption(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), test_pipeline_idle(), test_pipelined_insert(), test_prepared(), test_shm_mq(), test_shm_mq_pipelined(), test_simple_pipeline(), test_singlerowmode(), test_transaction(), test_uniqviol(), textarray_to_stringlist(), thesaurus_lexize(), timestamp_to_char(), timestamptz_to_char(), toast_open_indexes(), transform_jsonb_string_values(), transformTargetList(), trgm_contained_by(), trgm_presence_map(), try_complete_step(), tryExecuteStatement(), ts_lexize(), ts_match_tq(), ts_match_tt(), ts_rank_tt(), ts_rank_ttf(), ts_rank_wtt(), ts_rank_wttf(), ts_rankcd_tt(), ts_rankcd_ttf(), ts_rankcd_wtt(), ts_rankcd_wttf(), tsquery_and(), tsquery_cmp(), tsquery_not(), tsquery_or(), tsquery_phrase_distance(), tsquerytree(), tuple_data_split(), unaccent_dict(), unaccent_lexize(), uniqueentry(), uniqueifyJsonbObject(), uniquePos(), uniqueWORD(), uuid_abbrev_convert(), vacuum_one_database(), vacuumlo(), validate_remote_info(), varstr_abbrev_convert(), verify_btree_slot_handler(), verify_heap_slot_handler(), wait_for_connection_state(), WinRowsArePeers(), word_similarity(), word_similarity_commutator_op(), word_similarity_dist_commutator_op(), word_similarity_dist_op(), word_similarity_op(), wrap_process(), write_prefix(), write_symenc_sesskey(), WriteStr(), xpath_bool(), xpath_list(), xpath_nodeset(), xpath_number(), xpath_string(), and xpath_table().