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