PostgreSQL Source Code  git master
dblink.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/table.h"
#include "catalog/namespace.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_type.h"
#include "catalog/pg_user_mapping.h"
#include "executor/spi.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "libpq-fe.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "parser/scansup.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/varlena.h"
Include dependency graph for dblink.c:

Go to the source code of this file.

Data Structures

struct  remoteConn
 
struct  storeInfo
 
struct  remoteConnHashEnt
 

Macros

#define NUMCONN   16
 
#define DBLINK_NOTIFY_COLS   3
 

Typedefs

typedef struct remoteConn remoteConn
 
typedef struct storeInfo storeInfo
 
typedef struct remoteConnHashEnt remoteConnHashEnt
 

Functions

static Datum dblink_record_internal (FunctionCallInfo fcinfo, bool is_async)
 
static void prepTuplestoreResult (FunctionCallInfo fcinfo)
 
static void materializeResult (FunctionCallInfo fcinfo, PGconn *conn, PGresult *res)
 
static void materializeQueryResult (FunctionCallInfo fcinfo, PGconn *conn, const char *conname, const char *sql, bool fail)
 
static PGresultstoreQueryResult (volatile storeInfo *sinfo, PGconn *conn, const char *sql)
 
static void storeRow (volatile storeInfo *sinfo, PGresult *res, bool first)
 
static remoteConngetConnectionByName (const char *name)
 
static HTABcreateConnHash (void)
 
static void createNewConnection (const char *name, remoteConn *rconn)
 
static void deleteConnection (const char *name)
 
static char ** get_pkey_attnames (Relation rel, int16 *indnkeyatts)
 
static char ** get_text_array_contents (ArrayType *array, int *numitems)
 
