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 = NULL;
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  else
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 = NULL;
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  else
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  dblink_get_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)), &conn, &conname, &freeconn);
692  fail = PG_GETARG_BOOL(2);
693  }
694  else if (PG_NARGS() == 2)
695  {
696  /* text,text or text,bool */
697  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
698  {
699  conn = pconn->conn;
701  fail = PG_GETARG_BOOL(1);
702  }
703  else
704  {
705  dblink_get_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)), &conn, &conname, &freeconn);
707  }
708  }
709  else if (PG_NARGS() == 1)
710  {
711  /* text */
712  conn = pconn->conn;
714  }
715  else
716  /* shouldn't happen */
717  elog(ERROR, "wrong number of arguments");
718  }
719  else /* is_async */
720  {
721  /* get async result */
722  if (PG_NARGS() == 2)
723  {
724  /* text,bool */
726  fail = PG_GETARG_BOOL(1);
727  }
728  else if (PG_NARGS() == 1)
729  {
730  /* text */
732  }
733  else
734  /* shouldn't happen */
735  elog(ERROR, "wrong number of arguments");
736  }
737 
738  if (!conn)
739  dblink_conn_not_avail(conname);
740 
741  if (!is_async)
742  {
743  /* synchronous query, use efficient tuple collection method */
744  materializeQueryResult(fcinfo, conn, conname, sql, fail);
745  }
746  else
747  {
748  /* async result retrieval, do it the old way */
749  PGresult *res = PQgetResult(conn);
750 
751  /* NULL means we're all done with the async results */
752  if (res)
753  {
754  if (PQresultStatus(res) != PGRES_COMMAND_OK &&
756  {
757  dblink_res_error(conn, conname, res,
758  "could not execute query", fail);
759  /* if fail isn't set, we'll return an empty query result */
760  }
761  else
762  {
763  materializeResult(fcinfo, conn, res);
764  }
765  }
766  }
767  }
768  PG_CATCH();
769  {
770  /* if needed, close the connection to the database */
771  if (freeconn)
772  PQfinish(conn);
773  PG_RE_THROW();
774  }
775  PG_END_TRY();
776 
777  /* if needed, close the connection to the database */
778  if (freeconn)
779  PQfinish(conn);
780 
781  return (Datum) 0;
782 }
783 
784 /*
785  * Verify function caller can handle a tuplestore result, and set up for that.
786  *
787  * Note: if the caller returns without actually creating a tuplestore, the
788  * executor will treat the function result as an empty set.
789  */
790 static void
792 {
793  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
794 
795  /* check to see if query supports us returning a tuplestore */
796  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
797  ereport(ERROR,
798  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
799  errmsg("set-valued function called in context that cannot accept a set")));
800  if (!(rsinfo->allowedModes & SFRM_Materialize))
801  ereport(ERROR,
802  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
803  errmsg("materialize mode required, but it is not allowed in this context")));
804 
805  /* let the executor know we're sending back a tuplestore */
806  rsinfo->returnMode = SFRM_Materialize;
807 
808  /* caller must fill these to return a non-empty result */
809  rsinfo->setResult = NULL;
810  rsinfo->setDesc = NULL;
811 }
812 
813 /*
814  * Copy the contents of the PGresult into a tuplestore to be returned
815  * as the result of the current function.
816  * The PGresult will be released in this function.
817  */
818 static void
820 {
821  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
822 
823  /* prepTuplestoreResult must have been called previously */
824  Assert(rsinfo->returnMode == SFRM_Materialize);
825 
826  PG_TRY();
827  {
828  TupleDesc tupdesc;
829  bool is_sql_cmd;
830  int ntuples;
831  int nfields;
832 
833  if (PQresultStatus(res) == PGRES_COMMAND_OK)
834  {
835  is_sql_cmd = true;
836 
837  /*
838  * need a tuple descriptor representing one TEXT column to return
839  * the command status string as our result tuple
840  */
841  tupdesc = CreateTemplateTupleDesc(1, false);
842  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
843  TEXTOID, -1, 0);
844  ntuples = 1;
845  nfields = 1;
846  }
847  else
848  {
850 
851  is_sql_cmd = false;
852 
853  /* get a tuple descriptor for our result type */
854  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
855  {
856  case TYPEFUNC_COMPOSITE:
857  /* success */
858  break;
859  case TYPEFUNC_RECORD:
860  /* failed to determine actual type of RECORD */
861  ereport(ERROR,
862  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
863  errmsg("function returning record called in context "
864  "that cannot accept type record")));
865  break;
866  default:
867  /* result type isn't composite */
868  elog(ERROR, "return type must be a row type");
869  break;
870  }
871 
872  /* make sure we have a persistent copy of the tupdesc */
873  tupdesc = CreateTupleDescCopy(tupdesc);
874  ntuples = PQntuples(res);
875  nfields = PQnfields(res);
876  }
877 
878  /*
879  * check result and tuple descriptor have the same number of columns
880  */
881  if (nfields != tupdesc->natts)
882  ereport(ERROR,
883  (errcode(ERRCODE_DATATYPE_MISMATCH),
884  errmsg("remote query result rowtype does not match "
885  "the specified FROM clause rowtype")));
886 
887  if (ntuples > 0)
888  {
889  AttInMetadata *attinmeta;
890  int nestlevel = -1;
891  Tuplestorestate *tupstore;
892  MemoryContext oldcontext;
893  int row;
894  char **values;
895 
896  attinmeta = TupleDescGetAttInMetadata(tupdesc);
897 
898  /* Set GUCs to ensure we read GUC-sensitive data types correctly */
899  if (!is_sql_cmd)
900  nestlevel = applyRemoteGucs(conn);
901 
902  oldcontext = MemoryContextSwitchTo(
904  tupstore = tuplestore_begin_heap(true, false, work_mem);
905  rsinfo->setResult = tupstore;
906  rsinfo->setDesc = tupdesc;
907  MemoryContextSwitchTo(oldcontext);
908 
909  values = (char **) palloc(nfields * sizeof(char *));
910 
911  /* put all tuples into the tuplestore */
912  for (row = 0; row < ntuples; row++)
913  {
914  HeapTuple tuple;
915 
916  if (!is_sql_cmd)
917  {
918  int i;
919 
920  for (i = 0; i < nfields; i++)
921  {
922  if (PQgetisnull(res, row, i))
923  values[i] = NULL;
924  else
925  values[i] = PQgetvalue(res, row, i);
926  }
927  }
928  else
929  {
930  values[0] = PQcmdStatus(res);
931  }
932 
933  /* build the tuple and put it into the tuplestore. */
934  tuple = BuildTupleFromCStrings(attinmeta, values);
935  tuplestore_puttuple(tupstore, tuple);
936  }
937 
938  /* clean up GUC settings, if we changed any */
939  restoreLocalGucs(nestlevel);
940 
941  /* clean up and return the tuplestore */
942  tuplestore_donestoring(tupstore);
943  }
944 
945  PQclear(res);
946  }
947  PG_CATCH();
948  {
949  /* be sure to release the libpq result */
950  PQclear(res);
951  PG_RE_THROW();
952  }
953  PG_END_TRY();
954 }
955 
956 /*
957  * Execute the given SQL command and store its results into a tuplestore
958  * to be returned as the result of the current function.
959  *
960  * This is equivalent to PQexec followed by materializeResult, but we make
961  * use of libpq's single-row mode to avoid accumulating the whole result
962  * inside libpq before it gets transferred to the tuplestore.
963  */
964 static void
966  PGconn *conn,
967  const char *conname,
968  const char *sql,
969  bool fail)
970 {
971  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
972  PGresult *volatile res = NULL;
973  volatile storeInfo sinfo;
974 
975  /* prepTuplestoreResult must have been called previously */
976  Assert(rsinfo->returnMode == SFRM_Materialize);
977 
978  /* initialize storeInfo to empty */
979  memset((void *) &sinfo, 0, sizeof(sinfo));
980  sinfo.fcinfo = fcinfo;
981 
982  PG_TRY();
983  {
984  /* Create short-lived memory context for data conversions */
985  sinfo.tmpcontext = AllocSetContextCreate(CurrentMemoryContext,
986  "dblink temporary context",
988 
989  /* execute query, collecting any tuples into the tuplestore */
990  res = storeQueryResult(&sinfo, conn, sql);
991 
992  if (!res ||
993  (PQresultStatus(res) != PGRES_COMMAND_OK &&
995  {
996  /*
997  * dblink_res_error will clear the passed PGresult, so we need
998  * this ugly dance to avoid doing so twice during error exit
999  */
1000  PGresult *res1 = res;
1001 
1002  res = NULL;
1003  dblink_res_error(conn, conname, res1,
1004  "could not execute query", fail);
1005  /* if fail isn't set, we'll return an empty query result */
1006  }
1007  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1008  {
1009  /*
1010  * storeRow didn't get called, so we need to convert the command
1011  * status string to a tuple manually
1012  */
1013  TupleDesc tupdesc;
1014  AttInMetadata *attinmeta;
1015  Tuplestorestate *tupstore;
1016  HeapTuple tuple;
1017  char *values[1];
1018  MemoryContext oldcontext;
1019 
1020  /*
1021  * need a tuple descriptor representing one TEXT column to return
1022  * the command status string as our result tuple
1023  */
1024  tupdesc = CreateTemplateTupleDesc(1, false);
1025  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
1026  TEXTOID, -1, 0);
1027  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1028 
1029  oldcontext = MemoryContextSwitchTo(
1030  rsinfo->econtext->ecxt_per_query_memory);
1031  tupstore = tuplestore_begin_heap(true, false, work_mem);
1032  rsinfo->setResult = tupstore;
1033  rsinfo->setDesc = tupdesc;
1034  MemoryContextSwitchTo(oldcontext);
1035 
1036  values[0] = PQcmdStatus(res);
1037 
1038  /* build the tuple and put it into the tuplestore. */
1039  tuple = BuildTupleFromCStrings(attinmeta, values);
1040  tuplestore_puttuple(tupstore, tuple);
1041 
1042  PQclear(res);
1043  res = NULL;
1044  }
1045  else
1046  {
1048  /* storeRow should have created a tuplestore */
1049  Assert(rsinfo->setResult != NULL);
1050 
1051  PQclear(res);
1052  res = NULL;
1053  }
1054 
1055  /* clean up data conversion short-lived memory context */
1056  if (sinfo.tmpcontext != NULL)
1057  MemoryContextDelete(sinfo.tmpcontext);
1058  sinfo.tmpcontext = NULL;
1059 
1060  PQclear(sinfo.last_res);
1061  sinfo.last_res = NULL;
1062  PQclear(sinfo.cur_res);
1063  sinfo.cur_res = NULL;
1064  }
1065  PG_CATCH();
1066  {
1067  /* be sure to release any libpq result we collected */
1068  PQclear(res);
1069  PQclear(sinfo.last_res);
1070  PQclear(sinfo.cur_res);
1071  /* and clear out any pending data in libpq */
1072  while ((res = PQgetResult(conn)) != NULL)
1073  PQclear(res);
1074  PG_RE_THROW();
1075  }
1076  PG_END_TRY();
1077 }
1078 
1079 /*
1080  * Execute query, and send any result rows to sinfo->tuplestore.
1081  */
1082 static PGresult *
1083 storeQueryResult(volatile storeInfo *sinfo, PGconn *conn, const char *sql)
1084 {
1085  bool first = true;
1086  int nestlevel = -1;
1087  PGresult *res;
1088 
1089  if (!PQsendQuery(conn, sql))
1090  elog(ERROR, "could not send query: %s", pchomp(PQerrorMessage(conn)));
1091 
1092  if (!PQsetSingleRowMode(conn)) /* shouldn't fail */
1093  elog(ERROR, "failed to set single-row mode for dblink query");
1094 
1095  for (;;)
1096  {
1098 
1099  sinfo->cur_res = PQgetResult(conn);
1100  if (!sinfo->cur_res)
1101  break;
1102 
1103  if (PQresultStatus(sinfo->cur_res) == PGRES_SINGLE_TUPLE)
1104  {
1105  /* got one row from possibly-bigger resultset */
1106 
1107  /*
1108  * Set GUCs to ensure we read GUC-sensitive data types correctly.
1109  * We shouldn't do this until we have a row in hand, to ensure
1110  * libpq has seen any earlier ParameterStatus protocol messages.
1111  */
1112  if (first && nestlevel < 0)
1113  nestlevel = applyRemoteGucs(conn);
1114 
1115  storeRow(sinfo, sinfo->cur_res, first);
1116 
1117  PQclear(sinfo->cur_res);
1118  sinfo->cur_res = NULL;
1119  first = false;
1120  }
1121  else
1122  {
1123  /* if empty resultset, fill tuplestore header */
1124  if (first && PQresultStatus(sinfo->cur_res) == PGRES_TUPLES_OK)
1125  storeRow(sinfo, sinfo->cur_res, first);
1126 
1127  /* store completed result at last_res */
1128  PQclear(sinfo->last_res);
1129  sinfo->last_res = sinfo->cur_res;
1130  sinfo->cur_res = NULL;
1131  first = true;
1132  }
1133  }
1134 
1135  /* clean up GUC settings, if we changed any */
1136  restoreLocalGucs(nestlevel);
1137 
1138  /* return last_res */
1139  res = sinfo->last_res;
1140  sinfo->last_res = NULL;
1141  return res;
1142 }
1143 
1144 /*
1145  * Send single row to sinfo->tuplestore.
1146  *
1147  * If "first" is true, create the tuplestore using PGresult's metadata
1148  * (in this case the PGresult might contain either zero or one row).
1149  */
1150 static void
1151 storeRow(volatile storeInfo *sinfo, PGresult *res, bool first)
1152 {
1153  int nfields = PQnfields(res);
1154  HeapTuple tuple;
1155  int i;
1156  MemoryContext oldcontext;
1157 
1158  if (first)
1159  {
1160  /* Prepare for new result set */
1161  ReturnSetInfo *rsinfo = (ReturnSetInfo *) sinfo->fcinfo->resultinfo;
1162  TupleDesc tupdesc;
1163 
1164  /*
1165  * It's possible to get more than one result set if the query string
1166  * contained multiple SQL commands. In that case, we follow PQexec's
1167  * traditional behavior of throwing away all but the last result.
1168  */
1169  if (sinfo->tuplestore)
1170  tuplestore_end(sinfo->tuplestore);
1171  sinfo->tuplestore = NULL;
1172 
1173  /* get a tuple descriptor for our result type */
1174  switch (get_call_result_type(sinfo->fcinfo, NULL, &tupdesc))
1175  {
1176  case TYPEFUNC_COMPOSITE:
1177  /* success */
1178  break;
1179  case TYPEFUNC_RECORD:
1180  /* failed to determine actual type of RECORD */
1181  ereport(ERROR,
1182  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1183  errmsg("function returning record called in context "
1184  "that cannot accept type record")));
1185  break;
1186  default:
1187  /* result type isn't composite */
1188  elog(ERROR, "return type must be a row type");
1189  break;
1190  }
1191 
1192  /* make sure we have a persistent copy of the tupdesc */
1193  tupdesc = CreateTupleDescCopy(tupdesc);
1194 
1195  /* check result and tuple descriptor have the same number of columns */
1196  if (nfields != tupdesc->natts)
1197  ereport(ERROR,
1198  (errcode(ERRCODE_DATATYPE_MISMATCH),
1199  errmsg("remote query result rowtype does not match "
1200  "the specified FROM clause rowtype")));
1201 
1202  /* Prepare attinmeta for later data conversions */
1203  sinfo->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1204 
1205  /* Create a new, empty tuplestore */
1206  oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
1207  sinfo->tuplestore = tuplestore_begin_heap(true, false, work_mem);
1208  rsinfo->setResult = sinfo->tuplestore;
1209  rsinfo->setDesc = tupdesc;
1210  MemoryContextSwitchTo(oldcontext);
1211 
1212  /* Done if empty resultset */
1213  if (PQntuples(res) == 0)
1214  return;
1215 
1216  /*
1217  * Set up sufficiently-wide string pointers array; this won't change
1218  * in size so it's easy to preallocate.
1219  */
1220  if (sinfo->cstrs)
1221  pfree(sinfo->cstrs);
1222  sinfo->cstrs = (char **) palloc(nfields * sizeof(char *));
1223  }
1224 
1225  /* Should have a single-row result if we get here */
1226  Assert(PQntuples(res) == 1);
1227 
1228  /*
1229  * Do the following work in a temp context that we reset after each tuple.
1230  * This cleans up not only the data we have direct access to, but any
1231  * cruft the I/O functions might leak.
1232  */
1233  oldcontext = MemoryContextSwitchTo(sinfo->tmpcontext);
1234 
1235  /*
1236  * Fill cstrs with null-terminated strings of column values.
1237  */
1238  for (i = 0; i < nfields; i++)
1239  {
1240  if (PQgetisnull(res, 0, i))
1241  sinfo->cstrs[i] = NULL;
1242  else
1243  sinfo->cstrs[i] = PQgetvalue(res, 0, i);
1244  }
1245 
1246  /* Convert row to a tuple, and add it to the tuplestore */
1247  tuple = BuildTupleFromCStrings(sinfo->attinmeta, sinfo->cstrs);
1248 
1249  tuplestore_puttuple(sinfo->tuplestore, tuple);
1250 
1251  /* Clean up */
1252  MemoryContextSwitchTo(oldcontext);
1254 }
1255 
1256 /*
1257  * List all open dblink connections by name.
1258  * Returns an array of all connection names.
1259  * Takes no params
1260  */
1262 Datum
1264 {
1266  remoteConnHashEnt *hentry;
1267  ArrayBuildState *astate = NULL;
1268 
1269  if (remoteConnHash)
1270  {
1271  hash_seq_init(&status, remoteConnHash);
1272  while ((hentry = (remoteConnHashEnt *) hash_seq_search(&status)) != NULL)
1273  {
1274  /* stash away current value */
1275  astate = accumArrayResult(astate,
1276  CStringGetTextDatum(hentry->name),
1277  false, TEXTOID, CurrentMemoryContext);
1278  }
1279  }
1280 
1281  if (astate)
1284  else
1285  PG_RETURN_NULL();
1286 }
1287 
1288 /*
1289  * Checks if a given remote connection is busy
1290  *
1291  * Returns 1 if the connection is busy, 0 otherwise
1292  * Params:
1293  * text connection_name - name of the connection to check
1294  *
1295  */
1297 Datum
1299 {
1300  PGconn *conn;
1301 
1302  dblink_init();
1304 
1305  PQconsumeInput(conn);
1306  PG_RETURN_INT32(PQisBusy(conn));
1307 }
1308 
1309 /*
1310  * Cancels a running request on a connection
1311  *
1312  * Returns text:
1313  * "OK" if the cancel request has been sent correctly,
1314  * an error message otherwise
1315  *
1316  * Params:
1317  * text connection_name - name of the connection to check
1318  *
1319  */
1321 Datum
1323 {
1324  int res;
1325  PGconn *conn;
1326  PGcancel *cancel;
1327  char errbuf[256];
1328 
1329  dblink_init();
1331  cancel = PQgetCancel(conn);
1332 
1333  res = PQcancel(cancel, errbuf, 256);
1334  PQfreeCancel(cancel);
1335 
1336  if (res == 1)
1338  else
1340 }
1341 
1342 
1343 /*
1344  * Get error message from a connection
1345  *
1346  * Returns text:
1347  * "OK" if no error, an error message otherwise
1348  *
1349  * Params:
1350  * text connection_name - name of the connection to check
1351  *
1352  */
1354 Datum
1356 {
1357  char *msg;
1358  PGconn *conn;
1359 
1360  dblink_init();
1362 
1363  msg = PQerrorMessage(conn);
1364  if (msg == NULL || msg[0] == '\0')
1366  else
1368 }
1369 
1370 /*
1371  * Execute an SQL non-SELECT command
1372  */
1374 Datum
1376 {
1377  text *volatile sql_cmd_status = NULL;
1378  PGconn *volatile conn = NULL;
1379  volatile bool freeconn = false;
1380 
1381  dblink_init();
1382 
1383  PG_TRY();
1384  {
1385  PGresult *res = NULL;
1386  char *sql = NULL;
1387  char *conname = NULL;
1388  bool fail = true; /* default to backward compatible behavior */
1389 
1390  if (PG_NARGS() == 3)
1391  {
1392  /* must be text,text,bool */
1393  dblink_get_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)), &conn, &conname, &freeconn);
1395  fail = PG_GETARG_BOOL(2);
1396  }
1397  else if (PG_NARGS() == 2)
1398  {
1399  /* might be text,text or text,bool */
1400  if (get_fn_expr_argtype(fcinfo->flinfo, 1) == BOOLOID)
1401  {
1402  conn = pconn->conn;
1404  fail = PG_GETARG_BOOL(1);
1405  }
1406  else
1407  {
1408  dblink_get_conn(text_to_cstring(PG_GETARG_TEXT_PP(0)), &conn, &conname, &freeconn);
1410  }
1411  }
1412  else if (PG_NARGS() == 1)
1413  {
1414  /* must be single text argument */
1415  conn = pconn->conn;
1417  }
1418  else
1419  /* shouldn't happen */
1420  elog(ERROR, "wrong number of arguments");
1421 
1422  if (!conn)
1423  dblink_conn_not_avail(conname);
1424 
1425  res = PQexec(conn, sql);
1426  if (!res ||
1427  (PQresultStatus(res) != PGRES_COMMAND_OK &&
1429  {
1430  dblink_res_error(conn, conname, res,
1431  "could not execute command", fail);
1432 
1433  /*
1434  * and save a copy of the command status string to return as our
1435  * result tuple
1436  */
1437  sql_cmd_status = cstring_to_text("ERROR");
1438  }
1439  else if (PQresultStatus(res) == PGRES_COMMAND_OK)
1440  {
1441  /*
1442  * and save a copy of the command status string to return as our
1443  * result tuple
1444  */
1445  sql_cmd_status = cstring_to_text(PQcmdStatus(res));
1446  PQclear(res);
1447  }
1448  else
1449  {
1450  PQclear(res);
1451  ereport(ERROR,
1452  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
1453  errmsg("statement returning results not allowed")));
1454  }
1455  }
1456  PG_CATCH();
1457  {
1458  /* if needed, close the connection to the database */
1459  if (freeconn)
1460  PQfinish(conn);
1461  PG_RE_THROW();
1462  }
1463  PG_END_TRY();
1464 
1465  /* if needed, close the connection to the database */
1466  if (freeconn)
1467  PQfinish(conn);
1468 
1469  PG_RETURN_TEXT_P(sql_cmd_status);
1470 }
1471 
1472 
1473 /*
1474  * dblink_get_pkey
1475  *
1476  * Return list of primary key fields for the supplied relation,
1477  * or NULL if none exists.
1478  */
1480 Datum
1482 {
1483  int16 numatts;
1484  char **results;
1485  FuncCallContext *funcctx;
1486  int32 call_cntr;
1487  int32 max_calls;
1488  AttInMetadata *attinmeta;
1489  MemoryContext oldcontext;
1490 
1491  /* stuff done only on the first call of the function */
1492  if (SRF_IS_FIRSTCALL())
1493  {
1494  Relation rel;
1495  TupleDesc tupdesc;
1496 
1497  /* create a function context for cross-call persistence */
1498  funcctx = SRF_FIRSTCALL_INIT();
1499 
1500  /*
1501  * switch to memory context appropriate for multiple function calls
1502  */
1503  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1504 
1505  /* open target relation */
1507 
1508  /* get the array of attnums */
1509  results = get_pkey_attnames(rel, &numatts);
1510 
1512 
1513  /*
1514  * need a tuple descriptor representing one INT and one TEXT column
1515  */
1516  tupdesc = CreateTemplateTupleDesc(2, false);
1517  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
1518  INT4OID, -1, 0);
1519  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
1520  TEXTOID, -1, 0);
1521 
1522  /*
1523  * Generate attribute metadata needed later to produce tuples from raw
1524  * C strings
1525  */
1526  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1527  funcctx->attinmeta = attinmeta;
1528 
1529  if ((results != NULL) && (numatts > 0))
1530  {
1531  funcctx->max_calls = numatts;
1532 
1533  /* got results, keep track of them */
1534  funcctx->user_fctx = results;
1535  }
1536  else
1537  {
1538  /* fast track when no results */
1539  MemoryContextSwitchTo(oldcontext);
1540  SRF_RETURN_DONE(funcctx);
1541  }
1542 
1543  MemoryContextSwitchTo(oldcontext);
1544  }
1545 
1546  /* stuff done on every call of the function */
1547  funcctx = SRF_PERCALL_SETUP();
1548 
1549  /*
1550  * initialize per-call variables
1551  */
1552  call_cntr = funcctx->call_cntr;
1553  max_calls = funcctx->max_calls;
1554 
1555  results = (char **) funcctx->user_fctx;
1556  attinmeta = funcctx->attinmeta;
1557 
1558  if (call_cntr < max_calls) /* do when there is more left to send */
1559  {
1560  char **values;
1561  HeapTuple tuple;
1562  Datum result;
1563 
1564  values = (char **) palloc(2 * sizeof(char *));
1565  values[0] = psprintf("%d", call_cntr + 1);
1566  values[1] = results[call_cntr];
1567 
1568  /* build the tuple */
1569  tuple = BuildTupleFromCStrings(attinmeta, values);
1570 
1571  /* make the tuple into a datum */
1572  result = HeapTupleGetDatum(tuple);
1573 
1574  SRF_RETURN_NEXT(funcctx, result);
1575  }
1576  else
1577  {
1578  /* do when there is no more left */
1579  SRF_RETURN_DONE(funcctx);
1580  }
1581 }
1582 
1583 
1584 /*
1585  * dblink_build_sql_insert
1586  *
1587  * Used to generate an SQL insert statement
1588  * based on an existing tuple in a local relation.
1589  * This is useful for selectively replicating data
1590  * to another server via dblink.
1591  *
1592  * API:
1593  * <relname> - name of local table of interest
1594  * <pkattnums> - an int2vector of attnums which will be used
1595  * to identify the local tuple of interest
1596  * <pknumatts> - number of attnums in pkattnums
1597  * <src_pkattvals_arry> - text array of key values which will be used
1598  * to identify the local tuple of interest
1599  * <tgt_pkattvals_arry> - text array of key values which will be used
1600  * to build the string for execution remotely. These are substituted
1601  * for their counterparts in src_pkattvals_arry
1602  */
1604 Datum
1606 {
1607  text *relname_text = PG_GETARG_TEXT_PP(0);
1608  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1609  int32 pknumatts_arg = PG_GETARG_INT32(2);
1610  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1611  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1612  Relation rel;
1613  int *pkattnums;
1614  int pknumatts;
1615  char **src_pkattvals;
1616  char **tgt_pkattvals;
1617  int src_nitems;
1618  int tgt_nitems;
1619  char *sql;
1620 
1621  /*
1622  * Open target relation.
1623  */
1624  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1625 
1626  /*
1627  * Process pkattnums argument.
1628  */
1629  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1630  &pkattnums, &pknumatts);
1631 
1632  /*
1633  * Source array is made up of key values that will be used to locate the
1634  * tuple of interest from the local system.
1635  */
1636  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1637 
1638  /*
1639  * There should be one source array key value for each key attnum
1640  */
1641  if (src_nitems != pknumatts)
1642  ereport(ERROR,
1643  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1644  errmsg("source key array length must match number of key " \
1645  "attributes")));
1646 
1647  /*
1648  * Target array is made up of key values that will be used to build the
1649  * SQL string for use on the remote system.
1650  */
1651  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1652 
1653  /*
1654  * There should be one target array key value for each key attnum
1655  */
1656  if (tgt_nitems != pknumatts)
1657  ereport(ERROR,
1658  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1659  errmsg("target key array length must match number of key " \
1660  "attributes")));
1661 
1662  /*
1663  * Prep work is finally done. Go get the SQL string.
1664  */
1665  sql = get_sql_insert(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1666 
1667  /*
1668  * Now we can close the relation.
1669  */
1671 
1672  /*
1673  * And send it
1674  */
1676 }
1677 
1678 
1679 /*
1680  * dblink_build_sql_delete
1681  *
1682  * Used to generate an SQL delete statement.
1683  * This is useful for selectively replicating a
1684  * delete to another server via dblink.
1685  *
1686  * API:
1687  * <relname> - name of remote table of interest
1688  * <pkattnums> - an int2vector of attnums which will be used
1689  * to identify the remote tuple of interest
1690  * <pknumatts> - number of attnums in pkattnums
1691  * <tgt_pkattvals_arry> - text array of key values which will be used
1692  * to build the string for execution remotely.
1693  */
1695 Datum
1697 {
1698  text *relname_text = PG_GETARG_TEXT_PP(0);
1699  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1700  int32 pknumatts_arg = PG_GETARG_INT32(2);
1701  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1702  Relation rel;
1703  int *pkattnums;
1704  int pknumatts;
1705  char **tgt_pkattvals;
1706  int tgt_nitems;
1707  char *sql;
1708 
1709  /*
1710  * Open target relation.
1711  */
1712  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1713 
1714  /*
1715  * Process pkattnums argument.
1716  */
1717  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1718  &pkattnums, &pknumatts);
1719 
1720  /*
1721  * Target array is made up of key values that will be used to build the
1722  * SQL string for use on the remote system.
1723  */
1724  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1725 
1726  /*
1727  * There should be one target array key value for each key attnum
1728  */
1729  if (tgt_nitems != pknumatts)
1730  ereport(ERROR,
1731  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1732  errmsg("target key array length must match number of key " \
1733  "attributes")));
1734 
1735  /*
1736  * Prep work is finally done. Go get the SQL string.
1737  */
1738  sql = get_sql_delete(rel, pkattnums, pknumatts, tgt_pkattvals);
1739 
1740  /*
1741  * Now we can close the relation.
1742  */
1744 
1745  /*
1746  * And send it
1747  */
1749 }
1750 
1751 
1752 /*
1753  * dblink_build_sql_update
1754  *
1755  * Used to generate an SQL update statement
1756  * based on an existing tuple in a local relation.
1757  * This is useful for selectively replicating data
1758  * to another server via dblink.
1759  *
1760  * API:
1761  * <relname> - name of local table of interest
1762  * <pkattnums> - an int2vector of attnums which will be used
1763  * to identify the local tuple of interest
1764  * <pknumatts> - number of attnums in pkattnums
1765  * <src_pkattvals_arry> - text array of key values which will be used
1766  * to identify the local tuple of interest
1767  * <tgt_pkattvals_arry> - text array of key values which will be used
1768  * to build the string for execution remotely. These are substituted
1769  * for their counterparts in src_pkattvals_arry
1770  */
1772 Datum
1774 {
1775  text *relname_text = PG_GETARG_TEXT_PP(0);
1776  int2vector *pkattnums_arg = (int2vector *) PG_GETARG_POINTER(1);
1777  int32 pknumatts_arg = PG_GETARG_INT32(2);
1778  ArrayType *src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
1779  ArrayType *tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);
1780  Relation rel;
1781  int *pkattnums;
1782  int pknumatts;
1783  char **src_pkattvals;
1784  char **tgt_pkattvals;
1785  int src_nitems;
1786  int tgt_nitems;
1787  char *sql;
1788 
1789  /*
1790  * Open target relation.
1791  */
1792  rel = get_rel_from_relname(relname_text, AccessShareLock, ACL_SELECT);
1793 
1794  /*
1795  * Process pkattnums argument.
1796  */
1797  validate_pkattnums(rel, pkattnums_arg, pknumatts_arg,
1798  &pkattnums, &pknumatts);
1799 
1800  /*
1801  * Source array is made up of key values that will be used to locate the
1802  * tuple of interest from the local system.
1803  */
1804  src_pkattvals = get_text_array_contents(src_pkattvals_arry, &src_nitems);
1805 
1806  /*
1807  * There should be one source array key value for each key attnum
1808  */
1809  if (src_nitems != pknumatts)
1810  ereport(ERROR,
1811  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1812  errmsg("source key array length must match number of key " \
1813  "attributes")));
1814 
1815  /*
1816  * Target array is made up of key values that will be used to build the
1817  * SQL string for use on the remote system.
1818  */
1819  tgt_pkattvals = get_text_array_contents(tgt_pkattvals_arry, &tgt_nitems);
1820 
1821  /*
1822  * There should be one target array key value for each key attnum
1823  */
1824  if (tgt_nitems != pknumatts)
1825  ereport(ERROR,
1826  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
1827  errmsg("target key array length must match number of key " \
1828  "attributes")));
1829 
1830  /*
1831  * Prep work is finally done. Go get the SQL string.
1832  */
1833  sql = get_sql_update(rel, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);
1834 
1835  /*
1836  * Now we can close the relation.
1837  */
1839 
1840  /*
1841  * And send it
1842  */
1844 }
1845 
1846 /*
1847  * dblink_current_query
1848  * return the current query string
1849  * to allow its use in (among other things)
1850  * rewrite rules
1851  */
1853 Datum
1855 {
1856  /* This is now just an alias for the built-in function current_query() */
1857  PG_RETURN_DATUM(current_query(fcinfo));
1858 }
1859 
1860 /*
1861  * Retrieve async notifications for a connection.
1862  *
1863  * Returns a setof record of notifications, or an empty set if none received.
1864  * Can optionally take a named connection as parameter, but uses the unnamed
1865  * connection per default.
1866  *
1867  */
1868 #define DBLINK_NOTIFY_COLS 3
1869 
1871 Datum
1873 {
1874  PGconn *conn;
1875  PGnotify *notify;
1876  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1877  TupleDesc tupdesc;
1878  Tuplestorestate *tupstore;
1879  MemoryContext per_query_ctx;
1880  MemoryContext oldcontext;
1881 
1882  prepTuplestoreResult(fcinfo);
1883 
1884  dblink_init();
1885  if (PG_NARGS() == 1)
1887  else
1888  conn = pconn->conn;
1889 
1890  /* create the tuplestore in per-query memory */
1891  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1892  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1893 
1894  tupdesc = CreateTemplateTupleDesc(DBLINK_NOTIFY_COLS, false);
1895  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "notify_name",
1896  TEXTOID, -1, 0);
1897  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "be_pid",
1898  INT4OID, -1, 0);
1899  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "extra",
1900  TEXTOID, -1, 0);
1901 
1902  tupstore = tuplestore_begin_heap(true, false, work_mem);
1903  rsinfo->setResult = tupstore;
1904  rsinfo->setDesc = tupdesc;
1905 
1906  MemoryContextSwitchTo(oldcontext);
1907 
1908  PQconsumeInput(conn);
1909  while ((notify = PQnotifies(conn)) != NULL)
1910  {
1912  bool nulls[DBLINK_NOTIFY_COLS];
1913 
1914  memset(values, 0, sizeof(values));
1915  memset(nulls, 0, sizeof(nulls));
1916 
1917  if (notify->relname != NULL)
1918  values[0] = CStringGetTextDatum(notify->relname);
1919  else
1920  nulls[0] = true;
1921 
1922  values[1] = Int32GetDatum(notify->be_pid);
1923 
1924  if (notify->extra != NULL)
1925  values[2] = CStringGetTextDatum(notify->extra);
1926  else
1927  nulls[2] = true;
1928 
1929  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1930 
1931  PQfreemem(notify);
1932  PQconsumeInput(conn);
1933  }
1934 
1935  /* clean up and return the tuplestore */
1936  tuplestore_donestoring(tupstore);
1937 
1938  return (Datum) 0;
1939 }
1940 
1941 /*
1942  * Validate the options given to a dblink foreign server or user mapping.
1943  * Raise an error if any option is invalid.
1944  *
1945  * We just check the names of options here, so semantic errors in options,
1946  * such as invalid numeric format, will be detected at the attempt to connect.
1947  */
1949 Datum
1951 {
1952  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
1953  Oid context = PG_GETARG_OID(1);
1954  ListCell *cell;
1955 
1956  static const PQconninfoOption *options = NULL;
1957 
1958  /*
1959  * Get list of valid libpq options.
1960  *
1961  * To avoid unnecessary work, we get the list once and use it throughout
1962  * the lifetime of this backend process. We don't need to care about
1963  * memory context issues, because PQconndefaults allocates with malloc.
1964  */
1965  if (!options)
1966  {
1967  options = PQconndefaults();
1968  if (!options) /* assume reason for failure is OOM */
1969  ereport(ERROR,
1970  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
1971  errmsg("out of memory"),
1972  errdetail("could not get libpq's default connection options")));
1973  }
1974 
1975  /* Validate each supplied option. */
1976  foreach(cell, options_list)
1977  {
1978  DefElem *def = (DefElem *) lfirst(cell);
1979 
1980  if (!is_valid_dblink_option(options, def->defname, context))
1981  {
1982  /*
1983  * Unknown option, or invalid option for the context specified, so
1984  * complain about it. Provide a hint with list of valid options
1985  * for the context.
1986  */
1988  const PQconninfoOption *opt;
1989 
1990  initStringInfo(&buf);
1991  for (opt = options; opt->keyword; opt++)
1992  {
1993  if (is_valid_dblink_option(options, opt->keyword, context))
1994  appendStringInfo(&buf, "%s%s",
1995  (buf.len > 0) ? ", " : "",
1996  opt->keyword);
1997  }
1998  ereport(ERROR,
1999  (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND),
2000  errmsg("invalid option \"%s\"", def->defname),
2001  errhint("Valid options in this context are: %s",
2002  buf.data)));
2003  }
2004  }
2005 
2006  PG_RETURN_VOID();
2007 }
2008 
2009 
2010 /*************************************************************
2011  * internal functions
2012  */
2013 
2014 
2015 /*
2016  * get_pkey_attnames
2017  *
2018  * Get the primary key attnames for the given relation.
2019  * Return NULL, and set numatts = 0, if no primary key exists.
2020  */
2021 static char **
2023 {
2024  Relation indexRelation;
2025  ScanKeyData skey;
2026  SysScanDesc scan;
2027  HeapTuple indexTuple;
2028  int i;
2029  char **result = NULL;
2030  TupleDesc tupdesc;
2031 
2032  /* initialize numatts to 0 in case no primary key exists */
2033  *numatts = 0;
2034 
2035  tupdesc = rel->rd_att;
2036 
2037  /* Prepare to scan pg_index for entries having indrelid = this rel. */
2038  indexRelation = heap_open(IndexRelationId, AccessShareLock);
2039  ScanKeyInit(&skey,
2041  BTEqualStrategyNumber, F_OIDEQ,
2043 
2044  scan = systable_beginscan(indexRelation, IndexIndrelidIndexId, true,
2045  NULL, 1, &skey);
2046 
2047  while (HeapTupleIsValid(indexTuple = systable_getnext(scan)))
2048  {
2049  Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
2050 
2051  /* we're only interested if it is the primary key */
2052  if (index->indisprimary)
2053  {
2054  *numatts = index->indnatts;
2055  if (*numatts > 0)
2056  {
2057  result = (char **) palloc(*numatts * sizeof(char *));
2058 
2059  for (i = 0; i < *numatts; i++)
2060  result[i] = SPI_fname(tupdesc, index->indkey.values[i]);
2061  }
2062  break;
2063  }
2064  }
2065 
2066  systable_endscan(scan);
2067  heap_close(indexRelation, AccessShareLock);
2068 
2069  return result;
2070 }
2071 
2072 /*
2073  * Deconstruct a text[] into C-strings (note any NULL elements will be
2074  * returned as NULL pointers)
2075  */
2076 static char **
2077 get_text_array_contents(ArrayType *array, int *numitems)
2078 {
2079  int ndim = ARR_NDIM(array);
2080  int *dims = ARR_DIMS(array);
2081  int nitems;
2082  int16 typlen;
2083  bool typbyval;
2084  char typalign;
2085  char **values;
2086  char *ptr;
2087  bits8 *bitmap;
2088  int bitmask;
2089  int i;
2090 
2091  Assert(ARR_ELEMTYPE(array) == TEXTOID);
2092 
2093  *numitems = nitems = ArrayGetNItems(ndim, dims);
2094 
2096  &typlen, &typbyval, &typalign);
2097 
2098  values = (char **) palloc(nitems * sizeof(char *));
2099 
2100  ptr = ARR_DATA_PTR(array);
2101  bitmap = ARR_NULLBITMAP(array);
2102  bitmask = 1;
2103 
2104  for (i = 0; i < nitems; i++)
2105  {
2106  if (bitmap && (*bitmap & bitmask) == 0)
2107  {
2108  values[i] = NULL;
2109  }
2110  else
2111  {
2112  values[i] = TextDatumGetCString(PointerGetDatum(ptr));
2113  ptr = att_addlength_pointer(ptr, typlen, ptr);
2114  ptr = (char *) att_align_nominal(ptr, typalign);
2115  }
2116 
2117  /* advance bitmap pointer if any */
2118  if (bitmap)
2119  {
2120  bitmask <<= 1;
2121  if (bitmask == 0x100)
2122  {
2123  bitmap++;
2124  bitmask = 1;
2125  }
2126  }
2127  }
2128 
2129  return values;
2130 }
2131 
2132 static char *
2133 get_sql_insert(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
2134 {
2135  char *relname;
2136  HeapTuple tuple;
2137  TupleDesc tupdesc;
2138  int natts;
2140  char *val;
2141  int key;
2142  int i;
2143  bool needComma;
2144 
2145  initStringInfo(&buf);
2146 
2147  /* get relation name including any needed schema prefix and quoting */
2148  relname = generate_relation_name(rel);
2149 
2150  tupdesc = rel->rd_att;
2151  natts = tupdesc->natts;
2152 
2153  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2154  if (!tuple)
2155  ereport(ERROR,
2156  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2157  errmsg("source row not found")));
2158 
2159  appendStringInfo(&buf, "INSERT INTO %s(", relname);
2160 
2161  needComma = false;
2162  for (i = 0; i < natts; i++)
2163  {
2164  if (tupdesc->attrs[i]->attisdropped)
2165  continue;
2166 
2167  if (needComma)
2168  appendStringInfoChar(&buf, ',');
2169 
2171  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2172  needComma = true;
2173  }
2174 
2175  appendStringInfoString(&buf, ") VALUES(");
2176 
2177  /*
2178  * Note: i is physical column number (counting from 0).
2179  */
2180  needComma = false;
2181  for (i = 0; i < natts; i++)
2182  {
2183  if (tupdesc->attrs[i]->attisdropped)
2184  continue;
2185 
2186  if (needComma)
2187  appendStringInfoChar(&buf, ',');
2188 
2189  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2190 
2191  if (key >= 0)
2192  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2193  else
2194  val = SPI_getvalue(tuple, tupdesc, i + 1);
2195 
2196  if (val != NULL)
2197  {
2199  pfree(val);
2200  }
2201  else
2202  appendStringInfoString(&buf, "NULL");
2203  needComma = true;
2204  }
2205  appendStringInfoChar(&buf, ')');
2206 
2207  return (buf.data);
2208 }
2209 
2210 static char *
2211 get_sql_delete(Relation rel, int *pkattnums, int pknumatts, char **tgt_pkattvals)
2212 {
2213  char *relname;
2214  TupleDesc tupdesc;
2216  int i;
2217 
2218  initStringInfo(&buf);
2219 
2220  /* get relation name including any needed schema prefix and quoting */
2221  relname = generate_relation_name(rel);
2222 
2223  tupdesc = rel->rd_att;
2224 
2225  appendStringInfo(&buf, "DELETE FROM %s WHERE ", relname);
2226  for (i = 0; i < pknumatts; i++)
2227  {
2228  int pkattnum = pkattnums[i];
2229 
2230  if (i > 0)
2231  appendStringInfoString(&buf, " AND ");
2232 
2234  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2235 
2236  if (tgt_pkattvals[i] != NULL)
2237  appendStringInfo(&buf, " = %s",
2238  quote_literal_cstr(tgt_pkattvals[i]));
2239  else
2240  appendStringInfoString(&buf, " IS NULL");
2241  }
2242 
2243  return (buf.data);
2244 }
2245 
2246 static char *
2247 get_sql_update(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals, char **tgt_pkattvals)
2248 {
2249  char *relname;
2250  HeapTuple tuple;
2251  TupleDesc tupdesc;
2252  int natts;
2254  char *val;
2255  int key;
2256  int i;
2257  bool needComma;
2258 
2259  initStringInfo(&buf);
2260 
2261  /* get relation name including any needed schema prefix and quoting */
2262  relname = generate_relation_name(rel);
2263 
2264  tupdesc = rel->rd_att;
2265  natts = tupdesc->natts;
2266 
2267  tuple = get_tuple_of_interest(rel, pkattnums, pknumatts, src_pkattvals);
2268  if (!tuple)
2269  ereport(ERROR,
2270  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2271  errmsg("source row not found")));
2272 
2273  appendStringInfo(&buf, "UPDATE %s SET ", relname);
2274 
2275  /*
2276  * Note: i is physical column number (counting from 0).
2277  */
2278  needComma = false;
2279  for (i = 0; i < natts; i++)
2280  {
2281  if (tupdesc->attrs[i]->attisdropped)
2282  continue;
2283 
2284  if (needComma)
2285  appendStringInfoString(&buf, ", ");
2286 
2287  appendStringInfo(&buf, "%s = ",
2288  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2289 
2290  key = get_attnum_pk_pos(pkattnums, pknumatts, i);
2291 
2292  if (key >= 0)
2293  val = tgt_pkattvals[key] ? pstrdup(tgt_pkattvals[key]) : NULL;
2294  else
2295  val = SPI_getvalue(tuple, tupdesc, i + 1);
2296 
2297  if (val != NULL)
2298  {
2300  pfree(val);
2301  }
2302  else
2303  appendStringInfoString(&buf, "NULL");
2304  needComma = true;
2305  }
2306 
2307  appendStringInfoString(&buf, " WHERE ");
2308 
2309  for (i = 0; i < pknumatts; i++)
2310  {
2311  int pkattnum = pkattnums[i];
2312 
2313  if (i > 0)
2314  appendStringInfoString(&buf, " AND ");
2315 
2317  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2318 
2319  val = tgt_pkattvals[i];
2320 
2321  if (val != NULL)
2322  appendStringInfo(&buf, " = %s", quote_literal_cstr(val));
2323  else
2324  appendStringInfoString(&buf, " IS NULL");
2325  }
2326 
2327  return (buf.data);
2328 }
2329 
2330 /*
2331  * Return a properly quoted identifier.
2332  * Uses quote_ident in quote.c
2333  */
2334 static char *
2335 quote_ident_cstr(char *rawstr)
2336 {
2337  text *rawstr_text;
2338  text *result_text;
2339  char *result;
2340 
2341  rawstr_text = cstring_to_text(rawstr);
2343  PointerGetDatum(rawstr_text)));
2344  result = text_to_cstring(result_text);
2345 
2346  return result;
2347 }
2348 
2349 static int
2350 get_attnum_pk_pos(int *pkattnums, int pknumatts, int key)
2351 {
2352  int i;
2353 
2354  /*
2355  * Not likely a long list anyway, so just scan for the value
2356  */
2357  for (i = 0; i < pknumatts; i++)
2358  if (key == pkattnums[i])
2359  return i;
2360 
2361  return -1;
2362 }
2363 
2364 static HeapTuple
2365 get_tuple_of_interest(Relation rel, int *pkattnums, int pknumatts, char **src_pkattvals)
2366 {
2367  char *relname;
2368  TupleDesc tupdesc;
2369  int natts;
2371  int ret;
2372  HeapTuple tuple;
2373  int i;
2374 
2375  /*
2376  * Connect to SPI manager
2377  */
2378  if ((ret = SPI_connect()) < 0)
2379  /* internal error */
2380  elog(ERROR, "SPI connect failure - returned %d", ret);
2381 
2382  initStringInfo(&buf);
2383 
2384  /* get relation name including any needed schema prefix and quoting */
2385  relname = generate_relation_name(rel);
2386 
2387  tupdesc = rel->rd_att;
2388  natts = tupdesc->natts;
2389 
2390  /*
2391  * Build sql statement to look up tuple of interest, ie, the one matching
2392  * src_pkattvals. We used to use "SELECT *" here, but it's simpler to
2393  * generate a result tuple that matches the table's physical structure,
2394  * with NULLs for any dropped columns. Otherwise we have to deal with two
2395  * different tupdescs and everything's very confusing.
2396  */
2397  appendStringInfoString(&buf, "SELECT ");
2398 
2399  for (i = 0; i < natts; i++)
2400  {
2401  if (i > 0)
2402  appendStringInfoString(&buf, ", ");
2403 
2404  if (tupdesc->attrs[i]->attisdropped)
2405  appendStringInfoString(&buf, "NULL");
2406  else
2408  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
2409  }
2410 
2411  appendStringInfo(&buf, " FROM %s WHERE ", relname);
2412 
2413  for (i = 0; i < pknumatts; i++)
2414  {
2415  int pkattnum = pkattnums[i];
2416 
2417  if (i > 0)
2418  appendStringInfoString(&buf, " AND ");
2419 
2421  quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum]->attname)));
2422 
2423  if (src_pkattvals[i] != NULL)
2424  appendStringInfo(&buf, " = %s",
2425  quote_literal_cstr(src_pkattvals[i]));
2426  else
2427  appendStringInfoString(&buf, " IS NULL");
2428  }
2429 
2430  /*
2431  * Retrieve the desired tuple
2432  */
2433  ret = SPI_exec(buf.data, 0);
2434  pfree(buf.data);
2435 
2436  /*
2437  * Only allow one qualifying tuple
2438  */
2439  if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
2440  ereport(ERROR,
2441  (errcode(ERRCODE_CARDINALITY_VIOLATION),
2442  errmsg("source criteria matched more than one record")));
2443 
2444  else if (ret == SPI_OK_SELECT && SPI_processed == 1)
2445  {
2446  SPITupleTable *tuptable = SPI_tuptable;
2447 
2448  tuple = SPI_copytuple(tuptable->vals[0]);
2449  SPI_finish();
2450 
2451  return tuple;
2452  }
2453  else
2454  {
2455  /*
2456  * no qualifying tuples
2457  */
2458  SPI_finish();
2459 
2460  return NULL;
2461  }
2462 
2463  /*
2464  * never reached, but keep compiler quiet
2465  */
2466  return NULL;
2467 }
2468 
2469 /*
2470  * Open the relation named by relname_text, acquire specified type of lock,
2471  * verify we have specified permissions.
2472  * Caller must close rel when done with it.
2473  */
2474 static Relation
2475 get_rel_from_relname(text *relname_text, LOCKMODE lockmode, AclMode aclmode)
2476 {
2477  RangeVar *relvar;
2478  Relation rel;
2479  AclResult aclresult;
2480 
2481  relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text));
2482  rel = heap_openrv(relvar, lockmode);
2483 
2484  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
2485  aclmode);
2486  if (aclresult != ACLCHECK_OK)
2487  aclcheck_error(aclresult, ACL_KIND_CLASS,
2489 
2490  return rel;
2491 }
2492 
2493 /*
2494  * generate_relation_name - copied from ruleutils.c
2495  * Compute the name to display for a relation
2496  *
2497  * The result includes all necessary quoting and schema-prefixing.
2498  */
2499 static char *
2501 {
2502  char *nspname;
2503  char *result;
2504 
2505  /* Qualify the name if not visible in search path */
2507  nspname = NULL;
2508  else
2509  nspname = get_namespace_name(rel->rd_rel->relnamespace);
2510 
2511  result = quote_qualified_identifier(nspname, RelationGetRelationName(rel));
2512 
2513  return result;
2514 }
2515 
2516 
2517 static remoteConn *
2519 {
2520  remoteConnHashEnt *hentry;
2521  char *key;
2522 
2523  if (!remoteConnHash)
2524  remoteConnHash = createConnHash();
2525 
2526  key = pstrdup(name);
2527  truncate_identifier(key, strlen(key), false);
2528  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
2529  key, HASH_FIND, NULL);
2530 
2531  if (hentry)
2532  return (hentry->rconn);
2533 
2534  return (NULL);
2535 }
2536 
2537 static HTAB *
2539 {
2540  HASHCTL ctl;
2541 
2542  ctl.keysize = NAMEDATALEN;
2543  ctl.entrysize = sizeof(remoteConnHashEnt);
2544 
2545  return hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
2546 }
2547 
2548 static void
2550 {
2551  remoteConnHashEnt *hentry;
2552  bool found;
2553  char *key;
2554 
2555  if (!remoteConnHash)
2556  remoteConnHash = createConnHash();
2557 
2558  key = pstrdup(name);
2559  truncate_identifier(key, strlen(key), true);
2560  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
2561  HASH_ENTER, &found);
2562 
2563  if (found)
2564  {
2565  PQfinish(rconn->conn);
2566  pfree(rconn);
2567 
2568  ereport(ERROR,
2570  errmsg("duplicate connection name")));
2571  }
2572 
2573  hentry->rconn = rconn;
2574  strlcpy(hentry->name, name, sizeof(hentry->name));
2575 }
2576 
2577 static void
2579 {
2580  remoteConnHashEnt *hentry;
2581  bool found;
2582  char *key;
2583 
2584  if (!remoteConnHash)
2585  remoteConnHash = createConnHash();
2586 
2587  key = pstrdup(name);
2588  truncate_identifier(key, strlen(key), false);
2589  hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
2590  key, HASH_REMOVE, &found);
2591 
2592  if (!hentry)
2593  ereport(ERROR,
2594  (errcode(ERRCODE_UNDEFINED_OBJECT),
2595  errmsg("undefined connection name")));
2596 
2597 }
2598 
2599 static void
2601 {
2602  if (!superuser())
2603  {
2604  if (!PQconnectionUsedPassword(conn))
2605  {
2606  PQfinish(conn);
2607  if (rconn)
2608  pfree(rconn);
2609 
2610  ereport(ERROR,
2611  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2612  errmsg("password is required"),
2613  errdetail("Non-superuser cannot connect if the server does not request a password."),
2614  errhint("Target server's authentication method must be changed.")));
2615  }
2616  }
2617 }
2618 
2619 /*
2620  * For non-superusers, insist that the connstr specify a password. This
2621  * prevents a password from being picked up from .pgpass, a service file,
2622  * the environment, etc. We don't want the postgres user's passwords
2623  * to be accessible to non-superusers.
2624  */
2625 static void
2627 {
2628  if (!superuser())
2629  {
2632  bool connstr_gives_password = false;
2633 
2634  options = PQconninfoParse(connstr, NULL);
2635  if (options)
2636  {
2637  for (option = options; option->keyword != NULL; option++)
2638  {
2639  if (strcmp(option->keyword, "password") == 0)
2640  {
2641  if (option->val != NULL && option->val[0] != '\0')
2642  {
2643  connstr_gives_password = true;
2644  break;
2645  }
2646  }
2647  }
2648  PQconninfoFree(options);
2649  }
2650 
2651  if (!connstr_gives_password)
2652  ereport(ERROR,
2653  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
2654  errmsg("password is required"),
2655  errdetail("Non-superusers must provide a password in the connection string.")));
2656  }
2657 }
2658 
2659 static void
2660 dblink_res_error(PGconn *conn, const char *conname, PGresult *res,
2661  const char *dblink_context_msg, bool fail)
2662 {
2663  int level;
2664  char *pg_diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2665  char *pg_diag_message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2666  char *pg_diag_message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
2667  char *pg_diag_message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
2668  char *pg_diag_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
2669  int sqlstate;
2670  char *message_primary;
2671  char *message_detail;
2672  char *message_hint;
2673  char *message_context;
2674  const char *dblink_context_conname = "unnamed";
2675 
2676  if (fail)
2677  level = ERROR;
2678  else
2679  level = NOTICE;
2680 
2681  if (pg_diag_sqlstate)
2682  sqlstate = MAKE_SQLSTATE(pg_diag_sqlstate[0],
2683  pg_diag_sqlstate[1],
2684  pg_diag_sqlstate[2],
2685  pg_diag_sqlstate[3],
2686  pg_diag_sqlstate[4]);
2687  else
2688  sqlstate = ERRCODE_CONNECTION_FAILURE;
2689 
2690  message_primary = xpstrdup(pg_diag_message_primary);
2691  message_detail = xpstrdup(pg_diag_message_detail);
2692  message_hint = xpstrdup(pg_diag_message_hint);
2693  message_context = xpstrdup(pg_diag_context);
2694 
2695  /*
2696  * If we don't get a message from the PGresult, try the PGconn. This
2697  * is needed because for connection-level failures, PQexec may just
2698  * return NULL, not a PGresult at all.
2699  */
2700  if (message_primary == NULL)
2701  message_primary = pchomp(PQerrorMessage(conn));
2702 
2703  if (res)
2704  PQclear(res);
2705 
2706  if (conname)
2707  dblink_context_conname = conname;
2708 
2709  ereport(level,
2710  (errcode(sqlstate),
2711  message_primary ? errmsg_internal("%s", message_primary) :
2712  errmsg("could not obtain message string for remote error"),
2713  message_detail ? errdetail_internal("%s", message_detail) : 0,
2714  message_hint ? errhint("%s", message_hint) : 0,
2715  message_context ? errcontext("%s", message_context) : 0,
2716  errcontext("Error occurred on dblink connection named \"%s\": %s.",
2717  dblink_context_conname, dblink_context_msg)));
2718 }
2719 
2720 /*
2721  * Obtain connection string for a foreign server
2722  */
2723 static char *
2724 get_connect_string(const char *servername)
2725 {
2726  ForeignServer *foreign_server = NULL;
2727  UserMapping *user_mapping;
2728  ListCell *cell;
2730  ForeignDataWrapper *fdw;
2731  AclResult aclresult;
2732  char *srvname;
2733 
2734  static const PQconninfoOption *options = NULL;
2735 
2736  initStringInfo(&buf);
2737 
2738  /*
2739  * Get list of valid libpq options.
2740  *
2741  * To avoid unnecessary work, we get the list once and use it throughout
2742  * the lifetime of this backend process. We don't need to care about
2743  * memory context issues, because PQconndefaults allocates with malloc.
2744  */
2745  if (!options)
2746  {
2747  options = PQconndefaults();
2748  if (!options) /* assume reason for failure is OOM */
2749  ereport(ERROR,
2750  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
2751  errmsg("out of memory"),
2752  errdetail("could not get libpq's default connection options")));
2753  }
2754 
2755  /* first gather the server connstr options */
2756  srvname = pstrdup(servername);
2757  truncate_identifier(srvname, strlen(srvname), false);
2758  foreign_server = GetForeignServerByName(srvname, true);
2759 
2760  if (foreign_server)
2761  {
2762  Oid serverid = foreign_server->serverid;
2763  Oid fdwid = foreign_server->fdwid;
2764  Oid userid = GetUserId();
2765 
2766  user_mapping = GetUserMapping(userid, serverid);
2767  fdw = GetForeignDataWrapper(fdwid);
2768 
2769  /* Check permissions, user must have usage on the server. */
2770  aclresult = pg_foreign_server_aclcheck(serverid, userid, ACL_USAGE);
2771  if (aclresult != ACLCHECK_OK)
2772  aclcheck_error(aclresult, ACL_KIND_FOREIGN_SERVER, foreign_server->servername);
2773 
2774  foreach(cell, fdw->options)
2775  {
2776  DefElem *def = lfirst(cell);
2777 
2779  appendStringInfo(&buf, "%s='%s' ", def->defname,
2780  escape_param_str(strVal(def->arg)));
2781  }
2782 
2783  foreach(cell, foreign_server->options)
2784  {
2785  DefElem *def = lfirst(cell);
2786 
2788  appendStringInfo(&buf, "%s='%s' ", def->defname,
2789  escape_param_str(strVal(def->arg)));
2790  }
2791 
2792  foreach(cell, user_mapping->options)
2793  {
2794 
2795  DefElem *def = lfirst(cell);
2796 
2798  appendStringInfo(&buf, "%s='%s' ", def->defname,
2799  escape_param_str(strVal(def->arg)));
2800  }
2801 
2802  return buf.data;
2803  }
2804  else
2805  return NULL;
2806 }
2807 
2808 /*
2809  * Escaping libpq connect parameter strings.
2810  *
2811  * Replaces "'" with "\'" and "\" with "\\".
2812  */
2813 static char *
2814 escape_param_str(const char *str)
2815 {
2816  const char *cp;
2818 
2819  initStringInfo(&buf);
2820 
2821  for (cp = str; *cp; cp++)
2822  {
2823  if (*cp == '\\' || *cp == '\'')
2824  appendStringInfoChar(&buf, '\\');
2825  appendStringInfoChar(&buf, *cp);
2826  }
2827 
2828  return buf.data;
2829 }
2830 
2831 /*
2832  * Validate the PK-attnums argument for dblink_build_sql_insert() and related
2833  * functions, and translate to the internal representation.
2834  *
2835  * The user supplies an int2vector of 1-based logical attnums, plus a count
2836  * argument (the need for the separate count argument is historical, but we
2837  * still check it). We check that each attnum corresponds to a valid,
2838  * non-dropped attribute of the rel. We do *not* prevent attnums from being
2839  * listed twice, though the actual use-case for such things is dubious.
2840  * Note that before Postgres 9.0, the user's attnums were interpreted as
2841  * physical not logical column numbers; this was changed for future-proofing.
2842  *
2843  * The internal representation is a palloc'd int array of 0-based physical
2844  * attnums.
2845  */
2846 static void
2848  int2vector *pkattnums_arg, int32 pknumatts_arg,
2849  int **pkattnums, int *pknumatts)
2850 {
2851  TupleDesc tupdesc = rel->rd_att;
2852  int natts = tupdesc->natts;
2853  int i;
2854 
2855  /* Don't take more array elements than there are */
2856  pknumatts_arg = Min(pknumatts_arg, pkattnums_arg->dim1);
2857 
2858  /* Must have at least one pk attnum selected */
2859  if (pknumatts_arg <= 0)
2860  ereport(ERROR,
2861  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2862  errmsg("number of key attributes must be > 0")));
2863 
2864  /* Allocate output array */
2865  *pkattnums = (int *) palloc(pknumatts_arg * sizeof(int));
2866  *pknumatts = pknumatts_arg;
2867 
2868  /* Validate attnums and convert to internal form */
2869  for (i = 0; i < pknumatts_arg; i++)
2870  {
2871  int pkattnum = pkattnums_arg->values[i];
2872  int lnum;
2873  int j;
2874 
2875  /* Can throw error immediately if out of range */
2876  if (pkattnum <= 0 || pkattnum > natts)
2877  ereport(ERROR,
2878  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2879  errmsg("invalid attribute number %d", pkattnum)));
2880 
2881  /* Identify which physical column has this logical number */
2882  lnum = 0;
2883  for (j = 0; j < natts; j++)
2884  {
2885  /* dropped columns don't count */
2886  if (tupdesc->attrs[j]->attisdropped)
2887  continue;
2888 
2889  if (++lnum == pkattnum)
2890  break;
2891  }
2892 
2893  if (j < natts)
2894  (*pkattnums)[i] = j;
2895  else
2896  ereport(ERROR,
2897  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2898  errmsg("invalid attribute number %d", pkattnum)));
2899  }
2900 }
2901 
2902 /*
2903  * Check if the specified connection option is valid.
2904  *
2905  * We basically allow whatever libpq thinks is an option, with these
2906  * restrictions:
2907  * debug options: disallowed
2908  * "client_encoding": disallowed
2909  * "user": valid only in USER MAPPING options
2910  * secure options (eg password): valid only in USER MAPPING options
2911  * others: valid only in FOREIGN SERVER options
2912  *
2913  * We disallow client_encoding because it would be overridden anyway via
2914  * PQclientEncoding; allowing it to be specified would merely promote
2915  * confusion.
2916  */
2917 static bool
2919  Oid context)
2920 {
2921  const PQconninfoOption *opt;
2922 
2923  /* Look up the option in libpq result */
2924  for (opt = options; opt->keyword; opt++)
2925  {
2926  if (strcmp(opt->keyword, option) == 0)
2927  break;
2928  }
2929  if (opt->keyword == NULL)
2930  return false;
2931 
2932  /* Disallow debug options (particularly "replication") */
2933  if (strchr(opt->dispchar, 'D'))
2934  return false;
2935 
2936  /* Disallow "client_encoding" */
2937  if (strcmp(opt->keyword, "client_encoding") == 0)
2938  return false;
2939 
2940  /*
2941  * If the option is "user" or marked secure, it should be specified only
2942  * in USER MAPPING. Others should be specified only in SERVER.
2943  */
2944  if (strcmp(opt->keyword, "user") == 0 || strchr(opt->dispchar, '*'))
2945  {
2946  if (context != UserMappingRelationId)
2947  return false;
2948  }
2949  else
2950  {
2951  if (context != ForeignServerRelationId)
2952  return false;
2953  }
2954 
2955  return true;
2956 }
2957 
2958 /*
2959  * Copy the remote session's values of GUCs that affect datatype I/O
2960  * and apply them locally in a new GUC nesting level. Returns the new
2961  * nestlevel (which is needed by restoreLocalGucs to undo the settings),
2962  * or -1 if no new nestlevel was needed.
2963  *
2964  * We use the equivalent of a function SET option to allow the settings to
2965  * persist only until the caller calls restoreLocalGucs. If an error is
2966  * thrown in between, guc.c will take care of undoing the settings.
2967  */
2968 static int
2970 {
2971  static const char *const GUCsAffectingIO[] = {
2972  "DateStyle",
2973  "IntervalStyle"
2974  };
2975 
2976  int nestlevel = -1;
2977  int i;
2978 
2979  for (i = 0; i < lengthof(GUCsAffectingIO); i++)
2980  {
2981  const char *gucName = GUCsAffectingIO[i];
2982  const char *remoteVal = PQparameterStatus(conn, gucName);
2983  const char *localVal;
2984 
2985  /*
2986  * If the remote server is pre-8.4, it won't have IntervalStyle, but
2987  * that's okay because its output format won't be ambiguous. So just
2988  * skip the GUC if we don't get a value for it. (We might eventually
2989  * need more complicated logic with remote-version checks here.)
2990  */
2991  if (remoteVal == NULL)
2992  continue;
2993 
2994  /*
2995  * Avoid GUC-setting overhead if the remote and local GUCs already
2996  * have the same value.
2997  */
2998  localVal = GetConfigOption(gucName, false, false);
2999  Assert(localVal != NULL);
3000 
3001  if (strcmp(remoteVal, localVal) == 0)
3002  continue;
3003 
3004  /* Create new GUC nest level if we didn't already */
3005  if (nestlevel < 0)
3006  nestlevel = NewGUCNestLevel();
3007 
3008  /* Apply the option (this will throw error on failure) */
3009  (void) set_config_option(gucName, remoteVal,
3011  GUC_ACTION_SAVE, true, 0, false);
3012  }
3013 
3014  return nestlevel;
3015 }
3016 
3017 /*
3018  * Restore local GUCs after they have been overlaid with remote settings.
3019  */
3020 static void
3021 restoreLocalGucs(int nestlevel)
3022 {
3023  /* Do nothing if no new nestlevel was created */
3024  if (nestlevel > 0)
3025  AtEOXact_GUC(true, nestlevel);
3026 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:735
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_superuser)
Definition: guc.c:6663
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:226
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:6011
int openCursorCount
Definition: dblink.c:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:569
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:5976
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:1989
#define PointerGetDatum(X)
Definition: postgres.h:562
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:225
#define IndexRelationId
Definition: pg_index.h:29
void PQfreeCancel(PGcancel *cancel)
Definition: fe-connect.c:3712
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:248
int SPI_finish(void)
Definition: spi.c:147
#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:306
#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:3568
bool superuser(void)
Definition: superuser.c:47
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1263
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:233
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
HeapTuple SPI_copytuple(HeapTuple tuple)
Definition: spi.c:630
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:2857
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:576
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:231
#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:113
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:27
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:6071
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:265
#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:781
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:803
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:71
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
uint32 AclMode
Definition: parsenodes.h:63
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:4655
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:331
#define FALSE
Definition: c.h:221
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:2270
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:715
AclResult pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4496
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:3006
static char * buf
Definition: pg_test_fsync.c:65
#define PG_GETARG_OID(n)
Definition: fmgr.h:232
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3377
int PQsetSingleRowMode(PGconn *conn)
Definition: fe-exec.c:1604
PGcancel * PQgetCancel(PGconn *conn)
Definition: fe-connect.c:3689
AttInMetadata * attinmeta
Definition: funcapi.h:99
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5046
int errdetail(const char *fmt,...)
Definition: elog.c:873
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5861
#define RelationGetRelationName(relation)
Definition: rel.h:433
fmNodePtr resultinfo
Definition: fmgr.h:73
List * options
Definition: foreign.h:61
#define ACL_USAGE
Definition: parsenodes.h:73
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:493
#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:3057
Node * arg
Definition: parsenodes.h:709
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:5966
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:10200
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:316
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:305
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
#define ACL_SELECT
Definition: parsenodes.h:66
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1068
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
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:898
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6079
TupleDesc rd_att
Definition: rel.h:114
#define SPI_OK_SELECT
Definition: spi.h:51
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1315
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:60
int allowedModes
Definition: execnodes.h:201
void PQclear(PGresult *res)
Definition: fe-exec.c:650
#define NOTICE
Definition: elog.h:37
#define PG_RETURN_VOID()
Definition: fmgr.h:301
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:322
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:203
#define ForeignServerRelationId
#define PG_CATCH()
Definition: elog.h:293
text * cstring_to_text(const char *s)
Definition: varlena.c:151
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:1107
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:109
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:450
#define ForeignDataWrapperRelationId
#define PG_NARGS()
Definition: fmgr.h:160
#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:1353
#define BOOLOID
Definition: pg_type.h:288
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:135
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:1343
const char * name
Definition: encode.c:521
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4396
Tuplestorestate * setResult
Definition: execnodes.h:206
static Datum values[MAXATTR]
Definition: bootstrap.c:162
char * text_to_cstring(const text *t)
Definition: varlena.c:184
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:6060
ExprContext * econtext
Definition: execnodes.h:199
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
Definition: fe-connect.c:3844
#define Int32GetDatum(X)
Definition: postgres.h:485
int NewGUCNestLevel(void)
Definition: guc.c:5032
FunctionCallInfo fcinfo
Definition: dblink.c:75
void * user_fctx
Definition: funcapi.h:90
TupleDesc setDesc
Definition: execnodes.h:207
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:150
char * defname
Definition: parsenodes.h:708
#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:5958
#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:5875
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:413
#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:297
#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:526
#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