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