PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/tuplestore.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 charget_sql_insert (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static charget_sql_delete (Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
 
static charget_sql_update (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static charquote_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 chargenerate_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 charget_connect_string (const char *servername)
 
static charescape_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)
 
static void RangeVarCallbackForDblink (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 

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

◆ NUMCONN

#define NUMCONN   16

Definition at line 172 of file dblink.c.

Typedef Documentation

◆ remoteConn

◆ remoteConnHashEnt

◆ storeInfo

Function Documentation

◆ appendSCRAMKeysInfo()

static void appendSCRAMKeysInfo ( StringInfo  buf)
static

Definition at line 3199 of file dblink.c.

3200{
3201 int len;
3202 int encoded_len;
3203 char *client_key;
3204 char *server_key;
3205
3207 /* don't forget the zero-terminator */
3208 client_key = palloc0(len + 1);
3210 sizeof(MyProcPort->scram_ClientKey),
3211 client_key, len);
3212 if (encoded_len < 0)
3213 elog(ERROR, "could not encode SCRAM client key");
3214
3216 /* don't forget the zero-terminator */
3217 server_key = palloc0(len + 1);
3219 sizeof(MyProcPort->scram_ServerKey),
3220 server_key, len);
3221 if (encoded_len < 0)
3222 elog(ERROR, "could not encode SCRAM server key");
3223
3224 appendStringInfo(buf, "scram_client_key='%s' ", client_key);
3225 appendStringInfo(buf, "scram_server_key='%s' ", server_key);
3226 appendStringInfoString(buf, "require_auth='scram-sha-256' ");
3227
3230}
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:40
#define elog(elevel,...)
Definition elog.h:228
struct Port * MyProcPort
Definition globals.c:53
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
const void size_t len
static char buf[DEFAULT_XLOG_SEG_SIZE]
static int fb(int x)
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, fb(), 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 3135 of file dblink.c.

3136{
3137 static const char *const GUCsAffectingIO[] = {
3138 "DateStyle",
3139 "IntervalStyle"
3140 };
3141
3142 int nestlevel = -1;
3143 int i;
3144
3145 for (i = 0; i < lengthof(GUCsAffectingIO); i++)
3146 {
3147 const char *gucName = GUCsAffectingIO[i];
3148 const char *remoteVal = PQparameterStatus(conn, gucName);
3149 const char *localVal;
3150
3151 /*
3152 * If the remote server is pre-8.4, it won't have IntervalStyle, but
3153 * that's okay because its output format won't be ambiguous. So just
3154 * skip the GUC if we don't get a value for it. (We might eventually
3155 * need more complicated logic with remote-version checks here.)
3156 */
3157 if (remoteVal == NULL)
3158 continue;
3159
3160 /*
3161 * Avoid GUC-setting overhead if the remote and local GUCs already
3162 * have the same value.
3163 */
3164 localVal = GetConfigOption(gucName, false, false);
3165 Assert(localVal != NULL);
3166
3167 if (strcmp(remoteVal, localVal) == 0)
3168 continue;
3169
3170 /* Create new GUC nest level if we didn't already */
3171 if (nestlevel < 0)
3173
3174 /* Apply the option (this will throw error on failure) */
3177 GUC_ACTION_SAVE, true, 0, false);
3178 }
3179
3180 return nestlevel;
3181}
#define Assert(condition)
Definition c.h:943
#define lengthof(array)
Definition c.h:873
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
int NewGUCNestLevel(void)
Definition guc.c:2142
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition guc.c:4257
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:3248
@ GUC_ACTION_SAVE
Definition guc.h:205
@ PGC_S_SESSION
Definition guc.h:126
@ PGC_USERSET
Definition guc.h:79
int i
Definition isn.c:77
PGconn * conn
Definition streamutil.c:52

References Assert, conn, fb(), 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 2549 of file dblink.c.

2550{
2551 HASHCTL ctl;
2552
2554 ctl.entrysize = sizeof(remoteConnHashEnt);
2555
2556 return hash_create("Remote Con hash", NUMCONN, &ctl,
2558}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
#define HASH_STRINGS
Definition hsearch.h:91
#define HASH_ELEM
Definition hsearch.h:90
#define NAMEDATALEN
tree ctl
Definition radixtree.h:1838
Size keysize
Definition hsearch.h:69

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

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

◆ createNewConnection()

static remoteConn * createNewConnection ( const char name)
static

Definition at line 2561 of file dblink.c.

2562{
2564 bool found;
2565 char *key;
2566
2567 if (!remoteConnHash)
2569
2570 key = pstrdup(name);
2571 truncate_identifier(key, strlen(key), true);
2573 HASH_ENTER, &found);
2574
2575 if (found && hentry->rconn.conn != NULL)
2576 ereport(ERROR,
2578 errmsg("duplicate connection name")));
2579
2580 /* New, or reusable, so initialize the rconn struct to zeroes */
2581 memset(&hentry->rconn, 0, sizeof(remoteConn));
2582
2583 return &hentry->rconn;
2584}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
int errcode(int sqlerrcode)
Definition elog.c:874
#define ereport(elevel,...)
Definition elog.h:152
@ HASH_ENTER
Definition hsearch.h:109
char * pstrdup(const char *in)
Definition mcxt.c:1781
static char * errmsg
void truncate_identifier(char *ident, int len, bool warn)
Definition scansup.c:81
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
const char * name

References createConnHash(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg, ERROR, fb(), HASH_ENTER, hash_search(), name, pstrdup(), remoteConnHash, and truncate_identifier().

Referenced by dblink_connect().

◆ dblink_build_sql_delete()

Datum dblink_build_sql_delete ( PG_FUNCTION_ARGS  )

Definition at line 1710 of file dblink.c.

1711{
1716 Relation rel;
1717 int *pkattnums;
1718 int pknumatts;
1719 char **tgt_pkattvals;
1720 int tgt_nitems;
1721 char *sql;
1722
1723 /*
1724 * Open target relation.
1725 */
1727
1728 /*
1729 * Process pkattnums argument.
1730 */
1732 &pkattnums, &pknumatts);
1733
1734 /*
1735 * Target array is made up of key values that will be used to build the
1736 * SQL string for use on the remote system.
1737 */
1739
1740 /*
1741 * There should be one target array key value for each key attnum
1742 */
1743 if (tgt_nitems != pknumatts)
1744 ereport(ERROR,
1746 errmsg("target key array length must match number of key attributes")));
1747
1748 /*
1749 * Prep work is finally done. Go get the SQL string.
1750 */
1752
1753 /*
1754 * Now we can close the relation.
1755 */
1757
1758 /*
1759 * And send it
1760 */
1762}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition array.h:263
int32_t int32
Definition c.h:620
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_GETARG_POINTER(n)
Definition fmgr.h:277
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
#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:206
Definition c.h:776
text * cstring_to_text(const char *s)
Definition varlena.c:184

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg, ERROR, fb(), 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 1621 of file dblink.c.