static char * get_sql_insert (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static char * get_sql_delete (Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
 
static char * get_sql_update (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static char * quote_ident_cstr (char *rawstr)
 
static int get_attnum_pk_pos (int *pkattnums, int pknumatts, int key)
 
static HeapTuple get_tuple_of_interest (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
 
static Relation get_rel_from_relname (text *relname_text, LOCKMODE lockmode, AclMode aclmode)
 
static char * generate_relation_name (Relation rel)
 
static void dblink_connstr_check (const char *connstr)
 
static void dblink_security_check (PGconn *conn, remoteConn *rconn)
 
static void dblink_res_error (PGconn *conn, const char *conname, PGresult *res, bool fail, const char *fmt,...) pg_attribute_printf(5
 
static void static char * get_connect_string (const char *servername)
 
static char * escape_param_str (const char *from)
 
static void validate_pkattnums (Relation rel, int2vector *pkattnums_arg, int32 pknumatts_arg, int **pkattnums, int *pknumatts)
 
static bool is_valid_dblink_option (const PQconninfoOption *options, const char *option, Oid context)
 
static int applyRemoteGucs (PGconn *conn)
 
static void restoreLocalGucs (int nestlevel)
 
static char * xpstrdup (const char *in)
 
static void pg_attribute_noreturn () dblink_res_internalerror(PGconn *conn
 
 if (res)
 
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 void PGresultres
 
static void PGresult const char * p2
 

Macro Definition Documentation

◆ DBLINK_NOTIFY_COLS

#define DBLINK_NOTIFY_COLS   3

Definition at line 1921 of file dblink.c.

◆ NUMCONN

#define NUMCONN   16

Definition at line 144 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 3037 of file dblink.c.

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

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

2578 {
2579  HASHCTL ctl;
2580 
2581  ctl.keysize = NAMEDATALEN;
2582  ctl.entrysize = sizeof(remoteConnHashEnt);
2583 
2584  return hash_create("Remote Con hash", NUMCONN, &ctl,
2586 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
#define HASH_STRINGS
Definition: hsearch.h:96
#define HASH_ELEM
Definition: hsearch.h:95
#define NAMEDATALEN
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76

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

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

◆ createNewConnection()

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

Definition at line 2589 of file dblink.c.

2590 {
2591  remoteConnHashEnt *hentry;
2592  bool found;
2593  char *key;
2594 
2595  if (!remoteConnHash)
2597 
2598  key = pstrdup(name);
2599  truncate_identifier(key, strlen(key), true);
2601  HASH_ENTER, &found);
2602 
2603  if (found)
2604  {
2605  PQfinish(rconn->conn);
2607  pfree(rconn);
2608 
2609  ereport(ERROR,
2611  errmsg("duplicate connection name")));
2612  }
2613 
2614  hentry->rconn = rconn;
2615  strlcpy(hentry->name, name, sizeof(hentry->name));
2616 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
const char * name
Definition: encode.c:561
void ReleaseExternalFD(void)
Definition: fd.c:1230
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4261
@ HASH_ENTER
Definition: hsearch.h:114
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void pfree(void *pointer)
Definition: mcxt.c:1175
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
char name[NAMEDATALEN]
Definition: dblink.c:139
remoteConn * rconn
Definition: dblink.c:140
PGconn * conn
Definition: dblink.c:67

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

Referenced by dblink_connect().

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1752 of file dblink.c.

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

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

1664 {
1665  text *relname_text = PG_GETARG_TEXT_PP(0);
1666  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1667  int32 pknumatts_arg = PG_GETARG_INT32(2);
1668  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1669  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1670  Relation rel;
1671  int *pkattnums;
1672  int pknumatts;
1673  char **src_pkattvals;
1674  char **tgt_pkattvals;
1675  int src_nitems;
1676  int tgt_nitems;
1677  char *sql;
1678 
1679  /*
1680  * Open target relation.
1681  */
1682  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1683 
1684  /*
1685  * Process pkattnums argument.
1686  */
1687  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1688  &pkattnums, &pknumatts);
1689 
1690  /*
1691  * Source array is made up of key values that will be used to locate the
1692  * tuple of interest from the local system.
1693  */
1694  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1695 
1696  /*
1697  * There should be one source array key value for each key attnum
1698  */
1699  if (src_nitems != pknumatts)
1700  ereport(ERROR,
1701  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1702  errmsg("source key array length must match number of key attributes")));
1703 
1704  /*
1705  * Target array is made up of key values that will be used to build the
1706  * SQL string for use on the remote system.
1707  */
1708  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1709 
1710  /*
1711  * There should be one target array key value for each key attnum
1712  */
1713  if (tgt_nitems != pknumatts)
1714  ereport(ERROR,
1715  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1716  errmsg("target key array length must match number of key attributes")));
1717 
1718  /*
1719  * Prep work is finally done. Go get the SQL string.
1720  */
1721  sql = get_sql_insert(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1722 
1723  /*
1724  * Now we can close the relation.
1725  */
1727 
1728  /*
1729  * And send it
1730  */
1732 }

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

1829 {
1830  text *relname_text = PG_GETARG_TEXT_PP(0);
1831  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1832  int32 pknumatts_arg = PG_GETARG_INT32(2);
1833  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1834  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1835  Relation rel;
1836  int *pkattnums;
1837  int pknumatts;
1838  char **src_pkattvals;
1839  char **tgt_pkattvals;
1840  int src_nitems;
1841  int tgt_nitems;
1842  char *sql;
1843 
1844  /*
1845  * Open target relation.
1846  */
1847  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1848 
1849  /*
1850  * Process pkattnums argument.
1851  */
1852  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1853  &pkattnums, &pknumatts);
1854 
1855  /*
1856  * Source array is made up of key values that will be used to locate the
1857  * tuple of interest from the local system.
1858  */
1859  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1860 
1861  /*
1862  * There should be one source array key value for each key attnum
1863  */
1864  if (src_nitems != pknumatts)
1865  ereport(ERROR,
1866  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1867  errmsg("source key array length must match number of key attributes")));
1868 
1869  /*
1870  * Target array is made up of key values that will be used to build the
1871  * SQL string for use on the remote system.
1872  */
1873  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1874 
1875  /*
1876  * There should be one target array key value for each key attnum
1877  */
1878  if (tgt_nitems != pknumatts)
1879  ereport(ERROR,
1880  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1881  errmsg("target key array length must match number of key attributes")));
1882 
1883  /*
1884  * Prep work is finally done. Go get the SQL string.
1885  */
1886  sql = get_sql_update(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1887 
1888  /*
1889  * Now we can close the relation.
1890  */
1892 
1893  /*
1894  * And send it
1895  */
1897 }

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

1381 {
1382  int res;
1383  PGconn *conn;
1384  PGcancel *cancel;
1385  char errbuf[256];
1386 
1387  dblink_init();
1389  cancel = PQgetCancel(conn);
1390 
1391  res = PQcancel(cancel, errbuf, 256);
1392  PQfreeCancel(cancel);
1393 
1394  if (res == 1)
1396  else
1398 }
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4366
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4481
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4434
char * text_to_cstring(const text *t)
Definition: varlena.c:221

References conn, cstring_to_text(), dblink_get_named_conn(), dblink_init(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PQcancel(), PQfreeCancel(), PQgetCancel(), res, and text_to_cstring().

◆ dblink_close()

Datum dblink_close ( PG_FUNCTION_ARGS  )

Definition at line 517 of file dblink.c.

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

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

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 280 of file dblink.c.

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

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

◆ dblink_connstr_check()

static void dblink_connstr_check ( const char *  connstr)
static

Definition at line 2667 of file dblink.c.

2668 {
2669  if (!superuser())
2670  {
2673  bool connstr_gives_password = false;
2674 
2675  options = PQconninfoParse(connstr, NULL);
2676  if (options)
2677  {
2678  for (option = options; option->keyword != NULL; option++)
2679  {
2680  if (strcmp(option->keyword, "password") == 0)
2681  {
2682  if (option->val != NULL && option->val[0] != '\0')
2683  {
2684  connstr_gives_password = true;
2685  break;
2686  }
2687  }
2688  }
2690  }
2691 
2692  if (!connstr_gives_password)
2693  ereport(ERROR,
2694  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2695  errmsg("password is required"),
2696  errdetail("Non-superusers must provide a password in the connection string.")));
2697  }
2698 }
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5501
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6736
static char ** options
int val
Definition: getopt_long.h:21
bool superuser(void)
Definition: superuser.c:46

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

Referenced by dblink_connect(), and dblink_get_conn().

◆ dblink_current_query()

Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1907 of file dblink.c.

1908 {
1909  /* This is now just an alias for the built-in function current_query() */
1910  PG_RETURN_DATUM(current_query(fcinfo));
1911 }
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:191
#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 385 of file dblink.c.

386 {
387  char *conname = NULL;
388  remoteConn *rconn = NULL;
389  PGconn *conn = NULL;
390 
391  dblink_init();
392 
393  if (PG_NARGS() == 1)
394  {
395  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
396  rconn = getConnectionByName(conname);
397  if (rconn)
398  conn = rconn->conn;
399  }
400  else
401  conn = pconn->conn;
402 
403  if (!conn)
404  dblink_conn_not_avail(conname);
405 
406  PQfinish(conn);
408  if (rconn)
409  {
410  deleteConnection(conname);
411  pfree(rconn);
412  }
413  else
414  pconn->conn = NULL;
415 
417 }

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

◆ dblink_error_message()

Datum dblink_error_message ( PG_FUNCTION_ARGS  )

Definition at line 1413 of file dblink.c.

1414 {
1415  char *msg;
1416  PGconn *conn;
1417 
1418  dblink_init();
1420 
1421  msg = PQerrorMessage(conn);
1422  if (msg == NULL || msg[0] == '\0')
1424  else
1426 }

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

1434 {
1435  text *volatile sql_cmd_status = NULL;
1436  PGconn *volatile conn = NULL;
1437  volatile bool freeconn = false;
1438 
1439  dblink_init();
1440 
1441  PG_TRY();
1442  {
1443  PGresult *res = NULL;
1444  char *sql = NULL;
1445  char *conname = NULL;
1446  bool fail = true; /* default to backward compatible behavior */
1447 
1448  if (PG_NARGS() == 3)
1449  {
1450  /* must be text,text,bool */
1451  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1453  fail = PG_GETARG_BOOL(2);
1454  dblink_get_conn(conname, &conn, &conname, &freeconn);
1455  }
1456  else if (PG_NARGS() == 2)
1457  {
1458  /* might be text,text or text,bool */
1459  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1460  {
1462  fail = PG_GETARG_BOOL(1);
1463  conn = pconn->conn;
1464  }
1465  else
1466  {
1467  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1469  dblink_get_conn(conname, &conn, &conname, &freeconn);
1470  }
1471  }
1472  else if (PG_NARGS() == 1)
1473  {
1474  /* must be single text argument */
1475  conn = pconn->conn;
1477  }
1478  else
1479  /* shouldn't happen */
1480  elog(ERROR, "wrong number of arguments");
1481 
1482  if (!conn)
1483  dblink_conn_not_avail(conname);
1484 
1485  res = PQexec(conn, sql);
1486  if (!res ||
1489  {
1490  dblink_res_error(conn, conname, res, fail,
1491  "while executing command");
1492 
1493  /*
1494  * and save a copy of the command status string to return as our
1495  * result tuple
1496  */
1497  sql_cmd_status = cstring_to_text("ERROR");
1498  }
1499  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1500  {
1501  /*
1502  * and save a copy of the command status string to return as our
1503  * result tuple
1504  */
1505  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1506  PQclear(res);
1507  }
1508  else
1509  {
1510  PQclear(res);
1511  ereport(ERROR,
1512  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1513  errmsg("statement returning results not allowed")));
1514  }
1515  }
1516  PG_FINALLY();
1517  {
1518  /* if needed, close the connection to the database */
1519  if (freeconn)
1520  {
1521  PQfinish(conn);
1523  }
1524  }
1525  PG_END_TRY();
1526 
1527  PG_RETURN_TEXT_P(sql_cmd_status);
1528 }
#define PG_END_TRY()
Definition: elog.h:324
#define PG_TRY()
Definition: elog.h:299
#define PG_FINALLY()
Definition: elog.h:316
#define elog(elevel,...)
Definition: elog.h:218
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3611
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100

References remoteConn::conn, conn, cstring_to_text(), dblink_get_conn(), dblink_init(), dblink_res_error(), elog, ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), 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(), PQexec(), PQfinish(), PQresultStatus(), ReleaseExternalFD(), res, and text_to_cstring().

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 1978 of file dblink.c.

1979 {
1980  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
1981  Oid context = PG_GETARG_OID(1);
1982  ListCell *cell;
1983 
1984  static const PQconninfoOption *options = NULL;
1985 
1986  /*
1987  * Get list of valid libpq options.
1988  *
1989  * To avoid unnecessary work, we get the list once and use it throughout
1990  * the lifetime of this backend process. We don't need to care about
1991  * memory context issues, because PQconndefaults allocates with malloc.
1992  */
1993  if (!options)
1994  {
1995  options = PQconndefaults();
1996  if (!options) /* assume reason for failure is OOM */
1997  ereport(ERROR,
1998  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
1999  errmsg("out of memory"),
2000  errdetail("Could not get libpq's default connection options.")));
2001  }
2002 
2003  /* Validate each supplied option. */
2004  foreach(cell, options_list)
2005  {
2006  DefElem *def = (DefElem *) lfirst(cell);
2007 
2008  if (!is_valid_dblink_option(options, def->defname, context))
2009  {
2010  /*
2011  * Unknown option, or invalid option for the context specified, so
2012  * complain about it. Provide a hint with list of valid options
2013  * for the context.
2014  */
2016  const PQconninfoOption *opt;
2017 
2018  initStringInfo(&buf);
2019  for (opt = options; opt->keyword; opt++)
2020  {
2021  if (is_valid_dblink_option(options, opt->keyword, context))
2022  appendStringInfo(&buf, "%s%s",
2023  (buf.len > 0) ? ", " : "",
2024  opt->keyword);
2025  }
2026  ereport(ERROR,
2027  (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
2028  errmsg("invalid option \"%s\"", def->defname),
2029  buf.len > 0
2030  ? errhint("Valid options in this context are: %s",
2031  buf.data)
2032  : errhint("There are no valid options in this context.")));
2033  }
2034  }
2035 
2036  PG_RETURN_VOID();
2037 }
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1477
#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
#define lfirst(lc)
Definition: pg_list.h:169
unsigned int Oid
Definition: postgres_ext.h:31
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1334
char * defname
Definition: parsenodes.h:765
Definition: pg_list.h:51

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

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

Definition at line 604 of file dblink.c.

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

References appendStringInfo(), buf, remoteConn::conn, conn, dblink_init(), dblink_res_error(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), materializeResult(), pconn, PG_GETARG_BOOL, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_NARGS, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQexec(), 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 180 of file dblink.c.

182 {
183  remoteConn *rconn = getConnectionByName(conname_or_str);
184  PGconn *conn;
185  char *conname;
186  bool freeconn;
187 
188  if (rconn)
189  {
190  conn = rconn->conn;
191  conname = conname_or_str;
192  freeconn = false;
193  }
194  else
195  {
196  const char *connstr;
197 
198  connstr = get_connect_string(conname_or_str);
199  if (connstr == NULL)
200  connstr = conname_or_str;
202 
203  /*
204  * We must obey fd.c's limit on non-virtual file descriptors. Assume
205  * that a PGconn represents one long-lived FD. (Doing this here also
206  * ensures that VFDs are closed if needed to make room.)
207  */
208  if (!AcquireExternalFD())
209  {
210 #ifndef WIN32 /* can't write #if within ereport() macro */
211  ereport(ERROR,
212  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
213  errmsg("could not establish connection"),
214  errdetail("There are too many open files on the local server."),
215  errhint("Raise the server's max_files_per_process and/or \"ulimit -n\" limits.")));
216 #else
217  ereport(ERROR,
218  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
219  errmsg("could not establish connection"),
220  errdetail("There are too many open files on the local server."),
221  errhint("Raise the server's max_files_per_process setting.")));
222 #endif
223  }
224 
225  /* OK to make connection */
227 
228  if (PQstatus(conn) == CONNECTION_BAD)
229  {
230  char *msg = pchomp(PQerrorMessage(conn));
231 
232  PQfinish(conn);
234  ereport(ERROR,
235  (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
236  errmsg("could not establish connection"),
237  errdetail_internal("%s", msg)));
238  }
239  dblink_security_check(conn, rconn);
242  freeconn = true;
243  conname = NULL;
244  }
245 
246  *conn_p = conn;
247  *conname_p = conname;
248  *freeconn_p = freeconn;
249 }

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

