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