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