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

◆ NUMCONN

#define NUMCONN   16

Definition at line 171 of file dblink.c.

Typedef Documentation

◆ remoteConn

◆ remoteConnHashEnt

◆ storeInfo

Function Documentation

◆ appendSCRAMKeysInfo()

static void appendSCRAMKeysInfo ( StringInfo  buf)
static

Definition at line 3198 of file dblink.c.

3199{
3200 int len;
3201 int encoded_len;
3202 char *client_key;
3203 char *server_key;
3204
3206 /* don't forget the zero-terminator */
3207 client_key = palloc0(len + 1);
3209 sizeof(MyProcPort->scram_ClientKey),
3210 client_key, len);
3211 if (encoded_len < 0)
3212 elog(ERROR, "could not encode SCRAM client key");
3213
3215 /* don't forget the zero-terminator */
3216 server_key = palloc0(len + 1);
3218 sizeof(MyProcPort->scram_ServerKey),
3219 server_key, len);
3220 if (encoded_len < 0)
3221 elog(ERROR, "could not encode SCRAM server key");
3222
3223 appendStringInfo(buf, "scram_client_key='%s' ", client_key);
3224 appendStringInfo(buf, "scram_server_key='%s' ", server_key);
3225 appendStringInfoString(buf, "require_auth='scram-sha-256' ");
3226
3229}
int pg_b64_enc_len(int srclen)
Definition base64.c:224
int pg_b64_encode(const uint8 *src, int len, char *dst, int dstlen)
Definition base64.c:49
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
struct Port * MyProcPort
Definition globals.c:51
void pfree(void *pointer)
Definition mcxt.c: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 3134 of file dblink.c.

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

2549{
2550 HASHCTL ctl;
2551
2553 ctl.entrysize = sizeof(remoteConnHashEnt);
2554
2555 return hash_create("Remote Con hash", NUMCONN, &ctl,
2557}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
#define HASH_STRINGS
Definition hsearch.h:96
#define HASH_ELEM
Definition hsearch.h:95
#define NAMEDATALEN
tree ctl
Definition radixtree.h:1838
Size keysize
Definition hsearch.h:75

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

2561{
2563 bool found;
2564 char *key;
2565
2566 if (!remoteConnHash)
2568
2569 key = pstrdup(name);
2570 truncate_identifier(key, strlen(key), true);
2572 HASH_ENTER, &found);
2573
2574 if (found && hentry->rconn.conn != NULL)
2575 ereport(ERROR,
2577 errmsg("duplicate connection name")));
2578
2579 /* New, or reusable, so initialize the rconn struct to zeroes */
2580 memset(&hentry->rconn, 0, sizeof(remoteConn));
2581
2582 return &hentry->rconn;
2583}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
int errcode(int sqlerrcode)
Definition elog.c:874
#define ereport(elevel,...)
Definition elog.h:150
@ HASH_ENTER
Definition hsearch.h:114
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 1709 of file dblink.c.

1710{
1715 Relation rel;
1716 int *pkattnums;
1717 int pknumatts;
1718 char **tgt_pkattvals;
1719 int tgt_nitems;
1720 char *sql;
1721
1722 /*
1723 * Open target relation.
1724 */
1726
1727 /*
1728 * Process pkattnums argument.
1729 */
1731 &pkattnums, &pknumatts);
1732
1733 /*
1734 * Target array is made up of key values that will be used to build the
1735 * SQL string for use on the remote system.
1736 */
1738
1739 /*
1740 * There should be one target array key value for each key attnum
1741 */
1742 if (tgt_nitems != pknumatts)
1743 ereport(ERROR,
1745 errmsg("target key array length must match number of key attributes")));
1746
1747 /*
1748 * Prep work is finally done. Go get the SQL string.
1749 */
1751
1752 /*
1753 * Now we can close the relation.
1754 */
1756
1757 /*
1758 * And send it
1759 */
1761}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition array.h:263
int32_t int32
Definition c.h:614
#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:205
Definition c.h:778
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 1620 of file dblink.c.

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

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

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

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