Referenced by dblink_exec(), and dblink_record_internal().

◆ dblink_get_connections()

Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1321 of file dblink.c.

1322 {
1324  remoteConnHashEnt *hentry;
1325  ArrayBuildState *astate = NULL;
1326 
1327  if (remoteConnHash)
1328  {
1330  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1331  {
1332  /* stash away current value */
1333  astate = accumArrayResult(astate,
1334  CStringGetTextDatum(hentry->name),
1335  false, TEXTOID, CurrentMemoryContext);
1336  }
1337  }
1338 
1339  if (astate)
1342  else
1343  PG_RETURN_NULL();
1344 }
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:258
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5123
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5187
#define CStringGetTextDatum(s)
Definition: builtins.h:85
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1436
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1426
#define PG_RETURN_NULL()
Definition: fmgr.h:345
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229

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

◆ dblink_get_named_conn()

static PGconn* dblink_get_named_conn ( const char *  conname)
static

Definition at line 252 of file dblink.c.

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

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

1926 {
1927  PGconn *conn;
1928  PGnotify *notify;
1929  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1930 
1931  dblink_init();
1932  if (PG_NARGS() == 1)
1934  else
1935  conn = pconn->conn;
1936 
1937  SetSingleFuncCall(fcinfo, 0);
1938 
1940  while ((notify = PQnotifies(conn)) != NULL)
1941  {
1943  bool nulls[DBLINK_NOTIFY_COLS];
1944 
1945  memset(values, 0, sizeof(values));
1946  memset(nulls, 0, sizeof(nulls));
1947 
1948  if (notify->relname != NULL)
1949  values[0] = CStringGetTextDatum(notify->relname);
1950  else
1951  nulls[0] = true;
1952 
1953  values[1] = Int32GetDatum(notify->be_pid);
1954 
1955  if (notify->extra != NULL)
1956  values[2] = CStringGetTextDatum(notify->extra);
1957  else
1958  nulls[2] = true;
1959 
1960  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1961 
1962  PQfreemem(notify);
1964  }
1965 
1966  return (Datum) 0;
1967 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
void PQfreemem(void *ptr)
Definition: fe-exec.c:3891
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2599
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:2004
void SetSingleFuncCall(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
#define Int32GetDatum(X)
Definition: postgres.h:523
TupleDesc setDesc
Definition: execnodes.h:317
Tuplestorestate * setResult
Definition: execnodes.h:316
int be_pid
Definition: libpq-fe.h:190
char * relname
Definition: libpq-fe.h:189
char * extra
Definition: libpq-fe.h:191
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750

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

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1539 of file dblink.c.

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

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(), 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 730 of file dblink.c.

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

References dblink_record_internal().

◆ dblink_init()

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1356 of file dblink.c.

1357 {
1358  PGconn *conn;
1359 
1360  dblink_init();
1362 
1365 }
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2051
#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 424 of file dblink.c.

425 {
426  PGresult *res = NULL;
427  PGconn *conn;
428  char *curname = NULL;
429  char *sql = NULL;
430  char *conname = NULL;
432  remoteConn *rconn = NULL;
433  bool fail = true; /* default to backward compatible behavior */
434 
435  dblink_init();
437 
438  if (PG_NARGS() == 2)
439  {
440  /* text,text */
441  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
443  rconn = pconn;
444  }
445  else if (PG_NARGS() == 3)
446  {
447  /* might be text,text,text or text,text,bool */
448  if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
449  {
450  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
452  fail = PG_GETARG_BOOL(2);
453  rconn = pconn;
454  }
455  else
456  {
457  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
458  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
460  rconn = getConnectionByName(conname);
461  }
462  }
463  else if (PG_NARGS() == 4)
464  {
465  /* text,text,text,bool */
466  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
467  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
469  fail = PG_GETARG_BOOL(3);
470  rconn = getConnectionByName(conname);
471  }
472 
473  if (!rconn || !rconn->conn)
474  dblink_conn_not_avail(conname);
475 
476  conn = rconn->conn;
477 
478  /* If we are not in a transaction, start one */
480  {
481  res = PQexec(conn, "BEGIN");
483  dblink_res_internalerror(conn, res, "begin error");
484  PQclear(res);
485  rconn->newXactForCursor = true;
486 
487  /*
488  * Since transaction state was IDLE, we force cursor count to
489  * initially be 0. This is needed as a previous ABORT might have wiped
490  * out our transaction without maintaining the cursor count for us.
491  */
492  rconn->openCursorCount = 0;
493  }
494 
495  /* if we started a transaction, increment cursor count */
496  if (rconn->newXactForCursor)
497  (rconn->openCursorCount)++;
498 
499  appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
500  res = PQexec(conn, buf.data);
502  {
503  dblink_res_error(conn, conname, res, fail,
504  "while opening cursor \"%s\"", curname);
506  }
507 
508  PQclear(res);
510 }
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6863
@ PQTRANS_IDLE
Definition: libpq-fe.h:118

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

◆ dblink_record()

Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 698 of file dblink.c.

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

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 736 of file dblink.c.

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

References remoteConn::conn, conn, dblink_get_conn(), dblink_get_named_conn(), dblink_init(), dblink_res_error(), elog, ERROR, FunctionCallInfoBaseData::flinfo, get_fn_expr_argtype(), materializeQueryResult(), materializeResult(), pconn, PG_END_TRY, PG_FINALLY, PG_GETARG_BOOL, PG_GETARG_TEXT_PP, PG_NARGS, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQfinish(), PQgetResult(), PQresultStatus(), prepTuplestoreResult(), ReleaseExternalFD(), 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 2709 of file dblink.c.

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

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 
)
static

Definition at line 2640 of file dblink.c.

2641 {
2642  if (!superuser())
2643  {
2645  {
2646  PQfinish(conn);
2648  if (rconn)
2649  pfree(rconn);
2650 
2651  ereport(ERROR,
2652  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2653  errmsg("password is required"),
2654  errdetail("Non-superuser cannot connect if the server does not request a password."),
2655  errhint("Target server's authentication method must be changed.")));
2656  }
2657  }
2658 }
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:6974

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

