Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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 "commands/defrem.h"
#include "common/base64.h"
#include "executor/spi.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "libpq-fe.h"
#include "libpq/libpq-be.h"
#include "libpq/libpq-be-fe-helpers.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "parser/scansup.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/varlena.h"
#include "utils/wait_event.h"
Include dependency graph for dblink.c:

Go to the source code of this file.

Data Structures

struct  remoteConn
 
struct  storeInfo
 
struct  remoteConnHashEnt
 

Macros

#define NUMCONN   16
 
#define DBLINK_NOTIFY_COLS   3
 

Typedefs

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

Functions

 PG_MODULE_MAGIC_EXT (.name="dblink",.version=PG_VERSION)
 
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 (storeInfo *sinfo, PGconn *conn, const char *sql)
 
static void storeRow (storeInfo *sinfo, PGresult *res, bool first)
 
static remoteConngetConnectionByName (const char *name)
 
static HTABcreateConnHash (void)
 
static remoteConncreateNewConnection (const char *name)
 
static void deleteConnection (const char *name)
 
static char ** get_pkey_attnames (Relation rel, int16 *indnkeyatts)
 
static char ** get_text_array_contents (ArrayType *array, int *numitems)
 
static char * get_sql_insert (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static char * get_sql_delete (Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
 
static char * get_sql_update (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static char * quote_ident_cstr (char *rawstr)
 
static int get_attnum_pk_pos (int *pkattnums, int pknumatts, int key)
 
static HeapTuple get_tuple_of_interest (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
 
static Relation get_rel_from_relname (text *relname_text, LOCKMODE lockmode, AclMode aclmode)
 
static char * generate_relation_name (Relation rel)
 
static void dblink_connstr_check (const char *connstr)
 
static bool dblink_connstr_has_pw (const char *connstr)
 
static void dblink_security_check (PGconn *conn, const char *connname, const char *connstr)
 
static void dblink_res_error (PGconn *conn, const char *conname, PGresult *res, bool fail, const char *fmt,...) pg_attribute_printf(5
 
static void static char * get_connect_string (const char *servername)
 
static char * escape_param_str (const char *str)
 
static void validate_pkattnums (Relation rel, int2vector *pkattnums_arg, int32 pknumatts_arg, int **pkattnums, int *pknumatts)
 
static bool is_valid_dblink_option (const PQconninfoOption *options, const char *option, Oid context)
 
static int applyRemoteGucs (PGconn *conn)
 
static void restoreLocalGucs (int nestlevel)
 
static bool UseScramPassthrough (ForeignServer *foreign_server, UserMapping *user)
 
static void appendSCRAMKeysInfo (StringInfo buf)
 
static bool is_valid_dblink_fdw_option (const PQconninfoOption *options, const char *option, Oid context)
 
static bool dblink_connstr_has_required_scram_options (const char *connstr)
 
static pg_noreturn void dblink_res_internalerror (PGconn *conn, PGresult *res, const char *p2)
 
static pg_noreturn void dblink_conn_not_avail (const char *conname)
 
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

static remoteConnpconn = NULL
 
static HTABremoteConnHash = NULL
 
static uint32 dblink_we_connect = 0
 
static uint32 dblink_we_get_conn = 0
 
static uint32 dblink_we_get_result = 0
 

Macro Definition Documentation

◆ DBLINK_NOTIFY_COLS

#define DBLINK_NOTIFY_COLS   3

Definition at line 1873 of file dblink.c.

◆ NUMCONN

#define NUMCONN   16

Definition at line 170 of file dblink.c.

Typedef Documentation

◆ remoteConn

typedef struct remoteConn remoteConn

◆ remoteConnHashEnt

◆ storeInfo

typedef struct storeInfo storeInfo

Function Documentation

◆ appendSCRAMKeysInfo()

static void appendSCRAMKeysInfo ( StringInfo  buf)
static

Definition at line 3182 of file dblink.c.

3183{
3184 int len;
3185 int encoded_len;
3186 char *client_key;
3187 char *server_key;
3188
3190 /* don't forget the zero-terminator */
3191 client_key = palloc0(len + 1);
3193 sizeof(MyProcPort->scram_ClientKey),
3194 client_key, len);
3195 if (encoded_len < 0)
3196 elog(ERROR, "could not encode SCRAM client key");
3197
3199 /* don't forget the zero-terminator */
3200 server_key = palloc0(len + 1);
3202 sizeof(MyProcPort->scram_ServerKey),
3203 server_key, len);
3204 if (encoded_len < 0)
3205 elog(ERROR, "could not encode SCRAM server key");
3206
3207 appendStringInfo(buf, "scram_client_key='%s' ", client_key);
3208 appendStringInfo(buf, "scram_server_key='%s' ", server_key);
3209 appendStringInfoString(buf, "require_auth='scram-sha-256' ");
3210
3211 pfree(client_key);
3212 pfree(server_key);
3213}
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
int pg_b64_encode(const uint8 *src, int len, char *dst, int dstlen)
Definition: base64.c:49
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
struct Port * MyProcPort
Definition: globals.c:51
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
const void size_t len
static char * buf
Definition: pg_test_fsync.c:72
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
uint8 scram_ServerKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:187
uint8 scram_ClientKey[SCRAM_MAX_KEY_LEN]
Definition: libpq-be.h:186

References appendStringInfo(), appendStringInfoString(), buf, elog, ERROR, len, MyProcPort, palloc0(), pfree(), pg_b64_enc_len(), pg_b64_encode(), Port::scram_ClientKey, and Port::scram_ServerKey.

Referenced by get_connect_string().

◆ applyRemoteGucs()

static int applyRemoteGucs ( PGconn conn)
static

Definition at line 3118 of file dblink.c.

3119{
3120 static const char *const GUCsAffectingIO[] = {
3121 "DateStyle",
3122 "IntervalStyle"
3123 };
3124
3125 int nestlevel = -1;
3126 int i;
3127
3128 for (i = 0; i < lengthof(GUCsAffectingIO); i++)
3129 {
3130 const char *gucName = GUCsAffectingIO[i];
3131 const char *remoteVal = PQparameterStatus(conn, gucName);
3132 const char *localVal;
3133
3134 /*
3135 * If the remote server is pre-8.4, it won't have IntervalStyle, but
3136 * that's okay because its output format won't be ambiguous. So just
3137 * skip the GUC if we don't get a value for it. (We might eventually
3138 * need more complicated logic with remote-version checks here.)
3139 */
3140 if (remoteVal == NULL)
3141 continue;
3142
3143 /*
3144 * Avoid GUC-setting overhead if the remote and local GUCs already
3145 * have the same value.
3146 */
3147 localVal = GetConfigOption(gucName, false, false);
3148 Assert(localVal != NULL);
3149
3150 if (strcmp(remoteVal, localVal) == 0)
3151 continue;
3152
3153 /* Create new GUC nest level if we didn't already */
3154 if (nestlevel < 0)
3155 nestlevel = NewGUCNestLevel();
3156
3157 /* Apply the option (this will throw error on failure) */
3158 (void) set_config_option(gucName, remoteVal,
3160 GUC_ACTION_SAVE, true, 0, false);
3161 }
3162
3163 return nestlevel;
3164}
#define lengthof(array)
Definition: c.h:788
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7634
int NewGUCNestLevel(void)
Definition: guc.c:2240
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4360
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:3347
@ GUC_ACTION_SAVE
Definition: guc.h:205
@ PGC_S_SESSION
Definition: guc.h:126
@ PGC_USERSET
Definition: guc.h:79
Assert(PointerIsAligned(start, uint64))
int i
Definition: isn.c:77
PGconn * conn
Definition: streamutil.c:52

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

2533{
2534 HASHCTL ctl;
2535
2536 ctl.keysize = NAMEDATALEN;
2537 ctl.entrysize = sizeof(remoteConnHashEnt);
2538
2539 return hash_create("Remote Con hash", NUMCONN, &ctl,
2541}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
#define HASH_STRINGS
Definition: hsearch.h:96
#define HASH_ELEM
Definition: hsearch.h:95
#define NAMEDATALEN
tree ctl
Definition: radixtree.h:1838

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

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

◆ createNewConnection()

static remoteConn * createNewConnection ( const char *  name)
static

Definition at line 2544 of file dblink.c.

2545{
2546 remoteConnHashEnt *hentry;
2547 bool found;
2548 char *key;
2549
2550 if (!remoteConnHash)
2552
2553 key = pstrdup(name);
2554 truncate_identifier(key, strlen(key), true);
2556 HASH_ENTER, &found);
2557
2558 if (found && hentry->rconn.conn != NULL)
2559 ereport(ERROR,
2561 errmsg("duplicate connection name")));
2562
2563 /* New, or reusable, so initialize the rconn struct to zeroes */
2564 memset(&hentry->rconn, 0, sizeof(remoteConn));
2565
2566 return &hentry->rconn;
2567}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ereport(elevel,...)
Definition: elog.h:150
@ HASH_ENTER
Definition: hsearch.h:114
char * pstrdup(const char *in)
Definition: mcxt.c:1759
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
remoteConn rconn
Definition: dblink.c:166
PGconn * conn
Definition: dblink.c:75
const char * name

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

Referenced by dblink_connect().

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1704 of file dblink.c.

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

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

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

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

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

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

1339{
1340 PGconn *conn;
1341 const char *msg;
1342 TimestampTz endtime;
1343
1344 dblink_init();
1347 30000);
1348 msg = libpqsrv_cancel(conn, endtime);
1349 if (msg == NULL)
1350 msg = "OK";
1351
1353}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
int64 TimestampTz
Definition: timestamp.h:39
static const char * libpqsrv_cancel(PGconn *conn, TimestampTz endtime)
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
char * text_to_cstring(const text *t)
Definition: varlena.c:214

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

◆ dblink_close()

Datum dblink_close ( PG_FUNCTION_ARGS  )

Definition at line 495 of file dblink.c.

496{
497 PGconn *conn;
498 PGresult *res = NULL;
499 char *curname = NULL;
500 char *conname = NULL;
502 remoteConn *rconn = NULL;
503 bool fail = true; /* default to backward compatible behavior */
504
505 dblink_init();
507
508 if (PG_NARGS() == 1)
509 {
510 /* text */
512 rconn = pconn;
513 }
514 else if (PG_NARGS() == 2)
515 {
516 /* might be text,text or text,bool */
517 if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
518 {
520 fail = PG_GETARG_BOOL(1);
521 rconn = pconn;
522 }
523 else
524 {
527 rconn = getConnectionByName(conname);
528 }
529 }
530 if (PG_NARGS() == 3)
531 {
532 /* text,text,bool */
535 fail = PG_GETARG_BOOL(2);
536 rconn = getConnectionByName(conname);
537 }
538
539 if (!rconn || !rconn->conn)
540 dblink_conn_not_avail(conname);
541
542 conn = rconn->conn;
543
544 appendStringInfo(&buf, "CLOSE %s", curname);
545
546 /* close the cursor */
548 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
549 {
550 dblink_res_error(conn, conname, res, fail,
551 "while closing cursor \"%s\"", curname);
553 }
554
555 PQclear(res);
556
557 /* if we started a transaction, decrement cursor count */
558 if (rconn->newXactForCursor)
559 {
560 (rconn->openCursorCount)--;
561
562 /* if count is zero, commit the transaction */
563 if (rconn->openCursorCount == 0)
564 {
565 rconn->newXactForCursor = false;
566
567 res = libpqsrv_exec(conn, "COMMIT", dblink_we_get_result);
569 dblink_res_internalerror(conn, res, "commit error");
570 PQclear(res);
571 }
572 }
573
575}
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1874
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
static PGresult * libpqsrv_exec(PGconn *conn, const char *query, uint32 wait_event_info)
#define PQclear
Definition: libpq-be-fe.h:245
#define PQresultStatus
Definition: libpq-be-fe.h:247
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:125
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
bool newXactForCursor
Definition: dblink.c:77
int openCursorCount
Definition: dblink.c:76

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

◆ dblink_conn_not_avail()

static pg_noreturn void dblink_conn_not_avail ( const char *  conname)
static

Definition at line 182 of file dblink.c.

183{
184 if (conname)
186 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
187 errmsg("connection \"%s\" not available", conname)));
188 else
190 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
191 errmsg("connection not available")));
192}

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

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

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 283 of file dblink.c.