1622{
1628 Relation rel;
1629 int *pkattnums;
1630 int pknumatts;
1631 char **src_pkattvals;
1632 char **tgt_pkattvals;
1633 int src_nitems;
1634 int tgt_nitems;
1635 char *sql;
1636
1637 /*
1638 * Open target relation.
1639 */
1641
1642 /*
1643 * Process pkattnums argument.
1644 */
1646 &pkattnums, &pknumatts);
1647
1648 /*
1649 * Source array is made up of key values that will be used to locate the
1650 * tuple of interest from the local system.
1651 */
1653
1654 /*
1655 * There should be one source array key value for each key attnum
1656 */
1657 if (src_nitems != pknumatts)
1658 ereport(ERROR,
1660 errmsg("source key array length must match number of key attributes")));
1661
1662 /*
1663 * Target array is made up of key values that will be used to build the
1664 * SQL string for use on the remote system.
1665 */
1667
1668 /*
1669 * There should be one target array key value for each key attnum
1670 */
1671 if (tgt_nitems != pknumatts)
1672 ereport(ERROR,
1674 errmsg("target key array length must match number of key attributes")));
1675
1676 /*
1677 * Prep work is finally done. Go get the SQL string.
1678 */
1680
1681 /*
1682 * Now we can close the relation.
1683 */
1685
1686 /*
1687 * And send it
1688 */
1690}

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg, ERROR, fb(), 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 1786 of file dblink.c.

1787{
1793 Relation rel;
1794 int *pkattnums;
1795 int pknumatts;
1796 char **src_pkattvals;
1797 char **tgt_pkattvals;
1798 int src_nitems;
1799 int tgt_nitems;
1800 char *sql;
1801
1802 /*
1803 * Open target relation.
1804 */
1806
1807 /*
1808 * Process pkattnums argument.
1809 */
1811 &pkattnums, &pknumatts);
1812
1813 /*
1814 * Source array is made up of key values that will be used to locate the
1815 * tuple of interest from the local system.
1816 */
1818
1819 /*
1820 * There should be one source array key value for each key attnum
1821 */
1822 if (src_nitems != pknumatts)
1823 ereport(ERROR,
1825 errmsg("source key array length must match number of key attributes")));
1826
1827 /*
1828 * Target array is made up of key values that will be used to build the
1829 * SQL string for use on the remote system.
1830 */
1832
1833 /*
1834 * There should be one target array key value for each key attnum
1835 */
1836 if (tgt_nitems != pknumatts)
1837 ereport(ERROR,
1839 errmsg("target key array length must match number of key attributes")));
1840
1841 /*
1842 * Prep work is finally done. Go get the SQL string.
1843 */
1845
1846 /*
1847 * Now we can close the relation.
1848 */
1850
1851 /*
1852 * And send it
1853 */
1855}

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg, ERROR, fb(), 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 1342 of file dblink.c.

1343{
1344 PGconn *conn;
1345 const char *msg;
1347
1348 dblink_init();
1351 30000);
1353 if (msg == NULL)
1354 msg = "OK";
1355
1357}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
int64 TimestampTz
Definition timestamp.h:39
static const char * libpqsrv_cancel(PGconn *conn, TimestampTz endtime)
#define TimestampTzPlusMilliseconds(tz, ms)
Definition timestamp.h:85
char * text_to_cstring(const text *t)
Definition varlena.c:217

References conn, cstring_to_text(), dblink_get_named_conn(), dblink_init(), fb(), 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 497 of file dblink.c.

498{
499 PGconn *conn;
500 PGresult *res = NULL;
501 char *curname = NULL;
502 char *conname = NULL;
504 remoteConn *rconn = NULL;
505 bool fail = true; /* default to backward compatible behavior */
506
507 dblink_init();
509
510 if (PG_NARGS() == 1)
511 {
512 /* text */
514 rconn = pconn;
515 }
516 else if (PG_NARGS() == 2)
517 {
518 /* might be text,text or text,bool */
519 if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
520 {
522 fail = PG_GETARG_BOOL(1);
523 rconn = pconn;
524 }
525 else
526 {
529 rconn = getConnectionByName(conname);
530 }
531 }
532 if (PG_NARGS() == 3)
533 {
534 /* text,text,bool */
537 fail = PG_GETARG_BOOL(2);
538 rconn = getConnectionByName(conname);
539 }
540
541 if (!rconn || !rconn->conn)
542 dblink_conn_not_avail(conname);
543
544 conn = rconn->conn;
545
546 appendStringInfo(&buf, "CLOSE %s", curname);
547
548 /* close the cursor */
550 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
551 {
552 dblink_res_error(conn, conname, res, fail,
553 "while closing cursor \"%s\"", curname);
555 }
556
557 PQclear(res);
558
559 /* if we started a transaction, decrement cursor count */
560 if (rconn->newXactForCursor)
561 {
562 (rconn->openCursorCount)--;
563
564 /* if count is zero, commit the transaction */
565 if (rconn->openCursorCount == 0)
566 {
567 rconn->newXactForCursor = false;
568
569 res = libpqsrv_exec(conn, "COMMIT", dblink_we_get_result);
571 dblink_res_internalerror(conn, res, "commit error");
572 PQclear(res);
573 }
574 }
575
577}
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition fmgr.c:1876
#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
#define PQresultStatus
@ PGRES_COMMAND_OK
Definition libpq-fe.h:131
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
bool newXactForCursor
Definition dblink.c:79
int openCursorCount
Definition dblink.c:78
PGconn * conn
Definition dblink.c:77

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

185{
186 if (conname)
189 errmsg("connection \"%s\" not available", conname)));
190 else
193 errmsg("connection not available")));
194}

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

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