1342{
1343 PGconn *conn;
1344 const char *msg;
1346
1347 dblink_init();
1350 30000);
1352 if (msg == NULL)
1353 msg = "OK";
1354
1356}
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 496 of file dblink.c.

497{
498 PGconn *conn;
499 PGresult *res = NULL;
500 char *curname = NULL;
501 char *conname = NULL;
503 remoteConn *rconn = NULL;
504 bool fail = true; /* default to backward compatible behavior */
505
506 dblink_init();
508
509 if (PG_NARGS() == 1)
510 {
511 /* text */
513 rconn = pconn;
514 }
515 else if (PG_NARGS() == 2)
516 {
517 /* might be text,text or text,bool */
518 if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
519 {
521 fail = PG_GETARG_BOOL(1);
522 rconn = pconn;
523 }
524 else
525 {
528 rconn = getConnectionByName(conname);
529 }
530 }
531 if (PG_NARGS() == 3)
532 {
533 /* text,text,bool */
536 fail = PG_GETARG_BOOL(2);
537 rconn = getConnectionByName(conname);
538 }
539
540 if (!rconn || !rconn->conn)
541 dblink_conn_not_avail(conname);
542
543 conn = rconn->conn;
544
545 appendStringInfo(&buf, "CLOSE %s", curname);
546
547 /* close the cursor */
549 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
550 {
551 dblink_res_error(conn, conname, res, fail,
552 "while closing cursor \"%s\"", curname);
554 }
555
556 PQclear(res);
557
558 /* if we started a transaction, decrement cursor count */
559 if (rconn->newXactForCursor)
560 {
561 (rconn->openCursorCount)--;
562
563 /* if count is zero, commit the transaction */
564 if (rconn->openCursorCount == 0)
565 {
566 rconn->newXactForCursor = false;
567
568 res = libpqsrv_exec(conn, "COMMIT", dblink_we_get_result);
570 dblink_res_internalerror(conn, res, "commit error");
571 PQclear(res);
572 }
573 }
574
576}
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:78
int openCursorCount
Definition dblink.c:77
PGconn * conn
Definition dblink.c:76

References appendStringInfo(), buf, remoteConn::conn, conn, cstring_to_text(), dblink_conn_not_avail(), dblink_init(), dblink_res_error(), dblink_res_internalerror(), dblink_we_get_result, 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 183 of file dblink.c.

184{
185 if (conname)
188 errmsg("connection \"%s\" not available", conname)));
189 else
192 errmsg("connection not available")));
193}

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

285{
286 char *conname_or_str = NULL;
287 char *connstr = NULL;
288 char *connname = NULL;
289 char *msg;
290 PGconn *conn = NULL;
291 remoteConn *rconn = NULL;
292
293 dblink_init();
294
295 if (PG_NARGS() == 2)
296 {
299 }
300 else if (PG_NARGS() == 1)
302
303 /* first check for valid foreign data server */
305 if (connstr == NULL)
307
308 /* check password in connection string if not superuser */
310
311 /* first time, allocate or get the custom wait event */
312 if (dblink_we_connect == 0)
313 dblink_we_connect = WaitEventExtensionNew("DblinkConnect");
314
315 /* if we need a hashtable entry, make that first, since it might fail */
316 if (connname)
317 {
319 Assert(rconn->conn == NULL);
320 }
321
322 /* OK to make connection */
324
326 {
327 msg = pchomp(PQerrorMessage(conn));
329 if (connname)
331
334 errmsg("could not establish connection"),
335 errdetail_internal("%s", msg)));
336 }
337
339 "received message via remote connection");
340
341 /* check password actually used if not superuser */
343
344 /* attempt to set client encoding to match server encoding, if needed */
347
348 /* all OK, save away the conn */
349 if (connname)
350 {
351 rconn->conn = conn;
352 }
353 else
354 {
355 if (pconn->conn)
357 pconn->conn = conn;
358 }
359
361}
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:1389
const char * GetDatabaseEncodingName(void)
Definition mbutils.c:1395
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:163

