Branch data Line data Source code
1 : : /*
2 : : * dblink.c
3 : : *
4 : : * Functions returning results from a remote database
5 : : *
6 : : * Joe Conway <mail@joeconway.com>
7 : : * And contributors:
8 : : * Darko Prenosil <Darko.Prenosil@finteh.hr>
9 : : * Shridhar Daithankar <shridhar_daithankar@persistent.co.in>
10 : : *
11 : : * contrib/dblink/dblink.c
12 : : * Copyright (c) 2001-2026, PostgreSQL Global Development Group
13 : : * ALL RIGHTS RESERVED;
14 : : *
15 : : * Permission to use, copy, modify, and distribute this software and its
16 : : * documentation for any purpose, without fee, and without a written agreement
17 : : * is hereby granted, provided that the above copyright notice and this
18 : : * paragraph and the following two paragraphs appear in all copies.
19 : : *
20 : : * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
21 : : * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
22 : : * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
23 : : * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
24 : : * POSSIBILITY OF SUCH DAMAGE.
25 : : *
26 : : * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
27 : : * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
28 : : * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
29 : : * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
30 : : * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
31 : : *
32 : : */
33 : : #include "postgres.h"
34 : :
35 : : #include <limits.h>
36 : :
37 : : #include "access/htup_details.h"
38 : : #include "access/relation.h"
39 : : #include "access/reloptions.h"
40 : : #include "access/table.h"
41 : : #include "catalog/namespace.h"
42 : : #include "catalog/pg_foreign_data_wrapper.h"
43 : : #include "catalog/pg_foreign_server.h"
44 : : #include "catalog/pg_type.h"
45 : : #include "catalog/pg_user_mapping.h"
46 : : #include "commands/defrem.h"
47 : : #include "common/base64.h"
48 : : #include "executor/spi.h"
49 : : #include "foreign/foreign.h"
50 : : #include "funcapi.h"
51 : : #include "lib/stringinfo.h"
52 : : #include "libpq-fe.h"
53 : : #include "libpq/libpq-be.h"
54 : : #include "libpq/libpq-be-fe-helpers.h"
55 : : #include "mb/pg_wchar.h"
56 : : #include "miscadmin.h"
57 : : #include "parser/scansup.h"
58 : : #include "utils/acl.h"
59 : : #include "utils/builtins.h"
60 : : #include "utils/fmgroids.h"
61 : : #include "utils/guc.h"
62 : : #include "utils/hsearch.h"
63 : : #include "utils/lsyscache.h"
64 : : #include "utils/memutils.h"
65 : : #include "utils/rel.h"
66 : : #include "utils/tuplestore.h"
67 : : #include "utils/varlena.h"
68 : : #include "utils/wait_event.h"
69 : :
70 : 21 : PG_MODULE_MAGIC_EXT(
71 : : .name = "dblink",
72 : : .version = PG_VERSION
73 : : );
74 : :
75 : : typedef struct remoteConn
76 : : {
77 : : PGconn *conn; /* Hold the remote connection */
78 : : int openCursorCount; /* The number of open cursors */
79 : : bool newXactForCursor; /* Opened a transaction for a cursor */
80 : :
81 : : /*
82 : : * True while a dblink call is materializing a result read from this
83 : : * connection. Converting a row runs the column types' input functions,
84 : : * and a domain type runs its CHECK constraints there, so user-defined
85 : : * code can execute during conversion. That code must not be able to close
86 : : * the connection or start another operation on it. No other dblink
87 : : * operation runs user-defined code while it holds a connection, so this
88 : : * is the only window that needs protecting.
89 : : *
90 : : * Row conversion happens only under materializeResult() and
91 : : * materializeQueryResult(), which set this themselves; everything else
92 : : * just checks that the connection is not in use. A transient connection
93 : : * has no remoteConn entry and needs none, since no SQL can name it.
94 : : */
95 : : bool materializingResult;
96 : : } remoteConn;
97 : :
98 : : typedef struct storeInfo
99 : : {
100 : : FunctionCallInfo fcinfo;
101 : : Tuplestorestate *tuplestore;
102 : : AttInMetadata *attinmeta;
103 : : MemoryContext tmpcontext;
104 : : char **cstrs;
105 : : /* temp storage for results to avoid leaks on exception */
106 : : PGresult *last_res;
107 : : PGresult *cur_res;
108 : : } storeInfo;
109 : :
110 : : /*
111 : : * Internal declarations
112 : : */
113 : : static Datum dblink_record_internal(FunctionCallInfo fcinfo, bool is_async);
114 : : static void prepTuplestoreResult(FunctionCallInfo fcinfo);
115 : : static void materializeResult(FunctionCallInfo fcinfo, PGconn *conn,
116 : : remoteConn *rconn, PGresult *res);
117 : : static void materializeQueryResult(FunctionCallInfo fcinfo,
118 : : PGconn *conn,
119 : : remoteConn *rconn,
120 : : const char *conname,
121 : : const char *sql,
122 : : bool fail);
123 : : static PGresult *storeQueryResult(storeInfo *sinfo, PGconn *conn, const char *sql);
124 : : static void storeRow(storeInfo *sinfo, PGresult *res, bool first);
125 : : static remoteConn *getConnectionByName(const char *name);
126 : : static void dblink_check_conn_not_in_use(remoteConn *rconn, const char *conname);
127 : : static HTAB *createConnHash(void);
128 : : static remoteConn *createNewConnection(const char *name);
129 : : static void deleteConnection(const char *name);
130 : : static char **get_pkey_attnames(Relation rel, int16 *indnkeyatts);
131 : : static char **get_text_array_contents(ArrayType *array, int *numitems);
132 : : static char *get_sql_insert(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals);
133 : : static char *get_sql_delete(Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals);
134 : : static char *get_sql_update(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals);
135 : : static char *quote_ident_cstr(char *rawstr);
136 : : static int get_attnum_pk_pos(int *pkattnums, int pknumatts, int key);
137 : : static HeapTuple get_tuple_of_interest(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals);
138 : : static Relation get_rel_from_relname(text *relname_text, LOCKMODE lockmode, AclMode aclmode);
139 : : static char *generate_relation_name(Relation rel);
140 : : static void dblink_connstr_check(const char *connstr);
141 : : static bool dblink_connstr_has_pw(const char *connstr);
142 : : static void dblink_security_check(PGconn *conn, const char *connname,
143 : : const char *connstr);
144 : : static void dblink_res_error(PGconn *conn, const char *conname, PGresult *res,
145 : : bool fail, const char *fmt, ...) pg_attribute_printf(5, 6);
146 : : static char *get_connect_string(const char *servername);
147 : : static char *escape_param_str(const char *str);
148 : : static void validate_pkattnums(Relation rel,
149 : : int2vector *pkattnums_arg, int32 pknumatts_arg,
150 : : int **pkattnums, int *pknumatts);
151 : : static bool is_valid_dblink_option(const PQconninfoOption *options,
152 : : const char *option, Oid context);
153 : : static int applyRemoteGucs(PGconn *conn);
154 : : static void restoreLocalGucs(int nestlevel);
155 : : static bool UseScramPassthrough(ForeignServer *foreign_server, UserMapping *user);
156 : : static void appendSCRAMKeysInfo(StringInfo buf);
157 : : static bool is_valid_dblink_fdw_option(const PQconninfoOption *options, const char *option,
158 : : Oid context);
159 : : static bool dblink_connstr_has_required_scram_options(const char *connstr);
160 : :
161 : : /* Global */
162 : : static remoteConn *pconn = NULL;
163 : : static HTAB *remoteConnHash = NULL;
164 : :
165 : : /* custom wait event values, retrieved from shared memory */
166 : : static uint32 dblink_we_connect = 0;
167 : : static uint32 dblink_we_get_conn = 0;
168 : : static uint32 dblink_we_get_result = 0;
169 : :
170 : : /*
171 : : * Following is hash that holds multiple remote connections.
172 : : * Calling convention of each dblink function changes to accept
173 : : * connection name as the first parameter. The connection hash is
174 : : * much like ecpg e.g. a mapping between a name and a PGconn object.
175 : : *
176 : : * To avoid potentially leaking a PGconn object in case of out-of-memory
177 : : * errors, we first create the hash entry, then open the PGconn.
178 : : * Hence, a hash entry whose rconn.conn pointer is NULL must be
179 : : * understood as a leftover from a failed create; it should be ignored
180 : : * by lookup operations, and silently replaced by create operations.
181 : : */
182 : :
183 : : typedef struct remoteConnHashEnt
184 : : {
185 : : char name[NAMEDATALEN];
186 : : remoteConn rconn;
187 : : } remoteConnHashEnt;
188 : :
189 : : /* initial number of connection hashes */
190 : : #define NUMCONN 16
191 : :
192 : : pg_noreturn static void
193 : 0 : dblink_res_internalerror(PGconn *conn, PGresult *res, const char *p2)
194 : : {
195 : 0 : char *msg = pchomp(PQerrorMessage(conn));
196 : :
197 : 0 : PQclear(res);
198 [ # # ]: 0 : elog(ERROR, "%s: %s", p2, msg);
199 : : }
200 : :
201 : : pg_noreturn static void
202 : 3 : dblink_conn_not_avail(const char *conname)
203 : : {
204 [ + + ]: 3 : if (conname)
205 [ + - ]: 1 : ereport(ERROR,
206 : : (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
207 : : errmsg("connection \"%s\" not available", conname)));
208 : : else
209 [ + - ]: 2 : ereport(ERROR,
210 : : (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
211 : : errmsg("connection not available")));
212 : : }
213 : :
214 : : /*
215 : : * Raise an error if some dblink call is already reading results from this
216 : : * connection. Call this wherever we resolve a connection to operate on.
217 : : * remoteConn.materializingResult defines what counts as being in use.
218 : : */
219 : : static void
220 : 137 : dblink_check_conn_not_in_use(remoteConn *rconn, const char *conname)
221 : : {
222 [ + + + + ]: 137 : if (rconn == NULL || !rconn->materializingResult)
223 : 127 : return;
224 : :
225 [ + + ]: 10 : if (conname)
226 [ + - ]: 8 : ereport(ERROR,
227 : : (errcode(ERRCODE_OBJECT_IN_USE),
228 : : errmsg("connection \"%s\" is already in use", conname)));
229 : : else
230 [ + - ]: 2 : ereport(ERROR,
231 : : (errcode(ERRCODE_OBJECT_IN_USE),
232 : : errmsg("connection is already in use")));
233 : : }
234 : :
235 : : static void
236 : 53 : dblink_get_conn(char *conname_or_str,
237 : : PGconn *volatile *conn_p, char **conname_p, volatile bool *freeconn_p,
238 : : remoteConn **rconn_p)
239 : : {
240 : 53 : remoteConn *rconn = getConnectionByName(conname_or_str);
241 : : PGconn *conn;
242 : : char *conname;
243 : : bool freeconn;
244 : :
245 [ + + ]: 53 : if (rconn)
246 : : {
247 : 40 : conn = rconn->conn;
248 : 40 : conname = conname_or_str;
249 : 40 : freeconn = false;
250 : : }
251 : : else
252 : : {
253 : : const char *connstr;
254 : :
255 : 13 : connstr = get_connect_string(conname_or_str);
256 [ + + ]: 13 : if (connstr == NULL)
257 : 8 : connstr = conname_or_str;
258 : 13 : dblink_connstr_check(connstr);
259 : :
260 : : /* first time, allocate or get the custom wait event */
261 [ + + ]: 11 : if (dblink_we_get_conn == 0)
262 : 5 : dblink_we_get_conn = WaitEventExtensionNew("DblinkGetConnect");
263 : :
264 : : /*
265 : : * Final security check on the proxied connection options. Like
266 : : * dblink_connect, this happens whether the current user is a
267 : : * superuser or not.
268 : : */
269 : 11 : libpqsrv_check_proxy_conninfo(connstr);
270 : :
271 : : /* OK to make connection */
272 : 7 : conn = libpqsrv_connect_start(connstr);
273 : 7 : PQsetNoticeReceiver(conn, libpqsrv_notice_receiver,
274 : : "received message via remote connection");
275 : 7 : libpqsrv_connect_complete(conn, dblink_we_get_conn);
276 : :
277 [ + + ]: 7 : if (PQstatus(conn) == CONNECTION_BAD)
278 : : {
279 : 1 : char *msg = pchomp(PQerrorMessage(conn));
280 : :
281 : 1 : libpqsrv_disconnect(conn);
282 [ + - ]: 1 : ereport(ERROR,
283 : : (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
284 : : errmsg("could not establish connection"),
285 : : errdetail_internal("%s", msg)));
286 : : }
287 : :
288 : 6 : dblink_security_check(conn, NULL, connstr);
289 [ - + ]: 6 : if (PQclientEncoding(conn) != GetDatabaseEncoding())
290 : 0 : PQsetClientEncoding(conn, GetDatabaseEncodingName());
291 : 6 : freeconn = true;
292 : 6 : conname = NULL;
293 : : }
294 : :
295 : 46 : *conn_p = conn;
296 : 46 : *conname_p = conname;
297 : 46 : *freeconn_p = freeconn;
298 : 46 : *rconn_p = rconn;
299 : 46 : }
300 : :
301 : : static PGconn *
302 : 10 : dblink_get_named_conn(const char *conname)
303 : : {
304 : 10 : remoteConn *rconn = getConnectionByName(conname);
305 : :
306 [ + - ]: 10 : if (rconn)
307 : : {
308 : 10 : dblink_check_conn_not_in_use(rconn, conname);
309 : 9 : return rconn->conn;
310 : : }
311 : :
312 : 0 : dblink_conn_not_avail(conname);
313 : : return NULL; /* keep compiler quiet */
314 : : }
315 : :
316 : : static void
317 : 162 : dblink_init(void)
318 : : {
319 [ + + ]: 162 : if (!pconn)
320 : : {
321 [ + - ]: 8 : if (dblink_we_get_result == 0)
322 : 8 : dblink_we_get_result = WaitEventExtensionNew("DblinkGetResult");
323 : :
324 : 8 : pconn = (remoteConn *) MemoryContextAlloc(TopMemoryContext, sizeof(remoteConn));
325 : 8 : pconn->conn = NULL;
326 : 8 : pconn->openCursorCount = 0;
327 : 8 : pconn->newXactForCursor = false;
328 : 8 : pconn->materializingResult = false;
329 : : }
330 : 162 : }
331 : :
332 : : /*
333 : : * Create a persistent connection to another database
334 : : */
335 : 13 : PG_FUNCTION_INFO_V1(dblink_connect);
336 : : Datum
337 : 23 : dblink_connect(PG_FUNCTION_ARGS)
338 : : {
339 : 23 : char *conname_or_str = NULL;
340 : 23 : char *connstr = NULL;
341 : 23 : char *connname = NULL;
342 : : char *msg;
343 : 23 : PGconn *conn = NULL;
344 : 23 : remoteConn *rconn = NULL;
345 : :
346 : 23 : dblink_init();
347 : :
348 [ + + ]: 23 : if (PG_NARGS() == 2)
349 : : {
350 : 14 : conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(1));
351 : 14 : connname = text_to_cstring(PG_GETARG_TEXT_PP(0));
352 : : }
353 [ + - ]: 9 : else if (PG_NARGS() == 1)
354 : 9 : conname_or_str = text_to_cstring(PG_GETARG_TEXT_PP(0));
355 : :
356 : : /* first check for valid foreign data server */
357 : 23 : connstr = get_connect_string(conname_or_str);
358 [ + + ]: 23 : if (connstr == NULL)
359 : 21 : connstr = conname_or_str;
360 : :
361 : : /* check password in connection string if not superuser */
362 : 23 : dblink_connstr_check(connstr);
363 : :
364 : : /* first time, allocate or get the custom wait event */
365 [ + + ]: 22 : if (dblink_we_connect == 0)
366 : 2 : dblink_we_connect = WaitEventExtensionNew("DblinkConnect");
367 : :
368 : : /* if we need a hashtable entry, make that first, since it might fail */
369 [ + + ]: 22 : if (connname)
370 : : {
371 : 13 : rconn = createNewConnection(connname);
372 : : Assert(rconn->conn == NULL);
373 : : }
374 : :
375 : : /*
376 : : * Opening an unnamed connection closes the one we already have further
377 : : * down, so it had better not be in use. Check before connecting, so that
378 : : * we don't have to throw away a connection we just made. A named
379 : : * connection can't get here with a live PGconn, since
380 : : * createNewConnection() rejects the duplicate name above.
381 : : */
382 [ + + + + ]: 21 : if (!connname && pconn->conn)
383 : 2 : dblink_check_conn_not_in_use(pconn, NULL);
384 : :
385 : : /*
386 : : * Final security check on the proxied connection options.
387 : : *
388 : : * NB: Validation happens regardless of whether the current user is a
389 : : * superuser, because dblink_connect_u is implemented as a SECURITY
390 : : * DEFINER function, and it's only documented to grant an exception for
391 : : * the dblink_security_check. We don't really want to expand that set of
392 : : * privileges arbitrarily.
393 : : */
394 : 20 : libpqsrv_check_proxy_conninfo(connstr);
395 : :
396 : : /* OK to make connection */
397 : 17 : conn = libpqsrv_connect_start(connstr);
398 [ + - ]: 17 : if (conn != NULL)
399 : 17 : PQsetNoticeReceiver(conn, libpqsrv_notice_receiver,
400 : : "received message via remote connection");
401 : 17 : libpqsrv_connect_complete(conn, dblink_we_connect);
402 : :
403 [ - + ]: 17 : if (PQstatus(conn) == CONNECTION_BAD)
404 : : {
405 : 0 : msg = pchomp(PQerrorMessage(conn));
406 : 0 : libpqsrv_disconnect(conn);
407 [ # # ]: 0 : if (connname)
408 : 0 : deleteConnection(connname);
409 : :
410 [ # # ]: 0 : ereport(ERROR,
411 : : (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
412 : : errmsg("could not establish connection"),
413 : : errdetail_internal("%s", msg)));
414 : : }
415 : :
416 : : /* check password actually used if not superuser */
417 : 17 : dblink_security_check(conn, connname, connstr);
418 : :
419 : : /* attempt to set client encoding to match server encoding, if needed */
420 [ - + ]: 17 : if (PQclientEncoding(conn) != GetDatabaseEncoding())
421 : 0 : PQsetClientEncoding(conn, GetDatabaseEncodingName());
422 : :
423 : : /* all OK, save away the conn */
424 [ + + ]: 17 : if (connname)
425 : : {
426 : 11 : rconn->conn = conn;
427 : : }
428 : : else
429 : : {
430 [ + + ]: 6 : if (pconn->conn)
431 : 1 : libpqsrv_disconnect(pconn->conn);
432 : 6 : pconn->conn = conn;
433 : : }
434 : :
435 : 17 : PG_RETURN_TEXT_P(cstring_to_text("OK"));
436 : : }
437 : :
438 : : /*
439 : : * Clear a persistent connection to another database
440 : : */
441 : 8 : PG_FUNCTION_INFO_V1(dblink_disconnect);
442 : : Datum
443 : 21 : dblink_disconnect(PG_FUNCTION_ARGS)
444 : : {
445 : 21 : char *conname = NULL;
446 : 21 : remoteConn *rconn = NULL;
447 : 21 : PGconn *conn = NULL;
448 : :
449 : 21 : dblink_init();
450 : :
451 [ + + ]: 21 : if (PG_NARGS() == 1)
452 : : {
453 : 15 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
454 : 15 : rconn = getConnectionByName(conname);
455 [ + + ]: 15 : if (rconn)
456 : 14 : conn = rconn->conn;
457 : : }
458 : : else
459 : 6 : conn = pconn->conn;
460 : :
461 [ + + ]: 21 : if (!conn)
462 : 1 : dblink_conn_not_avail(conname);
463 : :
464 [ + + ]: 20 : dblink_check_conn_not_in_use(rconn != NULL ? rconn : pconn, conname);
465 : :
466 : 15 : libpqsrv_disconnect(conn);
467 [ + + ]: 15 : if (rconn)
468 : 10 : deleteConnection(conname);
469 : : else
470 : 5 : pconn->conn = NULL;
471 : :
472 : 15 : PG_RETURN_TEXT_P(cstring_to_text("OK"));
473 : : }
474 : :
475 : : /*
476 : : * opens a cursor using a persistent connection
477 : : */
478 : 13 : PG_FUNCTION_INFO_V1(dblink_open);
479 : : Datum
480 : 10 : dblink_open(PG_FUNCTION_ARGS)
481 : : {
482 : 10 : PGresult *res = NULL;
483 : : PGconn *conn;
484 : 10 : char *curname = NULL;
485 : 10 : char *sql = NULL;
486 : 10 : char *conname = NULL;
487 : : StringInfoData buf;
488 : 10 : remoteConn *rconn = NULL;
489 : 10 : bool fail = true; /* default to backward compatible behavior */
490 : :
491 : 10 : dblink_init();
492 : 10 : initStringInfo(&buf);
493 : :
494 [ + + ]: 10 : if (PG_NARGS() == 2)
495 : : {
496 : : /* text,text */
497 : 2 : curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
498 : 2 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
499 : 2 : rconn = pconn;
500 : : }
501 [ + + ]: 8 : else if (PG_NARGS() == 3)
502 : : {
503 : : /* might be text,text,text or text,text,bool */
504 [ + + ]: 7 : if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
505 : : {
506 : 1 : curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
507 : 1 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
508 : 1 : fail = PG_GETARG_BOOL(2);
509 : 1 : rconn = pconn;
510 : : }
511 : : else
512 : : {
513 : 6 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
514 : 6 : curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
515 : 6 : sql = text_to_cstring(PG_GETARG_TEXT_PP(2));
516 : 6 : rconn = getConnectionByName(conname);
517 : : }
518 : : }
519 [ + - ]: 1 : else if (PG_NARGS() == 4)
520 : : {
521 : : /* text,text,text,bool */
522 : 1 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
523 : 1 : curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
524 : 1 : sql = text_to_cstring(PG_GETARG_TEXT_PP(2));
525 : 1 : fail = PG_GETARG_BOOL(3);
526 : 1 : rconn = getConnectionByName(conname);
527 : : }
528 : :
529 [ + - - + ]: 10 : if (!rconn || !rconn->conn)
530 : 0 : dblink_conn_not_avail(conname);
531 : 10 : dblink_check_conn_not_in_use(rconn, conname);
532 : :
533 : 10 : conn = rconn->conn;
534 : :
535 : : /* If we are not in a transaction, start one */
536 [ + + ]: 10 : if (PQtransactionStatus(conn) == PQTRANS_IDLE)
537 : : {
538 : 8 : res = libpqsrv_exec(conn, "BEGIN", dblink_we_get_result);
539 [ - + ]: 8 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
540 : 0 : dblink_res_internalerror(conn, res, "begin error");
541 : 8 : PQclear(res);
542 : 8 : rconn->newXactForCursor = true;
543 : :
544 : : /*
545 : : * Since transaction state was IDLE, we force cursor count to
546 : : * initially be 0. This is needed as a previous ABORT might have wiped
547 : : * out our transaction without maintaining the cursor count for us.
548 : : */
549 : 8 : rconn->openCursorCount = 0;
550 : : }
551 : :
552 : : /* if we started a transaction, increment cursor count */
553 [ + - ]: 10 : if (rconn->newXactForCursor)
554 : 10 : (rconn->openCursorCount)++;
555 : :
556 : 10 : appendStringInfo(&buf, "DECLARE %s CURSOR FOR %s", curname, sql);
557 : 10 : res = libpqsrv_exec(conn, buf.data, dblink_we_get_result);
558 [ + - + + ]: 10 : if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
559 : : {
560 : 2 : dblink_res_error(conn, conname, res, fail,
561 : : "while opening cursor \"%s\"", curname);
562 : 2 : PG_RETURN_TEXT_P(cstring_to_text("ERROR"));
563 : : }
564 : :
565 : 8 : PQclear(res);
566 : 8 : PG_RETURN_TEXT_P(cstring_to_text("OK"));
567 : : }
568 : :
569 : : /*
570 : : * closes a cursor
571 : : */
572 : 10 : PG_FUNCTION_INFO_V1(dblink_close);
573 : : Datum
574 : 6 : dblink_close(PG_FUNCTION_ARGS)
575 : : {
576 : : PGconn *conn;
577 : 6 : PGresult *res = NULL;
578 : 6 : char *curname = NULL;
579 : 6 : char *conname = NULL;
580 : : StringInfoData buf;
581 : 6 : remoteConn *rconn = NULL;
582 : 6 : bool fail = true; /* default to backward compatible behavior */
583 : :
584 : 6 : dblink_init();
585 : 6 : initStringInfo(&buf);
586 : :
587 [ - + ]: 6 : if (PG_NARGS() == 1)
588 : : {
589 : : /* text */
590 : 0 : curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
591 : 0 : rconn = pconn;
592 : : }
593 [ + - ]: 6 : else if (PG_NARGS() == 2)
594 : : {
595 : : /* might be text,text or text,bool */
596 [ + + ]: 6 : if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
597 : : {
598 : 2 : curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
599 : 2 : fail = PG_GETARG_BOOL(1);
600 : 2 : rconn = pconn;
601 : : }
602 : : else
603 : : {
604 : 4 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
605 : 4 : curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
606 : 4 : rconn = getConnectionByName(conname);
607 : : }
608 : : }
609 [ - + ]: 6 : if (PG_NARGS() == 3)
610 : : {
611 : : /* text,text,bool */
612 : 0 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
613 : 0 : curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
614 : 0 : fail = PG_GETARG_BOOL(2);
615 : 0 : rconn = getConnectionByName(conname);
616 : : }
617 : :
618 [ + - - + ]: 6 : if (!rconn || !rconn->conn)
619 : 0 : dblink_conn_not_avail(conname);
620 : 6 : dblink_check_conn_not_in_use(rconn, conname);
621 : :
622 : 6 : conn = rconn->conn;
623 : :
624 : 6 : appendStringInfo(&buf, "CLOSE %s", curname);
625 : :
626 : : /* close the cursor */
627 : 6 : res = libpqsrv_exec(conn, buf.data, dblink_we_get_result);
628 [ + - + + ]: 6 : if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
629 : : {
630 : 1 : dblink_res_error(conn, conname, res, fail,
631 : : "while closing cursor \"%s\"", curname);
632 : 1 : PG_RETURN_TEXT_P(cstring_to_text("ERROR"));
633 : : }
634 : :
635 : 5 : PQclear(res);
636 : :
637 : : /* if we started a transaction, decrement cursor count */
638 [ + - ]: 5 : if (rconn->newXactForCursor)
639 : : {
640 : 5 : (rconn->openCursorCount)--;
641 : :
642 : : /* if count is zero, commit the transaction */
643 [ + + ]: 5 : if (rconn->openCursorCount == 0)
644 : : {
645 : 3 : rconn->newXactForCursor = false;
646 : :
647 : 3 : res = libpqsrv_exec(conn, "COMMIT", dblink_we_get_result);
648 [ - + ]: 3 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
649 : 0 : dblink_res_internalerror(conn, res, "commit error");
650 : 3 : PQclear(res);
651 : : }
652 : : }
653 : :
654 : 5 : PG_RETURN_TEXT_P(cstring_to_text("OK"));
655 : : }
656 : :
657 : : /*
658 : : * Fetch results from an open cursor
659 : : */
660 : 13 : PG_FUNCTION_INFO_V1(dblink_fetch);
661 : : Datum
662 : 14 : dblink_fetch(PG_FUNCTION_ARGS)
663 : : {
664 : 14 : PGresult *res = NULL;
665 : 14 : char *conname = NULL;
666 : 14 : remoteConn *rconn = NULL;
667 : 14 : PGconn *conn = NULL;
668 : : StringInfoData buf;
669 : 14 : char *curname = NULL;
670 : 14 : int howmany = 0;
671 : 14 : bool fail = true; /* default to backward compatible */
672 : :
673 : 14 : prepTuplestoreResult(fcinfo);
674 : :
675 : 14 : dblink_init();
676 : :
677 [ + + ]: 14 : if (PG_NARGS() == 4)
678 : : {
679 : : /* text,text,int,bool */
680 : 1 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
681 : 1 : curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
682 : 1 : howmany = PG_GETARG_INT32(2);
683 : 1 : fail = PG_GETARG_BOOL(3);
684 : :
685 : 1 : rconn = getConnectionByName(conname);
686 [ + - ]: 1 : if (rconn)
687 : 1 : conn = rconn->conn;
688 : : }
689 [ + + ]: 13 : else if (PG_NARGS() == 3)
690 : : {
691 : : /* text,text,int or text,int,bool */
692 [ + + ]: 9 : if (get_fn_expr_argtype(fcinfo->flinfo, 2) == BOOLOID)
693 : : {
694 : 2 : curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
695 : 2 : howmany = PG_GETARG_INT32(1);
696 : 2 : fail = PG_GETARG_BOOL(2);
697 : 2 : rconn = pconn;
698 : 2 : conn = pconn->conn;
699 : : }
700 : : else
701 : : {
702 : 7 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
703 : 7 : curname = text_to_cstring(PG_GETARG_TEXT_PP(1));
704 : 7 : howmany = PG_GETARG_INT32(2);
705 : :
706 : 7 : rconn = getConnectionByName(conname);
707 [ + - ]: 7 : if (rconn)
708 : 7 : conn = rconn->conn;
709 : : }
710 : : }
711 [ + - ]: 4 : else if (PG_NARGS() == 2)
712 : : {
713 : : /* text,int */
714 : 4 : curname = text_to_cstring(PG_GETARG_TEXT_PP(0));
715 : 4 : howmany = PG_GETARG_INT32(1);
716 : 4 : rconn = pconn;
717 : 4 : conn = pconn->conn;
718 : : }
719 : :
720 [ - + ]: 14 : if (!conn)
721 : 0 : dblink_conn_not_avail(conname);
722 : 14 : dblink_check_conn_not_in_use(rconn, conname);
723 : :
724 : 14 : initStringInfo(&buf);
725 : 14 : appendStringInfo(&buf, "FETCH %d FROM %s", howmany, curname);
726 : :
727 : : /*
728 : : * Try to execute the query. Note that since libpq uses malloc, the
729 : : * PGresult will be long-lived even though we are still in a short-lived
730 : : * memory context.
731 : : */
732 : 14 : res = libpqsrv_exec(conn, buf.data, dblink_we_get_result);
733 [ + - + - ]: 28 : if (!res ||
734 [ + + ]: 28 : (PQresultStatus(res) != PGRES_COMMAND_OK &&
735 : 14 : PQresultStatus(res) != PGRES_TUPLES_OK))
736 : : {
737 : 5 : dblink_res_error(conn, conname, res, fail,
738 : : "while fetching from cursor \"%s\"", curname);
739 : 3 : return (Datum) 0;
740 : : }
741 [ - + ]: 9 : else if (PQresultStatus(res) == PGRES_COMMAND_OK)
742 : : {
743 : : /* cursor does not exist - closed already or bad name */
744 : 0 : PQclear(res);
745 [ # # ]: 0 : ereport(ERROR,
746 : : (errcode(ERRCODE_INVALID_CURSOR_NAME),
747 : : errmsg("cursor \"%s\" does not exist", curname)));
748 : : }
749 : :
750 : 9 : materializeResult(fcinfo, conn, rconn, res);
751 : 7 : return (Datum) 0;
752 : : }
753 : :
754 : : /*
755 : : * Note: this is the new preferred version of dblink
756 : : */
757 : 20 : PG_FUNCTION_INFO_V1(dblink_record);
758 : : Datum
759 : 46 : dblink_record(PG_FUNCTION_ARGS)
760 : : {
761 : 46 : return dblink_record_internal(fcinfo, false);
762 : : }
763 : :
764 : 4 : PG_FUNCTION_INFO_V1(dblink_send_query);
765 : : Datum
766 : 6 : dblink_send_query(PG_FUNCTION_ARGS)
767 : : {
768 : : PGconn *conn;
769 : : char *sql;
770 : : int retval;
771 : :
772 [ + - ]: 6 : if (PG_NARGS() == 2)
773 : : {
774 : 6 : conn = dblink_get_named_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)));
775 : 6 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
776 : : }
777 : : else
778 : : /* shouldn't happen */
779 [ # # ]: 0 : elog(ERROR, "wrong number of arguments");
780 : :
781 : : /* async query send */
782 : 6 : retval = PQsendQuery(conn, sql);
783 [ - + ]: 6 : if (retval != 1)
784 [ # # ]: 0 : elog(NOTICE, "could not send query: %s", pchomp(PQerrorMessage(conn)));
785 : :
786 : 6 : PG_RETURN_INT32(retval);
787 : : }
788 : :
789 : 6 : PG_FUNCTION_INFO_V1(dblink_get_result);
790 : : Datum
791 : 9 : dblink_get_result(PG_FUNCTION_ARGS)
792 : : {
793 : 9 : return dblink_record_internal(fcinfo, true);
794 : : }
795 : :
796 : : static Datum
797 : 55 : dblink_record_internal(FunctionCallInfo fcinfo, bool is_async)
798 : : {
799 : 55 : PGconn *volatile conn = NULL;
800 : 55 : volatile bool freeconn = false;
801 : :
802 : 55 : prepTuplestoreResult(fcinfo);
803 : :
804 : 55 : dblink_init();
805 : :
806 [ + + ]: 55 : PG_TRY();
807 : : {
808 : 55 : char *sql = NULL;
809 : 55 : char *conname = NULL;
810 : 55 : bool fail = true; /* default to backward compatible */
811 : 55 : remoteConn *rconn = NULL;
812 : :
813 [ + + ]: 55 : if (!is_async)
814 : : {
815 [ + + ]: 46 : if (PG_NARGS() == 3)
816 : : {
817 : : /* text,text,bool */
818 : 1 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
819 : 1 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
820 : 1 : fail = PG_GETARG_BOOL(2);
821 : 1 : dblink_get_conn(conname, &conn, &conname, &freeconn, &rconn);
822 : : }
823 [ + + ]: 45 : else if (PG_NARGS() == 2)
824 : : {
825 : : /* text,text or text,bool */
826 [ + + ]: 36 : if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
827 : : {
828 : 1 : sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
829 : 1 : fail = PG_GETARG_BOOL(1);
830 : 1 : rconn = pconn;
831 : 1 : conn = pconn->conn;
832 : : }
833 : : else
834 : : {
835 : 35 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
836 : 35 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
837 : 35 : dblink_get_conn(conname, &conn, &conname, &freeconn, &rconn);
838 : : }
839 : : }
840 [ + - ]: 9 : else if (PG_NARGS() == 1)
841 : : {
842 : : /* text */
843 : 9 : rconn = pconn;
844 : 9 : conn = pconn->conn;
845 : 9 : sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
846 : : }
847 : : else
848 : : /* shouldn't happen */
849 [ # # ]: 0 : elog(ERROR, "wrong number of arguments");
850 : : }
851 : : else /* is_async */
852 : : {
853 : : /* get async result */
854 : 9 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
855 : :
856 [ - + ]: 9 : if (PG_NARGS() == 2)
857 : : {
858 : : /* text,bool */
859 : 0 : fail = PG_GETARG_BOOL(1);
860 : 0 : rconn = getConnectionByName(conname);
861 : : }
862 [ + - ]: 9 : else if (PG_NARGS() == 1)
863 : : {
864 : : /* text */
865 : 9 : rconn = getConnectionByName(conname);
866 : : }
867 : : else
868 : : /* shouldn't happen */
869 [ # # ]: 0 : elog(ERROR, "wrong number of arguments");
870 : :
871 [ + - ]: 9 : if (rconn)
872 : 9 : conn = rconn->conn;
873 : : }
874 : :
875 [ + + ]: 49 : if (!conn)
876 : 2 : dblink_conn_not_avail(conname);
877 : 47 : dblink_check_conn_not_in_use(rconn, conname);
878 : :
879 : : /* a connection we are to close cannot be one that SQL can name */
880 : : Assert(!freeconn || rconn == NULL);
881 : :
882 [ + + ]: 44 : if (!is_async)
883 : : {
884 : : /* synchronous query, use efficient tuple collection method */
885 : 36 : materializeQueryResult(fcinfo, conn, rconn, conname, sql, fail);
886 : : }
887 : : else
888 : : {
889 : : /* async result retrieval, do it the old way */
890 : 8 : PGresult *res = libpqsrv_get_result(conn, dblink_we_get_result);
891 : :
892 : : /* NULL means we're all done with the async results */
893 [ + + ]: 8 : if (res)
894 : : {
895 [ + - ]: 5 : if (PQresultStatus(res) != PGRES_COMMAND_OK &&
896 [ - + ]: 5 : PQresultStatus(res) != PGRES_TUPLES_OK)
897 : : {
898 : 0 : dblink_res_error(conn, conname, res, fail,
899 : : "while executing query");
900 : : /* if fail isn't set, we'll return an empty query result */
901 : : }
902 : : else
903 : : {
904 : 5 : materializeResult(fcinfo, conn, rconn, res);
905 : : }
906 : : }
907 : : }
908 : : }
909 : 19 : PG_FINALLY();
910 : : {
911 : : /* if needed, close the connection to the database */
912 [ + + ]: 55 : if (freeconn)
913 : 5 : libpqsrv_disconnect(conn);
914 : : }
915 [ + + ]: 55 : PG_END_TRY();
916 : :
917 : 36 : return (Datum) 0;
918 : : }
919 : :
920 : : /*
921 : : * Verify function caller can handle a tuplestore result, and set up for that.
922 : : *
923 : : * Note: if the caller returns without actually creating a tuplestore, the
924 : : * executor will treat the function result as an empty set.
925 : : */
926 : : static void
927 : 69 : prepTuplestoreResult(FunctionCallInfo fcinfo)
928 : : {
929 : 69 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
930 : :
931 : : /* check to see if query supports us returning a tuplestore */
932 [ + - - + ]: 69 : if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
933 [ # # ]: 0 : ereport(ERROR,
934 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
935 : : errmsg("set-valued function called in context that cannot accept a set")));
936 [ - + ]: 69 : if (!(rsinfo->allowedModes & SFRM_Materialize))
937 [ # # ]: 0 : ereport(ERROR,
938 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
939 : : errmsg("materialize mode required, but it is not allowed in this context")));
940 : :
941 : : /* let the executor know we're sending back a tuplestore */
942 : 69 : rsinfo->returnMode = SFRM_Materialize;
943 : :
944 : : /* caller must fill these to return a non-empty result */
945 : 69 : rsinfo->setResult = NULL;
946 : 69 : rsinfo->setDesc = NULL;
947 : 69 : }
948 : :
949 : : /*
950 : : * Copy the contents of the PGresult into a tuplestore to be returned
951 : : * as the result of the current function.
952 : : * The PGresult will be released in this function.
953 : : *
954 : : * rconn is the corresponding connection cache entry to conn, or NULL
955 : : * if conn is a transient connection opened from a connection string.
956 : : */
957 : : static void
958 : 14 : materializeResult(FunctionCallInfo fcinfo, PGconn *conn, remoteConn *rconn,
959 : : PGresult *res)
960 : : {
961 : 14 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
962 : :
963 : : /* prepTuplestoreResult must have been called previously */
964 : : Assert(rsinfo->returnMode == SFRM_Materialize);
965 : :
966 : : /* Refuse other dblink calls on this connection while converting rows */
967 [ + - ]: 14 : if (rconn)
968 : : {
969 : : Assert(!rconn->materializingResult);
970 : 14 : rconn->materializingResult = true;
971 : : }
972 : :
973 [ + + ]: 14 : PG_TRY();
974 : : {
975 : : TupleDesc tupdesc;
976 : : bool is_sql_cmd;
977 : : int ntuples;
978 : : int nfields;
979 : :
980 [ - + ]: 14 : if (PQresultStatus(res) == PGRES_COMMAND_OK)
981 : : {
982 : 0 : is_sql_cmd = true;
983 : :
984 : : /*
985 : : * need a tuple descriptor representing one TEXT column to return
986 : : * the command status string as our result tuple
987 : : */
988 : 0 : tupdesc = CreateTemplateTupleDesc(1);
989 : 0 : TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
990 : : TEXTOID, -1, 0);
991 : 0 : TupleDescFinalize(tupdesc);
992 : 0 : ntuples = 1;
993 : 0 : nfields = 1;
994 : : }
995 : : else
996 : : {
997 : : Assert(PQresultStatus(res) == PGRES_TUPLES_OK);
998 : :
999 : 14 : is_sql_cmd = false;
1000 : :
1001 : : /* get a tuple descriptor for our result type */
1002 [ + - - ]: 14 : switch (get_call_result_type(fcinfo, NULL, &tupdesc))
1003 : : {
1004 : 14 : case TYPEFUNC_COMPOSITE:
1005 : : /* success */
1006 : 14 : break;
1007 : 0 : case TYPEFUNC_RECORD:
1008 : : /* failed to determine actual type of RECORD */
1009 [ # # ]: 0 : ereport(ERROR,
1010 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1011 : : errmsg("function returning record called in context "
1012 : : "that cannot accept type record")));
1013 : : break;
1014 : 0 : default:
1015 : : /* result type isn't composite */
1016 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
1017 : : break;
1018 : : }
1019 : :
1020 : : /* make sure we have a persistent copy of the tupdesc */
1021 : 14 : tupdesc = CreateTupleDescCopy(tupdesc);
1022 : 14 : ntuples = PQntuples(res);
1023 : 14 : nfields = PQnfields(res);
1024 : : }
1025 : :
1026 : : /*
1027 : : * check result and tuple descriptor have the same number of columns
1028 : : */
1029 [ - + ]: 14 : if (nfields != tupdesc->natts)
1030 [ # # ]: 0 : ereport(ERROR,
1031 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1032 : : errmsg("remote query result rowtype does not match "
1033 : : "the specified FROM clause rowtype")));
1034 : :
1035 [ + - ]: 14 : if (ntuples > 0)
1036 : : {
1037 : : AttInMetadata *attinmeta;
1038 : 14 : int nestlevel = -1;
1039 : : Tuplestorestate *tupstore;
1040 : : MemoryContext oldcontext;
1041 : : int row;
1042 : : char **values;
1043 : :
1044 : 14 : attinmeta = TupleDescGetAttInMetadata(tupdesc);
1045 : :
1046 : : /* Set GUCs to ensure we read GUC-sensitive data types correctly */
1047 [ + - ]: 14 : if (!is_sql_cmd)
1048 : 14 : nestlevel = applyRemoteGucs(conn);
1049 : :
1050 : 14 : oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1051 : 14 : tupstore = tuplestore_begin_heap(true, false, work_mem);
1052 : 14 : rsinfo->setResult = tupstore;
1053 : 14 : rsinfo->setDesc = tupdesc;
1054 : 14 : MemoryContextSwitchTo(oldcontext);
1055 : :
1056 : 14 : values = palloc_array(char *, nfields);
1057 : :
1058 : : /* put all tuples into the tuplestore */
1059 [ + + ]: 50 : for (row = 0; row < ntuples; row++)
1060 : : {
1061 : : HeapTuple tuple;
1062 : :
1063 [ + - ]: 38 : if (!is_sql_cmd)
1064 : : {
1065 : : int i;
1066 : :
1067 [ + + ]: 140 : for (i = 0; i < nfields; i++)
1068 : : {
1069 [ - + ]: 102 : if (PQgetisnull(res, row, i))
1070 : 0 : values[i] = NULL;
1071 : : else
1072 : 102 : values[i] = PQgetvalue(res, row, i);
1073 : : }
1074 : : }
1075 : : else
1076 : : {
1077 : 0 : values[0] = PQcmdStatus(res);
1078 : : }
1079 : :
1080 : : /* build the tuple and put it into the tuplestore. */
1081 : 38 : tuple = BuildTupleFromCStrings(attinmeta, values);
1082 : 36 : tuplestore_puttuple(tupstore, tuple);
1083 : : }
1084 : :
1085 : : /* clean up GUC settings, if we changed any */
1086 : 12 : restoreLocalGucs(nestlevel);
1087 : : }
1088 : :
1089 : 12 : PQclear(res);
1090 : : }
1091 : 2 : PG_FINALLY();
1092 : : {
1093 : : /* Done converting rows, so other dblink calls may use it again */
1094 [ + - ]: 14 : if (rconn)
1095 : 14 : rconn->materializingResult = false;
1096 : : }
1097 [ + + ]: 14 : PG_END_TRY();
1098 : 12 : }
1099 : :
1100 : : /*
1101 : : * Execute the given SQL command and store its results into a tuplestore
1102 : : * to be returned as the result of the current function.
1103 : : *
1104 : : * This is equivalent to PQexec followed by materializeResult, but we make
1105 : : * use of libpq's single-row mode to avoid accumulating the whole result
1106 : : * inside libpq before it gets transferred to the tuplestore.
1107 : : */
1108 : : static void
1109 : 36 : materializeQueryResult(FunctionCallInfo fcinfo,
1110 : : PGconn *conn,
1111 : : remoteConn *rconn,
1112 : : const char *conname,
1113 : : const char *sql,
1114 : : bool fail)
1115 : : {
1116 : 36 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1117 : :
1118 : : /* prepTuplestoreResult must have been called previously */
1119 : : Assert(rsinfo->returnMode == SFRM_Materialize);
1120 : :
1121 : : /* Refuse other dblink calls on this connection while converting rows */
1122 [ + + ]: 36 : if (rconn)
1123 : : {
1124 : : Assert(!rconn->materializingResult);
1125 : 31 : rconn->materializingResult = true;
1126 : : }
1127 : :
1128 : : /* Use a PG_TRY block to ensure we pump libpq dry of results */
1129 [ + + ]: 36 : PG_TRY();
1130 : : {
1131 : 36 : storeInfo sinfo = {0};
1132 : : PGresult *res;
1133 : :
1134 : 36 : sinfo.fcinfo = fcinfo;
1135 : : /* Create short-lived memory context for data conversions */
1136 : 36 : sinfo.tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
1137 : : "dblink temporary context",
1138 : : ALLOCSET_DEFAULT_SIZES);
1139 : :
1140 : : /* execute query, collecting any tuples into the tuplestore */
1141 : 36 : res = storeQueryResult(&sinfo, conn, sql);
1142 : :
1143 [ + - ]: 28 : if (!res ||
1144 [ + - ]: 28 : (PQresultStatus(res) != PGRES_COMMAND_OK &&
1145 [ + + ]: 28 : PQresultStatus(res) != PGRES_TUPLES_OK))
1146 : : {
1147 : 2 : dblink_res_error(conn, conname, res, fail,
1148 : : "while executing query");
1149 : : /* if fail isn't set, we'll return an empty query result */
1150 : : }
1151 [ - + ]: 26 : else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1152 : : {
1153 : : /*
1154 : : * storeRow didn't get called, so we need to convert the command
1155 : : * status string to a tuple manually
1156 : : */
1157 : : TupleDesc tupdesc;
1158 : : AttInMetadata *attinmeta;
1159 : : Tuplestorestate *tupstore;
1160 : : HeapTuple tuple;
1161 : : char *values[1];
1162 : : MemoryContext oldcontext;
1163 : :
1164 : : /*
1165 : : * need a tuple descriptor representing one TEXT column to return
1166 : : * the command status string as our result tuple
1167 : : */
1168 : 0 : tupdesc = CreateTemplateTupleDesc(1);
1169 : 0 : TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1170 : : TEXTOID, -1, 0);
1171 : 0 : TupleDescFinalize(tupdesc);
1172 : 0 : attinmeta = TupleDescGetAttInMetadata(tupdesc);
1173 : :
1174 : 0 : oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1175 : 0 : tupstore = tuplestore_begin_heap(true, false, work_mem);
1176 : 0 : rsinfo->setResult = tupstore;
1177 : 0 : rsinfo->setDesc = tupdesc;
1178 : 0 : MemoryContextSwitchTo(oldcontext);
1179 : :
1180 : 0 : values[0] = PQcmdStatus(res);
1181 : :
1182 : : /* build the tuple and put it into the tuplestore. */
1183 : 0 : tuple = BuildTupleFromCStrings(attinmeta, values);
1184 : 0 : tuplestore_puttuple(tupstore, tuple);
1185 : :
1186 : 0 : PQclear(res);
1187 : : }
1188 : : else
1189 : : {
1190 : : Assert(PQresultStatus(res) == PGRES_TUPLES_OK);
1191 : : /* storeRow should have created a tuplestore */
1192 : : Assert(rsinfo->setResult != NULL);
1193 : :
1194 : 26 : PQclear(res);
1195 : : }
1196 : :
1197 : : /* clean up data conversion short-lived memory context */
1198 [ + - ]: 28 : if (sinfo.tmpcontext != NULL)
1199 : 28 : MemoryContextDelete(sinfo.tmpcontext);
1200 : :
1201 : 28 : PQclear(sinfo.last_res);
1202 : 28 : PQclear(sinfo.cur_res);
1203 : :
1204 : : /* Done converting rows, so other dblink calls may use it again */
1205 [ + + ]: 28 : if (rconn)
1206 : 23 : rconn->materializingResult = false;
1207 : : }
1208 : 8 : PG_CATCH();
1209 : : {
1210 : : PGresult *res;
1211 : :
1212 : : /*
1213 : : * Draining the pending data can be interrupted, so clear the mark
1214 : : * first to avoid leaving the connection marked in use for the rest of
1215 : : * the session. This is safe since draining runs no user-defined code.
1216 : : */
1217 [ + - ]: 8 : if (rconn)
1218 : 8 : rconn->materializingResult = false;
1219 : :
1220 : : /* be sure to clear out any pending data in libpq */
1221 [ + + ]: 16 : while ((res = libpqsrv_get_result(conn, dblink_we_get_result)) !=
1222 : : NULL)
1223 : 8 : PQclear(res);
1224 : :
1225 : 8 : PG_RE_THROW();
1226 : : }
1227 [ - + ]: 28 : PG_END_TRY();
1228 : 28 : }
1229 : :
1230 : : /*
1231 : : * Execute query, and send any result rows to sinfo->tuplestore.
1232 : : */
1233 : : static PGresult *
1234 : 36 : storeQueryResult(storeInfo *sinfo, PGconn *conn, const char *sql)
1235 : : {
1236 : 36 : bool first = true;
1237 : 36 : int nestlevel = -1;
1238 : : PGresult *res;
1239 : :
1240 [ - + ]: 36 : if (!PQsendQuery(conn, sql))
1241 [ # # ]: 0 : elog(ERROR, "could not send query: %s", pchomp(PQerrorMessage(conn)));
1242 : :
1243 [ - + ]: 36 : if (!PQsetSingleRowMode(conn)) /* shouldn't fail */
1244 [ # # ]: 0 : elog(ERROR, "failed to set single-row mode for dblink query");
1245 : :
1246 : : for (;;)
1247 : : {
1248 [ - + ]: 221 : CHECK_FOR_INTERRUPTS();
1249 : :
1250 : 221 : sinfo->cur_res = libpqsrv_get_result(conn, dblink_we_get_result);
1251 [ + + ]: 221 : if (!sinfo->cur_res)
1252 : 28 : break;
1253 : :
1254 [ + + ]: 193 : if (PQresultStatus(sinfo->cur_res) == PGRES_SINGLE_TUPLE)
1255 : : {
1256 : : /* got one row from possibly-bigger resultset */
1257 : :
1258 : : /*
1259 : : * Set GUCs to ensure we read GUC-sensitive data types correctly.
1260 : : * We shouldn't do this until we have a row in hand, to ensure
1261 : : * libpq has seen any earlier ParameterStatus protocol messages.
1262 : : */
1263 [ + + + - ]: 165 : if (first && nestlevel < 0)
1264 : 34 : nestlevel = applyRemoteGucs(conn);
1265 : :
1266 : 165 : storeRow(sinfo, sinfo->cur_res, first);
1267 : :
1268 : 157 : PQclear(sinfo->cur_res);
1269 : 157 : sinfo->cur_res = NULL;
1270 : 157 : first = false;
1271 : : }
1272 : : else
1273 : : {
1274 : : /* if empty resultset, fill tuplestore header */
1275 [ + + - + ]: 28 : if (first && PQresultStatus(sinfo->cur_res) == PGRES_TUPLES_OK)
1276 : 0 : storeRow(sinfo, sinfo->cur_res, first);
1277 : :
1278 : : /* store completed result at last_res */
1279 : 28 : PQclear(sinfo->last_res);
1280 : 28 : sinfo->last_res = sinfo->cur_res;
1281 : 28 : sinfo->cur_res = NULL;
1282 : 28 : first = true;
1283 : : }
1284 : : }
1285 : :
1286 : : /* clean up GUC settings, if we changed any */
1287 : 28 : restoreLocalGucs(nestlevel);
1288 : :
1289 : : /* return last_res */
1290 : 28 : res = sinfo->last_res;
1291 : 28 : sinfo->last_res = NULL;
1292 : 28 : return res;
1293 : : }
1294 : :
1295 : : /*
1296 : : * Send single row to sinfo->tuplestore.
1297 : : *
1298 : : * If "first" is true, create the tuplestore using PGresult's metadata
1299 : : * (in this case the PGresult might contain either zero or one row).
1300 : : */
1301 : : static void
1302 : 165 : storeRow(storeInfo *sinfo, PGresult *res, bool first)
1303 : : {
1304 : 165 : int nfields = PQnfields(res);
1305 : : HeapTuple tuple;
1306 : : int i;
1307 : : MemoryContext oldcontext;
1308 : :
1309 [ + + ]: 165 : if (first)
1310 : : {
1311 : : /* Prepare for new result set */
1312 : 34 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) sinfo->fcinfo->resultinfo;
1313 : : TupleDesc tupdesc;
1314 : :
1315 : : /*
1316 : : * It's possible to get more than one result set if the query string
1317 : : * contained multiple SQL commands. In that case, we follow PQexec's
1318 : : * traditional behavior of throwing away all but the last result.
1319 : : */
1320 [ - + ]: 34 : if (sinfo->tuplestore)
1321 : 0 : tuplestore_end(sinfo->tuplestore);
1322 : 34 : sinfo->tuplestore = NULL;
1323 : :
1324 : : /* get a tuple descriptor for our result type */
1325 [ + - - ]: 34 : switch (get_call_result_type(sinfo->fcinfo, NULL, &tupdesc))
1326 : : {
1327 : 34 : case TYPEFUNC_COMPOSITE:
1328 : : /* success */
1329 : 34 : break;
1330 : 0 : case TYPEFUNC_RECORD:
1331 : : /* failed to determine actual type of RECORD */
1332 [ # # ]: 0 : ereport(ERROR,
1333 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1334 : : errmsg("function returning record called in context "
1335 : : "that cannot accept type record")));
1336 : : break;
1337 : 0 : default:
1338 : : /* result type isn't composite */
1339 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
1340 : : break;
1341 : : }
1342 : :
1343 : : /* make sure we have a persistent copy of the tupdesc */
1344 : 34 : tupdesc = CreateTupleDescCopy(tupdesc);
1345 : :
1346 : : /* check result and tuple descriptor have the same number of columns */
1347 [ - + ]: 34 : if (nfields != tupdesc->natts)
1348 [ # # ]: 0 : ereport(ERROR,
1349 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1350 : : errmsg("remote query result rowtype does not match "
1351 : : "the specified FROM clause rowtype")));
1352 : :
1353 : : /* Prepare attinmeta for later data conversions */
1354 : 34 : sinfo->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1355 : :
1356 : : /* Create a new, empty tuplestore */
1357 : 34 : oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1358 : 34 : sinfo->tuplestore = tuplestore_begin_heap(true, false, work_mem);
1359 : 34 : rsinfo->setResult = sinfo->tuplestore;
1360 : 34 : rsinfo->setDesc = tupdesc;
1361 : 34 : MemoryContextSwitchTo(oldcontext);
1362 : :
1363 : : /* Done if empty resultset */
1364 [ - + ]: 34 : if (PQntuples(res) == 0)
1365 : 0 : return;
1366 : :
1367 : : /*
1368 : : * Set up sufficiently-wide string pointers array; this won't change
1369 : : * in size so it's easy to preallocate.
1370 : : */
1371 [ - + ]: 34 : if (sinfo->cstrs)
1372 : 0 : pfree(sinfo->cstrs);
1373 : 34 : sinfo->cstrs = palloc_array(char *, nfields);
1374 : : }
1375 : :
1376 : : /* Should have a single-row result if we get here */
1377 : : Assert(PQntuples(res) == 1);
1378 : :
1379 : : /*
1380 : : * Do the following work in a temp context that we reset after each tuple.
1381 : : * This cleans up not only the data we have direct access to, but any
1382 : : * cruft the I/O functions might leak.
1383 : : */
1384 : 165 : oldcontext = MemoryContextSwitchTo(sinfo->tmpcontext);
1385 : :
1386 : : /*
1387 : : * Fill cstrs with null-terminated strings of column values.
1388 : : */
1389 [ + + ]: 596 : for (i = 0; i < nfields; i++)
1390 : : {
1391 [ - + ]: 431 : if (PQgetisnull(res, 0, i))
1392 : 0 : sinfo->cstrs[i] = NULL;
1393 : : else
1394 : 431 : sinfo->cstrs[i] = PQgetvalue(res, 0, i);
1395 : : }
1396 : :
1397 : : /* Convert row to a tuple, and add it to the tuplestore */
1398 : 165 : tuple = BuildTupleFromCStrings(sinfo->attinmeta, sinfo->cstrs);
1399 : :
1400 : 157 : tuplestore_puttuple(sinfo->tuplestore, tuple);
1401 : :
1402 : : /* Clean up */
1403 : 157 : MemoryContextSwitchTo(oldcontext);
1404 : 157 : MemoryContextReset(sinfo->tmpcontext);
1405 : : }
1406 : :
1407 : : /*
1408 : : * List all open dblink connections by name.
1409 : : * Returns an array of all connection names.
1410 : : * Takes no params
1411 : : */
1412 : 3 : PG_FUNCTION_INFO_V1(dblink_get_connections);
1413 : : Datum
1414 : 1 : dblink_get_connections(PG_FUNCTION_ARGS)
1415 : : {
1416 : : HASH_SEQ_STATUS status;
1417 : : remoteConnHashEnt *hentry;
1418 : 1 : ArrayBuildState *astate = NULL;
1419 : :
1420 [ + - ]: 1 : if (remoteConnHash)
1421 : : {
1422 : 1 : hash_seq_init(&status, remoteConnHash);
1423 [ + + ]: 4 : while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1424 : : {
1425 : : /* ignore it if it's not an open connection */
1426 [ - + ]: 3 : if (hentry->rconn.conn == NULL)
1427 : 0 : continue;
1428 : : /* stash away current value */
1429 : 3 : astate = accumArrayResult(astate,
1430 : 3 : CStringGetTextDatum(hentry->name),
1431 : : false, TEXTOID, CurrentMemoryContext);
1432 : : }
1433 : : }
1434 : :
1435 [ + - ]: 1 : if (astate)
1436 : 1 : PG_RETURN_DATUM(makeArrayResult(astate,
1437 : : CurrentMemoryContext));
1438 : : else
1439 : 0 : PG_RETURN_NULL();
1440 : : }
1441 : :
1442 : : /*
1443 : : * Checks if a given remote connection is busy
1444 : : *
1445 : : * Returns 1 if the connection is busy, 0 otherwise
1446 : : * Params:
1447 : : * text connection_name - name of the connection to check
1448 : : *
1449 : : */
1450 : 3 : PG_FUNCTION_INFO_V1(dblink_is_busy);
1451 : : Datum
1452 : 2 : dblink_is_busy(PG_FUNCTION_ARGS)
1453 : : {
1454 : : PGconn *conn;
1455 : :
1456 : 2 : dblink_init();
1457 : 2 : conn = dblink_get_named_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)));
1458 : :
1459 : 1 : PQconsumeInput(conn);
1460 : 1 : PG_RETURN_INT32(PQisBusy(conn));
1461 : : }
1462 : :
1463 : : /*
1464 : : * Cancels a running request on a connection
1465 : : *
1466 : : * Returns text:
1467 : : * "OK" if the cancel request has been sent correctly,
1468 : : * an error message otherwise
1469 : : *
1470 : : * Params:
1471 : : * text connection_name - name of the connection to check
1472 : : *
1473 : : */
1474 : 3 : PG_FUNCTION_INFO_V1(dblink_cancel_query);
1475 : : Datum
1476 : 1 : dblink_cancel_query(PG_FUNCTION_ARGS)
1477 : : {
1478 : : PGconn *conn;
1479 : : const char *msg;
1480 : : TimestampTz endtime;
1481 : :
1482 : 1 : dblink_init();
1483 : 1 : conn = dblink_get_named_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)));
1484 : 1 : endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
1485 : : 30000);
1486 : 1 : msg = libpqsrv_cancel(conn, endtime);
1487 [ + - ]: 1 : if (msg == NULL)
1488 : 1 : msg = "OK";
1489 : :
1490 : 1 : PG_RETURN_TEXT_P(cstring_to_text(msg));
1491 : : }
1492 : :
1493 : :
1494 : : /*
1495 : : * Get error message from a connection
1496 : : *
1497 : : * Returns text:
1498 : : * "OK" if no error, an error message otherwise
1499 : : *
1500 : : * Params:
1501 : : * text connection_name - name of the connection to check
1502 : : *
1503 : : */
1504 : 3 : PG_FUNCTION_INFO_V1(dblink_error_message);
1505 : : Datum
1506 : 1 : dblink_error_message(PG_FUNCTION_ARGS)
1507 : : {
1508 : : char *msg;
1509 : : PGconn *conn;
1510 : :
1511 : 1 : dblink_init();
1512 : 1 : conn = dblink_get_named_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)));
1513 : :
1514 : 1 : msg = PQerrorMessage(conn);
1515 [ + - + - ]: 1 : if (msg == NULL || msg[0] == '\0')
1516 : 1 : PG_RETURN_TEXT_P(cstring_to_text("OK"));
1517 : : else
1518 : 0 : PG_RETURN_TEXT_P(cstring_to_text(pchomp(msg)));
1519 : : }
1520 : :
1521 : : /*
1522 : : * Execute an SQL non-SELECT command
1523 : : */
1524 : 13 : PG_FUNCTION_INFO_V1(dblink_exec);
1525 : : Datum
1526 : 27 : dblink_exec(PG_FUNCTION_ARGS)
1527 : : {
1528 : 27 : text *volatile sql_cmd_status = NULL;
1529 : 27 : PGconn *volatile conn = NULL;
1530 : 27 : volatile bool freeconn = false;
1531 : :
1532 : 27 : dblink_init();
1533 : :
1534 [ + + ]: 27 : PG_TRY();
1535 : : {
1536 : 27 : PGresult *res = NULL;
1537 : 27 : char *sql = NULL;
1538 : 27 : char *conname = NULL;
1539 : 27 : remoteConn *rconn = NULL;
1540 : 27 : bool fail = true; /* default to backward compatible behavior */
1541 : :
1542 [ - + ]: 27 : if (PG_NARGS() == 3)
1543 : : {
1544 : : /* must be text,text,bool */
1545 : 0 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1546 : 0 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
1547 : 0 : fail = PG_GETARG_BOOL(2);
1548 : 0 : dblink_get_conn(conname, &conn, &conname, &freeconn, &rconn);
1549 : : }
1550 [ + + ]: 27 : else if (PG_NARGS() == 2)
1551 : : {
1552 : : /* might be text,text or text,bool */
1553 [ + + ]: 18 : if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1554 : : {
1555 : 1 : sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
1556 : 1 : fail = PG_GETARG_BOOL(1);
1557 : 1 : rconn = pconn;
1558 : 1 : conn = pconn->conn;
1559 : : }
1560 : : else
1561 : : {
1562 : 17 : conname = text_to_cstring(PG_GETARG_TEXT_PP(0));
1563 : 17 : sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
1564 : 17 : dblink_get_conn(conname, &conn, &conname, &freeconn, &rconn);
1565 : : }
1566 : : }
1567 [ + - ]: 9 : else if (PG_NARGS() == 1)
1568 : : {
1569 : : /* must be single text argument */
1570 : 9 : rconn = pconn;
1571 : 9 : conn = pconn->conn;
1572 : 9 : sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
1573 : : }
1574 : : else
1575 : : /* shouldn't happen */
1576 [ # # ]: 0 : elog(ERROR, "wrong number of arguments");
1577 : :
1578 [ - + ]: 26 : if (!conn)
1579 : 0 : dblink_conn_not_avail(conname);
1580 : :
1581 : 26 : dblink_check_conn_not_in_use(rconn, conname);
1582 : :
1583 : 26 : res = libpqsrv_exec(conn, sql, dblink_we_get_result);
1584 [ + - ]: 26 : if (!res ||
1585 [ + + ]: 26 : (PQresultStatus(res) != PGRES_COMMAND_OK &&
1586 [ + - ]: 2 : PQresultStatus(res) != PGRES_TUPLES_OK))
1587 : : {
1588 : 2 : dblink_res_error(conn, conname, res, fail,
1589 : : "while executing command");
1590 : :
1591 : : /*
1592 : : * and save a copy of the command status string to return as our
1593 : : * result tuple
1594 : : */
1595 : 1 : sql_cmd_status = cstring_to_text("ERROR");
1596 : : }
1597 [ + - ]: 24 : else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1598 : : {
1599 : : /*
1600 : : * and save a copy of the command status string to return as our
1601 : : * result tuple
1602 : : */
1603 : 24 : sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1604 : 24 : PQclear(res);
1605 : : }
1606 : : else
1607 : : {
1608 : 0 : PQclear(res);
1609 [ # # ]: 0 : ereport(ERROR,
1610 : : (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1611 : : errmsg("statement returning results not allowed")));
1612 : : }
1613 : : }
1614 : 2 : PG_FINALLY();
1615 : : {
1616 : : /* if needed, close the connection to the database */
1617 [ + + ]: 27 : if (freeconn)
1618 : 1 : libpqsrv_disconnect(conn);
1619 : : }
1620 [ + + ]: 27 : PG_END_TRY();
1621 : :
1622 : 25 : PG_RETURN_TEXT_P(sql_cmd_status);
1623 : : }
1624 : :
1625 : :
1626 : : /*
1627 : : * dblink_get_pkey
1628 : : *
1629 : : * Return list of primary key fields for the supplied relation,
1630 : : * or NULL if none exists.
1631 : : */
1632 : 3 : PG_FUNCTION_INFO_V1(dblink_get_pkey);
1633 : : Datum
1634 : 9 : dblink_get_pkey(PG_FUNCTION_ARGS)
1635 : : {
1636 : : int16 indnkeyatts;
1637 : : char **results;
1638 : : FuncCallContext *funcctx;
1639 : : int32 call_cntr;
1640 : : int32 max_calls;
1641 : : AttInMetadata *attinmeta;
1642 : : MemoryContext oldcontext;
1643 : :
1644 : : /* stuff done only on the first call of the function */
1645 [ + + ]: 9 : if (SRF_IS_FIRSTCALL())
1646 : : {
1647 : : Relation rel;
1648 : : TupleDesc tupdesc;
1649 : :
1650 : : /* create a function context for cross-call persistence */
1651 : 3 : funcctx = SRF_FIRSTCALL_INIT();
1652 : :
1653 : : /*
1654 : : * switch to memory context appropriate for multiple function calls
1655 : : */
1656 : 3 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1657 : :
1658 : : /* open target relation */
1659 : 3 : rel = get_rel_from_relname(PG_GETARG_TEXT_PP(0), AccessShareLock, ACL_SELECT);
1660 : :
1661 : : /* get the array of attnums */
1662 : 3 : results = get_pkey_attnames(rel, &indnkeyatts);
1663 : :
1664 : 3 : relation_close(rel, AccessShareLock);
1665 : :
1666 : : /*
1667 : : * need a tuple descriptor representing one INT and one TEXT column
1668 : : */
1669 : 3 : tupdesc = CreateTemplateTupleDesc(2);
1670 : 3 : TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
1671 : : INT4OID, -1, 0);
1672 : 3 : TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
1673 : : TEXTOID, -1, 0);
1674 : :
1675 : 3 : TupleDescFinalize(tupdesc);
1676 : :
1677 : : /*
1678 : : * Generate attribute metadata needed later to produce tuples from raw
1679 : : * C strings
1680 : : */
1681 : 3 : attinmeta = TupleDescGetAttInMetadata(tupdesc);
1682 : 3 : funcctx->attinmeta = attinmeta;
1683 : :
1684 [ + - + - ]: 3 : if ((results != NULL) && (indnkeyatts > 0))
1685 : : {
1686 : 3 : funcctx->max_calls = indnkeyatts;
1687 : :
1688 : : /* got results, keep track of them */
1689 : 3 : funcctx->user_fctx = results;
1690 : : }
1691 : : else
1692 : : {
1693 : : /* fast track when no results */
1694 : 0 : MemoryContextSwitchTo(oldcontext);
1695 : 0 : SRF_RETURN_DONE(funcctx);
1696 : : }
1697 : :
1698 : 3 : MemoryContextSwitchTo(oldcontext);
1699 : : }
1700 : :
1701 : : /* stuff done on every call of the function */
1702 : 9 : funcctx = SRF_PERCALL_SETUP();
1703 : :
1704 : : /*
1705 : : * initialize per-call variables
1706 : : */
1707 : 9 : call_cntr = funcctx->call_cntr;
1708 : 9 : max_calls = funcctx->max_calls;
1709 : :
1710 : 9 : results = (char **) funcctx->user_fctx;
1711 : 9 : attinmeta = funcctx->attinmeta;
1712 : :
1713 [ + + ]: 9 : if (call_cntr < max_calls) /* do when there is more left to send */
1714 : : {
1715 : : char **values;
1716 : : HeapTuple tuple;
1717 : : Datum result;
1718 : :
1719 : 6 : values = palloc_array(char *, 2);
1720 : 6 : values[0] = psprintf("%d", call_cntr + 1);
1721 : 6 : values[1] = results[call_cntr];
1722 : :
1723 : : /* build the tuple */
1724 : 6 : tuple = BuildTupleFromCStrings(attinmeta, values);
1725 : :
1726 : : /* make the tuple into a datum */
1727 : 6 : result = HeapTupleGetDatum(tuple);
1728 : :
1729 : 6 : SRF_RETURN_NEXT(funcctx, result);
1730 : : }
1731 : : else
1732 : : {
1733 : : /* do when there is no more left */
1734 : 3 : SRF_RETURN_DONE(funcctx);
1735 : : }
1736 : : }
1737 : :
1738 : :
1739 : : /*
1740 : : * dblink_build_sql_insert
1741 : : *
1742 : : * Used to generate an SQL insert statement
1743 : : * based on an existing tuple in a local relation.
1744 : : * This is useful for selectively replicating data
1745 : : * to another server via dblink.
1746 : : *
1747 : : * API:
1748 : : * <relname> - name of local table of interest
1749 : : * <pkattnums> - an int2vector of attnums which will be used
1750 : : * to identify the local tuple of interest
1751 : : * <pknumatts> - number of attnums in pkattnums
1752 : : * <src_pkattvals_arry> - text array of key values which will be used
1753 : : * to identify the local tuple of interest
1754 : : * <tgt_pkattvals_arry> - text array of key values which will be used
1755 : : * to build the string for execution remotely. These are substituted
1756 : : * for their counterparts in src_pkattvals_arry
1757 : : */
1758 : 4 : PG_FUNCTION_INFO_V1(dblink_build_sql_insert);
1759 : : Datum
1760 : 6 : dblink_build_sql_insert(PG_FUNCTION_ARGS)
1761 : : {
1762 : 6 : text *relname_text = PG_GETARG_TEXT_PP(0);
1763 : 6 : int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1764 : 6 : int32 pknumatts_arg = PG_GETARG_INT32(2);
1765 : 6 : ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1766 : 6 : ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1767 : : Relation rel;
1768 : : int *pkattnums;
1769 : : int pknumatts;
1770 : : char **src_pkattvals;
1771 : : char **tgt_pkattvals;
1772 : : int src_nitems;
1773 : : int tgt_nitems;
1774 : : char *sql;
1775 : :
1776 : : /*
1777 : : * Open target relation.
1778 : : */
1779 : 6 : rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1780 : :
1781 : : /*
1782 : : * Process pkattnums argument.
1783 : : */
1784 : 6 : validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1785 : : &pkattnums, &pknumatts);
1786 : :
1787 : : /*
1788 : : * Source array is made up of key values that will be used to locate the
1789 : : * tuple of interest from the local system.
1790 : : */
1791 : 4 : src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1792 : :
1793 : : /*
1794 : : * There should be one source array key value for each key attnum
1795 : : */
1796 [ - + ]: 4 : if (src_nitems != pknumatts)
1797 [ # # ]: 0 : ereport(ERROR,
1798 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1799 : : errmsg("source key array length must match number of key attributes")));
1800 : :
1801 : : /*
1802 : : * Target array is made up of key values that will be used to build the
1803 : : * SQL string for use on the remote system.
1804 : : */
1805 : 4 : tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1806 : :
1807 : : /*
1808 : : * There should be one target array key value for each key attnum
1809 : : */
1810 [ - + ]: 4 : if (tgt_nitems != pknumatts)
1811 [ # # ]: 0 : ereport(ERROR,
1812 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1813 : : errmsg("target key array length must match number of key attributes")));
1814 : :
1815 : : /*
1816 : : * Prep work is finally done. Go get the SQL string.
1817 : : */
1818 : 4 : sql = get_sql_insert(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1819 : :
1820 : : /*
1821 : : * Now we can close the relation.
1822 : : */
1823 : 4 : relation_close(rel, AccessShareLock);
1824 : :
1825 : : /*
1826 : : * And send it
1827 : : */
1828 : 4 : PG_RETURN_TEXT_P(cstring_to_text(sql));
1829 : : }
1830 : :
1831 : :
1832 : : /*
1833 : : * dblink_build_sql_delete
1834 : : *
1835 : : * Used to generate an SQL delete statement.
1836 : : * This is useful for selectively replicating a
1837 : : * delete to another server via dblink.
1838 : : *
1839 : : * API:
1840 : : * <relname> - name of remote table of interest
1841 : : * <pkattnums> - an int2vector of attnums which will be used
1842 : : * to identify the remote tuple of interest
1843 : : * <pknumatts> - number of attnums in pkattnums
1844 : : * <tgt_pkattvals_arry> - text array of key values which will be used
1845 : : * to build the string for execution remotely.
1846 : : */
1847 : 4 : PG_FUNCTION_INFO_V1(dblink_build_sql_delete);
1848 : : Datum
1849 : 6 : dblink_build_sql_delete(PG_FUNCTION_ARGS)
1850 : : {
1851 : 6 : text *relname_text = PG_GETARG_TEXT_PP(0);
1852 : 6 : int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1853 : 6 : int32 pknumatts_arg = PG_GETARG_INT32(2);
1854 : 6 : ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1855 : : Relation rel;
1856 : : int *pkattnums;
1857 : : int pknumatts;
1858 : : char **tgt_pkattvals;
1859 : : int tgt_nitems;
1860 : : char *sql;
1861 : :
1862 : : /*
1863 : : * Open target relation.
1864 : : */
1865 : 6 : rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1866 : :
1867 : : /*
1868 : : * Process pkattnums argument.
1869 : : */
1870 : 6 : validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1871 : : &pkattnums, &pknumatts);
1872 : :
1873 : : /*
1874 : : * Target array is made up of key values that will be used to build the
1875 : : * SQL string for use on the remote system.
1876 : : */
1877 : 4 : tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1878 : :
1879 : : /*
1880 : : * There should be one target array key value for each key attnum
1881 : : */
1882 [ - + ]: 4 : if (tgt_nitems != pknumatts)
1883 [ # # ]: 0 : ereport(ERROR,
1884 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1885 : : errmsg("target key array length must match number of key attributes")));
1886 : :
1887 : : /*
1888 : : * Prep work is finally done. Go get the SQL string.
1889 : : */
1890 : 4 : sql = get_sql_delete(rel, pkattnums, pknumatts, tgt_pkattvals);
1891 : :
1892 : : /*
1893 : : * Now we can close the relation.
1894 : : */
1895 : 4 : relation_close(rel, AccessShareLock);
1896 : :
1897 : : /*
1898 : : * And send it
1899 : : */
1900 : 4 : PG_RETURN_TEXT_P(cstring_to_text(sql));
1901 : : }
1902 : :
1903 : :
1904 : : /*
1905 : : * dblink_build_sql_update
1906 : : *
1907 : : * Used to generate an SQL update statement
1908 : : * based on an existing tuple in a local relation.
1909 : : * This is useful for selectively replicating data
1910 : : * to another server via dblink.
1911 : : *
1912 : : * API:
1913 : : * <relname> - name of local table of interest
1914 : : * <pkattnums> - an int2vector of attnums which will be used
1915 : : * to identify the local tuple of interest
1916 : : * <pknumatts> - number of attnums in pkattnums
1917 : : * <src_pkattvals_arry> - text array of key values which will be used
1918 : : * to identify the local tuple of interest
1919 : : * <tgt_pkattvals_arry> - text array of key values which will be used
1920 : : * to build the string for execution remotely. These are substituted
1921 : : * for their counterparts in src_pkattvals_arry
1922 : : */
1923 : 4 : PG_FUNCTION_INFO_V1(dblink_build_sql_update);
1924 : : Datum
1925 : 6 : dblink_build_sql_update(PG_FUNCTION_ARGS)
1926 : : {
1927 : 6 : text *relname_text = PG_GETARG_TEXT_PP(0);
1928 : 6 : int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1929 : 6 : int32 pknumatts_arg = PG_GETARG_INT32(2);
1930 : 6 : ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1931 : 6 : ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1932 : : Relation rel;
1933 : : int *pkattnums;
1934 : : int pknumatts;
1935 : : char **src_pkattvals;
1936 : : char **tgt_pkattvals;
1937 : : int src_nitems;
1938 : : int tgt_nitems;
1939 : : char *sql;
1940 : :
1941 : : /*
1942 : : * Open target relation.
1943 : : */
1944 : 6 : rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1945 : :
1946 : : /*
1947 : : * Process pkattnums argument.
1948 : : */
1949 : 6 : validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1950 : : &pkattnums, &pknumatts);
1951 : :
1952 : : /*
1953 : : * Source array is made up of key values that will be used to locate the
1954 : : * tuple of interest from the local system.
1955 : : */
1956 : 4 : src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1957 : :
1958 : : /*
1959 : : * There should be one source array key value for each key attnum
1960 : : */
1961 [ - + ]: 4 : if (src_nitems != pknumatts)
1962 [ # # ]: 0 : ereport(ERROR,
1963 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1964 : : errmsg("source key array length must match number of key attributes")));
1965 : :
1966 : : /*
1967 : : * Target array is made up of key values that will be used to build the
1968 : : * SQL string for use on the remote system.
1969 : : */
1970 : 4 : tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1971 : :
1972 : : /*
1973 : : * There should be one target array key value for each key attnum
1974 : : */
1975 [ - + ]: 4 : if (tgt_nitems != pknumatts)
1976 [ # # ]: 0 : ereport(ERROR,
1977 : : (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1978 : : errmsg("target key array length must match number of key attributes")));
1979 : :
1980 : : /*
1981 : : * Prep work is finally done. Go get the SQL string.
1982 : : */
1983 : 4 : sql = get_sql_update(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1984 : :
1985 : : /*
1986 : : * Now we can close the relation.
1987 : : */
1988 : 4 : relation_close(rel, AccessShareLock);
1989 : :
1990 : : /*
1991 : : * And send it
1992 : : */
1993 : 4 : PG_RETURN_TEXT_P(cstring_to_text(sql));
1994 : : }
1995 : :
1996 : : /*
1997 : : * dblink_current_query
1998 : : * return the current query string
1999 : : * to allow its use in (among other things)
2000 : : * rewrite rules
2001 : : */
2002 : 2 : PG_FUNCTION_INFO_V1(dblink_current_query);
2003 : : Datum
2004 : 0 : dblink_current_query(PG_FUNCTION_ARGS)
2005 : : {
2006 : : /* This is now just an alias for the built-in function current_query() */
2007 : 0 : PG_RETURN_DATUM(current_query(fcinfo));
2008 : : }
2009 : :
2010 : : /*
2011 : : * Retrieve async notifications for a connection.
2012 : : *
2013 : : * Returns a setof record of notifications, or an empty set if none received.
2014 : : * Can optionally take a named connection as parameter, but uses the unnamed
2015 : : * connection per default.
2016 : : *
2017 : : */
2018 : : #define DBLINK_NOTIFY_COLS 3
2019 : :
2020 : 5 : PG_FUNCTION_INFO_V1(dblink_get_notify);
2021 : : Datum
2022 : 2 : dblink_get_notify(PG_FUNCTION_ARGS)
2023 : : {
2024 : : PGconn *conn;
2025 : : PGnotify *notify;
2026 : 2 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2027 : :
2028 : 2 : dblink_init();
2029 [ - + ]: 2 : if (PG_NARGS() == 1)
2030 : 0 : conn = dblink_get_named_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)));
2031 : : else
2032 : : {
2033 : 2 : dblink_check_conn_not_in_use(pconn, NULL);
2034 : 2 : conn = pconn->conn;
2035 : : }
2036 : :
2037 : 2 : InitMaterializedSRF(fcinfo, 0);
2038 : :
2039 : 2 : PQconsumeInput(conn);
2040 [ + + ]: 4 : while ((notify = PQnotifies(conn)) != NULL)
2041 : : {
2042 : : Datum values[DBLINK_NOTIFY_COLS];
2043 : : bool nulls[DBLINK_NOTIFY_COLS];
2044 : :
2045 : 2 : memset(values, 0, sizeof(values));
2046 : 2 : memset(nulls, 0, sizeof(nulls));
2047 : :
2048 [ + - ]: 2 : if (notify->relname != NULL)
2049 : 2 : values[0] = CStringGetTextDatum(notify->relname);
2050 : : else
2051 : 0 : nulls[0] = true;
2052 : :
2053 : 2 : values[1] = Int32GetDatum(notify->be_pid);
2054 : :
2055 [ + - ]: 2 : if (notify->extra != NULL)
2056 : 2 : values[2] = CStringGetTextDatum(notify->extra);
2057 : : else
2058 : 0 : nulls[2] = true;
2059 : :
2060 : 2 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2061 : :
2062 : 2 : PQfreemem(notify);
2063 : 2 : PQconsumeInput(conn);
2064 : : }
2065 : :
2066 : 2 : return (Datum) 0;
2067 : : }
2068 : :
2069 : : /*
2070 : : * Validate the options given to a dblink foreign server or user mapping.
2071 : : * Raise an error if any option is invalid.
2072 : : *
2073 : : * We just check the names of options here, so semantic errors in options,
2074 : : * such as invalid numeric format, will be detected at the attempt to connect.
2075 : : */
2076 : 17 : PG_FUNCTION_INFO_V1(dblink_fdw_validator);
2077 : : Datum
2078 : 25 : dblink_fdw_validator(PG_FUNCTION_ARGS)
2079 : : {
2080 : 25 : List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
2081 : 25 : Oid context = PG_GETARG_OID(1);
2082 : : ListCell *cell;
2083 : :
2084 : : static const PQconninfoOption *options = NULL;
2085 : :
2086 : : /*
2087 : : * Get list of valid libpq options.
2088 : : *
2089 : : * To avoid unnecessary work, we get the list once and use it throughout
2090 : : * the lifetime of this backend process. We don't need to care about
2091 : : * memory context issues, because PQconndefaults allocates with malloc.
2092 : : */
2093 [ + + ]: 25 : if (!options)
2094 : : {
2095 : 15 : options = PQconndefaults();
2096 [ - + ]: 15 : if (!options) /* assume reason for failure is OOM */
2097 [ # # ]: 0 : ereport(ERROR,
2098 : : (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2099 : : errmsg("out of memory"),
2100 : : errdetail("Could not get libpq's default connection options.")));
2101 : : }
2102 : :
2103 : : /* Validate each supplied option. */
2104 [ + + + + : 66 : foreach(cell, options_list)
+ + ]
2105 : : {
2106 : 52 : DefElem *def = (DefElem *) lfirst(cell);
2107 : :
2108 [ + + ]: 52 : if (!is_valid_dblink_fdw_option(options, def->defname, context))
2109 : : {
2110 : : /*
2111 : : * Unknown option, or invalid option for the context specified, so
2112 : : * complain about it. Provide a hint with a valid option that
2113 : : * looks similar, if there is one.
2114 : : */
2115 : : const PQconninfoOption *opt;
2116 : : const char *closest_match;
2117 : : ClosestMatchState match_state;
2118 : 11 : bool has_valid_options = false;
2119 : :
2120 : 11 : initClosestMatch(&match_state, def->defname, 4);
2121 [ + + ]: 572 : for (opt = options; opt->keyword; opt++)
2122 : : {
2123 [ + + ]: 561 : if (is_valid_dblink_option(options, opt->keyword, context))
2124 : : {
2125 : 132 : has_valid_options = true;
2126 : 132 : updateClosestMatch(&match_state, opt->keyword);
2127 : : }
2128 : : }
2129 : :
2130 : 11 : closest_match = getClosestMatch(&match_state);
2131 [ + - + + : 11 : ereport(ERROR,
- + ]
2132 : : (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
2133 : : errmsg("invalid option \"%s\"", def->defname),
2134 : : has_valid_options ? closest_match ?
2135 : : errhint("Perhaps you meant the option \"%s\".",
2136 : : closest_match) : 0 :
2137 : : errhint("There are no valid options in this context.")));
2138 : : }
2139 : :
2140 [ + + ]: 41 : if (strcmp(def->defname, "use_scram_passthrough") == 0)
2141 : 6 : (void) defGetBoolean(def); /* accept only boolean values */
2142 : : }
2143 : :
2144 : 14 : PG_RETURN_VOID();
2145 : : }
2146 : :
2147 : :
2148 : : /*************************************************************
2149 : : * internal functions
2150 : : */
2151 : :
2152 : :
2153 : : /*
2154 : : * get_pkey_attnames
2155 : : *
2156 : : * Get the primary key attnames for the given relation.
2157 : : * Return NULL, and set indnkeyatts = 0, if no primary key exists.
2158 : : */
2159 : : static char **
2160 : 3 : get_pkey_attnames(Relation rel, int16 *indnkeyatts)
2161 : : {
2162 : : Relation indexRelation;
2163 : : ScanKeyData skey;
2164 : : SysScanDesc scan;
2165 : : HeapTuple indexTuple;
2166 : : int i;
2167 : 3 : char **result = NULL;
2168 : : TupleDesc tupdesc;
2169 : :
2170 : : /* initialize indnkeyatts to 0 in case no primary key exists */
2171 : 3 : *indnkeyatts = 0;
2172 : :
2173 : 3 : tupdesc = rel->rd_att;
2174 : :
2175 : : /* Prepare to scan pg_index for entries having indrelid = this rel. */
2176 : 3 : indexRelation = table_open(IndexRelationId, AccessShareLock);
2177 : 3 : ScanKeyInit(&skey,
2178 : : Anum_pg_index_indrelid,
2179 : : BTEqualStrategyNumber, F_OIDEQ,
2180 : : ObjectIdGetDatum(RelationGetRelid(rel)));
2181 : :
2182 : 3 : scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2183 : : NULL, 1, &skey);
2184 : :
2185 [ + - ]: 3 : while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2186 : : {
2187 : 3 : Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2188 : :
2189 : : /* we're only interested if it is the primary key */
2190 [ + - ]: 3 : if (index->indisprimary)
2191 : : {
2192 : 3 : *indnkeyatts = index->indnkeyatts;
2193 [ + - ]: 3 : if (*indnkeyatts > 0)
2194 : : {
2195 : 3 : result = palloc_array(char *, *indnkeyatts);
2196 : :
2197 [ + + ]: 9 : for (i = 0; i < *indnkeyatts; i++)
2198 : 6 : result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2199 : : }
2200 : 3 : break;
2201 : : }
2202 : : }
2203 : :
2204 : 3 : systable_endscan(scan);
2205 : 3 : table_close(indexRelation, AccessShareLock);
2206 : :
2207 : 3 : return result;
2208 : : }
2209 : :
2210 : : /*
2211 : : * Deconstruct a text[] into C-strings (note any NULL elements will be
2212 : : * returned as NULL pointers)
2213 : : */
2214 : : static char **
2215 : 20 : get_text_array_contents(ArrayType *array, int *numitems)
2216 : : {
2217 : 20 : int ndim = ARR_NDIM(array);
2218 : 20 : int *dims = ARR_DIMS(array);
2219 : : int nitems;
2220 : : int16 typlen;
2221 : : bool typbyval;
2222 : : char typalign;
2223 : : uint8 typalignby;
2224 : : char **values;
2225 : : char *ptr;
2226 : : uint8 *bitmap;
2227 : : int bitmask;
2228 : : int i;
2229 : :
2230 : : Assert(ARR_ELEMTYPE(array) == TEXTOID);
2231 : :
2232 : 20 : *numitems = nitems = ArrayGetNItems(ndim, dims);
2233 : :
2234 : 20 : get_typlenbyvalalign(ARR_ELEMTYPE(array),
2235 : : &typlen, &typbyval, &typalign);
2236 : 20 : typalignby = typalign_to_alignby(typalign);
2237 : :
2238 : 20 : values = palloc_array(char *, nitems);
2239 : :
2240 [ - + ]: 20 : ptr = ARR_DATA_PTR(array);
2241 [ - + ]: 20 : bitmap = ARR_NULLBITMAP(array);
2242 : 20 : bitmask = 1;
2243 : :
2244 [ + + ]: 55 : for (i = 0; i < nitems; i++)
2245 : : {
2246 [ - + - - ]: 35 : if (bitmap && (*bitmap & bitmask) == 0)
2247 : : {
2248 : 0 : values[i] = NULL;
2249 : : }
2250 : : else
2251 : : {
2252 : 35 : values[i] = TextDatumGetCString(PointerGetDatum(ptr));
2253 [ - + + - ]: 35 : ptr = att_addlength_pointer(ptr, typlen, ptr);
2254 : 35 : ptr = (char *) att_nominal_alignby(ptr, typalignby);
2255 : : }
2256 : :
2257 : : /* advance bitmap pointer if any */
2258 [ - + ]: 35 : if (bitmap)
2259 : : {
2260 : 0 : bitmask <<= 1;
2261 [ # # ]: 0 : if (bitmask == 0x100)
2262 : : {
2263 : 0 : bitmap++;
2264 : 0 : bitmask = 1;
2265 : : }
2266 : : }
2267 : : }
2268 : :
2269 : 20 : return values;
2270 : : }
2271 : :
2272 : : static char *
2273 : 4 : get_sql_insert(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
2274 : : {
2275 : : char *relname;
2276 : : HeapTuple tuple;
2277 : : TupleDesc tupdesc;
2278 : : int natts;
2279 : : StringInfoData buf;
2280 : : char *val;
2281 : : int key;
2282 : : int i;
2283 : : bool needComma;
2284 : :
2285 : 4 : initStringInfo(&buf);
2286 : :
2287 : : /* get relation name including any needed schema prefix and quoting */
2288 : 4 : relname = generate_relation_name(rel);
2289 : :
2290 : 4 : tupdesc = rel->rd_att;
2291 : 4 : natts = tupdesc->natts;
2292 : :
2293 : 4 : tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2294 [ - + ]: 4 : if (!tuple)
2295 [ # # ]: 0 : ereport(ERROR,
2296 : : (errcode(ERRCODE_CARDINALITY_VIOLATION),
2297 : : errmsg("source row not found")));
2298 : :
2299 : 4 : appendStringInfo(&buf, "INSERT INTO %s(", relname);
2300 : :
2301 : 4 : needComma = false;
2302 [ + + ]: 19 : for (i = 0; i < natts; i++)
2303 : : {
2304 : 15 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2305 : :
2306 [ + + ]: 15 : if (att->attisdropped)
2307 : 2 : continue;
2308 : :
2309 [ + + ]: 13 : if (needComma)
2310 : 9 : appendStringInfoChar(&buf, ',');
2311 : :
2312 : 13 : appendStringInfoString(&buf,
2313 : 13 : quote_ident_cstr(NameStr(att->attname)));
2314 : 13 : needComma = true;
2315 : : }
2316 : :
2317 : 4 : appendStringInfoString(&buf, ") VALUES(");
2318 : :
2319 : : /*
2320 : : * Note: i is physical column number (counting from 0).
2321 : : */
2322 : 4 : needComma = false;
2323 [ + + ]: 19 : for (i = 0; i < natts; i++)
2324 : : {
2325 [ + + ]: 15 : if (TupleDescAttr(tupdesc, i)->attisdropped)
2326 : 2 : continue;
2327 : :
2328 [ + + ]: 13 : if (needComma)
2329 : 9 : appendStringInfoChar(&buf, ',');
2330 : :
2331 : 13 : key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2332 : :
2333 [ + + ]: 13 : if (key >= 0)
2334 [ + - ]: 7 : val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2335 : : else
2336 : 6 : val = SPI_getvalue(tuple, tupdesc, i + 1);
2337 : :
2338 [ + - ]: 13 : if (val != NULL)
2339 : : {
2340 : 13 : appendStringInfoString(&buf, quote_literal_cstr(val));
2341 : 13 : pfree(val);
2342 : : }
2343 : : else
2344 : 0 : appendStringInfoString(&buf, "NULL");
2345 : 13 : needComma = true;
2346 : : }
2347 : 4 : appendStringInfoChar(&buf, ')');
2348 : :
2349 : 4 : return buf.data;
2350 : : }
2351 : :
2352 : : static char *
2353 : 4 : get_sql_delete(Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
2354 : : {
2355 : : char *relname;
2356 : : TupleDesc tupdesc;
2357 : : StringInfoData buf;
2358 : : int i;
2359 : :
2360 : 4 : initStringInfo(&buf);
2361 : :
2362 : : /* get relation name including any needed schema prefix and quoting */
2363 : 4 : relname = generate_relation_name(rel);
2364 : :
2365 : 4 : tupdesc = rel->rd_att;
2366 : :
2367 : 4 : appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2368 [ + + ]: 11 : for (i = 0; i < pknumatts; i++)
2369 : : {
2370 : 7 : int pkattnum = pkattnums[i];
2371 : 7 : Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2372 : :
2373 [ + + ]: 7 : if (i > 0)
2374 : 3 : appendStringInfoString(&buf, " AND ");
2375 : :
2376 : 7 : appendStringInfoString(&buf,
2377 : 7 : quote_ident_cstr(NameStr(attr->attname)));
2378 : :
2379 [ + - ]: 7 : if (tgt_pkattvals[i] != NULL)
2380 : 7 : appendStringInfo(&buf, " = %s",
2381 : 7 : quote_literal_cstr(tgt_pkattvals[i]));
2382 : : else
2383 : 0 : appendStringInfoString(&buf, " IS NULL");
2384 : : }
2385 : :
2386 : 4 : return buf.data;
2387 : : }
2388 : :
2389 : : static char *
2390 : 4 : get_sql_update(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
2391 : : {
2392 : : char *relname;
2393 : : HeapTuple tuple;
2394 : : TupleDesc tupdesc;
2395 : : int natts;
2396 : : StringInfoData buf;
2397 : : char *val;
2398 : : int key;
2399 : : int i;
2400 : : bool needComma;
2401 : :
2402 : 4 : initStringInfo(&buf);
2403 : :
2404 : : /* get relation name including any needed schema prefix and quoting */
2405 : 4 : relname = generate_relation_name(rel);
2406 : :
2407 : 4 : tupdesc = rel->rd_att;
2408 : 4 : natts = tupdesc->natts;
2409 : :
2410 : 4 : tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2411 [ - + ]: 4 : if (!tuple)
2412 [ # # ]: 0 : ereport(ERROR,
2413 : : (errcode(ERRCODE_CARDINALITY_VIOLATION),
2414 : : errmsg("source row not found")));
2415 : :
2416 : 4 : appendStringInfo(&buf, "UPDATE %s SET ", relname);
2417 : :
2418 : : /*
2419 : : * Note: i is physical column number (counting from 0).
2420 : : */
2421 : 4 : needComma = false;
2422 [ + + ]: 19 : for (i = 0; i < natts; i++)
2423 : : {
2424 : 15 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2425 : :
2426 [ + + ]: 15 : if (attr->attisdropped)
2427 : 2 : continue;
2428 : :
2429 [ + + ]: 13 : if (needComma)
2430 : 9 : appendStringInfoString(&buf, ", ");
2431 : :
2432 : 13 : appendStringInfo(&buf, "%s = ",
2433 : 13 : quote_ident_cstr(NameStr(attr->attname)));
2434 : :
2435 : 13 : key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2436 : :
2437 [ + + ]: 13 : if (key >= 0)
2438 [ + - ]: 7 : val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2439 : : else
2440 : 6 : val = SPI_getvalue(tuple, tupdesc, i + 1);
2441 : :
2442 [ + - ]: 13 : if (val != NULL)
2443 : : {
2444 : 13 : appendStringInfoString(&buf, quote_literal_cstr(val));
2445 : 13 : pfree(val);
2446 : : }
2447 : : else
2448 : 0 : appendStringInfoString(&buf, "NULL");
2449 : 13 : needComma = true;
2450 : : }
2451 : :
2452 : 4 : appendStringInfoString(&buf, " WHERE ");
2453 : :
2454 [ + + ]: 11 : for (i = 0; i < pknumatts; i++)
2455 : : {
2456 : 7 : int pkattnum = pkattnums[i];
2457 : 7 : Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2458 : :
2459 [ + + ]: 7 : if (i > 0)
2460 : 3 : appendStringInfoString(&buf, " AND ");
2461 : :
2462 : 7 : appendStringInfoString(&buf,
2463 : 7 : quote_ident_cstr(NameStr(attr->attname)));
2464 : :
2465 : 7 : val = tgt_pkattvals[i];
2466 : :
2467 [ + - ]: 7 : if (val != NULL)
2468 : 7 : appendStringInfo(&buf, " = %s", quote_literal_cstr(val));
2469 : : else
2470 : 0 : appendStringInfoString(&buf, " IS NULL");
2471 : : }
2472 : :
2473 : 4 : return buf.data;
2474 : : }
2475 : :
2476 : : /*
2477 : : * Return a properly quoted identifier.
2478 : : * Uses quote_ident in quote.c
2479 : : */
2480 : : static char *
2481 : 80 : quote_ident_cstr(char *rawstr)
2482 : : {
2483 : : text *rawstr_text;
2484 : : text *result_text;
2485 : : char *result;
2486 : :
2487 : 80 : rawstr_text = cstring_to_text(rawstr);
2488 : 80 : result_text = DatumGetTextPP(DirectFunctionCall1(quote_ident,
2489 : : PointerGetDatum(rawstr_text)));
2490 : 80 : result = text_to_cstring(result_text);
2491 : :
2492 : 80 : return result;
2493 : : }
2494 : :
2495 : : static int
2496 : 26 : get_attnum_pk_pos(int *pkattnums, int pknumatts, int key)
2497 : : {
2498 : : int i;
2499 : :
2500 : : /*
2501 : : * Not likely a long list anyway, so just scan for the value
2502 : : */
2503 [ + + ]: 50 : for (i = 0; i < pknumatts; i++)
2504 [ + + ]: 38 : if (key == pkattnums[i])
2505 : 14 : return i;
2506 : :
2507 : 12 : return -1;
2508 : : }
2509 : :
2510 : : static HeapTuple
2511 : 8 : get_tuple_of_interest(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
2512 : : {
2513 : : char *relname;
2514 : : TupleDesc tupdesc;
2515 : : int natts;
2516 : : StringInfoData buf;
2517 : : int ret;
2518 : : HeapTuple tuple;
2519 : : int i;
2520 : :
2521 : : /*
2522 : : * Connect to SPI manager
2523 : : */
2524 : 8 : SPI_connect();
2525 : :
2526 : 8 : initStringInfo(&buf);
2527 : :
2528 : : /* get relation name including any needed schema prefix and quoting */
2529 : 8 : relname = generate_relation_name(rel);
2530 : :
2531 : 8 : tupdesc = rel->rd_att;
2532 : 8 : natts = tupdesc->natts;
2533 : :
2534 : : /*
2535 : : * Build sql statement to look up tuple of interest, ie, the one matching
2536 : : * src_pkattvals. We used to use "SELECT *" here, but it's simpler to
2537 : : * generate a result tuple that matches the table's physical structure,
2538 : : * with NULLs for any dropped columns. Otherwise we have to deal with two
2539 : : * different tupdescs and everything's very confusing.
2540 : : */
2541 : 8 : appendStringInfoString(&buf, "SELECT ");
2542 : :
2543 [ + + ]: 38 : for (i = 0; i < natts; i++)
2544 : : {
2545 : 30 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
2546 : :
2547 [ + + ]: 30 : if (i > 0)
2548 : 22 : appendStringInfoString(&buf, ", ");
2549 : :
2550 [ + + ]: 30 : if (attr->attisdropped)
2551 : 4 : appendStringInfoString(&buf, "NULL");
2552 : : else
2553 : 26 : appendStringInfoString(&buf,
2554 : 26 : quote_ident_cstr(NameStr(attr->attname)));
2555 : : }
2556 : :
2557 : 8 : appendStringInfo(&buf, " FROM %s WHERE ", relname);
2558 : :
2559 [ + + ]: 22 : for (i = 0; i < pknumatts; i++)
2560 : : {
2561 : 14 : int pkattnum = pkattnums[i];
2562 : 14 : Form_pg_attribute attr = TupleDescAttr(tupdesc, pkattnum);
2563 : :
2564 [ + + ]: 14 : if (i > 0)
2565 : 6 : appendStringInfoString(&buf, " AND ");
2566 : :
2567 : 14 : appendStringInfoString(&buf,
2568 : 14 : quote_ident_cstr(NameStr(attr->attname)));
2569 : :
2570 [ + - ]: 14 : if (src_pkattvals[i] != NULL)
2571 : 14 : appendStringInfo(&buf, " = %s",
2572 : 14 : quote_literal_cstr(src_pkattvals[i]));
2573 : : else
2574 : 0 : appendStringInfoString(&buf, " IS NULL");
2575 : : }
2576 : :
2577 : : /*
2578 : : * Retrieve the desired tuple
2579 : : */
2580 : 8 : ret = SPI_exec(buf.data, 0);
2581 : 8 : pfree(buf.data);
2582 : :
2583 : : /*
2584 : : * Only allow one qualifying tuple
2585 : : */
2586 [ + - - + ]: 8 : if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
2587 [ # # ]: 0 : ereport(ERROR,
2588 : : (errcode(ERRCODE_CARDINALITY_VIOLATION),
2589 : : errmsg("source criteria matched more than one record")));
2590 : :
2591 [ + - + - ]: 8 : else if (ret == SPI_OK_SELECT && SPI_processed == 1)
2592 : : {
2593 : 8 : SPITupleTable *tuptable = SPI_tuptable;
2594 : :
2595 : 8 : tuple = SPI_copytuple(tuptable->vals[0]);
2596 : 8 : SPI_finish();
2597 : :
2598 : 8 : return tuple;
2599 : : }
2600 : : else
2601 : : {
2602 : : /*
2603 : : * no qualifying tuples
2604 : : */
2605 : 0 : SPI_finish();
2606 : :
2607 : 0 : return NULL;
2608 : : }
2609 : :
2610 : : /*
2611 : : * never reached, but keep compiler quiet
2612 : : */
2613 : : return NULL;
2614 : : }
2615 : :
2616 : : static void
2617 : 21 : RangeVarCallbackForDblink(const RangeVar *relation,
2618 : : Oid relId, Oid oldRelId, void *arg)
2619 : : {
2620 : : AclResult aclresult;
2621 : :
2622 [ - + ]: 21 : if (!OidIsValid(relId))
2623 : 0 : return;
2624 : :
2625 : 21 : aclresult = pg_class_aclcheck(relId, GetUserId(), *((AclMode *) arg));
2626 [ - + ]: 21 : if (aclresult != ACLCHECK_OK)
2627 : 0 : aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(relId)),
2628 : 0 : relation->relname);
2629 : : }
2630 : :
2631 : : /*
2632 : : * Open the relation named by relname_text, acquire specified type of lock,
2633 : : * verify we have specified permissions.
2634 : : * Caller must close rel when done with it.
2635 : : */
2636 : : static Relation
2637 : 21 : get_rel_from_relname(text *relname_text, LOCKMODE lockmode, AclMode aclmode)
2638 : : {
2639 : : RangeVar *relvar;
2640 : : Oid relid;
2641 : :
2642 : 21 : relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2643 : 21 : relid = RangeVarGetRelidExtended(relvar, lockmode, 0,
2644 : : RangeVarCallbackForDblink, &aclmode);
2645 : :
2646 : 21 : return table_open(relid, NoLock);
2647 : : }
2648 : :
2649 : : /*
2650 : : * generate_relation_name - copied from ruleutils.c
2651 : : * Compute the name to display for a relation
2652 : : *
2653 : : * The result includes all necessary quoting and schema-prefixing.
2654 : : */
2655 : : static char *
2656 : 20 : generate_relation_name(Relation rel)
2657 : : {
2658 : : char *nspname;
2659 : : char *result;
2660 : :
2661 : : /* Qualify the name if not visible in search path */
2662 [ + + ]: 20 : if (RelationIsVisible(RelationGetRelid(rel)))
2663 : 15 : nspname = NULL;
2664 : : else
2665 : 5 : nspname = get_namespace_name(rel->rd_rel->relnamespace);
2666 : :
2667 : 20 : result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2668 : :
2669 : 20 : return result;
2670 : : }
2671 : :
2672 : :
2673 : : static remoteConn *
2674 : 106 : getConnectionByName(const char *name)
2675 : : {
2676 : : remoteConnHashEnt *hentry;
2677 : : char *key;
2678 : :
2679 [ + + ]: 106 : if (!remoteConnHash)
2680 : 7 : remoteConnHash = createConnHash();
2681 : :
2682 : 106 : key = pstrdup(name);
2683 : 106 : truncate_identifier(key, strlen(key), false);
2684 : 106 : hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
2685 : : key, HASH_FIND, NULL);
2686 : :
2687 [ + + + - ]: 106 : if (hentry && hentry->rconn.conn != NULL)
2688 : 92 : return &hentry->rconn;
2689 : :
2690 : 14 : return NULL;
2691 : : }
2692 : :
2693 : : static HTAB *
2694 : 8 : createConnHash(void)
2695 : : {
2696 : : HASHCTL ctl;
2697 : :
2698 : 8 : ctl.keysize = NAMEDATALEN;
2699 : 8 : ctl.entrysize = sizeof(remoteConnHashEnt);
2700 : :
2701 : 8 : return hash_create("Remote Con hash", NUMCONN, &ctl,
2702 : : HASH_ELEM | HASH_STRINGS);
2703 : : }
2704 : :
2705 : : static remoteConn *
2706 : 13 : createNewConnection(const char *name)
2707 : : {
2708 : : remoteConnHashEnt *hentry;
2709 : : bool found;
2710 : : char *key;
2711 : :
2712 [ + + ]: 13 : if (!remoteConnHash)
2713 : 1 : remoteConnHash = createConnHash();
2714 : :
2715 : 13 : key = pstrdup(name);
2716 : 13 : truncate_identifier(key, strlen(key), true);
2717 : 13 : hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2718 : : HASH_ENTER, &found);
2719 : :
2720 [ + + + - ]: 13 : if (found && hentry->rconn.conn != NULL)
2721 [ + - ]: 1 : ereport(ERROR,
2722 : : (errcode(ERRCODE_DUPLICATE_OBJECT),
2723 : : errmsg("duplicate connection name")));
2724 : :
2725 : : /* New, or reusable, so initialize the rconn struct to zeroes */
2726 : 12 : memset(&hentry->rconn, 0, sizeof(remoteConn));
2727 : :
2728 : 12 : return &hentry->rconn;
2729 : : }
2730 : :
2731 : : static void
2732 : 10 : deleteConnection(const char *name)
2733 : : {
2734 : : remoteConnHashEnt *hentry;
2735 : : bool found;
2736 : : char *key;
2737 : :
2738 [ - + ]: 10 : if (!remoteConnHash)
2739 : 0 : remoteConnHash = createConnHash();
2740 : :
2741 : 10 : key = pstrdup(name);
2742 : 10 : truncate_identifier(key, strlen(key), false);
2743 : 10 : hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
2744 : : key, HASH_REMOVE, &found);
2745 : :
2746 [ - + ]: 10 : if (!hentry)
2747 [ # # ]: 0 : ereport(ERROR,
2748 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
2749 : : errmsg("undefined connection name")));
2750 : 10 : }
2751 : :
2752 : : /*
2753 : : * Ensure that require_auth and SCRAM keys are correctly set on connstr.
2754 : : * SCRAM keys used to pass-through are coming from the initial connection
2755 : : * from the client with the server.
2756 : : *
2757 : : * All required SCRAM options are set by dblink, so we just need to ensure
2758 : : * that these options are not overwritten by the user.
2759 : : *
2760 : : * See appendSCRAMKeysInfo and its usage for more.
2761 : : */
2762 : : bool
2763 : 7 : dblink_connstr_has_required_scram_options(const char *connstr)
2764 : : {
2765 : : PQconninfoOption *options;
2766 : 7 : bool has_scram_server_key = false;
2767 : 7 : bool has_scram_client_key = false;
2768 : 7 : bool has_require_auth = false;
2769 : 7 : bool has_scram_keys = false;
2770 : :
2771 : 7 : options = PQconninfoParse(connstr, NULL);
2772 [ + - ]: 7 : if (options)
2773 : : {
2774 : : /*
2775 : : * Continue iterating even if we found the keys that we need to
2776 : : * validate to make sure that there is no other declaration of these
2777 : : * keys that can overwrite the first.
2778 : : */
2779 [ + + ]: 364 : for (PQconninfoOption *option = options; option->keyword != NULL; option++)
2780 : : {
2781 [ + + ]: 357 : if (strcmp(option->keyword, "require_auth") == 0)
2782 : : {
2783 [ + + + + ]: 7 : if (option->val != NULL && strcmp(option->val, "scram-sha-256") == 0)
2784 : 5 : has_require_auth = true;
2785 : : else
2786 : 2 : has_require_auth = false;
2787 : : }
2788 : :
2789 [ + + ]: 357 : if (strcmp(option->keyword, "scram_client_key") == 0)
2790 : : {
2791 [ + + + - ]: 7 : if (option->val != NULL && option->val[0] != '\0')
2792 : 6 : has_scram_client_key = true;
2793 : : else
2794 : 1 : has_scram_client_key = false;
2795 : : }
2796 : :
2797 [ + + ]: 357 : if (strcmp(option->keyword, "scram_server_key") == 0)
2798 : : {
2799 [ + + + - ]: 7 : if (option->val != NULL && option->val[0] != '\0')
2800 : 6 : has_scram_server_key = true;
2801 : : else
2802 : 1 : has_scram_server_key = false;
2803 : : }
2804 : : }
2805 : 7 : PQconninfoFree(options);
2806 : : }
2807 : :
2808 [ + + + - : 7 : has_scram_keys = has_scram_client_key && has_scram_server_key && MyProcPort != NULL && MyProcPort->has_scram_keys;
+ - + - ]
2809 : :
2810 [ + + + + ]: 7 : return (has_scram_keys && has_require_auth);
2811 : : }
2812 : :
2813 : : /*
2814 : : * We need to make sure that the connection made used credentials
2815 : : * which were provided by the user, so check what credentials were
2816 : : * used to connect and then make sure that they came from the user.
2817 : : *
2818 : : * On failure, we close "conn" and also delete the hashtable entry
2819 : : * identified by "connname" (if that's not NULL).
2820 : : */
2821 : : static void
2822 : 23 : dblink_security_check(PGconn *conn, const char *connname, const char *connstr)
2823 : : {
2824 : : /* Superuser bypasses security check */
2825 [ + + ]: 23 : if (superuser())
2826 : 21 : return;
2827 : :
2828 : : /* If password was used to connect, make sure it was one provided */
2829 [ + - - + ]: 2 : if (PQconnectionUsedPassword(conn) && dblink_connstr_has_pw(connstr))
2830 : 0 : return;
2831 : :
2832 : : /*
2833 : : * Password was not used to connect, check if SCRAM pass-through is in
2834 : : * use.
2835 : : *
2836 : : * If dblink_connstr_has_required_scram_options is true we assume that
2837 : : * UseScramPassthrough is also true because the required SCRAM keys are
2838 : : * only added if UseScramPassthrough is set, and the user is not allowed
2839 : : * to add the SCRAM keys on fdw and user mapping options.
2840 : : */
2841 [ + - + - : 2 : if (MyProcPort != NULL && MyProcPort->has_scram_keys && dblink_connstr_has_required_scram_options(connstr))
+ - ]
2842 : 2 : return;
2843 : :
2844 : : #ifdef ENABLE_GSS
2845 : : /* If GSSAPI creds used to connect, make sure it was one delegated */
2846 : : if (PQconnectionUsedGSSAPI(conn) && be_gssapi_get_delegation(MyProcPort))
2847 : : return;
2848 : : #endif
2849 : :
2850 : : /* Otherwise, fail out */
2851 : 0 : libpqsrv_disconnect(conn);
2852 [ # # ]: 0 : if (connname)
2853 : 0 : deleteConnection(connname);
2854 : :
2855 [ # # ]: 0 : ereport(ERROR,
2856 : : (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2857 : : errmsg("password or GSSAPI delegated credentials required"),
2858 : : errdetail("Non-superusers may only connect using credentials they provide, eg: password in connection string or delegated GSSAPI credentials."),
2859 : : errhint("Ensure provided credentials match target server's authentication method.")));
2860 : : }
2861 : :
2862 : : /*
2863 : : * Function to check if the connection string includes an explicit
2864 : : * password, needed to ensure that non-superuser password-based auth
2865 : : * is using a provided password and not one picked up from the
2866 : : * environment.
2867 : : */
2868 : : static bool
2869 : 8 : dblink_connstr_has_pw(const char *connstr)
2870 : : {
2871 : : PQconninfoOption *options;
2872 : : PQconninfoOption *option;
2873 : 8 : bool connstr_gives_password = false;
2874 : :
2875 : 8 : options = PQconninfoParse(connstr, NULL);
2876 [ + - ]: 8 : if (options)
2877 : : {
2878 [ + + ]: 416 : for (option = options; option->keyword != NULL; option++)
2879 : : {
2880 [ + + ]: 408 : if (strcmp(option->keyword, "password") == 0)
2881 : : {
2882 [ - + - - ]: 8 : if (option->val != NULL && option->val[0] != '\0')
2883 : : {
2884 : 0 : connstr_gives_password = true;
2885 : 0 : break;
2886 : : }
2887 : : }
2888 : : }
2889 : 8 : PQconninfoFree(options);
2890 : : }
2891 : :
2892 : 8 : return connstr_gives_password;
2893 : : }
2894 : :
2895 : : /*
2896 : : * For non-superusers, insist that the connstr specify a password, except if
2897 : : * GSSAPI credentials have been delegated (and we check that they are used for
2898 : : * the connection in dblink_security_check later) or if SCRAM pass-through is
2899 : : * being used. This prevents a password or GSSAPI credentials from being
2900 : : * picked up from .pgpass, a service file, the environment, etc. We don't want
2901 : : * the postgres user's passwords or Kerberos credentials to be accessible to
2902 : : * non-superusers. In case of SCRAM pass-through insist that the connstr
2903 : : * has the required SCRAM pass-through options.
2904 : : */
2905 : : static void
2906 : 36 : dblink_connstr_check(const char *connstr)
2907 : : {
2908 [ + + ]: 36 : if (superuser())
2909 : 30 : return;
2910 : :
2911 [ - + ]: 6 : if (dblink_connstr_has_pw(connstr))
2912 : 0 : return;
2913 : :
2914 [ + - + + : 6 : if (MyProcPort != NULL && MyProcPort->has_scram_keys && dblink_connstr_has_required_scram_options(connstr))
+ + ]
2915 : 3 : return;
2916 : :
2917 : : #ifdef ENABLE_GSS
2918 : : if (be_gssapi_get_delegation(MyProcPort))
2919 : : return;
2920 : : #endif
2921 : :
2922 [ + - ]: 3 : ereport(ERROR,
2923 : : (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2924 : : errmsg("password or GSSAPI delegated credentials required"),
2925 : : errdetail("Non-superusers must provide a password in the connection string or send delegated GSSAPI credentials.")));
2926 : : }
2927 : :
2928 : : /*
2929 : : * Report an error received from the remote server
2930 : : *
2931 : : * res: the received error result
2932 : : * fail: true for ERROR ereport, false for NOTICE
2933 : : * fmt and following args: sprintf-style format and values for errcontext;
2934 : : * the resulting string should be worded like "while <some action>"
2935 : : *
2936 : : * If "res" is not NULL, it'll be PQclear'ed here (unless we throw error,
2937 : : * in which case memory context cleanup will clear it eventually).
2938 : : */
2939 : : static void
2940 : 12 : dblink_res_error(PGconn *conn, const char *conname, PGresult *res,
2941 : : bool fail, const char *fmt, ...)
2942 : : {
2943 : : int level;
2944 : 12 : char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2945 : 12 : char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2946 : 12 : char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2947 : 12 : char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2948 : 12 : char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2949 : : int sqlstate;
2950 : : va_list ap;
2951 : : char dblink_context_msg[512];
2952 : :
2953 [ + + ]: 12 : if (fail)
2954 : 3 : level = ERROR;
2955 : : else
2956 : 9 : level = NOTICE;
2957 : :
2958 [ + - ]: 12 : if (pg_diag_sqlstate)
2959 : 12 : sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2960 : : pg_diag_sqlstate[1],
2961 : : pg_diag_sqlstate[2],
2962 : : pg_diag_sqlstate[3],
2963 : : pg_diag_sqlstate[4]);
2964 : : else
2965 : 0 : sqlstate = ERRCODE_CONNECTION_FAILURE;
2966 : :
2967 : : /*
2968 : : * If we don't get a message from the PGresult, try the PGconn. This is
2969 : : * needed because for connection-level failures, PQgetResult may just
2970 : : * return NULL, not a PGresult at all.
2971 : : */
2972 [ - + ]: 12 : if (message_primary == NULL)
2973 : 0 : message_primary = pchomp(PQerrorMessage(conn));
2974 : :
2975 : : /*
2976 : : * Format the basic errcontext string. Below, we'll add on something
2977 : : * about the connection name. That's a violation of the translatability
2978 : : * guidelines about constructing error messages out of parts, but since
2979 : : * there's no translation support for dblink, there's no need to worry
2980 : : * about that (yet).
2981 : : */
2982 : 12 : va_start(ap, fmt);
2983 : 12 : vsnprintf(dblink_context_msg, sizeof(dblink_context_msg), fmt, ap);
2984 : 12 : va_end(ap);
2985 : :
2986 [ + - + - : 12 : ereport(level,
+ - - + -
+ - + +
+ ]
2987 : : (errcode(sqlstate),
2988 : : (message_primary != NULL && message_primary[0] != '\0') ?
2989 : : errmsg_internal("%s", message_primary) :
2990 : : errmsg("could not obtain message string for remote error"),
2991 : : message_detail ? errdetail_internal("%s", message_detail) : 0,
2992 : : message_hint ? errhint("%s", message_hint) : 0,
2993 : : message_context ? (errcontext("%s", message_context)) : 0,
2994 : : conname ?
2995 : : (errcontext("%s on dblink connection named \"%s\"",
2996 : : dblink_context_msg, conname)) :
2997 : : (errcontext("%s on unnamed dblink connection",
2998 : : dblink_context_msg))));
2999 : 9 : PQclear(res);
3000 : 9 : }
3001 : :
3002 : : /*
3003 : : * Obtain connection string for a foreign server
3004 : : */
3005 : : static char *
3006 : 36 : get_connect_string(const char *servername)
3007 : : {
3008 : 36 : ForeignServer *foreign_server = NULL;
3009 : : UserMapping *user_mapping;
3010 : : ListCell *cell;
3011 : : StringInfoData buf;
3012 : : ForeignDataWrapper *fdw;
3013 : : AclResult aclresult;
3014 : : char *srvname;
3015 : :
3016 : : static const PQconninfoOption *options = NULL;
3017 : :
3018 : 36 : initStringInfo(&buf);
3019 : :
3020 : : /*
3021 : : * Get list of valid libpq options.
3022 : : *
3023 : : * To avoid unnecessary work, we get the list once and use it throughout
3024 : : * the lifetime of this backend process. We don't need to care about
3025 : : * memory context issues, because PQconndefaults allocates with malloc.
3026 : : */
3027 [ + + ]: 36 : if (!options)
3028 : : {
3029 : 8 : options = PQconndefaults();
3030 [ - + ]: 8 : if (!options) /* assume reason for failure is OOM */
3031 [ # # ]: 0 : ereport(ERROR,
3032 : : (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
3033 : : errmsg("out of memory"),
3034 : : errdetail("Could not get libpq's default connection options.")));
3035 : : }
3036 : :
3037 : : /* first gather the server connstr options */
3038 : 36 : srvname = pstrdup(servername);
3039 : 36 : truncate_identifier(srvname, strlen(srvname), false);
3040 : 36 : foreign_server = GetForeignServerByName(srvname, true);
3041 : :
3042 [ + + ]: 36 : if (foreign_server)
3043 : : {
3044 : 7 : Oid serverid = foreign_server->serverid;
3045 : 7 : Oid fdwid = foreign_server->fdwid;
3046 : 7 : Oid userid = GetUserId();
3047 : :
3048 : 7 : user_mapping = GetUserMapping(userid, serverid);
3049 : 7 : fdw = GetForeignDataWrapper(fdwid);
3050 : :
3051 : : /* Check permissions, user must have usage on the server. */
3052 : 7 : aclresult = object_aclcheck(ForeignServerRelationId, serverid, userid, ACL_USAGE);
3053 [ - + ]: 7 : if (aclresult != ACLCHECK_OK)
3054 : 0 : aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, foreign_server->servername);
3055 : :
3056 : : /*
3057 : : * First append hardcoded options needed for SCRAM pass-through, so if
3058 : : * the user overwrites these options we can ereport on
3059 : : * dblink_connstr_check and dblink_security_check.
3060 : : */
3061 [ + - + + : 7 : if (MyProcPort != NULL && MyProcPort->has_scram_keys && UseScramPassthrough(foreign_server, user_mapping))
+ + ]
3062 : 4 : appendSCRAMKeysInfo(&buf);
3063 : :
3064 [ - + - - : 7 : foreach(cell, fdw->options)
- + ]
3065 : : {
3066 : 0 : DefElem *def = lfirst(cell);
3067 : :
3068 [ # # ]: 0 : if (is_valid_dblink_option(options, def->defname, ForeignDataWrapperRelationId))
3069 : 0 : appendStringInfo(&buf, "%s='%s' ", def->defname,
3070 : 0 : escape_param_str(strVal(def->arg)));
3071 : : }
3072 : :
3073 [ + - + + : 32 : foreach(cell, foreign_server->options)
+ + ]
3074 : : {
3075 : 25 : DefElem *def = lfirst(cell);
3076 : :
3077 [ + + ]: 25 : if (is_valid_dblink_option(options, def->defname, ForeignServerRelationId))
3078 : 20 : appendStringInfo(&buf, "%s='%s' ", def->defname,
3079 : 20 : escape_param_str(strVal(def->arg)));
3080 : : }
3081 : :
3082 [ + - + + : 15 : foreach(cell, user_mapping->options)
+ + ]
3083 : : {
3084 : :
3085 : 8 : DefElem *def = lfirst(cell);
3086 : :
3087 [ + + ]: 8 : if (is_valid_dblink_option(options, def->defname, UserMappingRelationId))
3088 : 7 : appendStringInfo(&buf, "%s='%s' ", def->defname,
3089 : 7 : escape_param_str(strVal(def->arg)));
3090 : : }
3091 : :
3092 : 7 : return buf.data;
3093 : : }
3094 : : else
3095 : 29 : return NULL;
3096 : : }
3097 : :
3098 : : /*
3099 : : * Escaping libpq connect parameter strings.
3100 : : *
3101 : : * Replaces "'" with "\'" and "\" with "\\".
3102 : : */
3103 : : static char *
3104 : 27 : escape_param_str(const char *str)
3105 : : {
3106 : : const char *cp;
3107 : : StringInfoData buf;
3108 : :
3109 : 27 : initStringInfo(&buf);
3110 : :
3111 [ + + ]: 238 : for (cp = str; *cp; cp++)
3112 : : {
3113 [ + - - + ]: 211 : if (*cp == '\\' || *cp == '\'')
3114 : 0 : appendStringInfoChar(&buf, '\\');
3115 : 211 : appendStringInfoChar(&buf, *cp);
3116 : : }
3117 : :
3118 : 27 : return buf.data;
3119 : : }
3120 : :
3121 : : /*
3122 : : * Validate the PK-attnums argument for dblink_build_sql_insert() and related
3123 : : * functions, and translate to the internal representation.
3124 : : *
3125 : : * The user supplies an int2vector of 1-based logical attnums, plus a count
3126 : : * argument (the need for the separate count argument is historical, but we
3127 : : * still check it). We check that each attnum corresponds to a valid,
3128 : : * non-dropped attribute of the rel. We do *not* prevent attnums from being
3129 : : * listed twice, though the actual use-case for such things is dubious.
3130 : : * Note that before Postgres 9.0, the user's attnums were interpreted as
3131 : : * physical not logical column numbers; this was changed for future-proofing.
3132 : : *
3133 : : * The internal representation is a palloc'd int array of 0-based physical
3134 : : * attnums.
3135 : : */
3136 : : static void
3137 : 18 : validate_pkattnums(Relation rel,
3138 : : int2vector *pkattnums_arg, int32 pknumatts_arg,
3139 : : int **pkattnums, int *pknumatts)
3140 : : {
3141 : 18 : TupleDesc tupdesc = rel->rd_att;
3142 : 18 : int natts = tupdesc->natts;
3143 : : int i;
3144 : :
3145 : : /* Don't take more array elements than there are */
3146 : 18 : pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
3147 : :
3148 : : /* Must have at least one pk attnum selected */
3149 [ - + ]: 18 : if (pknumatts_arg <= 0)
3150 [ # # ]: 0 : ereport(ERROR,
3151 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3152 : : errmsg("number of key attributes must be > 0")));
3153 : :
3154 : : /* Allocate output array */
3155 : 18 : *pkattnums = palloc_array(int, pknumatts_arg);
3156 : 18 : *pknumatts = pknumatts_arg;
3157 : :
3158 : : /* Validate attnums and convert to internal form */
3159 [ + + ]: 57 : for (i = 0; i < pknumatts_arg; i++)
3160 : : {
3161 : 45 : int pkattnum = pkattnums_arg->values[i];
3162 : : int lnum;
3163 : : int j;
3164 : :
3165 : : /* Can throw error immediately if out of range */
3166 [ + - + + ]: 45 : if (pkattnum <= 0 || pkattnum > natts)
3167 [ + - ]: 6 : ereport(ERROR,
3168 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3169 : : errmsg("invalid attribute number %d", pkattnum)));
3170 : :
3171 : : /* Identify which physical column has this logical number */
3172 : 39 : lnum = 0;
3173 [ + - ]: 69 : for (j = 0; j < natts; j++)
3174 : : {
3175 : : /* dropped columns don't count */
3176 [ + + ]: 69 : if (TupleDescCompactAttr(tupdesc, j)->attisdropped)
3177 : 3 : continue;
3178 : :
3179 [ + + ]: 66 : if (++lnum == pkattnum)
3180 : 39 : break;
3181 : : }
3182 : :
3183 [ + - ]: 39 : if (j < natts)
3184 : 39 : (*pkattnums)[i] = j;
3185 : : else
3186 [ # # ]: 0 : ereport(ERROR,
3187 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3188 : : errmsg("invalid attribute number %d", pkattnum)));
3189 : : }
3190 : 12 : }
3191 : :
3192 : : /*
3193 : : * Check if the specified connection option is valid.
3194 : : *
3195 : : * We basically allow whatever libpq thinks is an option, with these
3196 : : * restrictions:
3197 : : * debug options: disallowed
3198 : : * "client_encoding": disallowed
3199 : : * "user": valid only in USER MAPPING options
3200 : : * secure options (eg password): valid only in USER MAPPING options
3201 : : * others: valid only in FOREIGN SERVER options
3202 : : *
3203 : : * We disallow client_encoding because it would be overridden anyway via
3204 : : * PQclientEncoding; allowing it to be specified would merely promote
3205 : : * confusion.
3206 : : */
3207 : : static bool
3208 : 640 : is_valid_dblink_option(const PQconninfoOption *options, const char *option,
3209 : : Oid context)
3210 : : {
3211 : : const PQconninfoOption *opt;
3212 : :
3213 : : /* Look up the option in libpq result */
3214 [ + + ]: 15883 : for (opt = options; opt->keyword; opt++)
3215 : : {
3216 [ + + ]: 15874 : if (strcmp(opt->keyword, option) == 0)
3217 : 631 : break;
3218 : : }
3219 [ + + ]: 640 : if (opt->keyword == NULL)
3220 : 9 : return false;
3221 : :
3222 : : /* Disallow debug options (particularly "replication") */
3223 [ + + ]: 631 : if (strchr(opt->dispchar, 'D'))
3224 : 48 : return false;
3225 : :
3226 : : /* Disallow "client_encoding" */
3227 [ + + ]: 583 : if (strcmp(opt->keyword, "client_encoding") == 0)
3228 : 11 : return false;
3229 : :
3230 : : /*
3231 : : * Disallow OAuth options for now, since the builtin flow communicates on
3232 : : * stderr by default and can't cache tokens yet.
3233 : : */
3234 [ + + ]: 572 : if (strncmp(opt->keyword, "oauth_", strlen("oauth_")) == 0)
3235 : 59 : return false;
3236 : :
3237 : : /*
3238 : : * If the option is "user" or marked secure, it should be specified only
3239 : : * in USER MAPPING. Others should be specified only in SERVER.
3240 : : */
3241 [ + + + + ]: 513 : if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
3242 : : {
3243 [ + + ]: 51 : if (context != UserMappingRelationId)
3244 : 15 : return false;
3245 : : }
3246 : : else
3247 : : {
3248 [ + + ]: 462 : if (context != ForeignServerRelationId)
3249 : 304 : return false;
3250 : : }
3251 : :
3252 : 194 : return true;
3253 : : }
3254 : :
3255 : : /*
3256 : : * Same as is_valid_dblink_option but also check for only dblink_fdw specific
3257 : : * options.
3258 : : */
3259 : : static bool
3260 : 52 : is_valid_dblink_fdw_option(const PQconninfoOption *options, const char *option,
3261 : : Oid context)
3262 : : {
3263 : : /*
3264 : : * These options are only valid for foreign server or user mapping
3265 : : * contexts
3266 : : */
3267 [ + + + + ]: 52 : if (context == ForeignServerRelationId || context == UserMappingRelationId)
3268 : : {
3269 [ + + ]: 50 : if (strcmp(option, "use_scram_passthrough") == 0)
3270 : 6 : return true;
3271 : : }
3272 : :
3273 : 46 : return is_valid_dblink_option(options, option, context);
3274 : : }
3275 : :
3276 : : /*
3277 : : * Copy the remote session's values of GUCs that affect datatype I/O
3278 : : * and apply them locally in a new GUC nesting level. Returns the new
3279 : : * nestlevel (which is needed by restoreLocalGucs to undo the settings),
3280 : : * or -1 if no new nestlevel was needed.
3281 : : *
3282 : : * We use the equivalent of a function SET option to allow the settings to
3283 : : * persist only until the caller calls restoreLocalGucs. If an error is
3284 : : * thrown in between, guc.c will take care of undoing the settings.
3285 : : */
3286 : : static int
3287 : 48 : applyRemoteGucs(PGconn *conn)
3288 : : {
3289 : : static const char *const GUCsAffectingIO[] = {
3290 : : "DateStyle",
3291 : : "IntervalStyle"
3292 : : };
3293 : :
3294 : 48 : int nestlevel = -1;
3295 : :
3296 [ + + ]: 144 : for (size_t i = 0; i < lengthof(GUCsAffectingIO); i++)
3297 : : {
3298 : 96 : const char *gucName = GUCsAffectingIO[i];
3299 : 96 : const char *remoteVal = PQparameterStatus(conn, gucName);
3300 : : const char *localVal;
3301 : :
3302 : : /*
3303 : : * If the remote server is pre-8.4, it won't have IntervalStyle, but
3304 : : * that's okay because its output format won't be ambiguous. So just
3305 : : * skip the GUC if we don't get a value for it. (We might eventually
3306 : : * need more complicated logic with remote-version checks here.)
3307 : : */
3308 [ - + ]: 96 : if (remoteVal == NULL)
3309 : 0 : continue;
3310 : :
3311 : : /*
3312 : : * Avoid GUC-setting overhead if the remote and local GUCs already
3313 : : * have the same value.
3314 : : */
3315 : 96 : localVal = GetConfigOption(gucName, false, false);
3316 : : Assert(localVal != NULL);
3317 : :
3318 [ + + ]: 96 : if (strcmp(remoteVal, localVal) == 0)
3319 : 79 : continue;
3320 : :
3321 : : /* Create new GUC nest level if we didn't already */
3322 [ + + ]: 17 : if (nestlevel < 0)
3323 : 9 : nestlevel = NewGUCNestLevel();
3324 : :
3325 : : /* Apply the option (this will throw error on failure) */
3326 : 17 : (void) set_config_option(gucName, remoteVal,
3327 : : PGC_USERSET, PGC_S_SESSION,
3328 : : GUC_ACTION_SAVE, true, 0, false);
3329 : : }
3330 : :
3331 : 48 : return nestlevel;
3332 : : }
3333 : :
3334 : : /*
3335 : : * Restore local GUCs after they have been overlaid with remote settings.
3336 : : */
3337 : : static void
3338 : 40 : restoreLocalGucs(int nestlevel)
3339 : : {
3340 : : /* Do nothing if no new nestlevel was created */
3341 [ + + ]: 40 : if (nestlevel > 0)
3342 : 8 : AtEOXact_GUC(true, nestlevel);
3343 : 40 : }
3344 : :
3345 : : /*
3346 : : * Append SCRAM client key and server key information from the global
3347 : : * MyProcPort into the given StringInfo buffer.
3348 : : */
3349 : : static void
3350 : 4 : appendSCRAMKeysInfo(StringInfo buf)
3351 : : {
3352 : : int len;
3353 : : int encoded_len;
3354 : : char *client_key;
3355 : : char *server_key;
3356 : :
3357 : 4 : len = pg_b64_enc_len(sizeof(MyProcPort->scram_ClientKey));
3358 : : /* don't forget the zero-terminator */
3359 : 4 : client_key = palloc0(len + 1);
3360 : 4 : encoded_len = pg_b64_encode(MyProcPort->scram_ClientKey,
3361 : : sizeof(MyProcPort->scram_ClientKey),
3362 : : client_key, len);
3363 [ - + ]: 4 : if (encoded_len < 0)
3364 [ # # ]: 0 : elog(ERROR, "could not encode SCRAM client key");
3365 : :
3366 : 4 : len = pg_b64_enc_len(sizeof(MyProcPort->scram_ServerKey));
3367 : : /* don't forget the zero-terminator */
3368 : 4 : server_key = palloc0(len + 1);
3369 : 4 : encoded_len = pg_b64_encode(MyProcPort->scram_ServerKey,
3370 : : sizeof(MyProcPort->scram_ServerKey),
3371 : : server_key, len);
3372 [ - + ]: 4 : if (encoded_len < 0)
3373 [ # # ]: 0 : elog(ERROR, "could not encode SCRAM server key");
3374 : :
3375 : 4 : appendStringInfo(buf, "scram_client_key='%s' ", client_key);
3376 : 4 : appendStringInfo(buf, "scram_server_key='%s' ", server_key);
3377 : 4 : appendStringInfoString(buf, "require_auth='scram-sha-256' ");
3378 : :
3379 : 4 : pfree(client_key);
3380 : 4 : pfree(server_key);
3381 : 4 : }
3382 : :
3383 : :
3384 : : /*
3385 : : * Return whether SCRAM pass-through is enabled.
3386 : : *
3387 : : * If use_scram_passthrough is specified in both the foreign server
3388 : : * and the user mapping, the user mapping setting takes precedence.
3389 : : */
3390 : : static bool
3391 : 5 : UseScramPassthrough(ForeignServer *foreign_server, UserMapping *user)
3392 : : {
3393 : : ListCell *cell;
3394 : :
3395 [ + - + + : 10 : foreach(cell, user->options)
+ + ]
3396 : : {
3397 : 6 : DefElem *def = lfirst(cell);
3398 : :
3399 [ + + ]: 6 : if (strcmp(def->defname, "use_scram_passthrough") == 0)
3400 : 1 : return defGetBoolean(def);
3401 : : }
3402 : :
3403 [ + - + - : 16 : foreach(cell, foreign_server->options)
+ - ]
3404 : : {
3405 : 16 : DefElem *def = (DefElem *) lfirst(cell);
3406 : :
3407 [ + + ]: 16 : if (strcmp(def->defname, "use_scram_passthrough") == 0)
3408 : 4 : return defGetBoolean(def);
3409 : : }
3410 : :
3411 : 0 : return false;
3412 : : }
|