286{
287 char *conname_or_str = NULL;
288 char *connstr = NULL;
289 char *connname = NULL;
290 char *msg;
291 PGconn *conn = NULL;
292 remoteConn *rconn = NULL;
293
294 dblink_init();
295
296 if (PG_NARGS() == 2)
297 {
300 }
301 else if (PG_NARGS() == 1)
303
304 /* first check for valid foreign data server */
306 if (connstr == NULL)
308
309 /* check password in connection string if not superuser */
311
312 /* first time, allocate or get the custom wait event */
313 if (dblink_we_connect == 0)
314 dblink_we_connect = WaitEventExtensionNew("DblinkConnect");
315
316 /* if we need a hashtable entry, make that first, since it might fail */
317 if (connname)
318 {
320 Assert(rconn->conn == NULL);
321 }
322
323 /* OK to make connection */
325
327 {
328 msg = pchomp(PQerrorMessage(conn));
330 if (connname)
332
335 errmsg("could not establish connection"),
336 errdetail_internal("%s", msg)));
337 }
338
340 "received message via remote connection");
341
342 /* check password actually used if not superuser */
344
345 /* attempt to set client encoding to match server encoding, if needed */
348
349 /* all OK, save away the conn */
350 if (connname)
351 {
352 rconn->conn = conn;
353 }
354 else
355 {
356 if (pconn->conn)
358 pconn->conn = conn;
359 }
360
362}
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
ConnStatusType PQstatus(const PGconn *conn)
int PQclientEncoding(const PGconn *conn)
PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
char * PQerrorMessage(const PGconn *conn)
int PQsetClientEncoding(PGconn *conn, const char *encoding)
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:91
int GetDatabaseEncoding(void)
Definition mbutils.c:1388
const char * GetDatabaseEncodingName(void)
Definition mbutils.c:1394
char * pchomp(const char *in)
Definition mcxt.c:1809
static const char * connstr
Definition pg_dumpall.c:95
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition wait_event.c:149

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

2762{
2763 if (superuser())
2764 return;
2765
2767 return;
2768
2770 return;
2771
2772#ifdef ENABLE_GSS
2774 return;
2775#endif
2776
2777 ereport(ERROR,
2779 errmsg("password or GSSAPI delegated credentials required"),
2780 errdetail("Non-superusers must provide a password in the connection string or send delegated GSSAPI credentials.")));
2781}
bool be_gssapi_get_delegation(Port *port)
int errdetail(const char *fmt,...) pg_attribute_printf(1
bool has_scram_keys
Definition libpq-be.h:188
bool superuser(void)
Definition superuser.c:47

References be_gssapi_get_delegation(), connstr, dblink_connstr_has_pw(), dblink_connstr_has_required_scram_options(), ereport, errcode(), errdetail(), errmsg, ERROR, fb(), 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 2724 of file dblink.c.

2725{
2728 bool connstr_gives_password = false;
2729
2731 if (options)
2732 {
2733 for (option = options; option->keyword != NULL; option++)
2734 {
2735 if (strcmp(option->keyword, "password") == 0)
2736 {
2737 if (option->val != NULL && option->val[0] != '\0')
2738 {
2740 break;
2741 }
2742 }
2743 }
2745 }
2746
2748}
void PQconninfoFree(PQconninfoOption *connOptions)
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
int val
Definition getopt_long.h:22

References connstr, fb(), 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 2618 of file dblink.c.

2619{
2621 bool has_scram_server_key = false;
2622 bool has_scram_client_key = false;
2623 bool has_require_auth = false;
2624 bool has_scram_keys = false;
2625
2627 if (options)
2628 {
2629 /*
2630 * Continue iterating even if we found the keys that we need to
2631 * validate to make sure that there is no other declaration of these
2632 * keys that can overwrite the first.
2633 */
2634 for (PQconninfoOption *option = options; option->keyword != NULL; option++)
2635 {
2636 if (strcmp(option->keyword, "require_auth") == 0)
2637 {
2638 if (option->val != NULL && strcmp(option->val, "scram-sha-256") == 0)
2639 has_require_auth = true;
2640 else
2641 has_require_auth = false;
2642 }
2643
2644 if (strcmp(option->keyword, "scram_client_key") == 0)
2645 {
2646 if (option->val != NULL && option->val[0] != '\0')
2647 has_scram_client_key = true;
2648 else
2649 has_scram_client_key = false;
2650 }
2651
2652 if (strcmp(option->keyword, "scram_server_key") == 0)
2653 {
2654 if (option->val != NULL && option->val[0] != '\0')
2655 has_scram_server_key = true;
2656 else
2657 has_scram_server_key = false;
2658 }
2659 }
2661 }
2662
2664
2665 return (has_scram_keys && has_require_auth);
2666}

References connstr, fb(), Port::has_scram_keys, MyProcPort, 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 1865 of file dblink.c.

1866{
1867 /* This is now just an alias for the built-in function current_query() */
1869}
Datum current_query(PG_FUNCTION_ARGS)
Definition misc.c:228
#define PG_RETURN_DATUM(x)
Definition fmgr.h:354

References current_query(), and PG_RETURN_DATUM.

◆ dblink_disconnect()

Datum dblink_disconnect ( PG_FUNCTION_ARGS  )

Definition at line 369 of file dblink.c.

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

References remoteConn::conn, conn, cstring_to_text(), dblink_conn_not_avail(), dblink_init(), deleteConnection(), fb(), 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 1372 of file dblink.c.

1373{
1374 char *msg;
1375 PGconn *conn;
1376
1377 dblink_init();
1379
1380 msg = PQerrorMessage(conn);
1381 if (msg == NULL || msg[0] == '\0')
1383 else
1385}

References conn, cstring_to_text(), dblink_get_named_conn(), dblink_init(), fb(), 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 1392 of file dblink.c.

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

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

1937{
1939 Oid context = PG_GETARG_OID(1);
1940 ListCell *cell;
1941
1942 static const PQconninfoOption *options = NULL;
1943
1944 /*
1945 * Get list of valid libpq options.
1946 *
1947 * To avoid unnecessary work, we get the list once and use it throughout
1948 * the lifetime of this backend process. We don't need to care about
1949 * memory context issues, because PQconndefaults allocates with malloc.
1950 */
1951 if (!options)
1952 {
1954 if (!options) /* assume reason for failure is OOM */
1955 ereport(ERROR,
1957 errmsg("out of memory"),
1958 errdetail("Could not get libpq's default connection options.")));
1959 }
1960
1961 /* Validate each supplied option. */
1962 foreach(cell, options_list)
1963 {
1964 DefElem *def = (DefElem *) lfirst(cell);
1965
1966 if (!is_valid_dblink_fdw_option(options, def->defname, context))
1967 {
1968 /*
1969 * Unknown option, or invalid option for the context specified, so
1970 * complain about it. Provide a hint with a valid option that
1971 * looks similar, if there is one.
1972 */
1973 const PQconninfoOption *opt;
1974 const char *closest_match;
1976 bool has_valid_options = false;
1977
1979 for (opt = options; opt->keyword; opt++)
1980 {
1981 if (is_valid_dblink_option(options, opt->keyword, context))
1982 {
1983 has_valid_options = true;
1985 }
1986 }
1987
1989 ereport(ERROR,
1991 errmsg("invalid option \"%s\"", def->defname),
1993 errhint("Perhaps you meant the option \"%s\".",
1994 closest_match) : 0 :
1995 errhint("There are no valid options in this context.")));
1996 }
1997 }
1998
2000}
int errhint(const char *fmt,...) pg_attribute_printf(1
PQconninfoOption * PQconndefaults(void)
#define PG_RETURN_VOID()
Definition fmgr.h:350
#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
List * untransformRelOptions(Datum options)
char * defname
Definition parsenodes.h:860
Definition pg_list.h:54
const char * getClosestMatch(ClosestMatchState *state)
Definition varlena.c:5386
void initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
Definition varlena.c:5331
void updateClosestMatch(ClosestMatchState *state, const char *candidate)
Definition varlena.c:5351

References DefElem::defname, ereport, errcode(), errdetail(), errhint(), errmsg, ERROR, fb(), 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 584 of file dblink.c.

585{
586 PGresult *res = NULL;
587 char *conname = NULL;
588 remoteConn *rconn = NULL;
589 PGconn *conn = NULL;
591 char *curname = NULL;
592 int howmany = 0;
593 bool fail = true; /* default to backward compatible */
594
595 prepTuplestoreResult(fcinfo);
596
597 dblink_init();
598
599 if (PG_NARGS() == 4)
600 {
601 /* text,text,int,bool */
605 fail = PG_GETARG_BOOL(3);
606
607 rconn = getConnectionByName(conname);
608 if (rconn)
609 conn = rconn->conn;
610 }
611 else if (PG_NARGS() == 3)
612 {
613 /* text,text,int or text,int,bool */
614 if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
615 {
618 fail = PG_GETARG_BOOL(2);
619 conn = pconn->conn;
620 }
621 else
622 {
626
627 rconn = getConnectionByName(conname);
628 if (rconn)
629 conn = rconn->conn;
630 }
631 }
632 else if (PG_NARGS() == 2)
633 {
634 /* text,int */
637 conn = pconn->conn;
638 }
639
640 if (!conn)
641 dblink_conn_not_avail(conname);
642
644 appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
645
646 /*
647 * Try to execute the query. Note that since libpq uses malloc, the
648 * PGresult will be long-lived even though we are still in a short-lived
649 * memory context.
650 */
652 if (!res ||
655 {
656 dblink_res_error(conn, conname, res, fail,
657 "while fetching from cursor \"%s\"", curname);
658 return (Datum) 0;
659 }
660 else if (PQresultStatus(res) == PGRES_COMMAND_OK)
661 {
662 /* cursor does not exist - closed already or bad name */
663 PQclear(res);
666 errmsg("cursor \"%s\" does not exist", curname)));
667 }
668
669 materializeResult(fcinfo, conn, res);
670 return (Datum) 0;
671}
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, fb(), 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 197 of file dblink.c.