References Assert, remoteConn::conn, conn, CONNECTION_BAD, connstr, createNewConnection(), cstring_to_text(), dblink_connstr_check(), dblink_init(), dblink_security_check(), dblink_we_connect, deleteConnection(), ereport, errcode(), errdetail_internal(), errmsg, ERROR, 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 2760 of file dblink.c.

2761{
2762 if (superuser())
2763 return;
2764
2766 return;
2767
2769 return;
2770
2771#ifdef ENABLE_GSS
2773 return;
2774#endif
2775
2776 ereport(ERROR,
2778 errmsg("password or GSSAPI delegated credentials required"),
2779 errdetail("Non-superusers must provide a password in the connection string or send delegated GSSAPI credentials.")));
2780}
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 2723 of file dblink.c.

2724{
2727 bool connstr_gives_password = false;
2728
2730 if (options)
2731 {
2732 for (option = options; option->keyword != NULL; option++)
2733 {
2734 if (strcmp(option->keyword, "password") == 0)
2735 {
2736 if (option->val != NULL && option->val[0] != '\0')
2737 {
2739 break;
2740 }
2741 }
2742 }
2744 }
2745
2747}
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 2617 of file dblink.c.

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

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

1865{
1866 /* This is now just an alias for the built-in function current_query() */
1868}
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 368 of file dblink.c.

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

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

1372{
1373 char *msg;
1374 PGconn *conn;
1375
1376 dblink_init();
1378
1379 msg = PQerrorMessage(conn);
1380 if (msg == NULL || msg[0] == '\0')
1382 else
1384}

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

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

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

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

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

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

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

