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

Go to the source code of this file.

Data Structures

struct  remoteConn
 
struct  storeInfo
 
struct  remoteConnHashEnt
 

Macros

#define NUMCONN   16
 
#define DBLINK_NOTIFY_COLS   3
 

Typedefs

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

Functions

 PG_MODULE_MAGIC_EXT (.name="dblink",.version=PG_VERSION)
 
static Datum dblink_record_internal (FunctionCallInfo fcinfo, bool is_async)
 
static void prepTuplestoreResult (FunctionCallInfo fcinfo)
 
static void materializeResult (FunctionCallInfo fcinfo, PGconn *conn, PGresult *res)
 
static void materializeQueryResult (FunctionCallInfo fcinfo, PGconn *conn, const char *conname, const char *sql, bool fail)
 
static PGresultstoreQueryResult (storeInfo *sinfo, PGconn *conn, const char *sql)
 
static void storeRow (storeInfo *sinfo, PGresult *res, bool first)
 
static remoteConngetConnectionByName (const char *name)
 
static HTABcreateConnHash (void)
 
static remoteConncreateNewConnection (const char *name)
 
static void deleteConnection (const char *name)
 
static char ** get_pkey_attnames (Relation rel, int16 *indnkeyatts)
 
static char ** get_text_array_contents (ArrayType *array, int *numitems)
 