284{
285 char *conname_or_str = NULL;
286 char *connstr = NULL;
287 char *connname = NULL;
288 char *msg;
289 PGconn *conn = NULL;
290 remoteConn *rconn = NULL;
291
292 dblink_init();
293
294 if (PG_NARGS() == 2)
295 {
296 conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
297 connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
298 }
299 else if (PG_NARGS() == 1)
300 conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
301
302 /* first check for valid foreign data server */
303 connstr = get_connect_string(conname_or_str);
304 if (connstr == NULL)
305 connstr = conname_or_str;
306
307 /* check password in connection string if not superuser */
309
310 /* first time, allocate or get the custom wait event */
311 if (dblink_we_connect == 0)
312 dblink_we_connect = WaitEventExtensionNew("DblinkConnect");
313
314 /* if we need a hashtable entry, make that first, since it might fail */
315 if (connname)
316 {
317 rconn = createNewConnection(connname);
318 Assert(rconn->conn == NULL);
319 }
320
321 /* OK to make connection */
323
325 {
326 msg = pchomp(PQerrorMessage(conn));
328 if (connname)
329 deleteConnection(connname);
330
332 (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
333 errmsg("could not establish connection"),
334 errdetail_internal("%s", msg)));
335 }
336
338 "received message via remote connection");
339
340 /* check password actually used if not superuser */
342
343 /* attempt to set client encoding to match server encoding, if needed */
346
347 /* all OK, save away the conn */
348 if (connname)
349 {
350 rconn->conn = conn;
351 }
352 else
353 {
354 if (pconn->conn)
356 pconn->conn = conn;
357 }
358
360}
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1234
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7616
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7769
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
Definition: fe-connect.c:7843
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7679
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7777
static PGconn * libpqsrv_connect(const char *conninfo, uint32 wait_event_info)
static void libpqsrv_notice_receiver(void *arg, const PGresult *res)
static void libpqsrv_disconnect(PGconn *conn)
@ CONNECTION_BAD
Definition: libpq-fe.h:85
int GetDatabaseEncoding(void)
Definition: mbutils.c:1262
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1268
char * pchomp(const char *in)
Definition: mcxt.c:1787
static const char * connstr
Definition: pg_dumpall.c:82
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition: wait_event.c:163

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