Referenced by dblink_connect(), and dblink_get_conn().

◆ dblink_send_query()

Datum dblink_send_query ( PG_FUNCTION_ARGS  )

Definition at line 705 of file dblink.c.

706 {
707  PGconn *conn;
708  char *sql;
709  int retval;
710 
711  if (PG_NARGS() == 2)
712  {
715  }
716  else
717  /* shouldn't happen */
718  elog(ERROR, "wrong number of arguments");
719 
720  /* async query send */
721  retval = PQsendQuery(conn, sql);
722  if (retval != 1)
723  elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
724 
725  PG_RETURN_INT32(retval);
726 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1424

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

2620 {
2621  remoteConnHashEnt *hentry;
2622  bool found;
2623  char *key;
2624 
2625  if (!remoteConnHash)
2627 
2628  key = pstrdup(name);
2629  truncate_identifier(key, strlen(key), false);
2631  key, HASH_REMOVE, &found);
2632 
2633  if (!hentry)
2634  ereport(ERROR,
2635  (errcode(ERRCODE_UNDEFINED_OBJECT),
2636  errmsg("undefined connection name")));
2637 }
@ 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().

◆ escape_param_str()

static char * escape_param_str ( const char *  from)
static

Definition at line 2882 of file dblink.c.

2883 {
2884  const char *cp;
2886 
2887  initStringInfo(&buf);
2888 
2889  for (cp = str; *cp; cp++)
2890  {
2891  if (*cp == '\\' || *cp == '\'')
2892  appendStringInfoChar(&buf, '\\');
2893  appendStringInfoChar(&buf, *cp);
2894  }
2895 
2896  return buf.data;
2897 }
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188

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

Referenced by get_connect_string().

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

Definition at line 2539 of file dblink.c.

2540 {
2541  char *nspname;
2542  char *result;
2543 
2544  /* Qualify the name if not visible in search path */
2546  nspname = NULL;
2547  else
2548  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2549 
2550  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2551 
2552  return result;
2553 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
bool RelationIsVisible(Oid relid)
Definition: namespace.c:710
#define RelationGetRelid(relation)
Definition: rel.h:489
#define RelationGetRelationName(relation)
Definition: rel.h:523
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12247
Form_pg_class rd_rel
Definition: rel.h:109

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

2387 {
2388  int i;
2389 
2390  /*
2391  * Not likely a long list anyway, so just scan for the value
2392  */
2393  for (i = 0; i < pknumatts; i++)
2394  if (key == pkattnums[i])
2395  return i;
2396 
2397  return -1;
2398 }

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

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

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_FOREIGN_SERVER, ForeignDataWrapper::options, ForeignServer::options, UserMapping::options, pg_foreign_server_aclcheck(), PQconndefaults(), pstrdup(), ForeignServer::serverid, ForeignServer::servername, strVal, and truncate_identifier().

Referenced by dblink_connect(), and dblink_get_conn().

◆ get_pkey_attnames()

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

Definition at line 2052 of file dblink.c.

2053 {
2054  Relation indexRelation;
2055  ScanKeyData skey;
2056  SysScanDesc scan;
2057  HeapTuple indexTuple;
2058  int i;
2059  char **result = NULL;
2060  TupleDesc tupdesc;
2061 
2062  /* initialize indnkeyatts to 0 in case no primary key exists */
2063  *indnkeyatts = 0;
2064 
2065  tupdesc = rel->rd_att;
2066 
2067  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2068  indexRelation = table_open(IndexRelationId, AccessShareLock);
2069  ScanKeyInit(&skey,
2070  Anum_pg_index_indrelid,
2071  BTEqualStrategyNumber, F_OIDEQ,
2073 
2074  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2075  NULL, 1, &skey);
2076 
2077  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2078  {
2079  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2080 
2081  /* we're only interested if it is the primary key */
2082  if (index->indisprimary)
2083  {
2084  *indnkeyatts = index->indnkeyatts;
2085  if (*indnkeyatts > 0)
2086  {
2087  result = (char **) palloc(*indnkeyatts * sizeof(char *));
2088 
2089  for (i = 0; i < *indnkeyatts; i++)
2090  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2091  }
2092  break;
2093  }
2094  }
2095 
2096  systable_endscan(scan);
2097  table_close(indexRelation, AccessShareLock);
2098 
2099  return result;
2100 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
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:1196
#define BTEqualStrategyNumber
Definition: stratnum.h:31
TupleDesc rd_att
Definition: rel.h:110
Definition: type.h:90
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

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

Referenced by dblink_get_pkey().

◆ get_rel_from_relname()

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

Definition at line 2514 of file dblink.c.

2515 {
2516  RangeVar *relvar;
2517  Relation rel;
2518  AclResult aclresult;
2519 
2520  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2521  rel = table_openrv(relvar, lockmode);
2522 
2523  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2524  aclmode);
2525  if (aclresult != ACLCHECK_OK)
2526  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2528 
2529  return rel;
2530 }
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:5007
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3108
ObjectType get_relkind_objtype(char relkind)
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3657

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

2244 {
2245  char *relname;
2246  TupleDesc tupdesc;
2248  int i;
2249 
2250  initStringInfo(&buf);
2251 
2252  /* get relation name including any needed schema prefix and quoting */
2254 
2255  tupdesc = rel->rd_att;
2256 
2257  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2258  for (i = 0; i < pknumatts; i++)
2259  {
2260  int pkattnum = pkattnums[i];
2261  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2262 
2263  if (i > 0)
2264  appendStringInfoString(&buf, " AND ");
2265 
2267  quote_ident_cstr(NameStr(attr->attname)));
2268 
2269  if (tgt_pkattvals[i] != NULL)
2270  appendStringInfo(&buf, " = %s",
2271  quote_literal_cstr(tgt_pkattvals[i]));
2272  else
2273  appendStringInfoString(&buf, " IS NULL");
2274  }
2275 
2276  return buf.data;
2277 }
#define NameStr(name)
Definition: c.h:681
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
NameData relname
Definition: pg_class.h:38
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
#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 2163 of file dblink.c.