static charget_sql_insert (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static charget_sql_delete (Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
 
static charget_sql_update (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
 
static charquote_ident_cstr (char *rawstr)
 
static int get_attnum_pk_pos (int *pkattnums, int pknumatts, int key)
 
static HeapTuple get_tuple_of_interest (Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
 
static Relation get_rel_from_relname (text *relname_text, LOCKMODE lockmode, AclMode aclmode)
 
static chargenerate_relation_name (Relation rel)
 
static void dblink_connstr_check (const char *connstr)
 
static bool dblink_connstr_has_pw (const char *connstr)
 
static void dblink_security_check (PGconn *conn, const char *connname, const char *connstr)
 
static void dblink_res_error (PGconn *conn, const char *conname, PGresult *res, bool fail, const char *fmt,...) pg_attribute_printf(5
 
static void static charget_connect_string (const char *servername)
 
static charescape_param_str (const char *str)
 
static void validate_pkattnums (Relation rel, int2vector *pkattnums_arg, int32 pknumatts_arg, int **pkattnums, int *pknumatts)
 
static bool is_valid_dblink_option (const PQconninfoOption *options, const char *option, Oid context)
 
static int applyRemoteGucs (PGconn *conn)
 
static void restoreLocalGucs (int nestlevel)
 
static bool UseScramPassthrough (ForeignServer *foreign_server, UserMapping *user)
 
static void appendSCRAMKeysInfo (StringInfo buf)
 
static bool is_valid_dblink_fdw_option (const PQconninfoOption *options, const char *option, Oid context)
 
static bool dblink_connstr_has_required_scram_options (const char *connstr)
 
static pg_noreturn void dblink_res_internalerror (PGconn *conn, PGresult *res, const char *p2)
 
static pg_noreturn void dblink_conn_not_avail (const char *conname)
 
static void dblink_get_conn (char *conname_or_str, PGconn *volatile *conn_p, char **conname_p, volatile bool *freeconn_p)
 
static PGconndblink_get_named_conn (const char *conname)
 
static void dblink_init (void)
 
 PG_FUNCTION_INFO_V1 (dblink_connect)
 
Datum dblink_connect (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_disconnect)
 
Datum dblink_disconnect (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_open)
 
Datum dblink_open (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_close)
 
Datum dblink_close (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_fetch)
 
Datum dblink_fetch (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_record)
 
Datum dblink_record (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_send_query)
 
Datum dblink_send_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_result)
 
Datum dblink_get_result (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_connections)
 
Datum dblink_get_connections (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_is_busy)
 
Datum dblink_is_busy (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_cancel_query)
 
Datum dblink_cancel_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_error_message)
 
Datum dblink_error_message (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_exec)
 
Datum dblink_exec (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_pkey)
 
Datum dblink_get_pkey (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_insert)
 
Datum dblink_build_sql_insert (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_delete)
 
Datum dblink_build_sql_delete (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_build_sql_update)
 
Datum dblink_build_sql_update (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_current_query)
 
Datum dblink_current_query (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_get_notify)
 
Datum dblink_get_notify (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (dblink_fdw_validator)
 
Datum dblink_fdw_validator (PG_FUNCTION_ARGS)
 
static void RangeVarCallbackForDblink (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 

Variables

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

Macro Definition Documentation

◆ DBLINK_NOTIFY_COLS

#define DBLINK_NOTIFY_COLS   3

Definition at line 1880 of file dblink.c.

◆ NUMCONN

#define NUMCONN   16

Definition at line 172 of file dblink.c.

Typedef Documentation

◆ remoteConn

◆ remoteConnHashEnt

◆ storeInfo

Function Documentation

◆ appendSCRAMKeysInfo()

static void appendSCRAMKeysInfo ( StringInfo  buf)
static

Definition at line 3200 of file dblink.c.

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

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

References Assert, conn, fb(), GetConfigOption(), GUC_ACTION_SAVE, i, lengthof, NewGUCNestLevel(), PGC_S_SESSION, PGC_USERSET, PQparameterStatus(), and set_config_option().

Referenced by materializeResult(), and storeQueryResult().

◆ createConnHash()

static HTAB * createConnHash ( void  )
static

Definition at line 2550 of file dblink.c.

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

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

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

◆ createNewConnection()

static remoteConn * createNewConnection ( const char name)
static

Definition at line 2562 of file dblink.c.

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

1712{
1717 Relation rel;
1718 int *pkattnums;
1719 int pknumatts;
1720 char **tgt_pkattvals;
1721 int tgt_nitems;
1722 char *sql;
1723
1724 /*
1725 * Open target relation.
1726 */
1728
1729 /*
1730 * Process pkattnums argument.
1731 */
1733 &pkattnums, &pknumatts);
1734
1735 /*
1736 * Target array is made up of key values that will be used to build the
1737 * SQL string for use on the remote system.
1738 */
1740
1741 /*
1742 * There should be one target array key value for each key attnum
1743 */
1744 if (tgt_nitems != pknumatts)
1745 ereport(ERROR,
1747 errmsg("target key array length must match number of key attributes")));
1748
1749 /*
1750 * Prep work is finally done. Go get the SQL string.
1751 */
1753
1754 /*
1755 * Now we can close the relation.
1756 */
1758
1759 /*
1760 * And send it
1761 */
1763}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition array.h:263
int32_t int32
Definition c.h:620
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_GETARG_POINTER(n)
Definition fmgr.h:277
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
#define AccessShareLock
Definition lockdefs.h:36
#define ACL_SELECT
Definition parsenodes.h:77
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:206
Definition c.h:776
text * cstring_to_text(const char *s)
Definition varlena.c:184

References AccessShareLock, ACL_SELECT, cstring_to_text(), ereport, errcode(), errmsg, ERROR, fb(), get_rel_from_relname(), get_sql_delete(), get_text_array_contents(), PG_GETARG_ARRAYTYPE_P, PG_GETARG_INT32, PG_GETARG_POINTER, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, relation_close(), and validate_pkattnums().

◆ dblink_build_sql_insert()

Datum dblink_build_sql_insert ( PG_FUNCTION_ARGS  )

Definition at line 1622 of file dblink.c.

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

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

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

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

1344{
1345 PGconn *conn;
1346 const char *msg;
1348
1349 dblink_init();
1352 30000);
1354 if (msg == NULL)
1355 msg = "OK";
1356
1358}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
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 498 of file dblink.c.

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

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

◆ dblink_conn_not_avail()

static pg_noreturn void dblink_conn_not_avail ( const char conname)
static

Definition at line 184 of file dblink.c.

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

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

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

◆ dblink_connect()

Datum dblink_connect ( PG_FUNCTION_ARGS  )

Definition at line 285 of file dblink.c.

286{
287 char *conname_or_str = NULL;
288 char *connstr = NULL;
289 char *connname = NULL;
290 char *msg;
291 PGconn *conn = NULL;
292 remoteConn *rconn = NULL;
293
294 dblink_init();
295
296 if (PG_NARGS() == 2)
297 {
300 }
301 else if (PG_NARGS() == 1)
303
304 /* first check for valid foreign data server */
306 if (connstr == NULL)
308
309 /* check password in connection string if not superuser */
311
312 /* first time, allocate or get the custom wait event */
313 if (dblink_we_connect == 0)
314 dblink_we_connect = WaitEventExtensionNew("DblinkConnect");
315
316 /* if we need a hashtable entry, make that first, since it might fail */
317 if (connname)
318 {
320 Assert(rconn->conn == NULL);
321 }
322
323 /* OK to make connection */
325 if (conn != NULL)
327 "received message via remote connection");
329
331 {
332 msg = pchomp(PQerrorMessage(conn));
334 if (connname)
336
339 errmsg("could not establish connection"),
340 errdetail_internal("%s", msg)));
341 }
342
343 /* check password actually used if not superuser */
345
346 /* attempt to set client encoding to match server encoding, if needed */
349
350 /* all OK, save away the conn */
351 if (connname)
352 {
353 rconn->conn = conn;
354 }
355 else
356 {
357 if (pconn->conn)
359 pconn->conn = conn;
360 }
361
363}
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 void libpqsrv_connect_complete(PGconn *conn, uint32 wait_event_info)
static void libpqsrv_notice_receiver(void *arg, const PGresult *res)
static PGconn * libpqsrv_connect_start(const char *conninfo)
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:1938
static const char * connstr
Definition pg_dumpall.c:95
uint32 WaitEventExtensionNew(const char *wait_event_name)
Definition wait_event.c:149

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

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

