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