1280{
1281 HASH_SEQ_STATUS status;
1283 ArrayBuildState *astate = NULL;
1284
1285 if (remoteConnHash)
1286 {
1287 hash_seq_init(&status, remoteConnHash);
1288 while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1289 {
1290 /* ignore it if it's not an open connection */
1291 if (hentry->rconn.conn == NULL)
1292 continue;
1293 /* stash away current value */
1294 astate = accumArrayResult(astate,
1297 }
1298 }
1299
1300 if (astate)
1303 else
1305}
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:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1380
#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 253 of file dblink.c.

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

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

1883{
1884 PGconn *conn;
1886 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1887
1888 dblink_init();
1889 if (PG_NARGS() == 1)
1891 else
1892 conn = pconn->conn;
1893
1894 InitMaterializedSRF(fcinfo, 0);
1895
1897 while ((notify = PQnotifies(conn)) != NULL)
1898 {
1900 bool nulls[DBLINK_NOTIFY_COLS];
1901
1902 memset(values, 0, sizeof(values));
1903 memset(nulls, 0, sizeof(nulls));
1904
1905 if (notify->relname != NULL)
1906 values[0] = CStringGetTextDatum(notify->relname);
1907 else
1908 nulls[0] = true;
1909
1910 values[1] = Int32GetDatum(notify->be_pid);
1911
1912 if (notify->extra != NULL)
1913 values[2] = CStringGetTextDatum(notify->extra);
1914 else
1915 nulls[2] = true;
1916
1917 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1918
1921 }
1922
1923 return (Datum) 0;
1924}
static Datum values[MAXATTR]
Definition bootstrap.c:188
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, bits32 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 1494 of file dblink.c.

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

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

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

References dblink_record_internal().

◆ dblink_init()

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1317 of file dblink.c.

1318{
1319 PGconn *conn;
1320
1321 dblink_init();
1323
1326}
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 403 of file dblink.c.

404{
405 PGresult *res = NULL;
406 PGconn *conn;
407 char *curname = NULL;
408 char *sql = NULL;
409 char *conname = NULL;
411 remoteConn *rconn = NULL;
412 bool fail = true; /* default to backward compatible behavior */
413
414 dblink_init();
416
417 if (PG_NARGS() == 2)
418 {
419 /* text,text */
422 rconn = pconn;
423 }
424 else if (PG_NARGS() == 3)
425 {
426 /* might be text,text,text or text,text,bool */
427 if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
428 {
431 fail = PG_GETARG_BOOL(2);
432 rconn = pconn;
433 }
434 else
435 {
439 rconn = getConnectionByName(conname);
440 }
441 }
442 else if (PG_NARGS() == 4)
443 {
444 /* text,text,text,bool */
448 fail = PG_GETARG_BOOL(3);
449 rconn = getConnectionByName(conname);
450 }
451
452 if (!rconn || !rconn->conn)
453 dblink_conn_not_avail(conname);
454
455 conn = rconn->conn;
456
457 /* If we are not in a transaction, start one */
459 {
460 res = libpqsrv_exec(conn, "BEGIN", dblink_we_get_result);
462 dblink_res_internalerror(conn, res, "begin error");
463 PQclear(res);
464 rconn->newXactForCursor = true;
465
466 /*
467 * Since transaction state was IDLE, we force cursor count to
468 * initially be 0. This is needed as a previous ABORT might have wiped
469 * out our transaction without maintaining the cursor count for us.
470 */
471 rconn->openCursorCount = 0;
472 }
473
474 /* if we started a transaction, increment cursor count */
475 if (rconn->newXactForCursor)
476 (rconn->openCursorCount)++;
477
478 appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
480 if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
481 {
482 dblink_res_error(conn, conname, res, fail,
483 "while opening cursor \"%s\"", curname);
485 }
486
487 PQclear(res);
489}
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 677 of file dblink.c.

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

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 715 of file dblink.c.

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

2796{
2797 int level;
2803 int sqlstate;
2804 va_list ap;
2805 char dblink_context_msg[512];
2806
2807 if (fail)
2808 level = ERROR;
2809 else
2810 level = NOTICE;
2811
2812 if (pg_diag_sqlstate)
2813 sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2817 pg_diag_sqlstate[4]);
2818 else
2819 sqlstate = ERRCODE_CONNECTION_FAILURE;
2820
2821 /*
2822 * If we don't get a message from the PGresult, try the PGconn. This is
2823 * needed because for connection-level failures, PQgetResult may just
2824 * return NULL, not a PGresult at all.
2825 */
2826 if (message_primary == NULL)
2828
2829 /*
2830 * Format the basic errcontext string. Below, we'll add on something
2831 * about the connection name. That's a violation of the translatability
2832 * guidelines about constructing error messages out of parts, but since
2833 * there's no translation support for dblink, there's no need to worry
2834 * about that (yet).
2835 */
2836 va_start(ap, fmt);
2838 va_end(ap);
2839
2840 ereport(level,
2841 (errcode(sqlstate),
2842 (message_primary != NULL && message_primary[0] != '\0') ?
2844 errmsg("could not obtain message string for remote error"),
2846 message_hint ? errhint("%s", message_hint) : 0,
2848 conname ?
2849 (errcontext("%s on dblink connection named \"%s\"",
2850 dblink_context_msg, conname)) :
2851 (errcontext("%s on unnamed dblink connection",
2853 PQclear(res);
2854}
#define errcontext
Definition elog.h:198
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define MAKE_SQLSTATE(ch1, ch2, ch3, ch4, ch5)
Definition elog.h:56
#define NOTICE
Definition elog.h:35
#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 174 of file dblink.c.

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

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

2677{
2678 /* Superuser bypasses security check */
2679 if (superuser())
2680 return;
2681
2682 /* If password was used to connect, make sure it was one provided */
2684 return;
2685
2686 /*
2687 * Password was not used to connect, check if SCRAM pass-through is in
2688 * use.
2689 *
2690 * If dblink_connstr_has_required_scram_options is true we assume that
2691 * UseScramPassthrough is also true because the required SCRAM keys are
2692 * only added if UseScramPassthrough is set, and the user is not allowed
2693 * to add the SCRAM keys on fdw and user mapping options.
2694 */
2696 return;
2697
2698#ifdef ENABLE_GSS
2699 /* If GSSAPI creds used to connect, make sure it was one delegated */
2701 return;
2702#endif
2703
2704 /* Otherwise, fail out */
2706 if (connname)
2708
2709 ereport(ERROR,
2711 errmsg("password or GSSAPI delegated credentials required"),
2712 errdetail("Non-superusers may only connect using credentials they provide, eg: password in connection string or delegated GSSAPI credentials"),
2713 errhint("Ensure provided credentials match target server's authentication method.")));
2714}
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 684 of file dblink.c.

685{
686 PGconn *conn;
687 char *sql;
688 int retval;
689
690 if (PG_NARGS() == 2)
691 {
694 }
695 else
696 /* shouldn't happen */
697 elog(ERROR, "wrong number of arguments");
698
699 /* async query send */
700 retval = PQsendQuery(conn, sql);
701 if (retval != 1)
702 elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
703
704 PG_RETURN_INT32(retval);
705}
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 2586 of file dblink.c.

2587{
2589 bool found;
2590 char *key;
2591
2592 if (!remoteConnHash)
2594
2595 key = pstrdup(name);
2596 truncate_identifier(key, strlen(key), false);
2598 key, HASH_REMOVE, &found);
2599
2600 if (!hentry)
2601 ereport(ERROR,
2603 errmsg("undefined connection name")));
2604}
@ HASH_REMOVE
Definition hsearch.h:115

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

2959{
2960 const char *cp;
2962
2964
2965 for (cp = str; *cp; cp++)
2966 {
2967 if (*cp == '\\' || *cp == '\'')
2968 appendStringInfoChar(&buf, '\\');
2970 }
2971
2972 return buf.data;
2973}
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 2510 of file dblink.c.

2511{
2512 char *nspname;
2513 char *result;
2514
2515 /* Qualify the name if not visible in search path */
2517 nspname = NULL;
2518 else
2519 nspname = get_namespace_name(rel->rd_rel->relnamespace);
2520
2522
2523 return result;
2524}
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3588
bool RelationIsVisible(Oid relid)
Definition namespace.c:914
#define RelationGetRelid(relation)
Definition rel.h:514
#define RelationGetRelationName(relation)
Definition rel.h:548
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, and RelationIsVisible().

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

◆ get_attnum_pk_pos()

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

Definition at line 2350 of file dblink.c.

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

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

2861{
2862 ForeignServer *foreign_server = NULL;
2864 ListCell *cell;
2868 char *srvname;
2869
2870 static const PQconninfoOption *options = NULL;
2871
2873
2874 /*
2875 * Get list of valid libpq options.
2876 *
2877 * To avoid unnecessary work, we get the list once and use it throughout
2878 * the lifetime of this backend process. We don't need to care about
2879 * memory context issues, because PQconndefaults allocates with malloc.
2880 */
2881 if (!options)
2882 {
2884 if (!options) /* assume reason for failure is OOM */
2885 ereport(ERROR,
2887 errmsg("out of memory"),
2888 errdetail("Could not get libpq's default connection options.")));
2889 }
2890
2891 /* first gather the server connstr options */
2892 srvname = pstrdup(servername);
2894 foreign_server = GetForeignServerByName(srvname, true);
2895
2896 if (foreign_server)
2897 {
2898 Oid serverid = foreign_server->serverid;
2899 Oid fdwid = foreign_server->fdwid;
2900 Oid userid = GetUserId();
2901
2902 user_mapping = GetUserMapping(userid, serverid);
2903 fdw = GetForeignDataWrapper(fdwid);
2904
2905 /* Check permissions, user must have usage on the server. */
2907 if (aclresult != ACLCHECK_OK)
2909
2910 /*
2911 * First append hardcoded options needed for SCRAM pass-through, so if
2912 * the user overwrites these options we can ereport on
2913 * dblink_connstr_check and dblink_security_check.
2914 */
2917
2918 foreach(cell, fdw->options)
2919 {
2920 DefElem *def = lfirst(cell);
2921
2923 appendStringInfo(&buf, "%s='%s' ", def->defname,
2924 escape_param_str(strVal(def->arg)));
2925 }
2926
2927 foreach(cell, foreign_server->options)
2928 {
2929 DefElem *def = lfirst(cell);
2930
2932 appendStringInfo(&buf, "%s='%s' ", def->defname,
2933 escape_param_str(strVal(def->arg)));
2934 }
2935
2936 foreach(cell, user_mapping->options)
2937 {
2938
2939 DefElem *def = lfirst(cell);
2940
2942 appendStringInfo(&buf, "%s='%s' ", def->defname,
2943 escape_param_str(strVal(def->arg)));
2944 }
2945
2946 return buf.data;
2947 }
2948 else
2949 return NULL;
2950}
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:210
UserMapping * GetUserMapping(Oid userid, Oid serverid)
Definition foreign.c:289
Oid GetUserId(void)
Definition miscinit.c:470
#define ACL_USAGE
Definition parsenodes.h:84
@ OBJECT_FOREIGN_SERVER
Node * arg
Definition parsenodes.h:858
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 2014 of file dblink.c.