◆ dblink_connstr_check()

static void dblink_connstr_check ( const char *  connstr)
static

Definition at line 2744 of file dblink.c.

2745{
2746 if (superuser())
2747 return;
2748
2750 return;
2751
2753 return;
2754
2755#ifdef ENABLE_GSS
2757 return;
2758#endif
2759
2760 ereport(ERROR,
2761 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2762 errmsg("password or GSSAPI delegated credentials required"),
2763 errdetail("Non-superusers must provide a password in the connection string or send delegated GSSAPI credentials.")));
2764}
bool be_gssapi_get_delegation(Port *port)
int errdetail(const char *fmt,...)
Definition: elog.c:1207
bool has_scram_keys
Definition: libpq-be.h:188
bool superuser(void)
Definition: superuser.c:46

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

Referenced by dblink_connect(), and dblink_get_conn().

◆ dblink_connstr_has_pw()

static bool dblink_connstr_has_pw ( const char *  connstr)
static

Definition at line 2707 of file dblink.c.

2708{
2711 bool connstr_gives_password = false;
2712
2714 if (options)
2715 {
2716 for (option = options; option->keyword != NULL; option++)
2717 {
2718 if (strcmp(option->keyword, "password") == 0)
2719 {
2720 if (option->val != NULL && option->val[0] != '\0')
2721 {
2722 connstr_gives_password = true;
2723 break;
2724 }
2725 }
2726 }
2728 }
2729
2730 return connstr_gives_password;
2731}
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7500
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:6216
static char ** options
int val
Definition: getopt_long.h:22

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

Referenced by dblink_connstr_check(), and dblink_security_check().

◆ dblink_connstr_has_required_scram_options()

bool dblink_connstr_has_required_scram_options ( const char *  connstr)
static

Definition at line 2601 of file dblink.c.

2602{
2604 bool has_scram_server_key = false;
2605 bool has_scram_client_key = false;
2606 bool has_require_auth = false;
2607 bool has_scram_keys = false;
2608
2610 if (options)
2611 {
2612 /*
2613 * Continue iterating even if we found the keys that we need to
2614 * validate to make sure that there is no other declaration of these
2615 * keys that can overwrite the first.
2616 */
2617 for (PQconninfoOption *option = options; option->keyword != NULL; option++)
2618 {
2619 if (strcmp(option->keyword, "require_auth") == 0)
2620 {
2621 if (option->val != NULL && strcmp(option->val, "scram-sha-256") == 0)
2622 has_require_auth = true;
2623 else
2624 has_require_auth = false;
2625 }
2626
2627 if (strcmp(option->keyword, "scram_client_key") == 0)
2628 {
2629 if (option->val != NULL && option->val[0] != '\0')
2630 has_scram_client_key = true;
2631 else
2632 has_scram_client_key = false;
2633 }
2634
2635 if (strcmp(option->keyword, "scram_server_key") == 0)
2636 {
2637 if (option->val != NULL && option->val[0] != '\0')
2638 has_scram_server_key = true;
2639 else
2640 has_scram_server_key = false;
2641 }
2642 }
2644 }
2645
2646 has_scram_keys = has_scram_client_key && has_scram_server_key && MyProcPort != NULL && MyProcPort->has_scram_keys;
2647
2648 return (has_scram_keys && has_require_auth);
2649}

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

Referenced by dblink_connstr_check(), and dblink_security_check().

◆ dblink_current_query()

Datum dblink_current_query ( PG_FUNCTION_ARGS  )

Definition at line 1859 of file dblink.c.

1860{
1861 /* This is now just an alias for the built-in function current_query() */
1863}
Datum current_query(PG_FUNCTION_ARGS)
Definition: misc.c:211
#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 367 of file dblink.c.

368{
369 char *conname = NULL;
370 remoteConn *rconn = NULL;
371 PGconn *conn = NULL;
372
373 dblink_init();
374
375 if (PG_NARGS() == 1)
376 {
378 rconn = getConnectionByName(conname);
379 if (rconn)
380 conn = rconn->conn;
381 }
382 else
383 conn = pconn->conn;
384
385 if (!conn)
386 dblink_conn_not_avail(conname);
387
389 if (rconn)
390 deleteConnection(conname);
391 else
392 pconn->conn = NULL;
393
395}

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

◆ dblink_error_message()

Datum dblink_error_message ( PG_FUNCTION_ARGS  )

Definition at line 1368 of file dblink.c.

1369{
1370 char *msg;
1371 PGconn *conn;
1372
1373 dblink_init();
1375
1376 msg = PQerrorMessage(conn);
1377 if (msg == NULL || msg[0] == '\0')
1379 else
1381}

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

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

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

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 1930 of file dblink.c.

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

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

◆ dblink_fetch()

Datum dblink_fetch ( PG_FUNCTION_ARGS  )

Definition at line 582 of file dblink.c.

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

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

