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 *str)
 
static void validate_pkattnums (Relation rel, int2vector *pkattnums_arg, int32 pknumatts_arg, int **pkattnums, int *pknumatts)
 
static bool is_valid_dblink_option (const PQconninfoOption *options, const char *option, Oid context)
 
static int applyRemoteGucs (PGconn *conn)
 
static void restoreLocalGucs (int nestlevel)
 
static char * xpstrdup (const char *in)
 
static void pg_attribute_noreturn () dblink_res_internalerror(PGconn *conn
 
 PQclear (res)
 
 elog (ERROR, "%s: %s", p2, msg)
 
static void dblink_get_conn (char *conname_or_str, PGconn *volatile *conn_p, char **conname_p, volatile bool *freeconn_p)
 
static PGconndblink_get_named_conn (const char *conname)
 
static void dblink_init (void)
 
 PG_FUNCTION_INFO_V1 (dblink_connect)
 
Datum dblink_connect (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_disconnect)
 
Datum dblink_disconnect (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_open)
 
Datum dblink_open (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_close)
 
Datum dblink_close (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_fetch)
 
Datum dblink_fetch (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_record)
 
Datum dblink_record (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_send_query)
 
Datum dblink_send_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_result)
 
Datum dblink_get_result (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_connections)
 
Datum dblink_get_connections (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_is_busy)
 
Datum dblink_is_busy (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_cancel_query)
 
Datum dblink_cancel_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_error_message)
 
Datum dblink_error_message (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_exec)
 
Datum dblink_exec (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_pkey)
 
Datum dblink_get_pkey (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_insert)
 
Datum dblink_build_sql_insert (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_delete)
 
Datum dblink_build_sql_delete (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_update)
 
Datum dblink_build_sql_update (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_current_query)
 
Datum dblink_current_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_notify)
 
Datum dblink_get_notify (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_fdw_validator)
 
Datum dblink_fdw_validator (PG_FUNCTION_ARGS)
 

Variables

 PG_MODULE_MAGIC
 
static remoteConnpconn = NULL
 
static HTABremoteConnHash = NULL
 
static void PGresultres
 
static void PGresult const char * p2
 

Macro Definition Documentation

◆ DBLINK_NOTIFY_COLS

#define DBLINK_NOTIFY_COLS   3

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

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

2582 {
2583  HASHCTL ctl;
2584 
2585  ctl.keysize = NAMEDATALEN;
2586  ctl.entrysize = sizeof(remoteConnHashEnt);
2587 
2588  return hash_create("Remote Con hash", NUMCONN, &ctl,
2590 }
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 2593 of file dblink.c.

2594 {
2595  remoteConnHashEnt *hentry;
2596  bool found;
2597  char *key;
2598 
2599  if (!remoteConnHash)
2601 
2602  key = pstrdup(name);
2603  truncate_identifier(key, strlen(key), true);
2605  HASH_ENTER, &found);
2606 
2607  if (found)
2608  {
2609  PQfinish(rconn->conn);
2611  pfree(rconn);
2612 
2613  ereport(ERROR,
2615  errmsg("duplicate connection name")));
2616  }
2617 
2618  hentry->rconn = rconn;
2619  strlcpy(hentry->name, name, sizeof(hentry->name));
2620 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
const char * name
Definition: encode.c:561
void ReleaseExternalFD(void)
Definition: fd.c:1153
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4181
@ HASH_ENTER
Definition: hsearch.h:114
char * pstrdup(const char *in)
Definition: mcxt.c:1392
void pfree(void *pointer)
Definition: mcxt.c:1252
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 1751 of file dblink.c.

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

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

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

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

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

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

1380 {
1381  int res;
1382  PGconn *conn;
1383  PGcancel *cancel;
1384  char errbuf[256];
1385 
1386  dblink_init();
1388  cancel = PQgetCancel(conn);
1389 
1390  res = PQcancel(cancel, errbuf, 256);
1391  PQfreeCancel(cancel);
1392 
1393  if (res == 1)
1395  else
1397 }
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:4286
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:4400
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:4354
char * text_to_cstring(const text *t)
Definition: varlena.c:222

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

517 {
518  PGconn *conn;
519  PGresult *res = NULL;
520  char *curname = NULL;
521  char *conname = NULL;
523  remoteConn *rconn = NULL;
524  bool fail = true; /* default to backward compatible behavior */
525 
526  dblink_init();
528 
529  if (PG_NARGS() == 1)
530  {
531  /* text */
532  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
533  rconn = pconn;
534  }
535  else if (PG_NARGS() == 2)
536  {
537  /* might be text,text or text,bool */
538  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
539  {
540  curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
541  fail = PG_GETARG_BOOL(1);
542  rconn = pconn;
543  }
544  else
545  {
546  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
547  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
548  rconn = getConnectionByName(conname);
549  }
550  }
551  if (PG_NARGS() == 3)
552  {
553  /* text,text,bool */
554  conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
555  curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
556  fail = PG_GETARG_BOOL(2);
557  rconn = getConnectionByName(conname);
558  }
559 
560  if (!rconn || !rconn->conn)
561  dblink_conn_not_avail(conname);
562 
563  conn = rconn->conn;
564 
565  appendStringInfo(&buf, "CLOSE %s", curname);
566 
567  /* close the cursor */
568  res = PQexec(conn, buf.data);
570  {
571  dblink_res_error(conn, conname, res, fail,
572  "while closing cursor \"%s\"", curname);
574  }
575 
576  PQclear(res);
577 
578  /* if we started a transaction, decrement cursor count */
579  if (rconn->newXactForCursor)
580  {
581  (rconn->openCursorCount)--;
582 
583  /* if count is zero, commit the transaction */
584  if (rconn->openCursorCount == 0)
585  {
586  rconn->newXactForCursor = false;
587 
588  res = PQexec(conn, "COMMIT");
590  dblink_res_internalerror(conn, res, "commit error");
591  PQclear(res);
592  }
593  }
594 
596 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3275
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2243
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 279 of file dblink.c.

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

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

2672 {
2673  if (!superuser())
2674  {
2677  bool connstr_gives_password = false;
2678 
2679  options = PQconninfoParse(connstr, NULL);
2680  if (options)
2681  {
2682  for (option = options; option->keyword != NULL; option++)
2683  {
2684  if (strcmp(option->keyword, "password") == 0)
2685  {
2686  if (option->val != NULL && option->val[0] != '\0')
2687  {
2688  connstr_gives_password = true;
2689  break;
2690  }
2691  }
2692  }
2694  }
2695 
2696  if (!connstr_gives_password)
2697  ereport(ERROR,
2698  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2699  errmsg("password is required"),
2700  errdetail("Non-superusers must provide a password in the connection string.")));
2701  }
2702 }
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5420
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6651
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 1906 of file dblink.c.

1907 {
1908  /* This is now just an alias for the built-in function current_query() */
1909  PG_RETURN_DATUM(current_query(fcinfo));
1910 }
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 384 of file dblink.c.

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

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

1413 {
1414  char *msg;
1415  PGconn *conn;
1416 
1417  dblink_init();
1419 
1420  msg = PQerrorMessage(conn);
1421  if (msg == NULL || msg[0] == '\0')
1423  else
1425 }

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

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

1978 {
1979  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
1980  Oid context = PG_GETARG_OID(1);
1981  ListCell *cell;
1982 
1983  static const PQconninfoOption *options = NULL;
1984 
1985  /*
1986  * Get list of valid libpq options.
1987  *
1988  * To avoid unnecessary work, we get the list once and use it throughout
1989  * the lifetime of this backend process. We don't need to care about
1990  * memory context issues, because PQconndefaults allocates with malloc.
1991  */
1992  if (!options)
1993  {
1994  options = PQconndefaults();
1995  if (!options) /* assume reason for failure is OOM */
1996  ereport(ERROR,
1997  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
1998  errmsg("out of memory"),
1999  errdetail("Could not get libpq's default connection options.")));
2000  }
2001 
2002  /* Validate each supplied option. */
2003  foreach(cell, options_list)
2004  {
2005  DefElem *def = (DefElem *) lfirst(cell);
2006 
2007  if (!is_valid_dblink_option(options, def->defname, context))
2008  {
2009  /*
2010  * Unknown option, or invalid option for the context specified, so
2011  * complain about it. Provide a hint with a valid option that
2012  * looks similar, if there is one.
2013  */
2014  const PQconninfoOption *opt;
2015  const char *closest_match;
2016  ClosestMatchState match_state;
2017  bool has_valid_options = false;
2018 
2019  initClosestMatch(&match_state, def->defname, 4);
2020  for (opt = options; opt->keyword; opt++)
2021  {
2022  if (is_valid_dblink_option(options, opt->keyword, context))
2023  {
2024  has_valid_options = true;
2025  updateClosestMatch(&match_state, opt->keyword);
2026  }
2027  }
2028 
2029  closest_match = getClosestMatch(&match_state);
2030  ereport(ERROR,
2031  (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
2032  errmsg("invalid option \"%s\"", def->defname),
2033  has_valid_options ? closest_match ?
2034  errhint("Perhaps you meant the option \"%s\".",
2035  closest_match) : 0 :
2036  errhint("There are no valid options in this context.")));
2037  }
2038  }
2039 
2040  PG_RETURN_VOID();
2041 }
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1462
#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:170
unsigned int Oid
Definition: postgres_ext.h:31
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1333
char * defname
Definition: parsenodes.h:775
Definition: pg_list.h:52
const char * getClosestMatch(ClosestMatchState *state)
Definition: varlena.c:6274
void initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
Definition: varlena.c:6219
void updateClosestMatch(ClosestMatchState *state, const char *candidate)
Definition: varlena.c:6239

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

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

Definition at line 603 of file dblink.c.

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

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

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

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

1321 {
1323  remoteConnHashEnt *hentry;
1324  ArrayBuildState *astate = NULL;
1325 
1326  if (remoteConnHash)
1327  {
1329  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1330  {
1331  /* stash away current value */
1332  astate = accumArrayResult(astate,
1333  CStringGetTextDatum(hentry->name),
1334  false, TEXTOID, CurrentMemoryContext);
1335  }
1336  }
1337 
1338  if (astate)
1341  else
1342  PG_RETURN_NULL();
1343 }
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5277
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5341
#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:87
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225

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

◆ dblink_get_named_conn()

static PGconn* dblink_get_named_conn ( const char *  conname)
static

Definition at line 251 of file dblink.c.

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

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