2726{
2729 bool connstr_gives_password = false;
2730
2732 if (options)
2733 {
2734 for (option = options; option->keyword != NULL; option++)
2735 {
2736 if (strcmp(option->keyword, "password") == 0)
2737 {
2738 if (option->val != NULL && option->val[0] != '\0')
2739 {
2741 break;
2742 }
2743 }
2744 }
2746 }
2747
2749}
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 2619 of file dblink.c.

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

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

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

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

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

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

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

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

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

◆ dblink_fdw_validator()

Datum dblink_fdw_validator ( PG_FUNCTION_ARGS  )

Definition at line 1937 of file dblink.c.

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

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

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

References appendStringInfo(), buf, remoteConn::conn, conn, dblink_conn_not_avail(), dblink_init(), dblink_res_error(), dblink_we_get_result, ereport, errcode(), errmsg, ERROR, fb(), get_fn_expr_argtype(), getConnectionByName(), initStringInfo(), libpqsrv_exec(), materializeResult(), pconn, PG_GETARG_BOOL, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_NARGS, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear, PQresultStatus, prepTuplestoreResult(), and text_to_cstring().

◆ dblink_get_conn()

static void dblink_get_conn ( char conname_or_str,
PGconn *volatile conn_p,
char **  conname_p,
volatile bool freeconn_p 
)
static

Definition at line 197 of file dblink.c.

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

References remoteConn::conn, conn, CONNECTION_BAD, connstr, dblink_connstr_check(), dblink_security_check(), dblink_we_get_conn, ereport, errcode(), errdetail_internal(), errmsg, ERROR, fb(), get_connect_string(), getConnectionByName(), GetDatabaseEncoding(), GetDatabaseEncodingName(), libpqsrv_connect_complete(), libpqsrv_connect_start(), 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 1281 of file dblink.c.

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

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

◆ dblink_get_named_conn()

static PGconn * dblink_get_named_conn ( const char conname)
static

Definition at line 254 of file dblink.c.

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

References remoteConn::conn, dblink_conn_not_avail(), fb(), and getConnectionByName().

Referenced by dblink_cancel_query(), dblink_error_message(), dblink_get_notify(), dblink_is_busy(), dblink_record_internal(), and dblink_send_query().

◆ dblink_get_notify()

Datum dblink_get_notify ( PG_FUNCTION_ARGS  )

Definition at line 1884 of file dblink.c.

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

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

◆ dblink_get_pkey()

Datum dblink_get_pkey ( PG_FUNCTION_ARGS  )