2164 {
2165  char *relname;
2166  HeapTuple tuple;
2167  TupleDesc tupdesc;
2168  int natts;
2170  char *val;
2171  int key;
2172  int i;
2173  bool needComma;
2174 
2175  initStringInfo(&buf);
2176 
2177  /* get relation name including any needed schema prefix and quoting */
2179 
2180  tupdesc = rel->rd_att;
2181  natts = tupdesc->natts;
2182 
2183  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2184  if (!tuple)
2185  ereport(ERROR,
2186  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2187  errmsg("source row not found")));
2188 
2189  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2190 
2191  needComma = false;
2192  for (i = 0; i < natts; i++)
2193  {
2194  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2195 
2196  if (att->attisdropped)
2197  continue;
2198 
2199  if (needComma)
2200  appendStringInfoChar(&buf, ',');
2201 
2203  quote_ident_cstr(NameStr(att->attname)));
2204  needComma = true;
2205  }
2206 
2207  appendStringInfoString(&buf, ") VALUES(");
2208 
2209  /*
2210  * Note: i is physical column number (counting from 0).
2211  */
2212  needComma = false;
2213  for (i = 0; i < natts; i++)
2214  {
2215  if (TupleDescAttr(tupdesc, i)->attisdropped)
2216  continue;
2217 
2218  if (needComma)
2219  appendStringInfoChar(&buf, ',');
2220 
2221  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2222 
2223  if (key >= 0)
2224  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2225  else
2226  val = SPI_getvalue(tuple, tupdesc, i + 1);
2227 
2228  if (val != NULL)
2229  {
2231  pfree(val);
2232  }
2233  else
2234  appendStringInfoString(&buf, "NULL");
2235  needComma = true;
2236  }
2237  appendStringInfoChar(&buf, ')');
2238 
2239  return buf.data;
2240 }
long val
Definition: informix.c:664
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1218

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

2281 {
2282  char *relname;
2283  HeapTuple tuple;
2284  TupleDesc tupdesc;
2285  int natts;
2287  char *val;
2288  int key;
2289  int i;
2290  bool needComma;
2291 
2292  initStringInfo(&buf);
2293 
2294  /* get relation name including any needed schema prefix and quoting */
2296 
2297  tupdesc = rel->rd_att;
2298  natts = tupdesc->natts;
2299 
2300  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2301  if (!tuple)
2302  ereport(ERROR,
2303  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2304  errmsg("source row not found")));
2305 
2306  appendStringInfo(&buf, "UPDATE %s SET ", relname);
2307 
2308  /*
2309  * Note: i is physical column number (counting from 0).
2310  */
2311  needComma = false;
2312  for (i = 0; i < natts; i++)
2313  {
2314  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2315 
2316  if (attr->attisdropped)
2317  continue;
2318 
2319  if (needComma)
2320  appendStringInfoString(&buf, ", ");
2321 
2322  appendStringInfo(&buf, "%s = ",
2323  quote_ident_cstr(NameStr(attr->attname)));
2324 
2325  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2326 
2327  if (key >= 0)
2328  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2329  else
2330  val = SPI_getvalue(tuple, tupdesc, i + 1);
2331 
2332  if (val != NULL)
2333  {
2335  pfree(val);
2336  }
2337  else
2338  appendStringInfoString(&buf, "NULL");
2339  needComma = true;
2340  }
2341 
2342  appendStringInfoString(&buf, " WHERE ");
2343 
2344  for (i = 0; i < pknumatts; i++)
2345  {
2346  int pkattnum = pkattnums[i];
2347  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2348 
2349  if (i > 0)
2350  appendStringInfoString(&buf, " AND ");
2351 
2353  quote_ident_cstr(NameStr(attr->attname)));
2354 
2355  val = tgt_pkattvals[i];
2356 
2357  if (val != NULL)
2359  else
2360  appendStringInfoString(&buf, " IS NULL");
2361  }
2362 
2363  return buf.data;
2364 }

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

2108 {
2109  int ndim = ARR_NDIM(array);
2110  int *dims = ARR_DIMS(array);
2111  int nitems;
2112  int16 typlen;
2113  bool typbyval;
2114  char typalign;
2115  char **values;
2116  char *ptr;
2117  bits8 *bitmap;
2118  int bitmask;
2119  int i;
2120 
2121  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2122 
2123  *numitems = nitems = ArrayGetNItems(ndim, dims);
2124 
2126  &typlen, &typbyval, &typalign);
2127 
2128  values = (char **) palloc(nitems * sizeof(char *));
2129 
2130  ptr = ARR_DATA_PTR(array);
2131  bitmap = ARR_NULLBITMAP(array);
2132  bitmask = 1;
2133 
2134  for (i = 0; i < nitems; i++)
2135  {
2136  if (bitmap && (*bitmap & bitmask) == 0)
2137  {
2138  values[i] = NULL;
2139  }
2140  else
2141  {
2143  ptr = att_addlength_pointer(ptr, typlen, ptr);
2144  ptr = (char *) att_align_nominal(ptr, typalign);
2145  }
2146 
2147  /* advance bitmap pointer if any */
2148  if (bitmap)
2149  {
2150  bitmask <<= 1;
2151  if (bitmask == 0x100)
2152  {
2153  bitmap++;
2154  bitmask = 1;
2155  }
2156  }
2157  }
2158 
2159  return values;
2160 }
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define ARR_NULLBITMAP(a)
Definition: array.h:293
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_DIMS(a)
Definition: array.h:287
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
#define TextDatumGetCString(d)
Definition: builtins.h:86
uint8 bits8
Definition: c.h:448
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2228
char typalign
Definition: pg_type.h:176
#define PointerGetDatum(X)
Definition: postgres.h:600
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:148
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:176

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

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

◆ get_tuple_of_interest()

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

Definition at line 2401 of file dblink.c.