2015{
2016 Relation indexRelation;
2018 SysScanDesc scan;
2020 int i;
2021 char **result = NULL;
2022 TupleDesc tupdesc;
2023
2024 /* initialize indnkeyatts to 0 in case no primary key exists */
2025 *indnkeyatts = 0;
2026
2027 tupdesc = rel->rd_att;
2028
2029 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2030 indexRelation = table_open(IndexRelationId, AccessShareLock);
2035
2036 scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2037 NULL, 1, &skey);
2038
2040 {
2042
2043 /* we're only interested if it is the primary key */
2044 if (index->indisprimary)
2045 {
2046 *indnkeyatts = index->indnkeyatts;
2047 if (*indnkeyatts > 0)
2048 {
2049 result = palloc_array(char *, *indnkeyatts);
2050
2051 for (i = 0; i < *indnkeyatts; i++)
2052 result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2053 }
2054 break;
2055 }
2056 }
2057
2058 systable_endscan(scan);
2059 table_close(indexRelation, AccessShareLock);
2060
2061 return result;
2062}
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
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, 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 2491 of file dblink.c.

2492{
2494 Oid relid;
2495
2497 relid = RangeVarGetRelidExtended(relvar, lockmode, 0,
2499
2500 return table_open(relid, NoLock);
2501}
#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 2207 of file dblink.c.

2208{
2209 char *relname;
2210 TupleDesc tupdesc;
2212 int i;
2213
2215
2216 /* get relation name including any needed schema prefix and quoting */
2218
2219 tupdesc = rel->rd_att;
2220
2221 appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2222 for (i = 0; i < pknumatts; i++)
2223 {
2224 int pkattnum = pkattnums[i];
2225 Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2226
2227 if (i > 0)
2228 appendStringInfoString(&buf, " AND ");
2229
2231 quote_ident_cstr(NameStr(attr->attname)));
2232
2233 if (tgt_pkattvals[i] != NULL)
2234 appendStringInfo(&buf, " = %s",
2236 else
2237 appendStringInfoString(&buf, " IS NULL");
2238 }
2239
2240 return buf.data;
2241}
#define NameStr(name)
Definition c.h:837
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 2127 of file dblink.c.

2128{
2129 char *relname;
2130 HeapTuple tuple;
2131 TupleDesc tupdesc;
2132 int natts;
2134 char *val;
2135 int key;
2136 int i;
2137 bool needComma;
2138
2140
2141 /* get relation name including any needed schema prefix and quoting */
2143
2144 tupdesc = rel->rd_att;
2145 natts = tupdesc->natts;
2146
2148 if (!tuple)
2149 ereport(ERROR,
2151 errmsg("source row not found")));
2152
2153 appendStringInfo(&buf, "INSERT INTO %s(", relname);
2154
2155 needComma = false;
2156 for (i = 0; i < natts; i++)
2157 {
2159
2160 if (att->attisdropped)
2161 continue;
2162
2163 if (needComma)
2165
2167 quote_ident_cstr(NameStr(att->attname)));
2168 needComma = true;
2169 }
2170
2171 appendStringInfoString(&buf, ") VALUES(");
2172
2173 /*
2174 * Note: i is physical column number (counting from 0).
2175 */
2176 needComma = false;
2177 for (i = 0; i < natts; i++)
2178 {
2179 if (TupleDescAttr(tupdesc, i)->attisdropped)
2180 continue;
2181
2182 if (needComma)
2184
2186
2187 if (key >= 0)
2189 else
2190 val = SPI_getvalue(tuple, tupdesc, i + 1);
2191
2192 if (val != NULL)
2193 {
2195 pfree(val);
2196 }
2197 else
2198 appendStringInfoString(&buf, "NULL");
2199 needComma = true;
2200 }
2202
2203 return buf.data;
2204}
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 2244 of file dblink.c.

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

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