199{
201 PGconn *conn;
202 char *conname;
203 bool freeconn;
204
205 if (rconn)
206 {
207 conn = rconn->conn;
208 conname = conname_or_str;
209 freeconn = false;
210 }
211 else
212 {
213 const char *connstr;
214
216 if (connstr == NULL)
219
220 /* first time, allocate or get the custom wait event */
221 if (dblink_we_get_conn == 0)
222 dblink_we_get_conn = WaitEventExtensionNew("DblinkGetConnect");
223
224 /* OK to make connection */
226
228 {
229 char *msg = pchomp(PQerrorMessage(conn));
230
234 errmsg("could not establish connection"),
235 errdetail_internal("%s", msg)));
236 }
237
239 "received message via remote connection");
240
244 freeconn = true;
245 conname = NULL;
246 }
247
248 *conn_p = conn;
249 *conname_p = conname;
251}

References remoteConn::conn, conn, CONNECTION_BAD, connstr, dblink_connstr_check(), dblink_security_check(), dblink_we_get_conn, ereport, errcode(), errdetail_internal(), errmsg, ERROR, fb(), 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 1280 of file dblink.c.

1281{
1282 HASH_SEQ_STATUS status;
1284 ArrayBuildState *astate = NULL;
1285
1286 if (remoteConnHash)
1287 {
1288 hash_seq_init(&status, remoteConnHash);
1289 while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1290 {
1291 /* ignore it if it's not an open connection */
1292 if (hentry->rconn.conn == NULL)
1293 continue;
1294 /* stash away current value */
1295 astate = accumArrayResult(astate,
1298 }
1299 }
1300
1301 if (astate)
1304 else
1306}
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
#define CStringGetTextDatum(s)
Definition builtins.h:98
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
#define PG_RETURN_NULL()
Definition fmgr.h:346
MemoryContext CurrentMemoryContext
Definition mcxt.c:160

References accumArrayResult(), CStringGetTextDatum, CurrentMemoryContext, fb(), hash_seq_init(), hash_seq_search(), makeArrayResult(), PG_RETURN_DATUM, PG_RETURN_NULL, and remoteConnHash.

◆ dblink_get_named_conn()

static PGconn * dblink_get_named_conn ( const char conname)
static

Definition at line 254 of file dblink.c.

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

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

1884{
1885 PGconn *conn;
1887 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1888
1889 dblink_init();
1890 if (PG_NARGS() == 1)
1892 else
1893 conn = pconn->conn;
1894
1895 InitMaterializedSRF(fcinfo, 0);
1896
1898 while ((notify = PQnotifies(conn)) != NULL)
1899 {
1901 bool nulls[DBLINK_NOTIFY_COLS];
1902
1903 memset(values, 0, sizeof(values));
1904 memset(nulls, 0, sizeof(nulls));
1905
1906 if (notify->relname != NULL)
1907 values[0] = CStringGetTextDatum(notify->relname);
1908 else
1909 nulls[0] = true;
1910
1911 values[1] = Int32GetDatum(notify->be_pid);
1912
1913 if (notify->extra != NULL)
1914 values[2] = CStringGetTextDatum(notify->extra);
1915 else
1916 nulls[2] = true;
1917
1918 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1919
1922 }
1923
1924 return (Datum) 0;
1925}
static Datum values[MAXATTR]
Definition bootstrap.c:190
void PQfreemem(void *ptr)
Definition fe-exec.c:4049
int PQconsumeInput(PGconn *conn)
Definition fe-exec.c:2001
PGnotify * PQnotifies(PGconn *conn)
Definition fe-exec.c:2684
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags)
Definition funcapi.c:76
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785