197{
198 remoteConn *rconn = getConnectionByName(conname_or_str);
199 PGconn *conn;
200 char *conname;
201 bool freeconn;
202
203 if (rconn)
204 {
205 conn = rconn->conn;
206 conname = conname_or_str;
207 freeconn = false;
208 }
209 else
210 {
211 const char *connstr;
212
213 connstr = get_connect_string(conname_or_str);
214 if (connstr == NULL)
215 connstr = conname_or_str;
217
218 /* first time, allocate or get the custom wait event */
219 if (dblink_we_get_conn == 0)
220 dblink_we_get_conn = WaitEventExtensionNew("DblinkGetConnect");
221
222 /* OK to make connection */
224
226 {
227 char *msg = pchomp(PQerrorMessage(conn));
228
231 (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
232 errmsg("could not establish connection"),
233 errdetail_internal("%s", msg)));
234 }
235
237 "received message via remote connection");
238
242 freeconn = true;
243 conname = NULL;
244 }
245
246 *conn_p = conn;
247 *conname_p = conname;
248 *freeconn_p = freeconn;
249}

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

Referenced by dblink_exec(), and dblink_record_internal().

◆ dblink_get_connections()

Datum dblink_get_connections ( PG_FUNCTION_ARGS  )

Definition at line 1276 of file dblink.c.

1277{
1278 HASH_SEQ_STATUS status;
1279 remoteConnHashEnt *hentry;
1280 ArrayBuildState *astate = NULL;
1281
1282 if (remoteConnHash)
1283 {
1284 hash_seq_init(&status, remoteConnHash);
1285 while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1286 {
1287 /* ignore it if it's not an open connection */
1288 if (hentry->rconn.conn == NULL)
1289 continue;
1290 /* stash away current value */
1291 astate = accumArrayResult(astate,
1292 CStringGetTextDatum(hentry->name),
1293 false, TEXTOID, CurrentMemoryContext);
1294 }
1295 }
1296
1297 if (astate)
1300 else
1302}
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5350
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5420
#define CStringGetTextDatum(s)
Definition: builtins.h:97
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1380
#define PG_RETURN_NULL()
Definition: fmgr.h:345
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
char name[NAMEDATALEN]
Definition: dblink.c:165

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

◆ dblink_get_named_conn()

static PGconn * dblink_get_named_conn ( const char *  conname)
static

Definition at line 252 of file dblink.c.

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

References remoteConn::conn, dblink_conn_not_avail(), 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 1877 of file dblink.c.

1878{
1879 PGconn *conn;
1880 PGnotify *notify;
1881 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1882
1883 dblink_init();
1884 if (PG_NARGS() == 1)
1886 else
1887 conn = pconn->conn;
1888
1889 InitMaterializedSRF(fcinfo, 0);
1890
1892 while ((notify = PQnotifies(conn)) != NULL)
1893 {
1895 bool nulls[DBLINK_NOTIFY_COLS];
1896
1897 memset(values, 0, sizeof(values));
1898 memset(nulls, 0, sizeof(nulls));
1899
1900 if (notify->relname != NULL)
1901 values[0] = CStringGetTextDatum(notify->relname);
1902 else
1903 nulls[0] = true;
1904
1905 values[1] = Int32GetDatum(notify->be_pid);
1906
1907 if (notify->extra != NULL)
1908 values[2] = CStringGetTextDatum(notify->extra);
1909 else
1910 nulls[2] = true;
1911
1912 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1913
1914 PQfreemem(notify);
1916 }
1917
1918 return (Datum) 0;
1919}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
void PQfreemem(void *ptr)
Definition: fe-exec.c:4043
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1995
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2678
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
TupleDesc setDesc
Definition: execnodes.h:364
Tuplestorestate * setResult
Definition: execnodes.h:363
int be_pid
Definition: libpq-fe.h:231
char * relname
Definition: libpq-fe.h:230
char * extra
Definition: libpq-fe.h:232
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784

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

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1491 of file dblink.c.

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

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

709{
710 return dblink_record_internal(fcinfo, true);
711}

References dblink_record_internal().

◆ dblink_init()

static void dblink_init ( void  )
static

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1314 of file dblink.c.

1315{
1316 PGconn *conn;
1317
1318 dblink_init();
1320
1323}
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2042
#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 402 of file dblink.c.

403{
404 PGresult *res = NULL;
405 PGconn *conn;
406 char *curname = NULL;
407 char *sql = NULL;
408 char *conname = NULL;
410 remoteConn *rconn = NULL;
411 bool fail = true; /* default to backward compatible behavior */
412
413 dblink_init();
415
416 if (PG_NARGS() == 2)
417 {
418 /* text,text */
421 rconn = pconn;
422 }
423 else if (PG_NARGS() == 3)
424 {
425 /* might be text,text,text or text,text,bool */
426 if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
427 {
430 fail = PG_GETARG_BOOL(2);
431 rconn = pconn;
432 }
433 else
434 {
438 rconn = getConnectionByName(conname);
439 }
440 }
441 else if (PG_NARGS() == 4)
442 {
443 /* text,text,text,bool */
447 fail = PG_GETARG_BOOL(3);
448 rconn = getConnectionByName(conname);
449 }
450
451 if (!rconn || !rconn->conn)
452 dblink_conn_not_avail(conname);
453
454 conn = rconn->conn;
455
456 /* If we are not in a transaction, start one */
458 {
459 res = libpqsrv_exec(conn, "BEGIN", dblink_we_get_result);
461 dblink_res_internalerror(conn, res, "begin error");
462 PQclear(res);
463 rconn->newXactForCursor = true;
464
465 /*
466 * Since transaction state was IDLE, we force cursor count to
467 * initially be 0. This is needed as a previous ABORT might have wiped
468 * out our transaction without maintaining the cursor count for us.
469 */
470 rconn->openCursorCount = 0;
471 }
472
473 /* if we started a transaction, increment cursor count */
474 if (rconn->newXactForCursor)
475 (rconn->openCursorCount)++;
476
477 appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
479 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
480 {
481 dblink_res_error(conn, conname, res, fail,
482 "while opening cursor \"%s\"", curname);
484 }
485
486 PQclear(res);
488}
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:7624
@ PQTRANS_IDLE
Definition: libpq-fe.h:147

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

◆ dblink_record()

Datum dblink_record ( PG_FUNCTION_ARGS  )

Definition at line 676 of file dblink.c.

677{
678 return dblink_record_internal(fcinfo, false);
679}

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 714 of file dblink.c.

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

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

