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