References remoteConn::conn, conn, CStringGetTextDatum, dblink_get_named_conn(), dblink_init(), DBLINK_NOTIFY_COLS, fb(), InitMaterializedSRF(), Int32GetDatum(), pconn, PG_GETARG_TEXT_PP, PG_NARGS, PQconsumeInput(), PQfreemem(), PQnotifies(), text_to_cstring(), tuplestore_putvalues(), and values.

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1495 of file dblink.c.

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

References AccessShareLock, ACL_SELECT, BuildTupleFromCStrings(), CreateTemplateTupleDesc(), fb(), get_pkey_attnames(), get_rel_from_relname(), HeapTupleGetDatum(), MemoryContextSwitchTo(), palloc_array, PG_GETARG_TEXT_PP, psprintf(), relation_close(), result, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TupleDescFinalize(), TupleDescGetAttInMetadata(), TupleDescInitEntry(), and values.

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 710 of file dblink.c.

711{
712 return dblink_record_internal(fcinfo, true);
713}

References dblink_record_internal().

◆ dblink_init()

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1318 of file dblink.c.

1319{
1320 PGconn *conn;
1321
1322 dblink_init();
1324
1327}
int PQisBusy(PGconn *conn)
Definition fe-exec.c:2048
#define PG_RETURN_INT32(x)
Definition fmgr.h:355

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

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

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

679{
680 return dblink_record_internal(fcinfo, false);
681}

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 716 of file dblink.c.

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

2797{
2798 int level;
2804 int sqlstate;
2805 va_list ap;
2806 char dblink_context_msg[512];
2807
2808 if (fail)
2809 level = ERROR;
2810 else
2811 level = NOTICE;
2812
2813 if (pg_diag_sqlstate)
2814 sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2818 pg_diag_sqlstate[4]);
2819 else
2820 sqlstate = ERRCODE_CONNECTION_FAILURE;
2821
2822 /*
2823 * If we don't get a message from the PGresult, try the PGconn. This is
2824 * needed because for connection-level failures, PQgetResult may just
2825 * return NULL, not a PGresult at all.
2826 */
2827 if (message_primary == NULL)
2829
2830 /*
2831 * Format the basic errcontext string. Below, we'll add on something
2832 * about the connection name. That's a violation of the translatability
2833 * guidelines about constructing error messages out of parts, but since
2834 * there's no translation support for dblink, there's no need to worry
2835 * about that (yet).
2836 */
2837 va_start(ap, fmt);
2839 va_end(ap);
2840
2841 ereport(level,
2842 (errcode(sqlstate),
2843 (message_primary != NULL && message_primary[0] != '\0') ?
2845 errmsg("could not obtain message string for remote error"),
2847 message_hint ? errhint("%s", message_hint) : 0,
2849 conname ?
2850 (errcontext("%s on dblink connection named \"%s\"",
2851 dblink_context_msg, conname)) :
2852 (errcontext("%s on unnamed dblink connection",
2854 PQclear(res);
2855}
#define errcontext
Definition elog.h:200
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition elog.h:58
#define NOTICE
Definition elog.h:36
#define PQresultErrorField
#define vsnprintf
Definition port.h:259
#define PG_DIAG_MESSAGE_HINT
#define PG_DIAG_SQLSTATE
#define PG_DIAG_MESSAGE_PRIMARY
#define PG_DIAG_MESSAGE_DETAIL
#define PG_DIAG_CONTEXT

References conn, ereport, errcode(), errcontext, errdetail_internal(), errhint(), errmsg, errmsg_internal(), ERROR, fb(), 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 175 of file dblink.c.

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

References conn, elog, ERROR, fb(), 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 2677 of file dblink.c.

2678{
2679 /* Superuser bypasses security check */
2680 if (superuser())
2681 return;
2682
2683 /* If password was used to connect, make sure it was one provided */
2685 return;
2686
2687 /*
2688 * Password was not used to connect, check if SCRAM pass-through is in
2689 * use.
2690 *
2691 * If dblink_connstr_has_required_scram_options is true we assume that
2692 * UseScramPassthrough is also true because the required SCRAM keys are
2693 * only added if UseScramPassthrough is set, and the user is not allowed
2694 * to add the SCRAM keys on fdw and user mapping options.
2695 */
2697 return;
2698
2699#ifdef ENABLE_GSS
2700 /* If GSSAPI creds used to connect, make sure it was one delegated */
2702 return;
2703#endif
2704
2705 /* Otherwise, fail out */
2707 if (connname)
2709
2710 ereport(ERROR,
2712 errmsg("password or GSSAPI delegated credentials required"),
2713 errdetail("Non-superusers may only connect using credentials they provide, eg: password in connection string or delegated GSSAPI credentials"),
2714 errhint("Ensure provided credentials match target server's authentication method.")));
2715}
int PQconnectionUsedPassword(const PGconn *conn)
int PQconnectionUsedGSSAPI(const PGconn *conn)

References be_gssapi_get_delegation(), conn, connstr, dblink_connstr_has_pw(), dblink_connstr_has_required_scram_options(), deleteConnection(), ereport, errcode(), errdetail(), errhint(), errmsg, ERROR, fb(), 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 685 of file dblink.c.

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

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

2588{
2590 bool found;
2591 char *key;
2592
2593 if (!remoteConnHash)
2595
2596 key = pstrdup(name);
2597 truncate_identifier(key, strlen(key), false);
2599 key, HASH_REMOVE, &found);
2600
2601 if (!hentry)
2602 ereport(ERROR,
2604 errmsg("undefined connection name")));
2605}
@ HASH_REMOVE
Definition hsearch.h:110