2780{
2781 int level;
2782 char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2783 char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2784 char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2785 char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2786 char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2787 int sqlstate;
2788 va_list ap;
2789 char dblink_context_msg[512];
2790
2791 if (fail)
2792 level = ERROR;
2793 else
2794 level = NOTICE;
2795
2796 if (pg_diag_sqlstate)
2797 sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2798 pg_diag_sqlstate[1],
2799 pg_diag_sqlstate[2],
2800 pg_diag_sqlstate[3],
2801 pg_diag_sqlstate[4]);
2802 else
2803 sqlstate = ERRCODE_CONNECTION_FAILURE;
2804
2805 /*
2806 * If we don't get a message from the PGresult, try the PGconn. This is
2807 * needed because for connection-level failures, PQgetResult may just
2808 * return NULL, not a PGresult at all.
2809 */
2810 if (message_primary == NULL)
2811 message_primary = pchomp(PQerrorMessage(conn));
2812
2813 /*
2814 * Format the basic errcontext string. Below, we'll add on something
2815 * about the connection name. That's a violation of the translatability
2816 * guidelines about constructing error messages out of parts, but since
2817 * there's no translation support for dblink, there's no need to worry
2818 * about that (yet).
2819 */
2820 va_start(ap, fmt);
2821 vsnprintf(dblink_context_msg, sizeof(dblink_context_msg), fmt, ap);
2822 va_end(ap);
2823
2824 ereport(level,
2825 (errcode(sqlstate),
2826 (message_primary != NULL && message_primary[0] != '\0') ?
2827 errmsg_internal("%s", message_primary) :
2828 errmsg("could not obtain message string for remote error"),
2829 message_detail ? errdetail_internal("%s", message_detail) : 0,
2830 message_hint ? errhint("%s", message_hint) : 0,
2831 message_context ? (errcontext("%s", message_context)) : 0,
2832 conname ?
2833 (errcontext("%s on dblink connection named \"%s\"",
2834 dblink_context_msg, conname)) :
2835 (errcontext("%s on unnamed dblink connection",
2836 dblink_context_msg))));
2837 PQclear(res);
2838}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1161
#define errcontext
Definition: elog.h:198
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition: elog.h:56
#define NOTICE
Definition: elog.h:35
#define PQresultErrorField
Definition: libpq-be-fe.h:249
#define vsnprintf
Definition: port.h:238
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:59
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:64

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

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

◆ dblink_res_internalerror()

static pg_noreturn void dblink_res_internalerror ( PGconn conn,
PGresult res,
const char *  p2 
)
static

Definition at line 173 of file dblink.c.

174{
175 char *msg = pchomp(PQerrorMessage(conn));
176
177 PQclear(res);
178 elog(ERROR, "%s: %s", p2, msg);
179}

References conn, elog, ERROR, pchomp(), PQclear, and PQerrorMessage().

Referenced by dblink_close(), and dblink_open().

◆ dblink_security_check()

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

Definition at line 2660 of file dblink.c.

2661{
2662 /* Superuser bypasses security check */
2663 if (superuser())
2664 return;
2665
2666 /* If password was used to connect, make sure it was one provided */
2668 return;
2669
2670 /*
2671 * Password was not used to connect, check if SCRAM pass-through is in
2672 * use.
2673 *
2674 * If dblink_connstr_has_required_scram_options is true we assume that
2675 * UseScramPassthrough is also true because the required SCRAM keys are
2676 * only added if UseScramPassthrough is set, and the user is not allowed
2677 * to add the SCRAM keys on fdw and user mapping options.
2678 */
2680 return;
2681
2682#ifdef ENABLE_GSS
2683 /* If GSSAPI creds used to connect, make sure it was one delegated */
2685 return;
2686#endif
2687
2688 /* Otherwise, fail out */
2690 if (connname)
2691 deleteConnection(connname);
2692
2693 ereport(ERROR,
2694 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2695 errmsg("password or GSSAPI delegated credentials required"),
2696 errdetail("Non-superusers may only connect using credentials they provide, eg: password in connection string or delegated GSSAPI credentials"),
2697 errhint("Ensure provided credentials match target server's authentication method.")));
2698}
int PQconnectionUsedPassword(const PGconn *conn)
Definition: fe-connect.c:7747
int PQconnectionUsedGSSAPI(const PGconn *conn)
Definition: fe-connect.c:7758

References be_gssapi_get_delegation(), conn, connstr, dblink_connstr_has_pw(), dblink_connstr_has_required_scram_options(), deleteConnection(), ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, Port::has_scram_keys, libpqsrv_disconnect(), MyProcPort, PQconnectionUsedGSSAPI(), PQconnectionUsedPassword(), and superuser().

Referenced by dblink_connect(), and dblink_get_conn().

◆ dblink_send_query()

Datum dblink_send_query ( PG_FUNCTION_ARGS  )

Definition at line 683 of file dblink.c.

684{
685 PGconn *conn;
686 char *sql;
687 int retval;
688
689 if (PG_NARGS() == 2)
690 {
693 }
694 else
695 /* shouldn't happen */
696 elog(ERROR, "wrong number of arguments");
697
698 /* async query send */
699 retval = PQsendQuery(conn, sql);
700 if (retval != 1)
701 elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
702
703 PG_RETURN_INT32(retval);
704}
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1427

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

2571{
2572 remoteConnHashEnt *hentry;
2573 bool found;
2574 char *key;
2575
2576 if (!remoteConnHash)
2578
2579 key = pstrdup(name);
2580 truncate_identifier(key, strlen(key), false);
2582 key, HASH_REMOVE, &found);
2583
2584 if (!hentry)
2585 ereport(ERROR,
2586 (errcode(ERRCODE_UNDEFINED_OBJECT),
2587 errmsg("undefined connection name")));
2588}
@ 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_connect(), dblink_disconnect(), and dblink_security_check().

◆ escape_param_str()

static char * escape_param_str ( const char *  str)
static

Definition at line 2942 of file dblink.c.

2943{
2944 const char *cp;
2946
2948
2949 for (cp = str; *cp; cp++)
2950 {
2951 if (*cp == '\\' || *cp == '\'')
2952 appendStringInfoChar(&buf, '\\');
2954 }
2955
2956 return buf.data;
2957}
const char * str
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242

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

Referenced by get_connect_string().

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

Definition at line 2494 of file dblink.c.

2495{
2496 char *nspname;
2497 char *result;
2498
2499 /* Qualify the name if not visible in search path */
2501 nspname = NULL;
2502 else
2503 nspname = get_namespace_name(rel->rd_rel->relnamespace);
2504
2506
2507 return result;
2508}
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3533
bool RelationIsVisible(Oid relid)
Definition: namespace.c:912
#define RelationGetRelid(relation)
Definition: rel.h:514
#define RelationGetRelationName(relation)
Definition: rel.h:548
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:13114
Form_pg_class rd_rel
Definition: rel.h:111

