Debian Codegraph @

contrib/dblink/dblink.c

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