2402 {
2403  char *relname;
2404  TupleDesc tupdesc;
2405  int natts;
2407  int ret;
2408  HeapTuple tuple;
2409  int i;
2410 
2411  /*
2412  * Connect to SPI manager
2413  */
2414  if ((ret = SPI_connect()) < 0)
2415  /* internal error */
2416  elog(ERROR, "SPI connect failure - returned %d", ret);
2417 
2418  initStringInfo(&buf);
2419 
2420  /* get relation name including any needed schema prefix and quoting */
2422 
2423  tupdesc = rel->rd_att;
2424  natts = tupdesc->natts;
2425 
2426  /*
2427  * Build sql statement to look up tuple of interest, ie, the one matching
2428  * src_pkattvals. We used to use "SELECT *" here, but it's simpler to
2429  * generate a result tuple that matches the table's physical structure,
2430  * with NULLs for any dropped columns. Otherwise we have to deal with two
2431  * different tupdescs and everything's very confusing.
2432  */
2433  appendStringInfoString(&buf, "SELECT ");
2434 
2435  for (i = 0; i < natts; i++)
2436  {
2437  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2438 
2439  if (i > 0)
2440  appendStringInfoString(&buf, ", ");
2441 
2442  if (attr->attisdropped)
2443  appendStringInfoString(&buf, "NULL");
2444  else
2446  quote_ident_cstr(NameStr(attr->attname)));
2447  }
2448 
2449  appendStringInfo(&buf, " FROM %s WHERE ", relname);
2450 
2451  for (i = 0; i < pknumatts; i++)
2452  {
2453  int pkattnum = pkattnums[i];
2454  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2455 
2456  if (i > 0)
2457  appendStringInfoString(&buf, " AND ");
2458 
2460  quote_ident_cstr(NameStr(attr->attname)));
2461 
2462  if (src_pkattvals[i] != NULL)
2463  appendStringInfo(&buf, " = %s",
2464  quote_literal_cstr(src_pkattvals[i]));
2465  else
2466  appendStringInfoString(&buf, " IS NULL");
2467  }
2468 
2469  /*
2470  * Retrieve the desired tuple
2471  */
2472  ret = SPI_exec(buf.data, 0);
2473  pfree(buf.data);
2474 
2475  /*
2476  * Only allow one qualifying tuple
2477  */
2478  if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
2479  ereport(ERROR,
2480  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2481  errmsg("source criteria matched more than one record")));
2482 
2483  else if (ret == SPI_OK_SELECT && SPI_processed == 1)
2484  {
2485  SPITupleTable *tuptable = SPI_tuptable;
2486 
2487  tuple = SPI_copytuple(tuptable->vals[0]);
2488  SPI_finish();
2489 
2490  return tuple;
2491  }
2492  else
2493  {
2494  /*
2495  * no qualifying tuples
2496  */
2497  SPI_finish();
2498 
2499  return NULL;
2500  }
2501 
2502  /*
2503  * never reached, but keep compiler quiet
2504  */
2505  return NULL;
2506 }
uint64 SPI_processed
Definition: spi.c:45
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int SPI_connect(void)
Definition: spi.c:95
int SPI_finish(void)
Definition: spi.c:183
int SPI_exec(const char *src, long tcount)
Definition: spi.c:628
HeapTuple SPI_copytuple(HeapTuple tuple)
Definition: spi.c:1045
#define SPI_OK_SELECT
Definition: spi.h:86
HeapTuple * vals
Definition: spi.h:26

References appendStringInfo(), appendStringInfoString(), buf, elog, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), i, initStringInfo(), NameStr, TupleDescData::natts, pfree(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, relname, SPI_connect(), SPI_copytuple(), SPI_exec(), SPI_finish(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, TupleDescAttr, and SPITupleTable::vals.

Referenced by get_sql_insert(), and get_sql_update().

◆ getConnectionByName()

static remoteConn * getConnectionByName ( const char *  name)
static

Definition at line 2557 of file dblink.c.

2558 {
2559  remoteConnHashEnt *hentry;
2560  char *key;
2561 
2562  if (!remoteConnHash)
2564 
2565  key = pstrdup(name);
2566  truncate_identifier(key, strlen(key), false);
2568  key, HASH_FIND, NULL);
2569 
2570  if (hentry)
2571  return hentry->rconn;
2572 
2573  return NULL;
2574 }
@ 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().

◆ if()

if ( res  )

Definition at line 160 of file dblink.c.

162  : %s", p2, msg);
163 }
164 
165 static void
166 pg_attribute_noreturn()
167 dblink_conn_not_avail(const char *conname)
168 {
169  if (conname)
170  ereport(ERROR,
171  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
172  errmsg("connection \"%s\" not available", conname)));
173  else
174  ereport(ERROR,
175  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
176  errmsg("connection not available")));
177 }