2070{
2071 int ndim = ARR_NDIM(array);
2072 int *dims = ARR_DIMS(array);
2073 int nitems;
2074 int16 typlen;
2075 bool typbyval;
2076 char typalign;
2077 uint8 typalignby;
2078 char **values;
2079 char *ptr;
2080 bits8 *bitmap;
2081 int bitmask;
2082 int i;
2083
2084 Assert(ARR_ELEMTYPE(array) == TEXTOID);
2085
2086 *numitems = nitems = ArrayGetNItems(ndim, dims);
2087
2089 &typlen, &typbyval, &typalign);
2090 typalignby = typalign_to_alignby(typalign);
2091
2092 values = palloc_array(char *, nitems);
2093
2094 ptr = ARR_DATA_PTR(array);
2095 bitmap = ARR_NULLBITMAP(array);
2096 bitmask = 1;
2097
2098 for (i = 0; i < nitems; i++)
2099 {
2100 if (bitmap && (*bitmap & bitmask) == 0)
2101 {
2102 values[i] = NULL;
2103 }
2104 else
2105 {
2107 ptr = att_addlength_pointer(ptr, typlen, ptr);
2108 ptr = (char *) att_nominal_alignby(ptr, typalignby);
2109 }
2110
2111 /* advance bitmap pointer if any */
2112 if (bitmap)
2113 {
2114 bitmask <<= 1;
2115 if (bitmask == 0x100)
2116 {
2117 bitmap++;
2118 bitmask = 1;
2119 }
2120 }
2121 }
2122
2123 return values;
2124}
#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:616
uint8 bits8
Definition c.h:625
#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 2365 of file dblink.c.

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

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

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

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

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

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

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

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

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