References createConnHash(), ereport, errcode(), errmsg, ERROR, fb(), HASH_REMOVE, hash_search(), 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 2959 of file dblink.c.

2960{
2961 const char *cp;
2963
2965
2966 for (cp = str; *cp; cp++)
2967 {
2968 if (*cp == '\\' || *cp == '\'')
2969 appendStringInfoChar(&buf, '\\');
2971 }
2972
2973 return buf.data;
2974}
const char * str
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242

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

Referenced by get_connect_string().

◆ generate_relation_name()

static char * generate_relation_name ( Relation  rel)
static

Definition at line 2511 of file dblink.c.

2512{
2513 char *nspname;
2514 char *result;
2515
2516 /* Qualify the name if not visible in search path */
2518 nspname = NULL;
2519 else
2520 nspname = get_namespace_name(rel->rd_rel->relnamespace);
2521
2523
2524 return result;
2525}
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3588
bool RelationIsVisible(Oid relid)
Definition namespace.c:914
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetRelationName(relation)
Definition rel.h:550
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Form_pg_class rd_rel
Definition rel.h:111

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

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

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

References fb(), and i.

Referenced by get_sql_insert(), and get_sql_update().

◆ get_connect_string()

static char * get_connect_string ( const char servername)
static

Definition at line 2861 of file dblink.c.

2862{
2863 ForeignServer *foreign_server = NULL;
2865 ListCell *cell;
2869 char *srvname;
2870
2871 static const PQconninfoOption *options = NULL;
2872
2874
2875 /*
2876 * Get list of valid libpq options.
2877 *
2878 * To avoid unnecessary work, we get the list once and use it throughout
2879 * the lifetime of this backend process. We don't need to care about
2880 * memory context issues, because PQconndefaults allocates with malloc.
2881 */
2882 if (!options)
2883 {
2885 if (!options) /* assume reason for failure is OOM */
2886 ereport(ERROR,
2888 errmsg("out of memory"),
2889 errdetail("Could not get libpq's default connection options.")));
2890 }
2891
2892 /* first gather the server connstr options */
2893 srvname = pstrdup(servername);
2895 foreign_server = GetForeignServerByName(srvname, true);
2896
2897 if (foreign_server)
2898 {
2899 Oid serverid = foreign_server->serverid;
2900 Oid fdwid = foreign_server->fdwid;
2901 Oid userid = GetUserId();
2902
2903 user_mapping = GetUserMapping(userid, serverid);
2904 fdw = GetForeignDataWrapper(fdwid);
2905
2906 /* Check permissions, user must have usage on the server. */
2908 if (aclresult != ACLCHECK_OK)
2910
2911 /*
2912 * First append hardcoded options needed for SCRAM pass-through, so if
2913 * the user overwrites these options we can ereport on
2914 * dblink_connstr_check and dblink_security_check.
2915 */
2918
2919 foreach(cell, fdw->options)
2920 {
2921 DefElem *def = lfirst(cell);
2922
2924 appendStringInfo(&buf, "%s='%s' ", def->defname,
2925 escape_param_str(strVal(def->arg)));
2926 }
2927
2928 foreach(cell, foreign_server->options)
2929 {
2930 DefElem *def = lfirst(cell);
2931
2933 appendStringInfo(&buf, "%s='%s' ", def->defname,
2934 escape_param_str(strVal(def->arg)));
2935 }
2936
2937 foreach(cell, user_mapping->options)
2938 {
2939
2940 DefElem *def = lfirst(cell);
2941
2943 appendStringInfo(&buf, "%s='%s' ", def->defname,
2944 escape_param_str(strVal(def->arg)));
2945 }
2946
2947 return buf.data;
2948 }
2949 else
2950 return NULL;
2951}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
ForeignDataWrapper * GetForeignDataWrapper(Oid fdwid)
Definition foreign.c:39
ForeignServer * GetForeignServerByName(const char *srvname, bool missing_ok)
Definition foreign.c:185
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition foreign.c:232
Oid GetUserId(void)
Definition miscinit.c:470
#define ACL_USAGE
Definition parsenodes.h:84
@ OBJECT_FOREIGN_SERVER
Node * arg
Definition parsenodes.h:861
List * options
Definition foreign.h:43
char * servername
Definition foreign.h:40
#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(), fb(), ForeignServer::fdwid, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), GetUserMapping(), Port::has_scram_keys, initStringInfo(), is_valid_dblink_option(), lfirst, MyProcPort, object_aclcheck(), OBJECT_FOREIGN_SERVER, ForeignServer::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 2015 of file dblink.c.

2016{
2017 Relation indexRelation;
2019 SysScanDesc scan;
2021 int i;
2022 char **result = NULL;
2023 TupleDesc tupdesc;
2024
2025 /* initialize indnkeyatts to 0 in case no primary key exists */
2026 *indnkeyatts = 0;
2027
2028 tupdesc = rel->rd_att;
2029
2030 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2031 indexRelation = table_open(IndexRelationId, AccessShareLock);
2036
2037 scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2038 NULL, 1, &skey);
2039
2041 {
2043
2044 /* we're only interested if it is the primary key */
2045 if (index->indisprimary)
2046 {
2047 *indnkeyatts = index->indnkeyatts;
2048 if (*indnkeyatts > 0)
2049 {
2050 result = palloc_array(char *, *indnkeyatts);
2051
2052 for (i = 0; i < *indnkeyatts; i++)
2053 result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2054 }
2055 break;
2056 }
2057 }
2058
2059 systable_endscan(scan);
2060 table_close(indexRelation, AccessShareLock);
2061
2062 return result;
2063}
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:612
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:523
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)
END_CATALOG_STRUCT typedef FormData_pg_index * Form_pg_index
Definition pg_index.h:74
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition spi.c:1199
#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, fb(), Form_pg_index, GETSTRUCT(), HeapTupleIsValid, i, ObjectIdGetDatum(), palloc_array, RelationData::rd_att, RelationGetRelid, result, 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 2492 of file dblink.c.

