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