Referenced by _bt_check_unique(), _bt_deltasortsplits(), _bt_next(), _bt_parallel_done(), _bt_preprocess_keys(), _bt_readnextpage(), _Clone(), _CloseArchive(), _EndBlob(), _EndBlobs(), _EndData(), _hash_next(), _hash_readnext(), _hash_readprev(), _PrepParallelRestore(), _PrintExtraToc(), _PrintFileData(), _PrintTocData(), _ReadBuf(), _ReadExtraToc(), _ReopenArchive(), _SPI_execute_plan(), _StartBlob(), _tarAddFile(), _WriteBuf(), _WriteByte(), _WriteData(), _WriteExtraToc(), add_paths_to_grouping_rel(), addRangeTableEntryForCTE(), AggGetAggref(), AggStateIsShared(), allocarc(), allocateReloptStruct(), AlterSubscription(), analyzeCTE(), apply_projection_to_path(), are_peers(), array_cmp(), array_eq(), array_fill_internal(), array_in(), array_out(), array_position_common(), array_positions(), array_recv(), array_replace_internal(), array_send(), array_subscript_assign(), array_subscript_assign_slice(), array_subscript_fetch_old(), array_subscript_fetch_old_slice(), array_to_text_internal(), arrayconst_next_fn(), arrayexpr_next_fn(), assign_param_for_placeholdervar(), assign_param_for_var(), ATExecAlterColumnType(), ATRewriteTables(), autoinc(), bbstreamer_gzip_decompressor_new(), bernoulli_nextsampletuple(), blendscan(), blgetbitmap(), bloom_get_procinfo(), BloomFillMetapage(), blrescan(), bms_add_members(), bms_join(), brin_page_items(), btendscan(), btgetbitmap(), btgettuple(), btrescan(), btrestrpos(), build_tlist_index_other_vars(), build_tlist_to_deparse(), BuildIndexInfo(), buildMatViewRefreshDependencies(), cash_out(), check_and_push_window_quals(), check_domain_for_new_tuple(), check_parameter_resolution_walker(), check_primary_key(), check_sql_fn_statements(), check_tuple_attribute(), check_variable_parameters(), checkAllTheSame(), compute_distinct_stats(), compute_function_attributes(), compute_range_stats(), concat_internal(), connectby_text(), connectby_text_serial(), ConstructTupleDescriptor(), CopyReadAttributesText(), count_rowexpr_columns(), create_bitmap_scan_plan(), create_cursor(), CreateRole(), CreateStatistics(), crosstab(), crosstab_hash(), cube_a_f8_f8(), currtid_for_view(), dblink_get_pkey(), deparse_lquery(), deparseAggref(), deparseFromExprForRel(), digest_finish(), digest_reset(), digest_update(), distribute_row_identity_vars(), domain_in(), domain_recv(), DoPortalRunFetch(), DropRelFileNodesAllBuffers(), dumpConstraint(), ecpg_build_params(), enum_cmp_internal(), estimate_rel_size(), eval_const_expressions_mutator(), examine_simple_variable(), examine_variable(), exec_check_rw_parameter(), exec_simple_query(), exec_stmt_case(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_fetch(), ExecAlterDefaultPrivilegesStmt(), ExecAppendAsyncEventWait(), ExecBuildProjectionInfo(), ExecEndForeignScan(), ExecForeignScan(), ExecGather(), ExecHashBuildSkewHash(), ExecInitMerge(), ExecInsert(), ExecReScanFunctionScan(), ExecSort(), execute_dml_stmt(), expand_indexqual_rowcompare(), expanded_record_set_tuple(), expandRecordVariable(), ExplainNode(), ExplainQuery(), exprCollation(), exprSetCollation(), exprType(), exprTypmod(), fetch_array_arg_replace_nulls(), FigureColnameInternal(), fileBeginForeignScan(), fileEndForeignScan(), fileGetForeignPaths(), final_cost_mergejoin(), finalize_grouping_exprs_walker(), find_forced_null_var(), fixed_paramref_hook(), fmgr_sql(), foreign_expr_walker(), foreign_grouping_ok(), foreign_join_ok(), GenericXLogFinish(), get_cached_rowtype(), get_fn_opclass_options(), get_multirange_io_data(), get_name_for_var_field(), get_range_io_data(), get_rule_expr(), get_rule_sortgroupclause(), get_setop_query(), get_update_query_targetlist_def(), get_useful_pathkeys_for_relation(), GetExistingLocalJoinPath(), getIthJsonbValueFromContainer(), GetJsonTableContext(), GetMultiXactIdMembers(), getNextNearest(), getSide(), getTables(), gimme_gene(), ginCompressPostingList(), gininsert(), gist_page_items(), gist_page_items_bytea(), gistbuild(), gistgetbitmap(), gistgettuple(), gistindex_keytest(), gistinsert(), gistrescan(), gistSplit(), gtrgm_consistent(), gtrgm_distance(), has_fn_opclass_options(), hash_array(), hash_array_extended(), hash_record(), hash_record_extended(), hashendscan(), hashgettuple(), hashrescan(), heap_beginscan(), heapgettup(), heapgettup_pagemode(), hstore_each(), hstore_from_record(), hstore_populate_record(), hstore_skeys(), hstore_svals(), ImportForeignSchema(), inclusion_get_procinfo(), inclusion_get_strategy_procinfo(), infer_arbiter_indexes(), inline_set_returning_function(), insert_username(), interval_to_char(), intset_flush_buffered_values(), intset_update_upper(), inv_getsize(), is_foreign_expr(), is_foreign_param(), is_foreign_pathkey(), IsBinaryTidClause(), IsCurrentOfClause(), IsPagerNeeded(), IsTidEqualAnyClause(), itm2interval(), itmin2interval(), json_lex(), json_object_keys(), jsonb_object_keys(), jsonb_subscript_assign(), jsonb_subscript_check_subscripts(), list_next_fn(), lo_initialize(), lo_manage(), ltree_concat(), main(), map_variable_attnos_mutator(), match_boolean_index_clause(), match_foreign_keys_to_quals(), match_opclause_to_indexcol(), match_rowcompare_to_indexcol(), match_saopclause_to_indexcol(), MemoizeHash_hash(), minmax_get_strategy_procinfo(), minmax_multi_get_procinfo(), minmax_multi_get_strategy_procinfo(), moddatetime(), multirange_get_typcache(), networkjoinsel_semi(), newstate(), nocachegetattr(), NormalizeSubWord(), ordered_set_startup(), PageIndexTupleDelete(), PageIndexTupleDeleteNoCompact(), pagetable_allocate(), pagetable_free(), paraminfo_get_equal_hashops(), paramlist_param_ref(), parse_one_reloption(), parse_publication_options(), parseqatom(), pg_check_frozen(), pg_check_visible(), pg_event_trigger_ddl_commands(), pg_event_trigger_dropped_objects(), pg_get_catalog_foreign_keys(), pg_get_publication_tables(), pg_logdir_ls_internal(), pg_partition_ancestors(), pg_partition_tree(), pg_regexec(), pg_regprefix(), pg_stat_get_progress_info(), pg_timezone_abbrevs(), pg_visibility_map_rel(), pg_visibility_rel(), pgoutput_message(), pgp_armor_headers(), pgstat_acquire_replslot(), pgstat_relation_delete_pending_cb(), pgstat_report_analyze(), pgstat_report_vacuum(), pgstathashindex(), plperl_func_handler(), plperl_return_next_internal(), plperl_trigger_handler(), plpgsql_compile(), plpgsql_exec_function(), plpgsql_post_column_ref(), plpgsql_pre_column_ref(), plsample_trigger_handler(), pltcl_event_trigger_handler(), pltcl_func_handler(), pltcl_trigger_handler(), PLy_exec_function(), PLy_exec_trigger(), populate_recordset_worker(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresEndDirectModify(), postgresEndForeignModify(), postgresEndForeignScan(), postgresExecForeignBatchInsert(), postgresExecForeignInsert(), postgresGetForeignPlan(), postgresIterateDirectModify(), postgresIterateForeignScan(), postgresPlanDirectModify(), postgresReScanForeignScan(), pqAddTuple(), prepTuplestoreResult(), process_subquery_nestloop_params(), prs_process_call(), pullup_replace_vars_callback(), qual_is_pushdown_safe(), range_get_typcache(), read_dictionary(), read_whole_file(), ReadNextXLogRecord(), ReadPageInternal(), reconsider_full_join_clause(), record_cmp(), record_eq(), record_image_cmp(), record_image_eq(), record_in(), record_out(), record_recv(), record_send(), regexp_instr(), regexp_matches(), regexp_split_to_table(), regexp_substr(), remove_unused_subquery_outputs(), remove_useless_groupby_columns(), RemoveUserMapping(), ReorderBufferSerializeChange(), ReplaceVarsFromTargetList_callback(), restriction_is_constant_false(), rewriteTargetListIU(), rewriteValuesRTE(), rfree(), ri_CheckTrigger(), RI_Initial_Check(), row_is_in_frame(), satisfies_hash_partition(), scram_init(), search_directory(), set_dummy_tlist_references(), set_output_count(), set_plan_refs(), set_subquery_pathlist(), set_subquery_size_estimates(), setFilePath(), SetSingleFuncCall(), show_agg_keys(), spg_box_quad_inner_consistent(), spggettuple(), SpGistUpdateMetaPage(), spgPrepareScanKeys(), spgrescan(), spool_tuples(), sql_exec_error_callback(), sql_fn_param_ref(), sql_fn_post_column_ref(), startScanKey(), statext_dependencies_build(), storeRow(), sts_parallel_scan_next(), SubTransSetParent(), suppress_redundant_updates_trigger(), system_nextsampletuple(), system_rows_nextsampleblock(), system_rows_nextsampletuple(), system_time_nextsampleblock(), system_time_nextsampletuple(), table_block_parallelscan_nextpage(), table_block_relation_estimate_size(), tarOpen(), test_regex(), thesaurus_lexize(), tlist_member_match_var(), transformCaseExpr(), transformTargetList(), trigger_return_old(), tsvector_unnest(), tsvector_update_trigger(), tt_process_call(), ttdummy(), TupleHashTableHash_internal(), tzparse(), unique_key_recheck(), update_frameheadpos(), update_frametailpos(), update_grouptailpos(), variable_coerce_param_hook(), variable_paramref_hook(), varstrfastcmp_locale(), verify_client_proof(), verify_heapam(), view_col_is_auto_updatable(), width_bucket_array(), WinRowsArePeers(), XLogDecodeNextRecord(), and XLogPrefetcherNextBlock().

◆ is_valid_dblink_option()

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

Definition at line 2986 of file dblink.c.

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

References _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 1026 of file dblink.c.

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

References res, and FunctionCallInfoBaseData::resultinfo.

Referenced by dblink_record_internal().

◆ materializeResult()

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

Definition at line 887 of file dblink.c.

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

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

◆ 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  )

◆ prepTuplestoreResult()

static void prepTuplestoreResult ( FunctionCallInfo  fcinfo)
static

Definition at line 859 of file dblink.c.

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

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

2372 {
2373  text *rawstr_text;
2374  text *result_text;
2375  char *result;
2376 
2377  rawstr_text = cstring_to_text(rawstr);
2379  PointerGetDatum(rawstr_text)));
2380  result = text_to_cstring(result_text);
2381 
2382  return result;
2383 }
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:631
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:24

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