2493{
2495 Oid relid;
2496
2498 relid = RangeVarGetRelidExtended(relvar, lockmode, 0,
2500
2501 return table_open(relid, NoLock);
2502}
#define NoLock
Definition lockdefs.h:34
RangeVar * makeRangeVarFromNameList(const List *names)
Definition namespace.c:3626
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:442
List * textToQualifiedNameList(text *textval)
Definition varlena.c:2719

References fb(), makeRangeVarFromNameList(), NoLock, RangeVarCallbackForDblink(), RangeVarGetRelidExtended(), table_open(), 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 2208 of file dblink.c.

2209{
2210 char *relname;
2211 TupleDesc tupdesc;
2213 int i;
2214
2216
2217 /* get relation name including any needed schema prefix and quoting */
2219
2220 tupdesc = rel->rd_att;
2221
2222 appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2223 for (i = 0; i < pknumatts; i++)
2224 {
2225 int pkattnum = pkattnums[i];
2226 Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2227
2228 if (i > 0)
2229 appendStringInfoString(&buf, " AND ");
2230
2232 quote_ident_cstr(NameStr(attr->attname)));
2233
2234 if (tgt_pkattvals[i] != NULL)
2235 appendStringInfo(&buf, " = %s",
2237 else
2238 appendStringInfoString(&buf, " IS NULL");
2239 }
2240
2241 return buf.data;
2242}
#define NameStr(name)
Definition c.h:835
FormData_pg_attribute * Form_pg_attribute
NameData relname
Definition pg_class.h:40
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References appendStringInfo(), appendStringInfoString(), buf, fb(), 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 2128 of file dblink.c.

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

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, ereport, errcode(), errmsg, ERROR, fb(), generate_relation_name(), get_attnum_pk_pos(), get_tuple_of_interest(), i, initStringInfo(), 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 2245 of file dblink.c.

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

References appendStringInfo(), appendStringInfoString(), buf, ereport, errcode(), errmsg, ERROR, fb(), generate_relation_name(), get_attnum_pk_pos(), get_tuple_of_interest(), i, initStringInfo(), 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 2070 of file dblink.c.

2071{
2072 int ndim = ARR_NDIM(array);
2073 int *dims = ARR_DIMS(array);
2074 int nitems;
2075 int16 typlen;
2076 bool typbyval;
2077 char typalign;
2078 uint8 typalignby;
2079 char **values;
2080 char *ptr;
2081 uint8 *bitmap;
2082 int bitmask;
2083 int i;
2084
2085 Assert(ARR_ELEMTYPE(array) == TEXTOID);
2086
2087 *numitems = nitems = ArrayGetNItems(ndim, dims);
2088
2090 &typlen, &typbyval, &typalign);
2091 typalignby = typalign_to_alignby(typalign);
2092
2093 values = palloc_array(char *, nitems);
2094
2095 ptr = ARR_DATA_PTR(array);
2096 bitmap = ARR_NULLBITMAP(array);
2097 bitmask = 1;
2098
2099 for (i = 0; i < nitems; i++)
2100 {
2101 if (bitmap && (*bitmap & bitmask) == 0)
2102 {
2103 values[i] = NULL;
2104 }
2105 else
2106 {
2108 ptr = att_addlength_pointer(ptr, typlen, ptr);
2109 ptr = (char *) att_nominal_alignby(ptr, typalignby);
2110 }
2111
2112 /* advance bitmap pointer if any */
2113 if (bitmap)
2114 {
2115 bitmask <<= 1;
2116 if (bitmask == 0x100)
2117 {
2118 bitmap++;
2119 bitmask = 1;
2120 }
2121 }
2122 }
2123
2124 return values;
2125}
#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:99
uint8_t uint8
Definition c.h:622
#define nitems(x)
Definition indent.h:31
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2491
char typalign
Definition pg_type.h:178
static Datum PointerGetDatum(const void *X)
Definition postgres.h:342
#define att_nominal_alignby(cur_offset, attalignby)
Definition tupmacs.h:411
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition tupmacs.h:431
static uint8 typalign_to_alignby(char typalign)
Definition tupmacs.h:302

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, ARR_NULLBITMAP, ArrayGetNItems(), Assert, att_addlength_pointer, att_nominal_alignby, fb(), get_typlenbyvalalign(), i, nitems, palloc_array, PointerGetDatum(), TextDatumGetCString, typalign, typalign_to_alignby(), 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 2366 of file dblink.c.

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

References appendStringInfo(), appendStringInfoString(), buf, ereport, errcode(), errmsg, ERROR, fb(), 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 2529 of file dblink.c.

2530{
2532 char *key;
2533
2534 if (!remoteConnHash)
2536
2537 key = pstrdup(name);
2538 truncate_identifier(key, strlen(key), false);
2540 key, HASH_FIND, NULL);
2541
2542 if (hentry && hentry->rconn.conn != NULL)
2543 return &hentry->rconn;
2544
2545 return NULL;
2546}
@ HASH_FIND
Definition hsearch.h:108

References createConnHash(), fb(), HASH_FIND, hash_search(), name, pstrdup(), 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 3115 of file dblink.c.

3117{
3118 if (strcmp(option, "use_scram_passthrough") == 0)
3119 return true;
3120
3121 return is_valid_dblink_option(options, option, context);
3122}

References fb(), and 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 3063 of file dblink.c.

3065{
3066 const PQconninfoOption *opt;
3067
3068 /* Look up the option in libpq result */
3069 for (opt = options; opt->keyword; opt++)
3070 {
3071 if (strcmp(opt->keyword, option) == 0)
3072 break;
3073 }
3074 if (opt->keyword == NULL)
3075 return false;
3076
3077 /* Disallow debug options (particularly "replication") */
3078 if (strchr(opt->dispchar, 'D'))
3079 return false;
3080
3081 /* Disallow "client_encoding" */
3082 if (strcmp(opt->keyword, "client_encoding") == 0)
3083 return false;
3084
3085 /*
3086 * Disallow OAuth options for now, since the builtin flow communicates on
3087 * stderr by default and can't cache tokens yet.
3088 */
3089 if (strncmp(opt->keyword, "oauth_", strlen("oauth_")) == 0)
3090 return false;
3091
3092 /*
3093 * If the option is "user" or marked secure, it should be specified only
3094 * in USER MAPPING. Others should be specified only in SERVER.
3095 */
3096 if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
3097 {
3098 if (context != UserMappingRelationId)
3099 return false;
3100 }
3101 else
3102 {
3103 if (context != ForeignServerRelationId)
3104 return false;
3105 }
3106
3107 return true;
3108}

