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