Definition at line 1496 of file dblink.c.

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

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

◆ dblink_get_result()

Datum dblink_get_result ( PG_FUNCTION_ARGS  )

Definition at line 711 of file dblink.c.

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

References dblink_record_internal().

◆ dblink_init()

◆ dblink_is_busy()

Datum dblink_is_busy ( PG_FUNCTION_ARGS  )

Definition at line 1319 of file dblink.c.

1320{
1321 PGconn *conn;
1322
1323 dblink_init();
1325
1328}
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 405 of file dblink.c.

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

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

References dblink_record_internal().

◆ dblink_record_internal()

static Datum dblink_record_internal ( FunctionCallInfo  fcinfo,
bool  is_async 
)
static

Definition at line 717 of file dblink.c.

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

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

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

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

◆ dblink_res_internalerror()

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

Definition at line 175 of file dblink.c.

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

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

Referenced by dblink_close(), and dblink_open().

◆ dblink_security_check()

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

Definition at line 2678 of file dblink.c.

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

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

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

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

Referenced by dblink_connect(), dblink_disconnect(), and dblink_security_check().

◆ escape_param_str()

static char * escape_param_str ( const char str)
static

Definition at line 2960 of file dblink.c.

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

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

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

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

◆ get_attnum_pk_pos()

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

Definition at line 2352 of file dblink.c.

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

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

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

References ACL_USAGE, aclcheck_error(), ACLCHECK_OK, appendSCRAMKeysInfo(), appendStringInfo(), DefElem::arg, buf, DefElem::defname, ereport, errcode(), errdetail(), errmsg, ERROR, escape_param_str(), fb(), ForeignServer::fdwid, GetForeignDataWrapper(), GetForeignServerByName(), GetUserId(), GetUserMapping(), Port::has_scram_keys, initStringInfo(), is_valid_dblink_option(), lfirst, MyProcPort, object_aclcheck(), OBJECT_FOREIGN_SERVER, ForeignServer::options, PQconndefaults(), pstrdup(), ForeignServer::serverid, ForeignServer::servername, strVal, truncate_identifier(), and UseScramPassthrough().

Referenced by dblink_connect(), and dblink_get_conn().

◆ get_pkey_attnames()

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

Definition at line 2016 of file dblink.c.

2017{
2018 Relation indexRelation;
2020 SysScanDesc scan;
2022 int i;
2023 char **result = NULL;
2024 TupleDesc tupdesc;
2025
2026 /* initialize indnkeyatts to 0 in case no primary key exists */
2027 *indnkeyatts = 0;
2028
2029 tupdesc = rel->rd_att;
2030
2031 /* Prepare to scan pg_index for entries having indrelid = this rel. */
2032 indexRelation = table_open(IndexRelationId, AccessShareLock);
2037
2038 scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2039 NULL, 1, &skey);
2040
2042 {
2044
2045 /* we're only interested if it is the primary key */
2046 if (index->indisprimary)
2047 {
2048 *indnkeyatts = index->indnkeyatts;
2049 if (*indnkeyatts > 0)
2050 {
2051 result = palloc_array(char *, *indnkeyatts);
2052
2053 for (i = 0; i < *indnkeyatts; i++)
2054 result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2055 }
2056 break;
2057 }
2058 }
2059
2060 systable_endscan(scan);
2061 table_close(indexRelation, AccessShareLock);
2062
2063 return result;
2064}
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:604
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:515
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:97
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40

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

Referenced by dblink_get_pkey().

◆ get_rel_from_relname()

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

Definition at line 2493 of file dblink.c.