References get_namespace_name(), quote_qualified_identifier(), RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, and RelationIsVisible().

Referenced by get_sql_delete(), get_sql_insert(), get_sql_update(), and get_tuple_of_interest().

◆ get_attnum_pk_pos()

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

Definition at line 2343 of file dblink.c.

2344{
2345 int i;
2346
2347 /*
2348 * Not likely a long list anyway, so just scan for the value
2349 */
2350 for (i = 0; i < pknumatts; i++)
2351 if (key == pkattnums[i])
2352 return i;
2353
2354 return -1;
2355}

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

2845{
2846 ForeignServer *foreign_server = NULL;
2847 UserMapping *user_mapping;
2848 ListCell *cell;
2850 ForeignDataWrapper *fdw;
2851 AclResult aclresult;
2852 char *srvname;
2853
2854 static const PQconninfoOption *options = NULL;
2855
2857
2858 /*
2859 * Get list of valid libpq options.
2860 *
2861 * To avoid unnecessary work, we get the list once and use it throughout
2862 * the lifetime of this backend process. We don't need to care about
2863 * memory context issues, because PQconndefaults allocates with malloc.
2864 */
2865 if (!options)
2866 {
2868 if (!options) /* assume reason for failure is OOM */
2869 ereport(ERROR,
2870 (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2871 errmsg("out of memory"),
2872 errdetail("Could not get libpq's default connection options.")));
2873 }
2874
2875 /* first gather the server connstr options */
2876 srvname = pstrdup(servername);
2877 truncate_identifier(srvname, strlen(srvname), false);
2878 foreign_server = GetForeignServerByName(srvname, true);
2879
2880 if (foreign_server)
2881 {
2882 Oid serverid = foreign_server->serverid;
2883 Oid fdwid = foreign_server->fdwid;
2884 Oid userid = GetUserId();
2885
2886 user_mapping = GetUserMapping(userid, serverid);
2887 fdw = GetForeignDataWrapper(fdwid);
2888
2889 /* Check permissions, user must have usage on the server. */
2890 aclresult = object_aclcheck(ForeignServerRelationId, serverid, userid, ACL_USAGE);
2891 if (aclresult != ACLCHECK_OK)
2892 aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, foreign_server->servername);
2893
2894 /*
2895 * First append hardcoded options needed for SCRAM pass-through, so if
2896 * the user overwrites these options we can ereport on
2897 * dblink_connstr_check and dblink_security_check.
2898 */
2899 if (MyProcPort != NULL && MyProcPort->has_scram_keys && UseScramPassthrough(foreign_server, user_mapping))
2901
2902 foreach(cell, fdw->options)
2903 {
2904 DefElem *def = lfirst(cell);
2905
2906 if (is_valid_dblink_option(options, def->defname, ForeignDataWrapperRelationId))
2907 appendStringInfo(&buf, "%s='%s' ", def->defname,
2908 escape_param_str(strVal(def->arg)));
2909 }
2910
2911 foreach(cell, foreign_server->options)
2912 {
2913 DefElem *def = lfirst(cell);
2914
2915 if (is_valid_dblink_option(options, def->defname, ForeignServerRelationId))
2916 appendStringInfo(&buf, "%s='%s' ", def->defname,
2917 escape_param_str(strVal(def->arg)));
2918 }
2919
2920 foreach(cell, user_mapping->options)
2921 {
2922
2923 DefElem *def = lfirst(cell);
2924
2925 if (is_valid_dblink_option(options, def->defname, UserMappingRelationId))
2926 appendStringInfo(&buf, "%s='%s' ", def->defname,
2927 escape_param_str(strVal(def->arg)));
2928 }
2929
2930 return buf.data;
2931 }
2932 else
2933 return NULL;
2934}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2652
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3834
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition: foreign.c:38
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition: foreign.c:183
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition: foreign.c:201
Oid GetUserId(void)
Definition: miscinit.c:469
#define ACL_USAGE
Definition: parsenodes.h:84
@ OBJECT_FOREIGN_SERVER
Definition: parsenodes.h:2341
Node * arg
Definition: parsenodes.h:843
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, appendSCRAMKeysInfo(), appendStringInfo(), DefElem::arg, buf, DefElem::defname, ereport, errcode(), errdetail(), errmsg(), ERROR, escape_param_str(), ForeignServer::fdwid, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), GetUserMapping(), Port::has_scram_keys, initStringInfo(), is_valid_dblink_option(), lfirst, MyProcPort, object_aclcheck(), OBJECT_FOREIGN_SERVER, ForeignDataWrapper::options, ForeignServer::options, UserMapping::options, PQconndefaults(), pstrdup(), ForeignServer::serverid, ForeignServer::servername, strVal, truncate_identifier(), and UseScramPassthrough().

Referenced by dblink_connect(), and dblink_get_conn().

◆ get_pkey_attnames()

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

Definition at line 2009 of file dblink.c.

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

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

Referenced by dblink_get_pkey().

◆ get_rel_from_relname()

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

Definition at line 2469 of file dblink.c.

2470{
2471 RangeVar *relvar;
2472 Relation rel;
2473 AclResult aclresult;
2474
2475 relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2476 rel = table_openrv(relvar, lockmode);
2477
2478 aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2479 aclmode);
2480 if (aclresult != ACLCHECK_OK)
2481 aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
2483
2484 return rel;
2485}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4037
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3624
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:2686

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

2201{
2202 char *relname;
2203 TupleDesc tupdesc;
2205 int i;
2206
2208
2209 /* get relation name including any needed schema prefix and quoting */
2211
2212 tupdesc = rel->rd_att;
2213
2214 appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2215 for (i = 0; i < pknumatts; i++)
2216 {
2217 int pkattnum = pkattnums[i];
2218 Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2219
2220 if (i > 0)
2221 appendStringInfoString(&buf, " AND ");
2222
2224 quote_ident_cstr(NameStr(attr->attname)));
2225
2226 if (tgt_pkattvals[i] != NULL)
2227 appendStringInfo(&buf, " = %s",
2228 quote_literal_cstr(tgt_pkattvals[i]));
2229 else
2230 appendStringInfoString(&buf, " IS NULL");
2231 }
2232
2233 return buf.data;
2234}
#define NameStr(name)
Definition: c.h:752
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
NameData relname
Definition: pg_class.h:38
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

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

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

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, ereport, errcode(), errmsg(), ERROR, generate_relation_name(), get_attnum_pk_pos(), get_tuple_of_interest(), i, initStringInfo(), sort-test::key, NameStr, TupleDescData::natts, pfree(), pstrdup(), quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, relname, SPI_getvalue(), TupleDescAttr(), and val.

