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