3090 {
3091  /* Do nothing if no new nestlevel was created */
3092  if (nestlevel > 0)
3093  AtEOXact_GUC(true, nestlevel);
3094 }
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6481

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

◆ storeQueryResult()

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

Definition at line 1141 of file dblink.c.

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

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

◆ storeRow()

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

Definition at line 1209 of file dblink.c.

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

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(), 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 2915 of file dblink.c.

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

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

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

◆ xpstrdup()

static char* xpstrdup ( const char *  in)
static

Definition at line 147 of file dblink.c.

148 {
149  if (in == NULL)
150  return NULL;
151  return pstrdup(in);
152 }

References pstrdup().

Referenced by dblink_res_error().

Variable Documentation

◆ p2

◆ pconn

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 63 of file dblink.c.

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static

◆ res

void PGresult* res

Definition at line 156 of file dblink.c.

Referenced by _bt_binsrch_posting(), _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(), _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(), cfb_process(), check_field_number(), check_for_data_types_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_tables_with_oids(), check_for_user_defined_encoding_conversions(), check_for_user_defined_postfix_ops(), check_is_install_user(), check_key_cksum(), check_key_sha1(), check_loadable_libraries(), check_locale(), check_locale_name(), check_param_number(), check_prepare_conn(), check_publications(), check_tuple_field_number(), checkcondition_str(), CheckForBufferLeaks(), clean_NOT_intree(), clean_stopword_intree(), close_cursor(), CloseArchive(), cmp_list_len_contents_asc(), cmpEntries(), cmpTheLexeme(), cnt_sml(), coerceJsonFuncExpr(), collectComments(), collectMatchesForHeapRow(), collectRoleNames(), collectSecLabels(), combo_decrypt(), combo_encrypt(), compareItems(), compareJsonbContainers(), comparePairs(), CompareTSQ(), compareWORD(), compile_database_list(), compile_relation_list_one_db(), ConditionalLockRelation(), ConditionalLockRelationOid(), contain_context_dependent_node_walker(), convert_charset(), convert_network_to_scalar(), convertToJsonb(), convertTSFunction(), copy_crlf(), copy_messages(), copy_table(), copyTSLexeme(), cpstrdup(), create_cursor(), create_secmsg(), 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_cancel_query(), 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(), define_custom_variable(), describeAccessMethods(), describeAggregates(), describeConfigurationParameters(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), DetermineTimeZoneOffsetInternal(), dintdict_lexize(), discardUntilSync(), dispell_lexize(), do_field(), do_header(), do_lo_import(), do_sql_command_end(), do_watch(), downcase_convert(), dropDBs(), DropReplicationSlot(), dropRoles(), dropTablespaces(), dsimple_lexize(), dsnowball_lexize(), dsynonym_lexize(), dump_lo_buf(), dumpAgg(), dumpBaseType(), dumpBlobs(), 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(), encrypt_and_write_elgamal(), encrypt_and_write_rsa(), encrypt_init(), encrypt_internal(), encrypt_process(), EndDBCopyMode(), evalStandardFunc(), exec_command_password(), ExecEvalJson(), ExecEvalJsonConstructor(), ExecEvalJsonExpr(), ExecEvalJsonExprCoercion(), ExecEvalJsonExprSubtrans(), ExecEvalJsonIsPredicate(), ExecEvalStepOp(), ExecPrepareJsonItemCoercion(), 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(), find_among(), find_among_b(), find_next_mcelem(), find_option(), find_provider(), find_window_run_conditions(), findTheLexeme(), finish_lo_xact(), float4_numeric(), float8_numeric(), freeaddrinfo(), 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(), get_canonical_locale_name(), 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_rel_infos(), get_remote_estimate(), get_subscription_list(), get_synchronized_snapshot(), get_tablespace_paths(), getAccessMethods(), getAdditionalACLs(), getaddrinfo(), getAggregates(), getArrayIndex(), getBlobs(), getCasts(), getCollations(), GetConnection(), getConstraints(), getConversions(), getDatumCopy(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getKeyJsonValueFromContainer(), GetLastImportantRecPtr(), getNamespaces(), getNextNearest(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), GetPrivateRefCountEntry(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRules(), GetSlotInformation(), GetSubscriptionNotReadyRelations(), GetSubscriptionRelations(), getSubscriptions(), getTableAttrs(), GetTableInfo(), getTables(), getTokenTypes(), 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(), 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(), initGenerateDataClientSide(), 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(), 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(), JsonTableResetContextItem(), keyGetItem(), lazy_scan_prune(), lca(), lca_inner(), lengthCompareJsonbPair(), LexizeExec(), libpq_fetch_file(), libpq_traverse_files(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_endstreaming(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), libpqrcv_receive(), libpqrcv_startstreaming(), limit_printout_length(), 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_sync_worker_count(), logicalrep_worker_find(), logicalrep_workers_find(), LogicalRepSyncTableStart(), lookup_object_oid(), LPLRemoveHead(), 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_isparent(), ltree_le(), ltree_lt(), ltree_ne(), ltree_recv(), ltree_risparent(), ltree_send(), ltree_strncasecmp(), 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(), my_sock_read(), my_sock_write(), 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(), 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_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(), pgfdw_finish_pre_commit_cleanup(), pgfdw_get_cleanup_result(), pgfdw_get_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(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresImportForeignSchema(), postgresReScanForeignScan(), pqAddTuple(), PQbinaryTuples(), pqBuildErrorMessage3(), 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(), PrintResultInCrosstab(), printResultSet(), printTypmod(), process_data_packets(), process_queued_fetch_requests(), process_result(), process_secret_key(), 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(), read_pubenc_keyid(), read_pubkey_keyid(), readCommandResponse(), readDatum(), ReadEndOfStreamingResult(), ReadInt(), readTimeLineHistory(), reap_child(), ReceiveCopyData(), ReceiveXlogStream(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), ReplicationSlotDropAtPubNode(), report_extension_updates(), ReservePrivateRefCountEntry(), ResourceOwnerReleaseAllPlanCacheRefs(), ResourceOwnerReleaseInternal(), RestoreOutput(), RetrieveDataDirCreatePerm(), RetrieveWalSegSize(), run_crypt_des(), run_crypt_md5(), run_permutation(), run_simple_command(), run_simple_query(), RunIdentifySystem(), runShellCommand(), sampler_random_fract(), sendCommand(), set_arg(), setNewTmpRes(), setPath(), shm_mq_receive(), shm_mq_sendv(), should_processing_continue(), 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(), TableCommandResultHandler(), tarRead(), tarWrite(), test_disallowed_in_pipeline(), test_indoption(), test_multi_pipelines(), test_nosync(), test_pipeline_abort(), 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(), transformJsonTableChildPlan(), 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(), vac_tid_reaped(), vacuum_one_database(), vacuumlo(), varstr_abbrev_convert(), verify_btree_slot_handler(), verify_heap_slot_handler(), 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().