Referenced by dblink_build_sql_insert().

◆ get_sql_update()

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

Definition at line 2237 of file dblink.c.

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

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

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

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

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

◆ get_tuple_of_interest()

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

Definition at line 2358 of file dblink.c.

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

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

Referenced by get_sql_insert(), and get_sql_update().

◆ getConnectionByName()

static remoteConn * getConnectionByName ( const char *  name)
static

Definition at line 2512 of file dblink.c.

2513{
2514 remoteConnHashEnt *hentry;
2515 char *key;
2516
2517 if (!remoteConnHash)
2519
2520 key = pstrdup(name);
2521 truncate_identifier(key, strlen(key), false);
2523 key, HASH_FIND, NULL);
2524
2525 if (hentry && hentry->rconn.conn != NULL)
2526 return &hentry->rconn;
2527
2528 return NULL;
2529}
@ HASH_FIND
Definition: hsearch.h:113

References remoteConn::conn, 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_fdw_option()

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

Definition at line 3098 of file dblink.c.

3100{
3101 if (strcmp(option, "use_scram_passthrough") == 0)
3102 return true;
3103
3104 return is_valid_dblink_option(options, option, context);
3105}

References is_valid_dblink_option().

Referenced by dblink_fdw_validator().

◆ is_valid_dblink_option()

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

Definition at line 3046 of file dblink.c.

3048{
3049 const PQconninfoOption *opt;
3050
3051 /* Look up the option in libpq result */
3052 for (opt = options; opt->keyword; opt++)
3053 {
3054 if (strcmp(opt->keyword, option) == 0)
3055 break;
3056 }
3057 if (opt->keyword == NULL)
3058 return false;
3059
3060 /* Disallow debug options (particularly "replication") */
3061 if (strchr(opt->dispchar, 'D'))
3062 return false;
3063
3064 /* Disallow "client_encoding" */
3065 if (strcmp(opt->keyword, "client_encoding") == 0)
3066 return false;
3067
3068 /*
3069 * Disallow OAuth options for now, since the builtin flow communicates on
3070 * stderr by default and can't cache tokens yet.
3071 */
3072 if (strncmp(opt->keyword, "oauth_", strlen("oauth_")) == 0)
3073 return false;
3074
3075 /*
3076 * If the option is "user" or marked secure, it should be specified only
3077 * in USER MAPPING. Others should be specified only in SERVER.
3078 */
3079 if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
3080 {
3081 if (context != UserMappingRelationId)
3082 return false;
3083 }
3084 else
3085 {
3086 if (context != ForeignServerRelationId)
3087 return false;
3088 }
3089
3090 return true;
3091}

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

Referenced by dblink_fdw_validator(), get_connect_string(), and is_valid_dblink_fdw_option().

◆ materializeQueryResult()

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

Definition at line 993 of file dblink.c.

998{
999 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1000
1001 /* prepTuplestoreResult must have been called previously */
1003
1004 /* Use a PG_TRY block to ensure we pump libpq dry of results */
1005 PG_TRY();
1006 {
1007 storeInfo sinfo = {0};
1008 PGresult *res;
1009
1010 sinfo.fcinfo = fcinfo;
1011 /* Create short-lived memory context for data conversions */
1013 "dblink temporary context",
1015
1016 /* execute query, collecting any tuples into the tuplestore */
1017 res = storeQueryResult(&sinfo, conn, sql);
1018
1019 if (!res ||
1022 {
1023 dblink_res_error(conn, conname, res, fail,
1024 "while executing query");
1025 /* if fail isn't set, we'll return an empty query result */
1026 }
1027 else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1028 {
1029 /*
1030 * storeRow didn't get called, so we need to convert the command
1031 * status string to a tuple manually
1032 */
1033 TupleDesc tupdesc;
1034 AttInMetadata *attinmeta;
1035 Tuplestorestate *tupstore;
1036 HeapTuple tuple;
1037 char *values[1];
1038 MemoryContext oldcontext;
1039
1040 /*
1041 * need a tuple descriptor representing one TEXT column to return
1042 * the command status string as our result tuple
1043 */
1044 tupdesc = CreateTemplateTupleDesc(1);
1045 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1046 TEXTOID, -1, 0);
1047 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1048
1050 tupstore = tuplestore_begin_heap(true, false, work_mem);
1051 rsinfo->setResult = tupstore;
1052 rsinfo->setDesc = tupdesc;
1053 MemoryContextSwitchTo(oldcontext);
1054
1055 values[0] = PQcmdStatus(res);
1056
1057 /* build the tuple and put it into the tuplestore. */
1058 tuple = BuildTupleFromCStrings(attinmeta, values);
1059 tuplestore_puttuple(tupstore, tuple);
1060
1061 PQclear(res);
1062 }
1063 else
1064 {
1066 /* storeRow should have created a tuplestore */
1067 Assert(rsinfo->setResult != NULL);
1068
1069 PQclear(res);
1070 }
1071
1072 /* clean up data conversion short-lived memory context */
1073 if (sinfo.tmpcontext != NULL)
1075
1076 PQclear(sinfo.last_res);
1077 PQclear(sinfo.cur_res);
1078 }
1079 PG_CATCH();
1080 {
1081 PGresult *res;
1082
1083 /* be sure to clear out any pending data in libpq */
1085 NULL)
1086 PQclear(res);
1087 PG_RE_THROW();
1088 }
1089 PG_END_TRY();
1090}
#define PG_RE_THROW()
Definition: elog.h:405
#define PG_CATCH(...)
Definition: elog.h:382
@ SFRM_Materialize
Definition: execnodes.h:341
int work_mem
Definition: globals.c:131
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:469
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:280
SetFunctionReturnMode returnMode
Definition: execnodes.h:360
ExprContext * econtext
Definition: execnodes.h:356
MemoryContext tmpcontext
Definition: dblink.c:85
PGresult * cur_res
Definition: dblink.c:89
FunctionCallInfo fcinfo
Definition: dblink.c:82
PGresult * last_res
Definition: dblink.c:88
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:330
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:764

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), BuildTupleFromCStrings(), conn, CreateTemplateTupleDesc(), storeInfo::cur_res, CurrentMemoryContext, dblink_res_error(), dblink_we_get_result, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, storeInfo::fcinfo, storeInfo::last_res, libpqsrv_get_result(), MemoryContextDelete(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear, PQcmdStatus, PQresultStatus, FunctionCallInfoBaseData::resultinfo, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, storeQueryResult(), storeInfo::tmpcontext, TupleDescGetAttInMetadata(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_puttuple(), values, and work_mem.

Referenced by dblink_record_internal().

◆ materializeResult()

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

Definition at line 862 of file dblink.c.

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

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(), palloc_array, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear, PQcmdStatus, PQgetisnull, PQgetvalue, PQnfields, PQntuples, PQresultStatus, restoreLocalGucs(), FunctionCallInfoBaseData::resultinfo, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, TupleDescGetAttInMetadata(), TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, values, and work_mem.

Referenced by dblink_fetch(), and dblink_record_internal().

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

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "dblink",
version = PG_VERSION 
)

◆ prepTuplestoreResult()

static void prepTuplestoreResult ( FunctionCallInfo  fcinfo)
static

Definition at line 834 of file dblink.c.

835{
836 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
837
838 /* check to see if query supports us returning a tuplestore */
839 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
841 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
842 errmsg("set-valued function called in context that cannot accept a set")));
843 if (!(rsinfo->allowedModes & SFRM_Materialize))
845 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
846 errmsg("materialize mode required, but it is not allowed in this context")));
847
848 /* let the executor know we're sending back a tuplestore */
850
851 /* caller must fill these to return a non-empty result */
852 rsinfo->setResult = NULL;
853 rsinfo->setDesc = NULL;
854}
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
int allowedModes
Definition: execnodes.h:358

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