2494{
2496 Oid relid;
2497
2499 relid = RangeVarGetRelidExtended(relvar, lockmode, 0,
2501
2502 return table_open(relid, NoLock);
2503}
#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:2722

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

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

References appendStringInfo(), appendStringInfoString(), buf, fb(), generate_relation_name(), i, initStringInfo(), NameStr, quote_ident_cstr(), quote_literal_cstr(), RelationData::rd_att, relname, and TupleDescAttr().

Referenced by dblink_build_sql_delete().

◆ get_sql_insert()

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

Definition at line 2129 of file dblink.c.

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

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

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

2072{
2073 int ndim = ARR_NDIM(array);
2074 int *dims = ARR_DIMS(array);
2075 int nitems;
2076 int16 typlen;
2077 bool typbyval;
2078 char typalign;
2079 uint8 typalignby;
2080 char **values;
2081 char *ptr;
2082 uint8 *bitmap;
2083 int bitmask;
2084 int i;
2085
2086 Assert(ARR_ELEMTYPE(array) == TEXTOID);
2087
2088 *numitems = nitems = ArrayGetNItems(ndim, dims);
2089
2091 &typlen, &typbyval, &typalign);
2092 typalignby = typalign_to_alignby(typalign);
2093
2094 values = palloc_array(char *, nitems);
2095
2096 ptr = ARR_DATA_PTR(array);
2097 bitmap = ARR_NULLBITMAP(array);
2098 bitmask = 1;
2099
2100 for (i = 0; i < nitems; i++)
2101 {
2102 if (bitmap && (*bitmap & bitmask) == 0)
2103 {
2104 values[i] = NULL;
2105 }
2106 else
2107 {
2109 ptr = att_addlength_pointer(ptr, typlen, ptr);
2110 ptr = (char *) att_nominal_alignby(ptr, typalignby);
2111 }
2112
2113 /* advance bitmap pointer if any */
2114 if (bitmap)
2115 {
2116 bitmask <<= 1;
2117 if (bitmask == 0x100)
2118 {
2119 bitmap++;
2120 bitmask = 1;
2121 }
2122 }
2123 }
2124
2125 return values;
2126}
#define ARR_NDIM(a)
Definition array.h:290
#define ARR_DATA_PTR(a)
Definition array.h:322
#define ARR_NULLBITMAP(a)
Definition array.h:300
#define ARR_ELEMTYPE(a)
Definition array.h:292
#define ARR_DIMS(a)
Definition array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition arrayutils.c:57
#define TextDatumGetCString(d)
Definition builtins.h:99
uint8_t uint8
Definition c.h:622
#define nitems(x)
Definition indent.h:31
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2502
char typalign
Definition pg_type.h:178
#define PointerGetDatum(X)
Definition postgres.h:354
#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 2367 of file dblink.c.

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

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

References createConnHash(), fb(), HASH_FIND, hash_search(), name, pstrdup(), remoteConnHash, and truncate_identifier().

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

◆ is_valid_dblink_fdw_option()

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

Definition at line 3116 of file dblink.c.

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

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

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

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

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

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

Referenced by dblink_record_internal().

◆ materializeResult()

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

Definition at line 865 of file dblink.c.

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

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

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

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

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

◆ RangeVarCallbackForDblink()

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

Definition at line 2473 of file dblink.c.

2475{
2477
2478 if (!OidIsValid(relId))
2479 return;
2480
2481 aclresult = pg_class_aclcheck(relId, GetUserId(), *((AclMode *) arg));
2482 if (aclresult != ACLCHECK_OK)
2484 relation->relname);
2485}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4083
#define OidIsValid(objectId)
Definition c.h:858
Datum arg
Definition elog.c:1323
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2234
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 3188 of file dblink.c.

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

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

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

Referenced by materializeQueryResult().

◆ storeRow()

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

Definition at line 1169 of file dblink.c.

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

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

Referenced by storeQueryResult().

◆ UseScramPassthrough()

static bool UseScramPassthrough ( ForeignServer foreign_server,
UserMapping user 
)
static

Definition at line 3235 of file dblink.c.

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

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

Referenced by get_connect_string().

◆ validate_pkattnums()

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

Definition at line 2993 of file dblink.c.

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

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

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

Variable Documentation

◆ dblink_we_connect

uint32 dblink_we_connect = 0
static

Definition at line 148 of file dblink.c.

Referenced by dblink_connect().

◆ dblink_we_get_conn

uint32 dblink_we_get_conn = 0
static

Definition at line 149 of file dblink.c.

Referenced by dblink_get_conn().

◆ dblink_we_get_result

◆ pconn

◆ remoteConnHash

HTAB* remoteConnHash = NULL
static