References _PQconninfoOption::dispchar, fb(), 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 996 of file dblink.c.

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

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BuildTupleFromCStrings(), conn, CreateTemplateTupleDesc(), storeInfo::cur_res, CurrentMemoryContext, dblink_res_error(), dblink_we_get_result, fb(), 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, SFRM_Materialize, storeQueryResult(), storeInfo::tmpcontext, TupleDescFinalize(), 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 864 of file dblink.c.

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

References applyRemoteGucs(), Assert, BuildTupleFromCStrings(), conn, CreateTemplateTupleDesc(), CreateTupleDescCopy(), elog, ereport, errcode(), errmsg, ERROR, fb(), get_call_result_type(), i, MemoryContextSwitchTo(), TupleDescData::natts, palloc_array, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear, PQcmdStatus, PQgetisnull, PQgetvalue, PQnfields, PQntuples, PQresultStatus, restoreLocalGucs(), FunctionCallInfoBaseData::resultinfo, SFRM_Materialize, TupleDescFinalize(), 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 836 of file dblink.c.

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

References ereport, errcode(), errmsg, ERROR, fb(), IsA, FunctionCallInfoBaseData::resultinfo, 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 2336 of file dblink.c.

2337{
2340 char *result;
2341
2346
2347 return result;
2348}
#define DatumGetTextPP(X)
Definition fmgr.h:293
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
Datum quote_ident(PG_FUNCTION_ARGS)
Definition quote.c:25

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

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

◆ RangeVarCallbackForDblink()

static void RangeVarCallbackForDblink ( const RangeVar relation,
Oid  relId,
Oid  oldRelId,
void arg 
)
static

Definition at line 2472 of file dblink.c.

2474{
2476
2477 if (!OidIsValid(relId))
2478 return;
2479
2480 aclresult = pg_class_aclcheck(relId, GetUserId(), *((AclMode *) arg));
2481 if (aclresult != ACLCHECK_OK)
2483 relation->relname);
2484}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4082
#define OidIsValid(objectId)
Definition c.h:858
Datum arg
Definition elog.c:1322
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2223
ObjectType get_relkind_objtype(char relkind)
uint64 AclMode
Definition parsenodes.h:74
char * relname
Definition primnodes.h:84

References aclcheck_error(), ACLCHECK_OK, arg, fb(), get_rel_relkind(), get_relkind_objtype(), GetUserId(), OidIsValid, pg_class_aclcheck(), and RangeVar::relname.

Referenced by get_rel_from_relname().

◆ restoreLocalGucs()

static void restoreLocalGucs ( int  nestlevel)
static

Definition at line 3187 of file dblink.c.

3188{
3189 /* Do nothing if no new nestlevel was created */
3190 if (nestlevel > 0)
3191 AtEOXact_GUC(true, nestlevel);
3192}
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2169

References AtEOXact_GUC(), and fb().

Referenced by materializeResult(), and storeQueryResult().

◆ storeQueryResult()

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

Definition at line 1100 of file dblink.c.

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

References applyRemoteGucs(), CHECK_FOR_INTERRUPTS, conn, storeInfo::cur_res, dblink_we_get_result, elog, ERROR, fb(), 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 1168 of file dblink.c.

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

References Assert, storeInfo::attinmeta, BuildTupleFromCStrings(), CreateTupleDescCopy(), storeInfo::cstrs, elog, ereport, errcode(), errmsg, ERROR, fb(), storeInfo::fcinfo, get_call_result_type(), i, MemoryContextReset(), MemoryContextSwitchTo(), TupleDescData::natts, palloc_array, pfree(), PQgetisnull, PQgetvalue, PQnfields, PQntuples, FunctionCallInfoBaseData::resultinfo, 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 3234 of file dblink.c.

3235{
3236 ListCell *cell;
3237
3238 foreach(cell, foreign_server->options)
3239 {
3240 DefElem *def = lfirst(cell);
3241
3242 if (strcmp(def->defname, "use_scram_passthrough") == 0)
3243 return defGetBoolean(def);
3244 }
3245
3246 foreach(cell, user->options)
3247 {
3248 DefElem *def = (DefElem *) lfirst(cell);
3249
3250 if (strcmp(def->defname, "use_scram_passthrough") == 0)
3251 return defGetBoolean(def);
3252 }
3253
3254 return false;
3255}
bool defGetBoolean(DefElem *def)
Definition define.c:93
static char * user
Definition pg_regress.c:121

References defGetBoolean(), DefElem::defname, fb(), 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 2992 of file dblink.c.

2995{
2996 TupleDesc tupdesc = rel->rd_att;
2997 int natts = tupdesc->natts;
2998 int i;
2999
3000 /* Don't take more array elements than there are */
3002
3003 /* Must have at least one pk attnum selected */
3004 if (pknumatts_arg <= 0)
3005 ereport(ERROR,
3007 errmsg("number of key attributes must be > 0")));
3008
3009 /* Allocate output array */
3012
3013 /* Validate attnums and convert to internal form */
3014 for (i = 0; i < pknumatts_arg; i++)
3015 {
3016 int pkattnum = pkattnums_arg->values[i];
3017 int lnum;
3018 int j;
3019
3020 /* Can throw error immediately if out of range */
3022 ereport(ERROR,
3024 errmsg("invalid attribute number %d", pkattnum)));
3025
3026 /* Identify which physical column has this logical number */
3027 lnum = 0;
3028 for (j = 0; j < natts; j++)
3029 {
3030 /* dropped columns don't count */
3031 if (TupleDescCompactAttr(tupdesc, j)->attisdropped)
3032 continue;
3033
3034 if (++lnum == pkattnum)
3035 break;
3036 }
3037
3038 if (j < natts)
3039 (*pkattnums)[i] = j;
3040 else
3041 ereport(ERROR,
3043 errmsg("invalid attribute number %d", pkattnum)));
3044 }
3045}
#define Min(x, y)
Definition c.h:1091
int j
Definition isn.c:78
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195

References ereport, errcode(), errmsg, ERROR, fb(), i, j, Min, TupleDescData::natts, palloc_array, RelationData::rd_att, and TupleDescCompactAttr().

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

Referenced by dblink_connect().

◆ dblink_we_get_conn

uint32 dblink_we_get_conn = 0
static

Definition at line 149 of file dblink.c.

Referenced by dblink_get_conn().

◆ dblink_we_get_result

◆ pconn

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static