836{
838
839 /* check to see if query supports us returning a tuplestore */
840 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
843 errmsg("set-valued function called in context that cannot accept a set")));
844 if (!(rsinfo->allowedModes & SFRM_Materialize))
847 errmsg("materialize mode required, but it is not allowed in this context")));
848
849 /* let the executor know we're sending back a tuplestore */
850 rsinfo->returnMode = SFRM_Materialize;
851
852 /* caller must fill these to return a non-empty result */
853 rsinfo->setResult = NULL;
854 rsinfo->setDesc = NULL;
855}
#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 2335 of file dblink.c.

2336{
2339 char *result;
2340
2344 result = text_to_cstring(result_text);
2345
2346 return result;
2347}
#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(), 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 2471 of file dblink.c.

2473{
2475
2476 if (!OidIsValid(relId))
2477 return;
2478
2479 aclresult = pg_class_aclcheck(relId, GetUserId(), *((AclMode *) arg));
2480 if (aclresult != ACLCHECK_OK)
2482 relation->relname);
2483}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4082
#define OidIsValid(objectId)
Definition c.h:860
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 3186 of file dblink.c.

3187{
3188 /* Do nothing if no new nestlevel was created */
3189 if (nestlevel > 0)
3190 AtEOXact_GUC(true, nestlevel);
3191}
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 1099 of file dblink.c.

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

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

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

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

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

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

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

Referenced by dblink_connect().

◆ dblink_we_get_conn

uint32 dblink_we_get_conn = 0
static

Definition at line 148 of file dblink.c.

Referenced by dblink_get_conn().

◆ dblink_we_get_result

◆ pconn

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static