2329{
2330 text *rawstr_text;
2331 text *result_text;
2332 char *result;
2333
2334 rawstr_text = cstring_to_text(rawstr);
2336 PointerGetDatum(rawstr_text)));
2337 result = text_to_cstring(result_text);
2338
2339 return result;
2340}
#define DatumGetTextPP(X)
Definition: fmgr.h:292
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:682
Datum quote_ident(PG_FUNCTION_ARGS)
Definition: quote.c:25

References cstring_to_text(), DatumGetTextPP, DirectFunctionCall1, PointerGetDatum(), quote_ident(), and text_to_cstring().

Referenced by get_sql_delete(), get_sql_insert(), get_sql_update(), and get_tuple_of_interest().

◆ restoreLocalGucs()

static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3170 of file dblink.c.

3171{
3172 /* Do nothing if no new nestlevel was created */
3173 if (nestlevel > 0)
3174 AtEOXact_GUC(true, nestlevel);
3175}
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2267

References AtEOXact_GUC().

Referenced by materializeResult(), and storeQueryResult().

◆ storeQueryResult()

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

Definition at line 1096 of file dblink.c.

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

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

Referenced by materializeQueryResult().

◆ storeRow()

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

Definition at line 1164 of file dblink.c.

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

References Assert(), storeInfo::attinmeta, BuildTupleFromCStrings(), CreateTupleDescCopy(), storeInfo::cstrs, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, storeInfo::fcinfo, get_call_result_type(), i, if(), MemoryContextReset(), MemoryContextSwitchTo(), palloc_array, pfree(), PQgetisnull, PQgetvalue, PQnfields, PQntuples, FunctionCallInfoBaseData::resultinfo, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, storeInfo::tmpcontext, TupleDescGetAttInMetadata(), storeInfo::tuplestore, tuplestore_begin_heap(), tuplestore_end(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, and work_mem.

Referenced by storeQueryResult().

◆ UseScramPassthrough()

static bool UseScramPassthrough ( ForeignServer foreign_server,
UserMapping user 
)
static

Definition at line 3217 of file dblink.c.

3218{
3219 ListCell *cell;
3220
3221 foreach(cell, foreign_server->options)
3222 {
3223 DefElem *def = lfirst(cell);
3224
3225 if (strcmp(def->defname, "use_scram_passthrough") == 0)
3226 return defGetBoolean(def);
3227 }
3228
3229 foreach(cell, user->options)
3230 {
3231 DefElem *def = (DefElem *) lfirst(cell);
3232
3233 if (strcmp(def->defname, "use_scram_passthrough") == 0)
3234 return defGetBoolean(def);
3235 }
3236
3237 return false;
3238}
bool defGetBoolean(DefElem *def)
Definition: define.c:94
static char * user
Definition: pg_regress.c:119

References defGetBoolean(), DefElem::defname, lfirst, ForeignServer::options, and user.

Referenced by get_connect_string().

◆ validate_pkattnums()

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

Definition at line 2975 of file dblink.c.

2978{
2979 TupleDesc tupdesc = rel->rd_att;
2980 int natts = tupdesc->natts;
2981 int i;
2982
2983 /* Don't take more array elements than there are */
2984 pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2985
2986 /* Must have at least one pk attnum selected */
2987 if (pknumatts_arg <= 0)
2988 ereport(ERROR,
2989 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2990 errmsg("number of key attributes must be > 0")));
2991
2992 /* Allocate output array */
2993 *pkattnums = palloc_array(int, pknumatts_arg);
2994 *pknumatts = pknumatts_arg;
2995
2996 /* Validate attnums and convert to internal form */
2997 for (i = 0; i < pknumatts_arg; i++)
2998 {
2999 int pkattnum = pkattnums_arg->values[i];
3000 int lnum;
3001 int j;
3002
3003 /* Can throw error immediately if out of range */
3004 if (pkattnum <= 0 || pkattnum > natts)
3005 ereport(ERROR,
3006 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3007 errmsg("invalid attribute number %d", pkattnum)));
3008
3009 /* Identify which physical column has this logical number */
3010 lnum = 0;
3011 for (j = 0; j < natts; j++)
3012 {
3013 /* dropped columns don't count */
3014 if (TupleDescAttr(tupdesc, j)->attisdropped)
3015 continue;
3016
3017 if (++lnum == pkattnum)
3018 break;
3019 }
3020
3021 if (j < natts)
3022 (*pkattnums)[i] = j;
3023 else
3024 ereport(ERROR,
3025 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3026 errmsg("invalid attribute number %d", pkattnum)));
3027 }
3028}
#define Min(x, y)
Definition: c.h:1004
int j
Definition: isn.c:78
int dim1
Definition: c.h:726
int16 values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:728

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

Variable Documentation

◆ dblink_we_connect

uint32 dblink_we_connect = 0
static

Definition at line 146 of file dblink.c.

Referenced by dblink_connect().

◆ dblink_we_get_conn

uint32 dblink_we_get_conn = 0
static

Definition at line 147 of file dblink.c.

Referenced by dblink_get_conn().

◆ dblink_we_get_result

◆ pconn

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static