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