1925 {
1926  PGconn *conn;
1927  PGnotify *notify;
1928  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1929 
1930  dblink_init();
1931  if (PG_NARGS() == 1)
1933  else
1934  conn = pconn->conn;
1935 
1936  SetSingleFuncCall(fcinfo, 0);
1937 
1939  while ((notify = PQnotifies(conn)) != NULL)
1940  {
1942  bool nulls[DBLINK_NOTIFY_COLS];
1943 
1944  memset(values, 0, sizeof(values));
1945  memset(nulls, 0, sizeof(nulls));
1946 
1947  if (notify->relname != NULL)
1948  values[0] = CStringGetTextDatum(notify->relname);
1949  else
1950  nulls[0] = true;
1951 
1952  values[1] = Int32GetDatum(notify->be_pid);
1953 
1954  if (notify->extra != NULL)
1955  values[2] = CStringGetTextDatum(notify->extra);
1956  else
1957  nulls[2] = true;
1958 
1959  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1960 
1961  PQfreemem(notify);
1963  }
1964 
1965  return (Datum) 0;
1966 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
void PQfreemem(void *ptr)
Definition: fe-exec.c:3900
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2568
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1969
void SetSingleFuncCall(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
TupleDesc setDesc
Definition: execnodes.h:332
Tuplestorestate * setResult
Definition: execnodes.h:331
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 1538 of file dblink.c.

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

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 729 of file dblink.c.

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

References dblink_record_internal().

◆ dblink_init()

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1355 of file dblink.c.

1356 {
1357  PGconn *conn;
1358 
1359  dblink_init();
1361 
1364 }
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2016
#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 423 of file dblink.c.

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

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

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 735 of file dblink.c.

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

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

References conn, ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, fmt, MAKE_SQLSTATE, NOTICE, pchomp(), PG_DIAG_CONTEXT, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SQLSTATE, PQclear(), PQerrorMessage(), PQresultErrorField(), res, va_end(), va_start(), vsnprintf, and xpstrdup().

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

◆ dblink_security_check()

static void dblink_security_check ( PGconn conn,
remoteConn rconn 
)
static

Definition at line 2644 of file dblink.c.

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

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

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

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

2624 {
2625  remoteConnHashEnt *hentry;
2626  bool found;
2627  char *key;
2628 
2629  if (!remoteConnHash)
2631 
2632  key = pstrdup(name);
2633  truncate_identifier(key, strlen(key), false);
2635  key, HASH_REMOVE, &found);
2636 
2637  if (!hentry)
2638  ereport(ERROR,
2639  (errcode(ERRCODE_UNDEFINED_OBJECT),
2640  errmsg("undefined connection name")));
2641 }
@ HASH_REMOVE
Definition: hsearch.h:115

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

Referenced by dblink_disconnect().

◆ elog()

elog ( ERROR  ,
"%s: %s"  ,
p2  ,
msg   
)

Referenced by _bt_allequalimage(), _bt_buildadd(), _bt_check_rowcompare(), _bt_check_third_page(), _bt_check_unique(), _bt_compare_scankey_args(), _bt_dedup_finish_pending(), _bt_dedup_pass(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_endpoint(), _bt_find_extreme_element(), _bt_findsplitloc(), _bt_finish_split(), _bt_first(), _bt_get_endpoint(), _bt_getbuf(), _bt_getroot(), _bt_gettrueroot(), _bt_insert_parent(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_mark_scankey_required(), _bt_moveright(), _bt_newroot(), _bt_preprocess_array_keys(), _bt_preprocess_keys(), _bt_restore_page(), _bt_sort_array_elements(), _bt_sortaddtup(), _bt_split(), _bt_start_vacuum(), _bt_stepright(), _bt_swap_posting(), _bt_unlink_halfdead_page(), _bt_walk_left(), _copyA_Const(), _equalList(), _hash_datum2hashkey_type(), _hash_firstfreebit(), _hash_freeovflpage(), _hash_getbuf(), _hash_getbuf_with_condlock_cleanup(), _hash_getbuf_with_strategy(), _hash_getinitbuf(), _hash_getnewbuf(), _hash_init(), _hash_pgaddmultitup(), _hash_pgaddtup(), _ltree_consistent(), _mdfd_getseg(), _metaphone(), _outA_Expr(), _outConstraint(), _outList(), _outRangeTblEntry(), _PG_init(), _readA_Expr(), _readBitmapset(), _readBoolExpr(), _readConstraint(), _readExtensibleNode(), _readRangeTblEntry(), _SPI_cursor_operation(), _SPI_pquery(), _tarWriteHeader(), AbortSubTransaction(), AbortTransaction(), aclcheck_error(), aclcheck_error_col(), acldefault(), acldefault_sql(), aclmask(), aclmask_direct(), AcquireRewriteLocks(), add_base_rels_to_query(), add_cast_to(), add_function_cost(), add_function_defaults(), add_row_identity_var(), add_vars_to_targetlist(), AddFileToBackupManifest(), addFkRecurseReferenced(), addLeafTuple(), addNode(), addOrReplaceTuple(), addRangeTableEntryForENR(), AddRoleMems(), AddSubscriptionRelState(), addTargetToSortList(), AddWaitEventToSet(), adjust_appendrel_attrs_multilevel(), adjust_appendrel_attrs_mutator(), adjust_child_relids_multilevel(), adjust_inherited_attnums(), adjust_inherited_attnums_multilevel(), adjust_partition_colnos_using_map(), adjust_view_column_set(), AdjustIntervalForTypmod(), advance_windowaggregate_base(), AdvanceXLInsertBuffer(), AfterTriggerExecute(), afterTriggerInvokeEvents(), AfterTriggerSaveEvent(), AggregateCreate(), AggRegisterCallback(), allocacl(), allocate_reloption(), AllocateDir(), AllocateFile(), AllocateVfd(), AllocSetFree(), AllocSetRealloc(), AlterCollation(), AlterDatabaseRefreshColl(), AlterDomainAddConstraint(), AlterDomainDefault(), AlterDomainDropConstraint(), AlterDomainNotNull(), AlterDomainValidateConstraint(), AlterEnum(), AlterExtensionNamespace(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterOpFamilyDrop(), AlterRelationNamespaceInternal(), AlterRole(), AlterSchemaOwner_oid(), AlterSequence(), AlterStatistics(), AlterSubscription(), AlterSystemSetConfigFile(), AlterTableGetLockLevel(), AlterTSDictionary(), AlterTypeNamespaceInternal(), AlterTypeOwner_oid(), AlterTypeOwnerInternal(), AlterTypeRecurse(), AlterUserMapping(), amvalidate(), analyzeCTE(), AnonymousShmemDetach(), appendFunctionName(), appendOrderByClause(), appendOrderBySuffix(), AppendStringToManifest(), apply_handle_delete_internal(), apply_handle_stream_commit(), apply_handle_stream_prepare(), apply_handle_tuple_routing(), apply_handle_update_internal(), apply_map_update(), apply_pathtarget_labeling_to_tlist(), apply_spooled_messages(), ApplyExtensionUpdates(), ApplyRetrieveRule(), ApplyWorkerMain(), array_agg_array_transfn(), array_agg_transfn(), array_create_iterator(), array_exec_setup(), array_fill(), array_fill_with_lower_bounds(), array_typanalyze(), ASN1_STRING_to_text(), assign_client_encoding(), assign_collations_walker(), assignOperTypes(), AssignPostmasterChildSlot(), assignProcTypes(), AssignTransactionId(), Async_Listen(), Async_Notify(), Async_Unlisten(), Async_UnlistenAll(), ATAddForeignKeyConstraint(), AtCleanup_Portals(), AtCommit_Notify(), ATDetachCheckNoForeignKeyRefs(), AtEOSubXact_cleanup(), AtEOSubXact_HashTables(), AtEOSubXact_Namespace(), AtEOSubXact_Parallel(), AtEOXact_cleanup(), AtEOXact_HashTables(), AtEOXact_Namespace(), AtEOXact_Parallel(), AtEOXact_Snapshot(), ATExecAddColumn(), ATExecAddConstraint(), ATExecAddIndexConstraint(), ATExecAddOf(), ATExecAlterColumnType(), ATExecChangeOwner(), ATExecCmd(), ATExecDetachPartition(), ATExecDropColumn(), ATExecDropConstraint(), ATExecDropExpression(), ATExecDropNotNull(), ATExecDropOf(), ATExecForceNoForceRowSecurity(), ATExecReplicaIdentity(), ATExecSetIdentity(), ATExecSetRelOptions(), ATExecSetRowSecurity(), ATExecValidateConstraint(), ATParseTransformCmd(), ATPostAlterTypeCleanup(), ATPostAlterTypeParse(), ATPrepCmd(), ATRewriteTable(), ATSimplePermissions(), AtStart_GUC(), AtSubCleanup_Portals(), AttachSession(), attnumAttName(), attnumCollationId(), attnumTypeId(), AttrDefaultFetch(), autoinc(), autovac_balance_cost(), AutoVacWorkerMain(), AuxiliaryProcessMain(), BackgroundWorkerStateChange(), basic_archive_file_internal(), be_gssapi_write(), be_lo_close(), be_lo_open(), before_stmt_triggers_fired(), begin_remote_xact(), BeginInternalSubTransaction(), BeginTransactionBlock(), BgBufferSync(), binary_decode(), binary_encode(), binary_upgrade_create_empty_extension(), binaryheap_add(), binaryheap_add_unordered(), BipartiteMatch(), bitmap_subplan_mark_shared(), BitmapAdjustPrefetchIterator(), BitmapHeapNext(), bitposition(), blbuild(), blinsert(), bloom_init(), bloomBuildCallback(), blvalidate(), bms_add_member(), bms_add_range(), bms_del_member(), bms_is_member(), bms_make_singleton(), bms_overlap_list(), bms_singleton_member(), bool_accum_inv(), booltestsel(), boot_get_type_io_data(), boot_openrel(), BootstrapModeMain(), BootstrapToastTable(), bqarr_in(), brin_bloom_consistent(), brin_doinsert(), brin_doupdate(), brin_inclusion_consistent(), brin_metapage_info(), brin_minmax_consistent(), brin_minmax_multi_consistent(), brin_page_items(), brin_redo(), brin_xlog_insert_update(), brin_xlog_samepage_update(), brinbuild(), brincostestimate(), brinvalidate(), bt_check_every_level(), bt_check_level_from_leftmost(), bt_downlink_missing_check(), bt_metap(), bt_page_items_bytea(), bt_page_items_internal(), bt_page_print_tuples(), bt_page_stats_internal(), bt_target_page_check(), btbuild(), btcostestimate(), btree_redo(), btree_xlog_dedup(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_updates(), btvalidate(), BufFileAppend(), BufFileDeleteFileSet(), BufFileSeek(), BufTableDelete(), build_coercion_expression(), build_column_default(), build_concat_foutcache(), build_datatype(), build_EvalXFuncInt(), build_expression_pathkey(), build_function_result_tupdesc_d(), build_index_tlist(), build_joinrel_tlist(), build_mss(), build_pgstattuple_type(), build_physical_tlist(), build_regexp_split_result(), build_replindex_scan_key(), build_row_from_vars(), build_server_final_message(), build_simple_rel(), build_subplan(), BuildDummyIndexInfo(), BuildIndexInfo(), buildMergedJoinVar(), BuildRelationExtStatistics(), BuildSpeculativeIndexInfo(), byteaout(), cache_locale_time(), cache_reduce_memory(), CachedPlanSetParentContext(), CacheInvalidateRelcacheByRelid(), CacheRegisterRelcacheCallback(), CacheRegisterSyscacheCallback(), calc_hist_selectivity(), calc_joinrel_size_estimate(), calc_multirangesel(), calc_rangesel(), call_pltcl_start_proc(), CallerFInfoFunctionCall1(), CallerFInfoFunctionCall2(), CallStmtResultDesc(), CallSyscacheCallbacks(), cancel_before_shmem_exit(), cannotCastJsonbValue(), CatalogCacheComputeHashValue(), CatalogCacheComputeTupleHashValue(), CatalogCacheInitializeCache(), char2wchar(), check_amop_signature(), check_amproc_signature(), check_default_text_search_config(), check_domain_for_new_field(), check_encoding_conversion_args(), check_exclusion_or_unique_constraint(), check_float8_array(), check_foreign_key(), check_hash_func_signature(), check_hostname(), check_locale(), check_new_partition_bound(), check_object_ownership(), check_on_shmem_exit_lists_are_empty(), check_primary_key(), check_role_grantor(), check_with_filler(), CheckArchiveTimeout(), CheckConstraintFetch(), CheckDateTokenTable(), CheckFunctionValidatorAccess(), CheckIndexCompatible(), CheckMyDatabase(), CheckPointLogicalRewriteHeap(), CheckPointReplicationSlots(), CheckPointSnapBuild(), CheckRecoveryConsistency(), CheckRelationLockedByMe(), CheckSASLAuth(), checkSplitConditions(), checkTargetlistEntrySQL92(), CheckValidResultRel(), CheckVarSlotCompatibility(), checkWellFormedRecursion(), checkWellFormedRecursionWalker(), checkWellFormedSelectStmt(), ChoosePortalStrategy(), cipher_free_callback(), ClassifyUtilityCommandAsReadOnly(), clause_selectivity_ext(), CleanupBackupHistory(), CleanUpLock(), CleanupProcSignalState(), CleanupSubTransaction(), CleanupTempFiles(), CleanupTransaction(), clear_subscription_skip_lsn(), clog_redo(), CloneFkReferenced(), CloneFkReferencing(), CloneRowTriggersToPartition(), ClosePipeStream(), closerel(), CloseTransientFile(), coerce_type(), CollationIsVisible(), collectMatchesForHeapRow(), CommandCounterIncrement(), CommandIsReadOnly(), commit_ts_redo(), CommitSubTransaction(), CommitTransaction(), CommitTransactionCommand(), CommuteOpExpr(), compare_tlist_datatypes(), compare_values_of_enum(), compareDatetime(), CompareIndexInfo(), compareItems(), compareJsonbContainers(), compareJsonbScalarValue(), comparison_shim(), compile_plperl_function(), compile_pltcl_function(), compute_array_stats(), compute_function_attributes(), compute_new_xmax_infomask(), compute_tsvector_stats(), computeDelta(), computeDistance(), ComputeIndexAttrs(), computeLeafRecompressWALData(), config_enum_lookup_by_value(), connectby(), ConstraintSetParentConstraint(), construct_array_builtin(), ConstructTupleDescriptor(), ConversionCreate(), ConversionIsVisible(), convert_aclright_to_string(), convert_subquery_pathkeys(), convert_testexpr_mutator(), convertJsonbScalar(), convertJsonbValue(), copy_plpgsql_datums(), copy_replication_slot(), copy_table_data(), CopyArrayEls(), CopyCachedPlan(), CopyConversionError(), copyObjectImpl(), CopyXLogRecordToWAL(), cost_bitmap_tree_node(), cost_qual_eval_walker(), count_usable_fds(), create_and_test_bloom(), create_append_plan(), create_bitmap_subplan(), create_ctescan_plan(), create_foreign_join_path(), create_foreign_modify(), create_gather_merge_plan(), create_hash_bounds(), create_indexscan_plan(), create_internal(), create_join_plan(), create_list_bounds(), create_merge_append_plan(), create_mergejoin_plan(), create_plan(), create_plan_recurse(), create_range_bounds(), create_scan_plan(), create_toast_table(), create_unique_plan(), create_worktablescan_plan(), CreateAnonymousSegment(), CreateCast(), CreateCheckPoint(), CreateCommandTag(), createdb(), CreateDecodingContext(), CreateEndOfRecoveryRecord(), CreateExtension(), createForeignKeyActionTriggers(), CreateInitDecodingContext(), CreateLockFile(), CreateOverwriteContrecordRecord(), CreatePartitionPruneState(), createPostingTree(), CreateRole(), CreateSchemaCommand(), CreateSharedMemoryAndSemaphores(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTriggerFiringOn(), CreateWaitEventSet(), crosstab(), cryptohash_internal(), currtid_for_view(), currtid_internal(), dataBeginPlaceToPageLeaf(), datum_image_eq(), datum_image_hash(), datum_to_jsonb(), datum_write(), datumGetSize(), dbase_redo(), dblink_exec(), dblink_record_internal(), dblink_send_query(), DCH_cache_getnew(), DeadLockCheck(), DeadLockCheckRecurse(), DecodeTextArrayToBitmapset(), DecodingContextFindStartpoint(), decompile_conbin(), deconstruct_array_builtin(), deconstruct_recurse(), DeconstructFkConstraintRow(), defGetString(), defGetStringList(), defGetTypeLength(), DefineAttr(), DefineCollation(), DefineDomain(), DefineIndex(), DefineOpClass(), DefineQueryRewrite(), DefineRelation(), DefineSavepoint(), DefineTSConfiguration(), DefineView(), Delete(), DeleteRelationTuple(), DeleteSequenceTuple(), DelRoleMems(), deparseExpr(), deparseOpExpr(), deparseScalarArrayOpExpr(), dependency_degree(), deregister_seq_scan(), deserialize_deflist(), DetachPartitionFinalize(), detoast_attr_slice(), digest_block_size(), digest_finish(), digest_free_callback(), digest_reset(), digest_result_size(), digest_update(), DirectFunctionCall1Coll(), DirectFunctionCall2Coll(), DirectFunctionCall3Coll(), DirectFunctionCall4Coll(), DirectFunctionCall5Coll(), DirectFunctionCall6Coll(), DirectFunctionCall7Coll(), DirectFunctionCall8Coll(), DirectFunctionCall9Coll(), DisableSubscription(), DiscardCommand(), disconnect_cached_connections(), distribute_qual_to_rels(), distribute_restrictinfo_to_rels(), do_analyze_rel(), do_autovacuum(), do_compile(), do_serialize(), do_serialize_binary(), do_setval(), doDeletion(), does_not_exist_skipping(), domain_check_input(), doPickSplit(), DoPortalRunFetch(), drain(), dropdb(), DropObjectById(), DropRelationAllLocalBuffers(), DropRelationLocalBuffers(), DropRole(), dsa_allocate_extended(), dsa_pin(), dsa_unpin(), dsm_attach(), dsm_cleanup_for_mmap(), dsm_cleanup_using_control_segment(), dsm_impl_op(), dsm_impl_sysv(), dsm_pin_segment(), dsm_postmaster_shutdown(), dsm_postmaster_startup(), dsm_unpin_segment(), dump_stmt(), dumptuples(), edge_failure(), enable_timeouts(), EncodeSpecialDate(), EncodeSpecialTimestamp(), encrypt_password(), EndTransactionBlock(), enlargeStringInfo(), ensure_active_superblock(), EnsurePortalSnapshotExists(), entryExecPlaceToPage(), entryLoadMoreItems(), entrySplitPage(), eqjoinsel(), equal(), equalsJsonbScalarValue(), err_generic_string(), errdatatype(), errdetail_relkind_not_supported(), estimate_multivariate_ndistinct(), eval_const_expressions_mutator(), eval_windowaggregates(), EvalPlanQualFetchRowMark(), EventTriggerCommonSetup(), EventTriggerInvoke(), examine_attribute(), examine_expression(), examine_simple_variable(), examine_variable(), exec_assign_value(), exec_check_assignable(), exec_dynquery_with_params(), exec_eval_datum(), Exec_ListenPreCommit(), exec_move_row_from_fields(), exec_object_restorecon(), exec_prepare_plan(), exec_replication_command(), exec_run_select(), exec_save_simple_expr(), exec_stmt_block(), exec_stmt_call(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_forc(), exec_stmt_getdiag(), exec_stmt_open(), exec_stmt_raise(), exec_stmt_return(), exec_stmt_return_next(), exec_stmt_return_query(), exec_stmts(), Exec_UnlistenAllCommit(), Exec_UnlistenCommit(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectSchemaStmt(), ExecAlterOwnerStmt(), ExecAsyncConfigureWait(), ExecAsyncNotify(), ExecAsyncRequest(), ExecAsyncResponse(), ExecBitmapAnd(), ExecBitmapIndexScan(), ExecBitmapOr(), ExecBuildAuxRowMark(), ExecBuildUpdateProjection(), ExecCheckIndexConstraints(), ExecCheckRTEPermsModified(), ExecCheckTIDVisible(), ExecComputeStoredGenerated(), ExecCreateTableAs(), ExecCrossPartitionUpdate(), execCurrentOf(), ExecDelete(), ExecEndNode(), ExecEvalFieldSelect(), ExecEvalFieldStoreDeForm(), ExecEvalNextValueExpr(), ExecEvalSysVar(), ExecEvalXmlExpr(), ExecFindRowMark(), ExecGetAncestorResultRels(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Parameter(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecGrantStmt_oids(), ExecHash(), ExecHashJoinImpl(), ExecHashSubPlan(), ExecHashTableCreate(), ExecIndexBuildScanKeys(), ExecIndexMarkPos(), ExecIndexOnlyMarkPos(), ExecIndexOnlyRestrPos(), ExecIndexRestrPos(), ExecInitAgg(), ExecInitCoerceToDomain(), ExecInitExprRec(), ExecInitForeignScan(), ExecInitFunctionResultSet(), ExecInitFunctionScan(), ExecInitHashJoin(), ExecInitMemoize(), ExecInitMerge(), ExecInitMergeJoin(), ExecInitModifyTable(), ExecInitNamedTuplestoreScan(), ExecInitNestLoop(), ExecInitNode(), ExecInitParallelPlan(), ExecInitPartitionInfo(), ExecInitSubPlan(), ExecInitWindowAgg(), ExecLimit(), ExecLockRows(), ExecLookupResultRelByOid(), ExecMarkPos(), ExecMemoize(), ExecMergeJoin(), ExecMergeMatched(), ExecMergeNotMatched(), ExecModifyTable(), ExecOnConflictUpdate(), ExecParallelHashJoinNewBatch(), ExecParallelReportInstrumentation(), ExecParallelRetrieveInstrumentation(), ExecRefreshMatView(), ExecReindex(), ExecRelCheck(), ExecRenameStmt(), ExecReScan(), ExecReScanModifyTable(), ExecReScanSetParamPlan(), ExecRestrPos(), ExecResultMarkPos(), ExecResultRestrPos(), ExecScanReScan(), ExecSetParamPlan(), ExecSetVariableStmt(), ExecStoreBufferHeapTuple(), ExecStoreHeapTuple(), ExecStoreMinimalTuple(), ExecStorePinnedBufferHeapTuple(), ExecSubPlan(), execTuplesHashPrepare(), ExecUpdate(), execute_extension_script(), execute_foreign_modify(), execute_jsp_gin_node(), executeBoolItem(), ExecuteCallStmt(), executeDateTimeMethod(), ExecuteDoStmt(), ExecuteGrantStmt(), executeItemOptUnwrapTarget(), executeItemUnwrapTargetArray(), ExecuteQuery(), ExecWindowAgg(), ExecWithCheckOptions(), expand_all_col_privileges(), expand_col_privileges(), expand_function_arguments(), expand_indexqual_rowcompare(), expand_insert_targetlist(), expand_partitioned_rtentry(), expand_vacuum_rel(), expanded_record_set_field_internal(), expandRecordVariable(), expandRTE(), expandTableLikeClause(), explain_get_index_name(), ExplainExecuteQuery(), ExplainOneUtility(), exprCollation(), expression_tree_mutator_impl(), expression_tree_walker_impl(), exprSetCollation(), exprType(), exprTypmod(), extension_config_remove(), extract_jsp_bool_expr(), FastPathGetRelationLockEntry(), fetch_att(), fetch_finfo_record(), fetch_fp_info(), fetch_function_defaults(), fetch_remote_table_info(), fetch_statentries_for_relation(), FileAccess(), FileClose(), fileGetOptions(), FilePrefetch(), FileRead(), FileSize(), FileSync(), FileTruncate(), FileWrite(), FileWriteback(), fill_seq_fork_with_data(), FillPortalStore(), fillRelOptions(), fillTypeDesc(), finalize_plan(), find_appinfos_by_relids(), find_base_rel(), find_coercion_pathway(), find_expr_references_walker(), find_in_dynamic_libpath(), find_indexpath_quals(), find_inheritance_children_extended(), find_join_input_rel(), find_jointree_node_for_rel(), find_nonnullable_rels_walker(), find_nonnullable_vars_walker(), find_or_make_matching_shared_tupledesc(), find_param_referent(), find_placeholder_info(), find_placeholders_recurse(), find_recursive_union(), find_window_functions_walker(), findDependentObjects(), findFkeyCast(), findoprnd(), findoprnd_recurse(), finish_heap_swap(), FinishSortSupportFunction(), fireASTriggers(), fireBSTriggers(), fix_indexqual_clause(), fix_indexqual_operand(), fix_join_expr_mutator(), fix_param_node(), fix_upper_expr_mutator(), fix_windowagg_condition_expr_mutator(), fixup_inherited_columns(), fixup_whole_row_references(), flatten_reloptions(), flatten_set_variable_args(), flattenJsonPathParseItem(), fmgr_c_validator(), fmgr_info_C_lang(), fmgr_info_cxt_security(), fmgr_info_other_lang(), fmgr_internal_validator(), fmgr_security_definer(), fmgr_sql(), fmgr_sql_validator(), fmgr_symbol(), foreign_join_ok(), forget_invalid_pages(), forget_invalid_pages_db(), ForgetPortalSnapshots(), format_operator_parts(), format_procedure_parts(), format_type_extended(), FormIndexDatum(), FormPartitionKeyDatum(), ForwardSyncRequest(), free_stmt(), FreeDesc(), FreeDir(), FreeFile(), FreePageManagerPutInternal(), FreeVfd(), fsm_search_avail(), fsm_space_needed_to_cat(), func_get_detail(), func_parallel(), func_strict(), func_volatile(), FuncnameGetCandidates(), function_inlinable(), function_selectivity(), FunctionCall0Coll(), FunctionCall1Coll(), FunctionCall2Coll(), FunctionCall3Coll(), FunctionCall4Coll(), FunctionCall5Coll(), FunctionCall6Coll(), FunctionCall7Coll(), FunctionCall8Coll(), FunctionCall9Coll(), FunctionIsVisible(), g_cube_distance(), g_int_compress(), g_int_picksplit(), gbt_num_distance(), gc_qtexts(), gen_prune_steps_from_opexps(), generate_collation_name(), generate_function_name(), generate_nonunion_paths(), generate_operator_clause(), generate_operator_name(), generate_partition_qual(), generate_qualified_relation_name(), generate_qualified_type_name(), generate_recursion_path(), generate_relation_name(), generateClonedExtStatsStmt(), generateClonedIndexStmt(), GenerationFree(), GenerationRealloc(), GenericXLogRegisterBuffer(), geqo(), get_actual_variable_endpoint(), get_agg_combine_expr(), get_altertable_subcmdinfo(), get_am_type_string(), get_attgenerated(), get_attname(), get_attoptions(), get_attstatsslot(), get_attstattarget(), get_atttypetypmodcoll(), get_collation(), get_collation_isdeterministic(), get_columns_length(), get_config_unit_name(), get_controlfile(), get_crosstab_tuplestore(), get_eclass_for_sort_expr(), get_explain_guc_options(), get_from_clause_item(), get_func_arg_info(), get_func_input_arg_names(), get_func_leakproof(), get_func_nargs(), get_func_prokind(), get_func_result_name(), get_func_retset(), get_func_rettype(), get_func_signature(), get_func_trftypes(), get_func_variadictype(), get_function_rows(), get_index_isclustered(), get_index_isvalid(), get_indexpath_pages(), get_insert_query_def(), get_join_variables(), get_jointype_name(), get_language_name(), get_last_relevant_decnum(), get_matching_list_bounds(), get_matching_location(), get_matching_partitions(), get_matching_range_bounds(), get_merged_range_bounds(), get_multirange_io_data(), get_mxact_status_for_lock(), get_name_for_var_field(), get_object_address(), get_object_address_opcf(), get_object_address_opf_member(), get_object_address_relobject(), get_object_address_unqualified(), get_object_namespace(), get_op_opfamily_properties(), get_opclass(), get_opclass_family(), get_opclass_input_type(), get_opclass_name(), get_partition_for_tuple(), get_partition_operator(), get_partition_parent(), get_perl_array_ref(), get_policies_for_relation(), get_primary_key_attnos(), get_publication_name(), get_qual_for_range(), get_qual_from_partbound(), get_query_def(), get_range_io_data(), get_range_key_properties(), get_range_nulltest(), get_rel_persistence(), get_relation_by_qualified_name(), get_relation_column_alias_ids(), get_relation_constraint_attnos(), get_relation_name(), get_relation_statistics(), get_relids_for_join(), get_relids_in_jointree(), get_remote_estimate(), get_ri_constraint_root(), get_rolespec_oid(), get_rolespec_tuple(), get_rte_attribute_is_dropped(), get_rte_attribute_name(), get_rule_expr(), get_segment_by_index(), get_select_query_def(), get_setop_query(), get_sortgroupref_clause(), get_sortgroupref_tle(), get_sublink_expr(), get_subscription_name(), get_sync_bit(), get_ts_parser_func(), get_ts_template_func(), get_tuple_of_interest(), get_typdefault(), get_type_category_preferred(), get_type_io_data(), get_typlenbyval(), get_typlenbyvalalign(), get_utility_query_def(), get_val(), get_variable(), get_view_query(), get_windowfunc_expr(), GetAccessStrategy(), GetAttributeByName(), GetAttributeByNum(), getBaseTypeAndTypmod(), GetBTPageStatistics(), GetCachedPlan(), GetCCHashEqFuncs(), GetCommandLogLevel(), GetCompressionMethodName(), GetConnection(), getConstraintTypeDescription(), GetCTEForRTE(), GetEpochTime(), GetFdwRoutine(), GetFdwRoutineByServerId(), GetForeignColumnOptions(), GetForeignDataWrapperExtended(), GetForeignKeyActionTriggers(), GetForeignKeyCheckTriggers(), GetForeignServerExtended(), GetForeignServerIdByRelId(), GetForeignTable(), getIdentitySequence(), GetIndexAmRoutine(), GetIndexAmRoutineByAmId(), GetIndexInputType(), getInsertSelectQuery(), getIthJsonbValueFromContainer(), getJsonPathItem(), GetLatestSnapshot(), getlen(), GetLockConflicts(), GetNamedLWLockTranche(), GetNewMultiXactId(), GetNewObjectId(), GetNewRelFileNumber(), GetNewTransactionId(), getNextFlagFromString(), GetNSItemByRangeTablePosn(), getObjectClass(), getObjectDescription(), getObjectIdentityParts(), getOpFamilyDescription(), getOpFamilyIdentity(), getProcedureTypeDescription(), GetPublication(), getPublicationSchemaInfo(), getQuadrant(), getRelationDescription(), getRelationIdentity(), getRelationTypeDescription(), GetSerializableTransactionSnapshotInt(), GetSharedMemName(), GetSubscription(), GetSysCacheHashValue(), GetTableAmRoutine(), gettoken_tsvector(), getTokenTypes(), GetTransactionSnapshot(), GetTSConfigTuple(), getTSCurrentConfig(), GetTsmRoutine(), GetTupleForTrigger(), gettype(), getTypeBinaryInputInfo(), getTypeBinaryOutputInfo(), getTypeInputInfo(), getTypeOutputInfo(), GetXLogBuffer(), ghstore_consistent(), ghstore_in(), ghstore_out(), gimme_gene(), gin_btree_compare_prefix(), gin_btree_extract_query(), gin_consistent_hstore(), gin_consistent_jsonb(), gin_consistent_jsonb_path(), gin_extract_hstore_query(), gin_extract_jsonb_path(), gin_extract_jsonb_query(), gin_extract_jsonb_query_path(), gin_extract_query_trgm(), gin_extract_trgm(), gin_extract_tsquery_5args(), gin_extract_tsvector_2args(), gin_leafpage_items(), gin_metapage_info(), gin_page_opaque_info(), gin_redo(), gin_trgm_consistent(), gin_trgm_triconsistent(), gin_triconsistent_jsonb(), gin_triconsistent_jsonb_path(), gin_tsquery_consistent_6args(), ginarrayconsistent(), ginarrayextract_2args(), ginarraytriconsistent(), ginbuild(), gincost_pattern(), gincostestimate(), ginEntryFillRoot(), ginFindParents(), ginFinishSplit(), ginHeapTupleFastCollect(), ginHeapTupleFastInsert(), ginint4_consistent(), ginint4_queryextract(), ginPlaceToPage(), ginqueryarrayextract(), ginReadTuple(), ginRedoInsertEntry(), ginRedoInsertListPage(), ginRedoRecompress(), ginRedoSplit(), ginRedoUpdateMetapage(), ginRedoVacuumPage(), ginStepRight(), ginVacuumEntryPage(), ginVacuumPostingTreeLeaf(), ginvalidate(), gist_bbox_distance(), gist_box_leaf_consistent(), gist_indexsortbuild_flush_ready_pages(), gist_indexsortbuild_levelstate_flush(), gist_page_items(), gist_page_items_bytea(), gist_page_opaque_info(), gist_point_consistent(), gist_point_consistent_internal(), gist_point_distance(), gist_redo(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistbuild(), gistEmptyAllBuffers(), gistfillbuffer(), gistFindPath(), gistGetParent(), gistgettuple(), gistindex_keytest(), gistInitBuffering(), gistplacetopage(), gistRedoPageUpdateRecord(), gistrescan(), gistvalidate(), grow_memtuples(), gtrgm_consistent(), gtrgm_distance(), gtrgm_in(), gtrgm_out(), HandleParallelMessage(), has_dangerous_join_using(), has_row_triggers(), has_subclass(), hash_bitmap_info(), hash_corrupted(), hash_create(), hash_freeze(), hash_metapage_info(), hash_ok_operator(), hash_page_items(), hash_page_stats(), hash_redo(), hash_search_with_hash_value(), hash_update_hash_key(), hash_xlog_insert(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_split_page(), hash_xlog_squeeze_page(), hashbpchar(), hashbpcharextended(), hashbuild(), hashtext(), hashtextextended(), hashvalidate(), heap2_decode(), heap2_redo(), heap_abort_speculative(), heap_attisnull(), heap_create_with_catalog(), heap_decode(), heap_drop_with_catalog(), heap_fetch_toast_slice(), heap_finish_speculative(), heap_getnext(), heap_getsysattr(), heap_inplace_update(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_modify_tuple_by_cols(), heap_page_is_all_visible(), heap_page_items(), heap_prune_chain(), heap_redo(), heap_tuple_infomask_flags(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heapam_index_build_range_scan(), heapam_relation_copy_for_cluster(), heapam_scan_analyze_next_tuple(), HeapCheckForSerializableConflictOut(), hexval(), hide_coercion_node(), HoldPinnedPortals(), hstoreUpgrade(), hypothetical_check_argtypes(), hypothetical_dense_rank_final(), hypothetical_rank_common(), identify_join_columns(), identify_opfamily_groups(), ImportForeignSchema(), ImportSnapshot(), inclusion_get_strategy_procinfo(), IncrementVarSublevelsUp_walker(), index_build(), index_check_primary_key(), index_concurrently_create_copy(), index_concurrently_swap(), index_constraint_create(), index_create(), index_drop(), index_get_partition(), index_getprocinfo(), index_other_operands_eval_cost(), index_set_state_flags(), index_store_float8_orderby_distances(), index_strategy_get_limit(), index_update_stats(), IndexGetRelation(), IndexNextWithReorder(), IndexOnlyNext(), IndexOnlyRecheck(), IndexSetParentIndex(), IndexSupportInitialize(), IndexSupportsBackwardScan(), inet_gist_consistent(), inet_opr_codenum(), inet_to_cidr(), infix(), init_custom_variable(), init_locale(), init_MultiFuncCall(), init_params(), init_sql_fcache(), init_toast_snapshot(), InitAuxiliaryProcess(), initBloomState(), InitCatalogCache(), initGinState(), initGISTstate(), initHyperLogLog(), initial_cost_mergejoin(), initialize_peragg(), initialize_worker_spi(), InitializeBackupManifest(), InitializeLatchSupport(), InitializeMaxBackends(), InitializeOneGUCOption(), InitLatch(), InitLocalBuffers(), InitPlan(), InitPostgres(), InitPostmasterChild(), InitProcess(), InitSharedLatch(), InitStandaloneProcess(), inittapes(), inline_function(), inline_set_returning_function(), InputFunctionCall(), Insert(), insert_timeout(), insert_username(), InsertOneNull(), InsertOneTuple(), InsertOneValue(), InstrEndLoop(), InstrStartNode(), InstrStopNode(), int2_accum_inv(), int2_avg_accum(), int2_avg_accum_inv(), int2int4_sum(), int4_accum_inv(), int4_avg_accum(), int4_avg_accum_inv(), int4_avg_combine(), int8_accum_inv(), int8_avg(), int8_avg_accum_inv(), int8_avg_combine(), int8_avg_deserialize(), int8_avg_serialize(), int_query_opr_selec(), internal_get_result_type(), InternalIpcMemoryCreate(), interpret_func_volatility(), interval_accum(), interval_accum_inv(), interval_avg(), interval_combine(), interval_in(), intervaltypmodleastfield(), intervaltypmodout(), intset_add_member(), intset_update_upper(), inv_getsize(), inv_read(), inv_truncate(), inv_write(), InvalidateAttoptCacheCallback(), InvalidateBuffer(), InvalidateOprCacheCallBack(), InvalidateShippableCacheCallback(), InvalidateTableSpaceCacheCallback(), IpcMemoryDelete(), IpcMemoryDetach(), IpcSemaphoreKill(), irbt_combine(), is_simple_subquery(), is_simple_union_all(), is_simple_union_all_recurse(), isCurrentGroup(), issue_xlog_fsync(), iteratorFromContainer(), join_search_one_level(), join_selectivity(), jointree_contains_lateral_outer_refs(), json_agg_transfn(), json_errdetail(), json_object_agg_transfn(), json_typeof(), jsonb_agg_transfn(), jsonb_get_element(), jsonb_hash(), jsonb_hash_extended(), jsonb_in_scalar(), jsonb_object_agg_transfn(), jsonb_put_escaped_value(), jsonb_recv(), Jsonb_to_SV(), JsonbContainerTypeName(), JsonbDeepContains(), JsonbHashScalarValue(), JsonbHashScalarValueExtended(), JsonbIteratorNext(), JsonbToCStringWorker(), JsonbType(), JsonbTypeName(), JsonbValue_to_SV(), JsonbValueAsText(), JsonEncodeDateTime(), jsonpath_recv(), jspInitByBuffer(), jspOperationName(), JumbleExpr(), JumbleRangeTable(), KnownAssignedXidsAdd(), KnownAssignedXidsDisplay(), KnownAssignedXidsRemove(), KnownAssignedXidsRemovePreceding(), lazy_scan_heap(), lazy_scan_noprune(), lazy_scan_prune(), lc_collate_is_c(), leader_takeover_tapes(), llvm_build_inline_plan(), llvm_compile_module(), llvm_create_types(), llvm_execute_inline_plan(), llvm_get_function(), llvm_load_summary(), llvm_pg_func(), llvm_pg_var_type(), llvm_resolve_symbol(), llvm_session_initialize(), lo_manage(), load_categories_hash(), load_critical_index(), load_domaintype_info(), load_module(), load_multirangetype_info(), load_rangetype_info(), load_relcache_init_file(), load_return_type(), load_typcache_tupdesc(), LoadOutputPlugin(), LocalBufferAlloc(), LocalExecuteInvalidationMessage(), LocalToUtf(), lock_twophase_postcommit(), lock_twophase_recover(), lock_twophase_standby_recover(), LockAcquireExtended(), LockBuffer(), LockBufferForCleanup(), LockCheckConflicts(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockReleaseSession(), LockWaiterCount(), log_invalid_page(), LogCurrentRunningXacts(), logical_heap_rewrite_flush_mappings(), LogicalConfirmReceivedLocation(), LogicalIncreaseRestartDecodingForSlot(), LogicalIncreaseXminForSlot(), logicalmsg_decode(), logicalmsg_redo(), LogicalOutputWrite(), logicalrep_message_type(), logicalrep_read_begin(), logicalrep_read_begin_prepare(), logicalrep_read_commit(), logicalrep_read_commit_prepared(), logicalrep_read_delete(), logicalrep_read_insert(), logicalrep_read_prepare_common(), logicalrep_read_rollback_prepared(), logicalrep_read_stream_commit(), logicalrep_read_tuple(), logicalrep_read_update(), logicalrep_rel_open(), logicalrep_worker_launch(), logicalrep_write_namespace(), logicalrep_write_tuple(), logicalrep_write_typ(), LogicalRepSyncTableStart(), LogicalTapeBackspace(), LogicalTapeCreate(), LogicalTapeSeek(), LogicalTapeWrite(), lookup_am_handler_func(), lookup_collation_cache(), lookup_ts_config_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), LookupBackgroundWorkerFunction(), LookupOpclassInfo(), LookupParallelWorkerFunction(), LookupTypeNameExtended(), lquery_recv(), LruDelete(), LruInsert(), ltree_consistent(), ltree_recv(), ltxtq_recv(), LWLockAcquire(), LWLockAcquireOrWait(), LWLockConditionalAcquire(), LWLockQueueSelf(), LWLockRelease(), lz4_compress_datum(), macaddr_abbrev_abort(), MaintainOldSnapshotTimeMapping(), make_absolute_path(), make_callstmt_target(), make_canonical_pathkey(), make_const(), make_inh_translation_list(), make_inner_pathkeys_for_merge(), make_new_connection(), make_new_heap(), make_one_partition_rbound(), make_partition_op_expr(), make_pathkey_from_sortinfo(), make_pathkey_from_sortop(), make_rel_from_joinlist(), make_result_opt_error(), make_ruledef(), make_scalar_key(), make_sort_from_groupcols(), make_tsvector(), make_tuple_from_result_row(), make_unique_from_pathkeys(), makeBoolAggState(), makeNumericAggState(), makepol(), makeStringAggState(), MakeTidOpExpr(), MakeTransitionCaptureState(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_variable_attnos_mutator(), mark_index_clustered(), MarkBufferDirty(), MarkBufferDirtyHint(), markQueryForLocking(), markRTEForSelectPriv(), markTargetListOrigin(), mask_unused_space(), match_clause_to_partition_key(), match_index_to_operand(), match_network_subset(), match_unsorted_outer(), materializeResult(), max_parallel_hazard_test(), maybe_reread_subscription(), mcelem_array_selec(), mcv_get_match_bitmap(), mcv_match_expression(), mdnblocks(), MemoryContextAlloc(), MemoryContextAllocExtended(), MemoryContextAllocHuge(), MemoryContextAllocZero(), MemoryContextAllocZeroAligned(), MergeAttributes(), mergeruns(), MergeWithExistingConstraint(), minmax_get_strategy_procinfo(), minmax_multi_get_strategy_procinfo(), MJExamineQuals(), mock_scram_secret(), moddatetime(), ModifyWaitEvent(), movedb(), moveLeafs(), mq_putmessage_noblock(), MultiExecBitmapAnd(), MultiExecBitmapOr(), MultiExecProcNode(), multirange_agg_transfn(), multirange_cmp(), multirange_constructor0(), multirange_constructor1(), multirange_constructor2(), multirange_eq_internal(), multirange_get_typcache(), multirange_in(), multirange_intersect_agg_transfn(), multixact_redo(), MultiXactIdCreateFromMembers(), mxstatus_to_string(), NameListToString(), NamespaceCreate(), ndistinct_for_combination(), negate_clause(), network_abbrev_abort(), networkjoinsel(), nextval_internal(), nodeRead(), NotifyMyFrontEnd(), nulltestsel(), NUM_cache_getnew(), NUM_numpart_from_char(), NUM_numpart_to_char(), NUM_processor(), numeric_abbrev_abort(), numeric_accum_inv(), numeric_avg_combine(), numeric_avg_deserialize(), numeric_avg_serialize(), numeric_combine(), numeric_deserialize(), numeric_poly_combine(), numeric_poly_deserialize(), numeric_poly_serialize(), numeric_serialize(), objectNamesToOids(), ObjectsInPublicationToOids(), objectsInSchemaToOids(), oidparse(), op_input_types(), op_strict(), op_volatile(), OpClassCacheLookup(), OpclassIsVisible(), OpenPipeStream(), OpenTemporaryFileInTablespace(), OpenTransientFilePerm(), operator_predicate_proof(), OperatorCreate(), OperatorIsVisible(), OpFamilyCacheLookup(), OpfamilyIsVisible(), ordered_set_startup(), outNode(), OutputPluginPrepareWrite(), OutputPluginWrite(), OwnLatch(), page_header(), PageAddItemExtended(), PageIndexMultiDelete(), PageIndexTupleDelete(), PageIndexTupleDeleteNoCompact(), PageIndexTupleOverwrite(), palloc(), palloc0(), palloc_extended(), parallel_vacuum_main(), parallel_vacuum_process_all_indexes(), parallel_vacuum_process_one_index(), parse_affentry(), parse_format(), parse_func_options(), parse_hstore(), parse_jsonb_index_flags(), parse_lquery(), parse_ltree(), parse_one_reloption(), parse_ooaffentry(), parse_output_parameters(), parse_policy_command(), parse_tsquery(), parseCreateReplSlotOptions(), ParseFuncOrColumn(), parseNodeString(), partition_bounds_create(), partition_bounds_merge(), PartitionHasPendingDetach(), PathNameOpenFilePerm(), pattern_fixed_prefix(), patternsel(), percentile_cont_final_common(), percentile_cont_multi_final_common(), percentile_disc_final(), percentile_disc_multi_final(), perform_pruning_base_step(), perform_pruning_combine_step(), perform_work_item(), PerformCursorOpen(), PerformMembersTruncation(), PerformWalRecovery(), PersistHoldablePortal(), pg_aclmask(), pg_armor(), pg_backup_stop(), pg_buffercache_pages(), pg_collation_actual_version(), pg_column_compression(), pg_column_size(), pg_crc32c_armv8_available(), pg_create_logical_replication_slot(), pg_create_physical_replication_slot(), pg_current_logfile(), pg_current_snapshot(), pg_database_collation_actual_version(), pg_do_encoding_conversion(), pg_event_trigger_ddl_commands(), pg_extension_config_dump(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_object_address(), pg_get_partkeydef_worker(), pg_get_ruledef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_get_viewdef_worker(), pg_get_wal_record_info(), pg_GSS_error_int(), pg_identify_object(), pg_import_system_collations(), pg_isolation_test_session_is_blocked(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), pg_newlocale_from_collation(), pg_parse_query(), pg_perm_setlocale(), pg_plan_query(), pg_relation_filepath(), pg_replication_origin_create(), pg_replication_slot_advance(), pg_rewrite_query(), pg_sequence_parameters(), pg_stat_get_wal_receiver(), pg_stat_statements_info(), pg_stat_statements_internal(), pg_timezone_abbrevs(), pg_type_aclmask(), pg_tzset(), pgfdw_inval_callback(), pgfdw_reset_xact_state(), pgfdw_subxact_callback(), pgfdw_xact_callback(), PGLC_localeconv(), pgoutput_change(), pgoutput_commit_txn(), pgoutput_row_filter(), pgoutput_row_filter_exec_expr(), pgp_armor_decode(), pgp_armor_encode(), pgp_armor_headers(), pgp_extract_armor_headers(), PGReserveSemaphores(), PGSemaphoreCreate(), PGSemaphoreLock(), PGSemaphoreReset(), PGSemaphoreTryLock(), PGSemaphoreUnlock(), PGSharedMemoryCreate(), PGSharedMemoryDetach(), PGSharedMemoryIsInUse(), PGSharedMemoryReAttach(), pgstat_discard_stats(), pgstat_drop_entry_internal(), pgstat_read_statsfile(), pgstat_release_entry_ref(), pgstat_write_statsfile(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), pgstattuple_approx_internal(), pgwin32_ReserveSharedMemoryRegion(), pgwin32_select(), pgxml_result_to_text(), PinPortal(), plperl_event_trigger_handler(), plperl_fini(), plperl_func_handler(), plperl_init_interp(), plperl_inline_handler(), plperl_return_next_internal(), plperl_spi_exec_prepared(), plperl_spi_freeplan(), plperl_spi_prepare(), plperl_spi_query(), plperl_spi_query_prepared(), plperl_trigger_handler(), plperl_util_elog(), plperl_validator(), plpgsql_build_datatype(), plpgsql_build_variable(), plpgsql_call_handler(), plpgsql_compile(), plpgsql_compile_inline(), plpgsql_exec_function(), plpgsql_exec_get_datum_type(), plpgsql_exec_get_datum_type_info(), plpgsql_exec_trigger(), plpgsql_free_function_memory(), plpgsql_fulfill_promise(), plpgsql_HashTableDelete(), plpgsql_HashTableInsert(), plpgsql_inline_handler(), plpgsql_parse_cwordtype(), plpgsql_parse_word(), plpgsql_validator(), plpython3_call_handler(), plpython3_inline_handler(), plpython3_validator(), plsample_func_handler(), plsample_trigger_handler(), pltcl_build_tuple_result(), pltcl_event_trigger_handler(), pltcl_func_handler(), pltcl_init_interp(), pltcl_returnnext(), pltcl_SPI_prepare(), pltcl_trigger_handler(), PLy_current_execution_context(), PLy_cursor_init_type(), PLy_cursor_plan(), PLy_cursor_query(), PLy_exception_set_with_details(), PLy_exec_function(), PLy_exec_trigger(), PLy_modify_tuple(), PLy_plan_init_type(), PLy_pop_execution_context(), PLy_procedure_compile(), PLy_procedure_create(), PLy_procedure_get(), PLy_procedure_munge_source(), PLy_result_init_type(), PLy_spi_exception_set(), PLy_spi_prepare(), PLy_subtransaction_init_type(), PLy_traceback(), PLy_trigger_build_args(), PLyObject_AsString(), PLyObject_FromJsonbContainer(), PLyObject_FromJsonbValue(), PopOverrideSearchPath(), PopTransaction(), populate_joinrel_with_paths(), populate_record_field(), populate_scalar(), PortalRun(), PortalRunFetch(), PosixSemaphoreCreate(), PosixSemaphoreKill(), postgresAnalyzeForeignTable(), postgresBeginForeignInsert(), postgresGetForeignJoinPaths(), postgresGetForeignUpperPaths(), postgresPlanDirectModify(), postgresPlanForeignModify(), PostmasterDeathSignalInit(), PostmasterIsAliveInternal(), PostPrepare_Locks(), postprocess_setop_tlist(), pq_getmsgint(), pq_parse_errornotice(), pq_sendint(), PreCommit_Notify(), PreCommit_Portals(), predicate_implied_by_recurse(), predicate_refuted_by_recurse(), prepare_column_cache(), prepare_sort_from_pathkeys(), PrepareInvalidationState(), preparePresortedCols(), PrepareRedoAdd(), PrepareRedoRemove(), PrepareSortSupportFromGistIndexRel(), PrepareSortSupportFromIndexRel(), PrepareSortSupportFromOrderingOp(), PrepareTransaction(), preprocess_aggref(), preprocess_minmax_aggregates(), preprocess_qual_conditions(), preprocess_targetlist(), PreventInTransactionBlock(), print_function_arguments(), PrintBufferLeakWarning(), PrintCatCacheLeakWarning(), PrintCatCacheListLeakWarning(), PrintCryptoHashLeakWarning(), PrintDSMLeakWarning(), PrintFileLeakWarning(), PrintHMACLeakWarning(), printJsonPathItem(), PrintPlanCacheLeakWarning(), PrintRelCacheLeakWarning(), printsimple(), PrintSnapshotLeakWarning(), PrintTupleDescLeakWarning(), privilege_to_string(), proc_exit(), proc_exit_prepare(), ProcArrayApplyRecoveryInfo(), ProcedureCreate(), process_equivalence(), process_matched_tle(), process_subquery_nestloop_params(), ProcessCatchupInterrupt(), ProcessCommittedInvalidationMessages(), ProcessIncomingNotify(), processIndirection(), ProcessStandbyHSFeedbackMessage(), ProcessStandbyReplyMessage(), ProcessSyncRequests(), ProcessUtilitySlow(), ProcessWalSndrMessage(), ProcSendSignal(), ProcSignalInit(), provider_init(), prune_element_hashtable(), prune_lexemes_hashtable(), pull_up_sublinks_jointree_recurse(), pull_up_subqueries_recurse(), pull_up_union_leaf_queries(), pull_var_clause_walker(), pullup_replace_vars_callback(), push_back_token(), pushJsonbValueScalar(), pushOpStack(), pvsnprintf(), QTNodeCompare(), query_planner(), query_to_oid_list(), query_to_xml_and_xmlschema(), query_to_xmlschema(), querytree(), radius_add_attribute(), random_init_pool(), range_adjacent_internal(), range_after_internal(), range_agg_finalfn(), range_agg_transfn(), range_before_internal(), range_cmp(), range_contains_internal(), range_eq_internal(), range_get_typcache(), range_gist_consistent_int_element(), range_gist_consistent_int_multirange(), range_gist_consistent_int_range(), range_gist_consistent_leaf_element(), range_gist_consistent_leaf_multirange(), range_gist_consistent_leaf_range(), range_gist_penalty(), range_intersect(), range_intersect_agg_transfn(), range_minus(), range_minus_internal(), range_overlaps_internal(), range_overleft_internal(), range_overright_internal(), range_union_internal(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForTruncate(), RangeVarCallbackOwnsRelation(), raw_expression_tree_walker_impl(), raw_heap_insert(), rbt_begin_iterate(), rbt_populate(), read_client_final_message(), read_gucstate(), read_gucstate_binary(), read_seq_tuple(), readDatum(), ReadTempFileBlock(), ReceiveFunctionCall(), ReceiveSharedInvalidMessages(), recheck_cast_function_args(), recomputeNamespacePath(), record_image_cmp(), recordExtObjInitPriv(), RecordKnownAssignedTransactionIds(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), recovery_create_dbdir(), recoveryApplyDelay(), RecoveryConflictInterrupt(), RecoveryRestartPoint(), recurse_push_qual(), recurse_pushdown_safe(), recurse_set_operations(), recv_password_packet(), reduce_outer_joins(), reduce_outer_joins_pass1(), reduce_outer_joins_pass2(), refresh_by_match_merge(), refresh_matview_datafill(), regclassin(), regcollationin(), regconfigin(), regdictionaryin(), register_seq_scan(), RegisterExtensibleNodeEntry(), regnamespacein(), regoperatorin(), regoperin(), regprocedurein(), regprocin(), REGRESS_object_access_hook_str(), regress_setenv(), regrolein(), regtypein(), RehashCatCache(), reindex_index(), reindex_relation(), ReindexRelationConcurrently(), relation_mark_replica_identity(), relation_needs_vacanalyze(), relation_open(), RelationAddExtraBlocks(), RelationBuildDesc(), RelationBuildLocalRelation(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildPublicationDesc(), RelationBuildRowSecurity(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationCacheInitializePhase3(), RelationClearMissing(), RelationClearRelation(), RelationCreateStorage(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), RelationForgetRelation(), RelationGetBufferForTuple(), RelationGetExclusionInfo(), RelationGetIdentityKeyBitmap(), RelationGetIndexAttrBitmap(), relationHasPrimaryKey(), RelationInitIndexAccessInfo(), RelationInitPhysicalAddr(), RelationInitTableAccessMethod(), RelationIsVisible(), RelationMapRemoveMapping(), RelationMapUpdateMap(), RelationPutHeapTuple(), RelationReloadIndexInfo(), RelationSetNewRelfilenumber(), ReleaseBuffer(), ReleaseCurrentSubTransaction(), ReleaseLockIfHeld(), ReleaseLruFile(), ReleaseSavepoint(), RelfilenumberMapInvalidateCallback(), RelidByRelfilenumber(), relmap_redo(), RememberClusterOnForRebuilding(), RememberReplicaIdentityForRebuilding(), remove_rel_from_joinlist(), remove_timeout_index(), remove_useless_joins(), remove_useless_results_recurse(), RemoveAttrDefault(), RemoveAttrDefaultById(), RemoveAttributeById(), RemoveConstraintById(), removeExtObjInitPriv(), RemoveFunctionById(), RemoveGXact(), RemoveInheritance(), RemoveLocalLock(), RemoveNonParentXlogFiles(), RemoveOldXlogFiles(), RemoveOperatorById(), RemovePartitionKeyByRelId(), RemovePolicyById(), RemovePublicationById(), RemovePublicationRelById(), RemovePublicationSchemaById(), RemoveReindexPending(), RemoveRelations(), RemoveRewriteRuleById(), RemoveRoleFromObjectACL(), RemoveRoleFromObjectPolicy(), RemoveStatisticsById(), RemoveTempXlogFiles(), RemoveTriggerById(), RemoveTSConfigurationById(), RemoveTypeById(), RemoveUserMapping(), rename_constraint_internal(), RenameConstraint(), RenameConstraintById(), RenameDatabase(), RenameRelationInternal(), RenameRole(), RenameTableSpace(), RenameType(), RenameTypeInternal(), reorder_function_arguments(), ReorderBufferAbortOld(), ReorderBufferIterTXNNext(), ReorderBufferProcessTXN(), ReorderBufferSerializeTXN(), ReorderBufferToastAppendChunk(), ReorderBufferToastReplace(), repalloc(), repalloc_huge(), replace_rte_variables(), replace_vars_in_jointree(), ReplaceVarsFromTargetList_callback(), replorigin_drop_guts(), replorigin_redo(), report_invalid_page(), report_name_conflict(), report_namespace_conflict(), ReportSlotConnectionError(), RequestAddinShmemSpace(), RequestCheckpoint(), RequestNamedLWLockTranche(), ResetRelRewrite(), ResetSequence(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), resolve_anyarray_from_others(), resolve_anyelement_from_others(), resolve_anymultirange_from_others(), resolve_anyrange_from_others(), resolve_column_ref(), resolve_special_varno(), ResourceOwnerForgetBuffer(), ResourceOwnerForgetCatCacheListRef(), ResourceOwnerForgetCatCacheRef(), ResourceOwnerForgetCryptoHash(), ResourceOwnerForgetDSM(), ResourceOwnerForgetFile(), ResourceOwnerForgetHMAC(), ResourceOwnerForgetJIT(), ResourceOwnerForgetLock(), ResourceOwnerForgetPlanCacheRef(), ResourceOwnerForgetRelationRef(), ResourceOwnerForgetSnapshot(), ResourceOwnerForgetTupleDesc(), RestoreArchivedFile(), RestoreComboCIDState(), RestoreRelationMap(), RestoreSlotFromDisk(), restrict_and_check_grant(), restriction_selectivity(), revmap_get_buffer(), RewriteQuery(), rewriteTargetListIU(), rewriteTargetView(), rewriteValuesRTE(), ri_Check_Pk_Match(), ri_FetchConstraintInfo(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_GenerateQualCollation(), ri_HashCompareOp(), RI_Initial_Check(), ri_LoadConstraintInfo(), RI_PartitionRemove_Check(), ri_PerformCheck(), ri_PlanCheck(), ri_restrict(), ri_set(), roles_is_member_of(), RollbackAndReleaseCurrentSubTransaction(), RollbackToSavepoint(), RS_compile(), RS_execute(), RS_isRegis(), rtree_internal_consistent(), s_check_valid(), s_lock_free_sema(), s_lock_stuck(), SaveCachedPlan(), ScanPgRelation(), ScanSourceDatabasePgClassTuple(), schedule_alarm(), scram_build_secret(), scram_exchange(), scram_verify_plain_password(), SearchSysCacheList(), seg_cmp(), select_rowmark_type(), send_feedback(), SendBackupManifest(), sendDir(), sendFile(), sendFileWithContent(), sepgsql_attribute_post_create(), sepgsql_database_post_create(), sepgsql_fmgr_hook(), sepgsql_object_access(), sepgsql_proc_post_create(), sepgsql_proc_setattr(), sepgsql_relation_post_create(), sepgsql_relation_setattr(), sepgsql_relation_setattr_extra(), sepgsql_schema_post_create(), seq_redo(), sequence_options(), SerializeComboCIDState(), set_baserel_partition_key_exprs(), set_cheapest(), set_config_option_ext(), set_cte_pathlist(), set_join_references(), set_joinrel_partition_key_exprs(), set_max_safe_fds(), set_output_count(), set_plan_refs(), set_rel_pathlist(), set_rel_size(), set_using_names(), set_worktable_pathlist(), SetAttrMissing(), SetDatabaseEncoding(), SetDefaultACL(), SetMatViewPopulatedState(), SetNextObjectId(), setPath(), SetReindexPending(), SetReindexProcessing(), SetRelationHasSubclass(), SetRelationNumChecks(), SetRelationRuleStatus(), SetRelationTableSpace(), SetSingleFuncCall(), Setup_AF_UNIX(), setup_firstcall(), setup_simple_rel_arrays(), SetupLockInTable(), SharedInvalBackendInit(), SharedRecordTypmodRegistryInit(), shdepChangeDep(), shdepDropOwned(), shdepLockAndCheckObject(), shdepReassignOwned(), shell_archive_file(), shm_toc_lookup(), shmem_exit(), show_grouping_set_keys(), show_sort_group_keys(), show_sortorder_options(), SICleanupQueue(), signal_child(), SignalBackends(), simple_heap_delete(), simple_heap_update(), simple_table_tuple_delete(), simple_table_tuple_update(), simplify_function(), SlabAlloc(), SlabContextCreate(), SlabFree(), SlabRealloc(), slot_compile_deform(), slot_getsomeattrs_int(), SlruReportIOError(), SlruScanDirectory(), smgr_redo(), smgrclose(), SnapBuildAddCommittedTxn(), SnapBuildClearExportedSnapshot(), SnapBuildCommitTxn(), SnapBuildDistributeNewCatalogSnapshot(), SnapBuildExportSnapshot(), SnapBuildFreeSnapshot(), SnapBuildInitialSnapshot(), SnapBuildProcessNewCid(), SnapBuildProcessRunningXacts(), SnapBuildPurgeOlderTxn(), SnapBuildSerialize(), SnapBuildSnapDecRefcount(), SnapBuildWaitSnapshot(), spg_box_quad_get_scankey_bbox(), spg_box_quad_inner_consistent(), spg_box_quad_leaf_consistent(), spg_kd_choose(), spg_kd_inner_consistent(), spg_quad_inner_consistent(), spg_quad_leaf_consistent(), spg_range_quad_inner_consistent(), spg_range_quad_leaf_consistent(), spg_redo(), spg_text_inner_consistent(), spg_text_leaf_consistent(), spgAddNodeAction(), spgbuild(), spgdoinsert(), spgExtractNodeLabels(), spgFormInnerTuple(), spgGetCache(), spggettuple(), spgInnerTest(), spgist_name_inner_consistent(), spgist_name_leaf_consistent(), SpGistGetBuffer(), SpGistPageAddNewItem(), spgMatchNodeAction(), spgPageIndexMultiDelete(), spgprocesspending(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoSplitTuple(), spgSplitNodeAction(), spgTestLeafTuple(), spgUpdateNodeLink(), spgvalidate(), spgWalk(), SPI_connect_ext(), SPI_cursor_close(), SPI_cursor_open_internal(), SPI_cursor_open_with_args(), SPI_cursor_parse_open(), SPI_datumTransfer(), spi_dest_startup(), SPI_freetuptable(), SPI_palloc(), spi_printtup(), ss_get_location(), SS_process_ctes(), ss_report_location(), ssl_extension_info(), standard_ExecutorRun(), standard_ExecutorStart(), standard_join_search(), standby_decode(), standby_redo(), StandbyAcquireAccessExclusiveLock(), StandbyReleaseAllLocks(), StandbyReleaseLockList(), StartBackgroundWorker(), StartSubTransaction(), StartTransactionCommand(), StartupReplicationOrigin(), StartupReplicationSlots(), statapprox_heap(), statext_dependencies_deserialize(), statext_dependencies_load(), statext_expressions_load(), statext_is_kind_built(), statext_mcv_deserialize(), statext_mcv_load(), statext_ndistinct_deserialize(), statext_ndistinct_load(), StatisticsGetRelation(), StatisticsObjIsVisible(), store_att_byval(), StoreAttrDefault(), StoreConstraints(), storeObjectDescription(), StorePartitionBound(), storeQueryResult(), storeRow(), StrategyGetBuffer(), stream_open_file(), string_to_const(), stringify_adefprivs_objtype(), stringify_grant_objtype(), sts_initialize(), substitute_actual_parameters_mutator(), substitute_actual_srf_parameters_mutator(), SubTransGetTopmostTransaction(), summarize_range(), swap_relation_files(), SyncRepReleaseWaiters(), SysCacheGetAttr(), SysCacheInvalidate(), SysLoggerMain(), systable_beginscan(), systable_beginscan_ordered(), systable_getnext(), systable_getnext_ordered(), SystemAttributeDefinition(), table_index_fetch_tuple(), table_scan_bitmap_next_block(), table_scan_bitmap_next_tuple(), table_scan_getnextslot(), table_scan_sample_next_block(), table_scan_sample_next_tuple(), table_tuple_fetch_row_version(), table_tuple_get_latest_tid(), tblspc_redo(), tbm_add_tuples(), tbm_intersect(), test_atomic_uint32(), test_atomic_uint64(), test_bloomfilter(), test_empty(), test_enc_conversion(), test_fdw_handler(), test_huge_distances(), test_itemptr_pair(), test_lfind32(), test_lfind8_internal(), test_lfind8_le_internal(), test_pattern(), test_predtest(), test_rb_tree(), test_shm_mq_main(), test_single_value(), test_single_value_and_filler(), test_spinlock(), testdelete(), testfind(), testfindltgt(), testleftmost(), testleftright(), testrightleft(), text_format(), text_substring(), thesaurus_lexize(), thesaurusRead(), TidExprListCreate(), timestamp_in(), timestamptz_in(), tliOfPointInHistory(), toast_compress_datum(), toast_decompress_datum(), toast_decompress_datum_slice(), toast_fetch_datum(), toast_fetch_datum_slice(), toast_open_indexes(), TransactionBlockStatusCode(), TransactionIdDidAbort(), TransactionIdDidCommit(), transformAExprBetween(), transformAlterTableStmt(), transformBooleanTest(), transformBoolExpr(), transformCallStmt(), transformColumnDefinition(), transformConstraintAttrs(), transformCreateSchemaStmt(), transformCreateStmt(), transformDeclareCursorStmt(), transformExprRecurse(), transformFkeyCheckAttrs(), transformFkeyGetPrimaryKey(), transformFromClauseItem(), transformGenericOptions(), transformInsertStmt(), transformLockingClause(), transformMergeStmt(), transformMultiAssignRef(), transformPartitionBound(), transformPartitionBoundValue(), transformPartitionCmd(), transformPLAssignStmt(), transformRangeSubselect(), transformRuleStmt(), transformSubLink(), transformTableConstraint(), transformUpdateTargetList(), transformWindowDefinitions(), trigger_return_old(), triggered_change_notification(), TriggerSetParentTrigger(), TruncateMultiXact(), try_partitionwise_join(), try_relation_open(), tryAttachPartitionForeignKey(), TryReuseForeignKey(), TS_execute_recurse(), TS_phrase_execute(), ts_stat_sql(), TSConfigIsVisible(), TSDictionaryIsVisible(), TSParserIsVisible(), tsquery_opr_selec(), tsquery_requires_match(), tsquery_rewrite_query(), tsqueryrecv(), tsquerysend(), TSTemplateIsVisible(), tsvector_setweight(), tsvector_setweight_by_filter(), tsvector_update_trigger(), tsvectorin(), tsvectorrecv(), tt_setup_firstcall(), ttdummy(), tts_virtual_getsomeattrs(), TupleDescInitBuiltinEntry(), TupleDescInitEntry(), tuplesort_begin_batch(), tuplesort_begin_cluster(), tuplesort_begin_common(), tuplesort_begin_datum(), tuplesort_begin_heap(), tuplesort_begin_index_btree(), tuplesort_begin_index_gist(), tuplesort_begin_index_hash(), tuplesort_free(), tuplesort_gettuple_common(), tuplesort_markpos(), tuplesort_performsort(), tuplesort_puttuple_common(), tuplesort_rescan(), tuplesort_restorepos(), tuplesort_skiptuples(), tuplestore_alloc_read_pointer(), tuplestore_copy_read_pointer(), tuplestore_gettuple(), tuplestore_puttuple_common(), tuplestore_rescan(), tuplestore_select_read_pointer(), tuplestore_set_eflags(), TwoPhaseGetGXact(), TypeCreate(), TypeGetTupleDesc(), typeidType(), typeidTypeRelid(), typeIsOfTypedTable(), TypeIsVisible(), typeOrDomainTypeRelid(), typeTypeId(), unify_hypothetical_args(), UnpinPortal(), update_default_partition_oid(), update_frameheadpos(), update_frametailpos(), update_relispartition(), UpdateActiveSnapshotCommandId(), UpdateDecodingStats(), UpdateLogicalMappings(), UpdateMinRecoveryPoint(), UpdateSharedMemoryConfig(), UpdateSubscriptionRelState(), UpdateTwoPhaseState(), UserAbortTransactionBlock(), UtfToLocal(), uuid_abbrev_abort(), uuid_generate_internal(), vac_update_datfrozenxid(), vac_update_relstats(), vacuumLeafPage(), vacuumLeafRoot(), validate_index(), validatePartitionedIndex(), varstr_abbrev_abort(), varstr_cmp(), varstrfastcmp_locale(), verify_client_proof(), verify_dictoptions(), verify_hash_page(), verifyBackupPageConsistency(), view_has_instead_trigger(), visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_prepare_truncate(), visibilitymap_set(), wait_pid(), WaitForProcSignalBarrier(), WaitForWALToBecomeAvailable(), WaitXLogInsertionsToFinish(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndKeepalive(), wchar2char(), window_gettupleslot(), WinGetFuncArgInFrame(), WinGetFuncArgInPartition(), WinRowsArePeers(), WinSetMarkPosition(), write_item(), write_relcache_init_file(), write_relmap_file(), writeListPage(), WriteTempFileBlock(), X509_NAME_to_cstring(), xact_decode(), xact_redo(), XidCacheRemoveRunningXids(), xlog_decode(), xlog_redo(), XLogBackgroundFlush(), XLogBeginInsert(), XLogCheckInvalidPages(), XLogCompressBackupBlock(), XLogEnsureRecordSpace(), XLogFileCopy(), XLogFileInitInternal(), XLogFileRead(), XLogFileReadAnyTLI(), XLogFlush(), XLogInsert(), XLogInsertRecord(), XLogPrefetcherIsFiltered(), XLogPrefetcherNextBlock(), XLogReadBufferForRedoExtended(), XLogReadDetermineTimeline(), XLogRecGetBlockTag(), XLogRecordAssemble(), xlogrecovery_redo(), XLogRegisterBlock(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), XLogSendLogical(), XLogSendPhysical(), XLogWalRcvSendHSFeedback(), XLogWalRcvSendReply(), XLogWrite(), XmlTableGetValue(), and xpath_table().

◆ escape_param_str()

static char * escape_param_str ( const char *  str)
static

Definition at line 2885 of file dblink.c.

2886 {
2887  const char *cp;
2889 
2890  initStringInfo(&buf);
2891 
2892  for (cp = str; *cp; cp++)
2893  {
2894  if (*cp == '\\' || *cp == '\'')
2895  appendStringInfoChar(&buf, '\\');
2896  appendStringInfoChar(&buf, *cp);
2897  }
2898 
2899  return buf.data;
2900 }
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 2543 of file dblink.c.

2544 {
2545  char *nspname;
2546  char *result;
2547 
2548  /* Qualify the name if not visible in search path */
2550  nspname = NULL;
2551  else
2552  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2553 
2554  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2555 
2556  return result;
2557 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3327
bool RelationIsVisible(Oid relid)
Definition: namespace.c:710
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationGetRelationName(relation)
Definition: rel.h:535
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11640
Form_pg_class rd_rel
Definition: rel.h:110

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

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

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

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

References ACL_USAGE, aclcheck_error(), ACLCHECK_OK, appendStringInfo(), DefElem::arg, buf, DefElem::defname, ereport, errcode(), errdetail(), errmsg(), ERROR, escape_param_str(), ForeignServer::fdwid, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), GetUserMapping(), initStringInfo(), is_valid_dblink_option(), lfirst, OBJECT_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 2056 of file dblink.c.

2057 {
2058  Relation indexRelation;
2059  ScanKeyData skey;
2060  SysScanDesc scan;
2061  HeapTuple indexTuple;
2062  int i;
2063  char **result = NULL;
2064  TupleDesc tupdesc;
2065 
2066  /* initialize indnkeyatts to 0 in case no primary key exists */
2067  *indnkeyatts = 0;
2068 
2069  tupdesc = rel->rd_att;
2070 
2071  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2072  indexRelation = table_open(IndexRelationId, AccessShareLock);
2073  ScanKeyInit(&skey,
2074  Anum_pg_index_indrelid,
2075  BTEqualStrategyNumber, F_OIDEQ,
2077 
2078  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2079  NULL, 1, &skey);
2080 
2081  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2082  {
2083  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2084 
2085  /* we're only interested if it is the primary key */
2086  if (index->indisprimary)
2087  {
2088  *indnkeyatts = index->indnkeyatts;
2089  if (*indnkeyatts > 0)
2090  {
2091  result = palloc_array(char *, *indnkeyatts);
2092 
2093  for (i = 0; i < *indnkeyatts; i++)
2094  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2095  }
2096  break;
2097  }
2098  }
2099 
2100  systable_endscan(scan);
2101  table_close(indexRelation, AccessShareLock);
2102 
2103  return result;
2104 }
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
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
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:111
Definition: type.h:95
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

Referenced by dblink_get_pkey().

◆ get_rel_from_relname()

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

Definition at line 2518 of file dblink.c.

2519 {
2520  RangeVar *relvar;
2521  Relation rel;
2522  AclResult aclresult;
2523 
2524  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2525  rel = table_openrv(relvar, lockmode);
2526 
2527  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2528  aclmode);
2529  if (aclresult != ACLCHECK_OK)
2530  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2532 
2533  return rel;
2534 }
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4953
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:83
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:3654

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

2248 {
2249  char *relname;
2250  TupleDesc tupdesc;
2252  int i;
2253 
2254  initStringInfo(&buf);
2255 
2256  /* get relation name including any needed schema prefix and quoting */
2258 
2259  tupdesc = rel->rd_att;
2260 
2261  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2262  for (i = 0; i < pknumatts; i++)
2263  {
2264  int pkattnum = pkattnums[i];
2265  Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2266 
2267  if (i > 0)
2268  appendStringInfoString(&buf, " AND ");
2269 
2271  quote_ident_cstr(NameStr(attr->attname)));
2272 
2273  if (tgt_pkattvals[i] != NULL)
2274  appendStringInfo(&buf, " = %s",
2275  quote_literal_cstr(tgt_pkattvals[i]));
2276  else
2277  appendStringInfoString(&buf, " IS NULL");
2278  }
2279 
2280  return buf.data;
2281 }
#define NameStr(name)
Definition: c.h:682
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 2167 of file dblink.c.

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

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

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

2112 {
2113  int ndim = ARR_NDIM(array);
2114  int *dims = ARR_DIMS(array);
2115  int nitems;
2116  int16 typlen;
2117  bool typbyval;
2118  char typalign;
2119  char **values;
2120  char *ptr;
2121  bits8 *bitmap;
2122  int bitmask;
2123  int i;
2124 
2125  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2126 
2127  *numitems = nitems = ArrayGetNItems(ndim, dims);
2128 
2130  &typlen, &typbyval, &typalign);
2131 
2132  values = palloc_array(char *, nitems);
2133 
2134  ptr = ARR_DATA_PTR(array);
2135  bitmap = ARR_NULLBITMAP(array);
2136  bitmask = 1;
2137 
2138  for (i = 0; i < nitems; i++)
2139  {
2140  if (bitmap && (*bitmap & bitmask) == 0)
2141  {
2142  values[i] = NULL;
2143  }
2144  else
2145  {
2147  ptr = att_addlength_pointer(ptr, typlen, ptr);
2148  ptr = (char *) att_align_nominal(ptr, typalign);
2149  }
2150 
2151  /* advance bitmap pointer if any */
2152  if (bitmap)
2153  {
2154  bitmask <<= 1;
2155  if (bitmask == 0x100)
2156  {
2157  bitmap++;
2158  bitmask = 1;
2159  }
2160  }
2161  }
2162 
2163  return values;
2164 }
#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:449
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2229
char typalign
Definition: pg_type.h:176
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:129
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:157

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

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

◆ get_tuple_of_interest()

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

Definition at line 2405 of file dblink.c.

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

2562 {
2563  remoteConnHashEnt *hentry;
2564  char *key;
2565 
2566  if (!remoteConnHash)
2568 
2569  key = pstrdup(name);
2570  truncate_identifier(key, strlen(key), false);
2572  key, HASH_FIND, NULL);
2573 
2574  if (hentry)
2575  return hentry->rconn;
2576 
2577  return NULL;
2578 }
@ HASH_FIND
Definition: hsearch.h:113

References createConnHash(), HASH_FIND, hash_search(), sort-test::key, name, pstrdup(), remoteConnHashEnt::rconn, remoteConnHash, and truncate_identifier().

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

◆ is_valid_dblink_option()

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

Definition at line 2989 of file dblink.c.

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

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

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

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

Referenced by dblink_fetch(), and dblink_record_internal().

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 165 of file dblink.c.

167 {
168  if (conname)
169  ereport(ERROR,
170  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
171  errmsg("connection \"%s\" not available", conname)));
172  else
173  ereport(ERROR,
174  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
175  errmsg("connection not available")));
176 }

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

◆ PG_FUNCTION_INFO_V1() [1/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_delete  )

◆ PG_FUNCTION_INFO_V1() [2/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_insert  )

◆ PG_FUNCTION_INFO_V1() [3/20]

PG_FUNCTION_INFO_V1 ( dblink_build_sql_update  )

◆ PG_FUNCTION_INFO_V1() [4/20]

PG_FUNCTION_INFO_V1 ( dblink_cancel_query  )

◆ PG_FUNCTION_INFO_V1() [5/20]

PG_FUNCTION_INFO_V1 ( dblink_close  )

◆ PG_FUNCTION_INFO_V1() [6/20]

PG_FUNCTION_INFO_V1 ( dblink_connect  )

◆ PG_FUNCTION_INFO_V1() [7/20]

PG_FUNCTION_INFO_V1 ( dblink_current_query  )

◆ PG_FUNCTION_INFO_V1() [8/20]

PG_FUNCTION_INFO_V1 ( dblink_disconnect  )

◆ PG_FUNCTION_INFO_V1() [9/20]

PG_FUNCTION_INFO_V1 ( dblink_error_message  )

◆ PG_FUNCTION_INFO_V1() [10/20]

PG_FUNCTION_INFO_V1 ( dblink_exec  )

◆ PG_FUNCTION_INFO_V1() [11/20]

PG_FUNCTION_INFO_V1 ( dblink_fdw_validator  )

◆ PG_FUNCTION_INFO_V1() [12/20]

PG_FUNCTION_INFO_V1 ( dblink_fetch  )

◆ PG_FUNCTION_INFO_V1() [13/20]

PG_FUNCTION_INFO_V1 ( dblink_get_connections  )

◆ PG_FUNCTION_INFO_V1() [14/20]

PG_FUNCTION_INFO_V1 ( dblink_get_notify  )

◆ PG_FUNCTION_INFO_V1() [15/20]

PG_FUNCTION_INFO_V1 ( dblink_get_pkey  )

◆ PG_FUNCTION_INFO_V1() [16/20]

PG_FUNCTION_INFO_V1 ( dblink_get_result  )

◆ PG_FUNCTION_INFO_V1() [17/20]

PG_FUNCTION_INFO_V1 ( dblink_is_busy  )

◆ PG_FUNCTION_INFO_V1() [18/20]

PG_FUNCTION_INFO_V1 ( dblink_open  )

◆ PG_FUNCTION_INFO_V1() [19/20]

PG_FUNCTION_INFO_V1 ( dblink_record  )

◆ PG_FUNCTION_INFO_V1() [20/20]

PG_FUNCTION_INFO_V1 ( dblink_send_query  )

◆ PQclear()

PQclear ( res  )

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

◆ prepTuplestoreResult()

static void prepTuplestoreResult ( FunctionCallInfo  fcinfo)
static

Definition at line 858 of file dblink.c.

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

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

2376 {
2377  text *rawstr_text;
2378  text *result_text;
2379  char *result;
2380 
2381  rawstr_text = cstring_to_text(rawstr);
2383  PointerGetDatum(rawstr_text)));
2384  result = text_to_cstring(result_text);
2385 
2386  return result;
2387 }
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
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 3092 of file dblink.c.

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

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

◆ storeQueryResult()

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

Definition at line 1140 of file dblink.c.

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

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

Referenced by storeQueryResult().

◆ validate_pkattnums()

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

Definition at line 2918 of file dblink.c.

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

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

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

◆ xpstrdup()

static char* xpstrdup ( const char *  in)
static

Definition at line 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_incompatible_polymorphics(), 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_publications_origin(), 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(), 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(), ExecEvalStepOp(), execute_foreign_modify(), execute_jsp_gin_node(), executeAnyItem(), executeBinaryArithmExpr(), executeBoolItem(), executeCommand(), executeDateTimeMethod(), executeItemOptUnwrapResult(), executeItemOptUnwrapResultNoThrow(), executeItemOptUnwrapTarget(), executeJsonPath(), executeKeyValueMethod(),