dblink.c 46.4 KB
Newer Older
1 2 3 4 5
/*
 * dblink.c
 *
 * Functions returning results from a remote database
 *
6
 * Joe Conway <mail@joeconway.com>
7 8 9
 * And contributors:
 * Darko Prenosil <Darko.Prenosil@finteh.hr>
 * Shridhar Daithankar <shridhar_daithankar@persistent.co.in>
10
 *
11
 * Copyright (c) 2001-2003, PostgreSQL Global Development Group
12
 * ALL RIGHTS RESERVED;
13
 *
14 15 16 17
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without a written agreement
 * is hereby granted, provided that the above copyright notice and this
 * paragraph and the following two paragraphs appear in all copies.
18
 *
19 20 21 22 23
 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
 * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
24
 *
25 26 27 28 29 30 31
 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 */
32
#include "postgres.h"
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include "libpq-fe.h"
#include "fmgr.h"
#include "funcapi.h"
#include "access/tupdesc.h"
#include "access/heapam.h"
#include "catalog/catname.h"
#include "catalog/namespace.h"
#include "catalog/pg_index.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "lib/stringinfo.h"
#include "nodes/nodes.h"
#include "nodes/execnodes.h"
#include "nodes/pg_list.h"
#include "parser/parse_type.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/array.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
56 57 58
#include "utils/dynahash.h"
#include "utils/hsearch.h"
#include "utils/memutils.h"
59

60
#include "dblink.h"
61

62 63
typedef struct remoteConn
{
Bruce Momjian's avatar
Bruce Momjian committed
64 65 66 67
	PGconn	   *con;			/* Hold the remote connection */
	bool		remoteTrFlag;	/* Indicates whether or not a transaction
								 * on remote database is in progress */
}	remoteConn;
68

69 70 71
/*
 * Internal declarations
 */
72 73
static remoteConn *getConnectionByName(const char *name);
static HTAB *createConnHash(void);
Bruce Momjian's avatar
Bruce Momjian committed
74
static void createNewConnection(const char *name, remoteConn * con);
75
static void deleteConnection(const char *name);
76 77 78 79 80 81 82 83
static char **get_pkey_attnames(Oid relid, int16 *numatts);
static char *get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals);
static char *get_sql_delete(Oid relid, int16 *pkattnums, int16 pknumatts, char **tgt_pkattvals);
static char *get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals);
static char *quote_literal_cstr(char *rawstr);
static char *quote_ident_cstr(char *rawstr);
static int16 get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key);
static HeapTuple get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals);
Bruce Momjian's avatar
Bruce Momjian committed
84
static Oid	get_relid_from_relname(text *relname_text);
85
static char *generate_relation_name(Oid relid);
86

87
/* Global */
Bruce Momjian's avatar
Bruce Momjian committed
88 89 90 91
List	   *res_id = NIL;
int			res_id_index = 0;
PGconn	   *persistent_conn = NULL;
static HTAB *remoteConnHash = NULL;
92

Bruce Momjian's avatar
Bruce Momjian committed
93
/*
94 95
Following is list that holds multiple remote connections.
Calling convention of each dblink function changes to accept
Bruce Momjian's avatar
Bruce Momjian committed
96
connection name as the first parameter. The connection list is
97 98 99 100 101 102 103
much like ecpg e.g. a mapping between a name and a PGconn object.
*/

typedef struct remoteConnHashEnt
{
	char		name[NAMEDATALEN];
	remoteConn *rcon;
Bruce Momjian's avatar
Bruce Momjian committed
104
}	remoteConnHashEnt;
105 106 107

/* initial number of connection hashes */
#define NUMCONN 16
108

109
/* general utility */
110 111 112 113 114 115 116 117 118 119
#define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
#define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
#define xpfree(var_) \
	do { \
		if (var_ != NULL) \
		{ \
			pfree(var_); \
			var_ = NULL; \
		} \
	} while (0)
120 121 122 123 124 125 126 127
#define DBLINK_RES_INTERNALERROR(p2) \
	do { \
			msg = pstrdup(PQerrorMessage(conn)); \
			if (res) \
				PQclear(res); \
			elog(ERROR, "%s: %s", p2, msg); \
	} while (0)
#define DBLINK_RES_ERROR(p2) \
128 129 130 131
	do { \
			msg = pstrdup(PQerrorMessage(conn)); \
			if (res) \
				PQclear(res); \
132 133 134 135
			ereport(ERROR, \
					(errcode(ERRCODE_SYNTAX_ERROR), \
					 errmsg("%s", p2), \
					 errdetail("%s", msg))); \
136
	} while (0)
137
#define DBLINK_CONN_NOT_AVAIL \
138 139
	do { \
		if(conname) \
140 141 142
			ereport(ERROR, \
					(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST), \
					 errmsg("connection \"%s\" not available", conname))); \
143
		else \
144 145 146
			ereport(ERROR, \
					(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST), \
					 errmsg("connection not available"))); \
147
	} while (0)
148
#define DBLINK_GET_CONN \
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
	do { \
			char *conname_or_str = GET_STR(PG_GETARG_TEXT_P(0)); \
			rcon = getConnectionByName(conname_or_str); \
			if(rcon) \
			{ \
				conn = rcon->con; \
				freeconn = false; \
			} \
			else \
			{ \
				connstr = conname_or_str; \
				conn = PQconnectdb(connstr); \
				if (PQstatus(conn) == CONNECTION_BAD) \
				{ \
					msg = pstrdup(PQerrorMessage(conn)); \
					PQfinish(conn); \
165 166 167 168
					ereport(ERROR, \
							(errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION), \
							 errmsg("could not establish connection"), \
							 errdetail("%s", msg))); \
169 170 171
				} \
			} \
	} while (0)
172 173 174 175 176 177 178 179 180


/*
 * Create a persistent connection to another database
 */
PG_FUNCTION_INFO_V1(dblink_connect);
Datum
dblink_connect(PG_FUNCTION_ARGS)
{
181 182
	char	   *connstr = NULL;
	char	   *connname = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
183 184
	char	   *msg;
	MemoryContext oldcontext;
185 186
	PGconn	   *conn = NULL;
	remoteConn *rcon = NULL;
187

Bruce Momjian's avatar
Bruce Momjian committed
188
	if (PG_NARGS() == 2)
189 190 191 192
	{
		connstr = GET_STR(PG_GETARG_TEXT_P(1));
		connname = GET_STR(PG_GETARG_TEXT_P(0));
	}
Bruce Momjian's avatar
Bruce Momjian committed
193
	else if (PG_NARGS() == 1)
194
		connstr = GET_STR(PG_GETARG_TEXT_P(0));
195 196

	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
197

Bruce Momjian's avatar
Bruce Momjian committed
198 199
	if (connname)
		rcon = (remoteConn *) palloc(sizeof(remoteConn));
200 201
	conn = PQconnectdb(connstr);

202 203
	MemoryContextSwitchTo(oldcontext);

204
	if (PQstatus(conn) == CONNECTION_BAD)
205
	{
206 207
		msg = pstrdup(PQerrorMessage(conn));
		PQfinish(conn);
Bruce Momjian's avatar
Bruce Momjian committed
208
		if (rcon)
209
			pfree(rcon);
210 211

		ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
212 213 214
		   (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
			errmsg("could not establish connection"),
			errdetail("%s", msg)));
215 216
	}

Bruce Momjian's avatar
Bruce Momjian committed
217
	if (connname)
218 219
	{
		rcon->con = conn;
220
		createNewConnection(connname, rcon);
221 222 223 224 225
	}
	else
		persistent_conn = conn;

	PG_RETURN_TEXT_P(GET_TEXT("OK"));
226 227 228 229 230 231 232 233 234
}

/*
 * Clear a persistent connection to another database
 */
PG_FUNCTION_INFO_V1(dblink_disconnect);
Datum
dblink_disconnect(PG_FUNCTION_ARGS)
{
235
	char	   *conname = NULL;
236 237 238
	remoteConn *rcon = NULL;
	PGconn	   *conn = NULL;

Bruce Momjian's avatar
Bruce Momjian committed
239
	if (PG_NARGS() == 1)
240
	{
241 242
		conname = GET_STR(PG_GETARG_TEXT_P(0));
		rcon = getConnectionByName(conname);
243 244 245 246 247
		if (rcon)
			conn = rcon->con;
	}
	else
		conn = persistent_conn;
248

249
	if (!conn)
250
		DBLINK_CONN_NOT_AVAIL;
251

252 253 254
	PQfinish(conn);
	if (rcon)
	{
255
		deleteConnection(conname);
256 257
		pfree(rcon);
	}
258 259
	else
		persistent_conn = NULL;
260

261
	PG_RETURN_TEXT_P(GET_TEXT("OK"));
262 263 264 265 266 267 268 269 270
}

/*
 * opens a cursor using a persistent connection
 */
PG_FUNCTION_INFO_V1(dblink_open);
Datum
dblink_open(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
271 272 273
	char	   *msg;
	PGresult   *res = NULL;
	PGconn	   *conn = NULL;
274 275 276
	char	   *curname = NULL;
	char	   *sql = NULL;
	char	   *conname = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
277
	StringInfo	str = makeStringInfo();
278
	remoteConn *rcon = NULL;
279

Bruce Momjian's avatar
Bruce Momjian committed
280
	if (PG_NARGS() == 2)
281 282 283
	{
		curname = GET_STR(PG_GETARG_TEXT_P(0));
		sql = GET_STR(PG_GETARG_TEXT_P(1));
284
		conn = persistent_conn;
285
	}
Bruce Momjian's avatar
Bruce Momjian committed
286
	else if (PG_NARGS() == 3)
287 288 289 290 291 292 293 294 295 296
	{
		conname = GET_STR(PG_GETARG_TEXT_P(0));
		curname = GET_STR(PG_GETARG_TEXT_P(1));
		sql = GET_STR(PG_GETARG_TEXT_P(2));
		rcon = getConnectionByName(conname);
		if (rcon)
			conn = rcon->con;
	}

	if (!conn)
297
		DBLINK_CONN_NOT_AVAIL;
298 299 300

	res = PQexec(conn, "BEGIN");
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
301
		DBLINK_RES_INTERNALERROR("begin error");
302 303 304

	PQclear(res);

305
	appendStringInfo(str, "DECLARE %s CURSOR FOR %s", curname, sql);
306 307 308 309
	res = PQexec(conn, str->data);
	if (!res ||
		(PQresultStatus(res) != PGRES_COMMAND_OK &&
		 PQresultStatus(res) != PGRES_TUPLES_OK))
310
		DBLINK_RES_ERROR("sql error");
311

312
	PQclear(res);
313

314
	PG_RETURN_TEXT_P(GET_TEXT("OK"));
315
}
316

317 318 319 320 321 322 323
/*
 * closes a cursor
 */
PG_FUNCTION_INFO_V1(dblink_close);
Datum
dblink_close(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
324 325
	PGconn	   *conn = NULL;
	PGresult   *res = NULL;
326 327
	char	   *curname = NULL;
	char	   *conname = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
328 329
	StringInfo	str = makeStringInfo();
	char	   *msg;
330
	remoteConn *rcon = NULL;
331

332 333 334
	if (PG_NARGS() == 1)
	{
		curname = GET_STR(PG_GETARG_TEXT_P(0));
335
		conn = persistent_conn;
336
	}
Bruce Momjian's avatar
Bruce Momjian committed
337
	else if (PG_NARGS() == 2)
338 339 340 341
	{
		conname = GET_STR(PG_GETARG_TEXT_P(0));
		curname = GET_STR(PG_GETARG_TEXT_P(1));
		rcon = getConnectionByName(conname);
Bruce Momjian's avatar
Bruce Momjian committed
342
		if (rcon)
343 344 345 346
			conn = rcon->con;
	}

	if (!conn)
347
		DBLINK_CONN_NOT_AVAIL;
348

349
	appendStringInfo(str, "CLOSE %s", curname);
350 351 352

	/* close the cursor */
	res = PQexec(conn, str->data);
Bruce Momjian's avatar
Bruce Momjian committed
353
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
354
		DBLINK_RES_ERROR("sql error");
355 356 357 358 359 360

	PQclear(res);

	/* commit the transaction */
	res = PQexec(conn, "COMMIT");
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
361
		DBLINK_RES_INTERNALERROR("commit error");
362 363 364

	PQclear(res);

365
	PG_RETURN_TEXT_P(GET_TEXT("OK"));
366 367 368 369 370 371 372 373 374
}

/*
 * Fetch results from an open cursor
 */
PG_FUNCTION_INFO_V1(dblink_fetch);
Datum
dblink_fetch(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
375 376 377 378 379 380 381 382 383
	FuncCallContext *funcctx;
	TupleDesc	tupdesc = NULL;
	int			call_cntr;
	int			max_calls;
	TupleTableSlot *slot;
	AttInMetadata *attinmeta;
	char	   *msg;
	PGresult   *res = NULL;
	MemoryContext oldcontext;
384
	char	   *conname = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
385
	remoteConn *rcon = NULL;
386 387

	/* stuff done only on the first call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
388 389 390 391 392 393 394
	if (SRF_IS_FIRSTCALL())
	{
		Oid			functypeid;
		char		functyptype;
		Oid			funcid = fcinfo->flinfo->fn_oid;
		PGconn	   *conn = NULL;
		StringInfo	str = makeStringInfo();
395 396
		char	   *curname = NULL;
		int			howmany = 0;
397
		ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
398 399 400 401 402 403 404 405

		if (PG_NARGS() == 3)
		{
			conname = GET_STR(PG_GETARG_TEXT_P(0));
			curname = GET_STR(PG_GETARG_TEXT_P(1));
			howmany = PG_GETARG_INT32(2);

			rcon = getConnectionByName(conname);
Bruce Momjian's avatar
Bruce Momjian committed
406
			if (rcon)
407 408 409 410 411 412 413 414 415
				conn = rcon->con;
		}
		else if (PG_NARGS() == 2)
		{
			curname = GET_STR(PG_GETARG_TEXT_P(0));
			howmany = PG_GETARG_INT32(1);
			conn = persistent_conn;
		}

Bruce Momjian's avatar
Bruce Momjian committed
416
		if (!conn)
417
			DBLINK_CONN_NOT_AVAIL;
418 419

		/* create a function context for cross-call persistence */
Bruce Momjian's avatar
Bruce Momjian committed
420
		funcctx = SRF_FIRSTCALL_INIT();
421

Bruce Momjian's avatar
Bruce Momjian committed
422 423 424 425
		/*
		 * switch to memory context appropriate for multiple function
		 * calls
		 */
426 427
		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

428
		appendStringInfo(str, "FETCH %d FROM %s", howmany, curname);
429 430 431 432 433

		res = PQexec(conn, str->data);
		if (!res ||
			(PQresultStatus(res) != PGRES_COMMAND_OK &&
			 PQresultStatus(res) != PGRES_TUPLES_OK))
434
			DBLINK_RES_ERROR("sql error");
435 436 437 438
		else if (PQresultStatus(res) == PGRES_COMMAND_OK)
		{
			/* cursor does not exist - closed already or bad name */
			PQclear(res);
439 440 441
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_CURSOR_NAME),
					 errmsg("cursor \"%s\" does not exist", curname)));
442 443 444 445 446 447 448 449 450
		}

		funcctx->max_calls = PQntuples(res);

		/* got results, keep track of them */
		funcctx->user_fctx = res;

		/* fast track when no results */
		if (funcctx->max_calls < 1)
Bruce Momjian's avatar
Bruce Momjian committed
451
			SRF_RETURN_DONE(funcctx);
452 453 454 455 456 457 458 459

		/* check typtype to see if we have a predetermined return type */
		functypeid = get_func_rettype(funcid);
		functyptype = get_typtype(functypeid);

		if (functyptype == 'c')
			tupdesc = TypeGetTupleDesc(functypeid, NIL);
		else if (functyptype == 'p' && functypeid == RECORDOID)
460 461 462 463 464 465 466 467 468 469
		{
			if (!rsinfo || !IsA(rsinfo, ReturnSetInfo))
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("function returning record called in context "
								"that cannot accept type record")));

			/* get the requested return tuple description */
			tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
		}
470
		else
471 472
			/* shouldn't happen */
			elog(ERROR, "return type must be a row type");
473 474 475 476 477 478 479 480

		/* store needed metadata for subsequent calls */
		slot = TupleDescGetSlot(tupdesc);
		funcctx->slot = slot;
		attinmeta = TupleDescGetAttInMetadata(tupdesc);
		funcctx->attinmeta = attinmeta;

		MemoryContextSwitchTo(oldcontext);
Bruce Momjian's avatar
Bruce Momjian committed
481
	}
482 483

	/* stuff done on every call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
484
	funcctx = SRF_PERCALL_SETUP();
485 486 487 488 489 490 491 492 493 494 495 496 497 498

	/*
	 * initialize per-call variables
	 */
	call_cntr = funcctx->call_cntr;
	max_calls = funcctx->max_calls;

	slot = funcctx->slot;

	res = (PGresult *) funcctx->user_fctx;
	attinmeta = funcctx->attinmeta;
	tupdesc = attinmeta->tupdesc;

	if (call_cntr < max_calls)	/* do when there is more left to send */
Bruce Momjian's avatar
Bruce Momjian committed
499
	{
500 501 502
		char	  **values;
		HeapTuple	tuple;
		Datum		result;
Bruce Momjian's avatar
Bruce Momjian committed
503 504
		int			i;
		int			nfields = PQnfields(res);
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

		values = (char **) palloc(nfields * sizeof(char *));
		for (i = 0; i < nfields; i++)
		{
			if (PQgetisnull(res, call_cntr, i) == 0)
				values[i] = PQgetvalue(res, call_cntr, i);
			else
				values[i] = NULL;
		}

		/* build the tuple */
		tuple = BuildTupleFromCStrings(attinmeta, values);

		/* make the tuple into a datum */
		result = TupleGetDatum(slot, tuple);

Bruce Momjian's avatar
Bruce Momjian committed
521
		SRF_RETURN_NEXT(funcctx, result);
522
	}
Bruce Momjian's avatar
Bruce Momjian committed
523
	else
524
	{
525
		/* do when there is no more left */
526
		PQclear(res);
Bruce Momjian's avatar
Bruce Momjian committed
527
		SRF_RETURN_DONE(funcctx);
528 529 530 531 532 533 534 535 536 537
	}
}

/*
 * Note: this is the new preferred version of dblink
 */
PG_FUNCTION_INFO_V1(dblink_record);
Datum
dblink_record(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
538 539 540 541 542 543 544 545 546 547 548
	FuncCallContext *funcctx;
	TupleDesc	tupdesc = NULL;
	int			call_cntr;
	int			max_calls;
	TupleTableSlot *slot;
	AttInMetadata *attinmeta;
	char	   *msg;
	PGresult   *res = NULL;
	bool		is_sql_cmd = false;
	char	   *sql_cmd_status = NULL;
	MemoryContext oldcontext;
549
	bool		freeconn = true;
550 551

	/* stuff done only on the first call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
552 553 554 555 556 557 558 559
	if (SRF_IS_FIRSTCALL())
	{
		Oid			functypeid;
		char		functyptype;
		Oid			funcid = fcinfo->flinfo->fn_oid;
		PGconn	   *conn = NULL;
		char	   *connstr = NULL;
		char	   *sql = NULL;
560
		char	   *conname = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
561
		remoteConn *rcon = NULL;
562
		ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
563 564

		/* create a function context for cross-call persistence */
Bruce Momjian's avatar
Bruce Momjian committed
565
		funcctx = SRF_FIRSTCALL_INIT();
566

Bruce Momjian's avatar
Bruce Momjian committed
567 568 569 570
		/*
		 * switch to memory context appropriate for multiple function
		 * calls
		 */
571 572
		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

573
		if (PG_NARGS() == 2)
574
		{
575
			DBLINK_GET_CONN;
576 577
			sql = GET_STR(PG_GETARG_TEXT_P(1));
		}
578
		else if (PG_NARGS() == 1)
579
		{
580
			conn = persistent_conn;
581 582 583
			sql = GET_STR(PG_GETARG_TEXT_P(0));
		}
		else
584 585
			/* shouldn't happen */
			elog(ERROR, "wrong number of arguments");
586

Bruce Momjian's avatar
Bruce Momjian committed
587
		if (!conn)
588
			DBLINK_CONN_NOT_AVAIL;
589

590 591
		res = PQexec(conn, sql);
		if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK))
592
			DBLINK_RES_ERROR("sql error");
593 594

		if (PQresultStatus(res) == PGRES_COMMAND_OK)
595
		{
596 597 598 599 600 601
			is_sql_cmd = true;

			/* need a tuple descriptor representing one TEXT column */
			tupdesc = CreateTemplateTupleDesc(1, false);
			TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
							   TEXTOID, -1, 0, false);
602

603
			/*
Bruce Momjian's avatar
Bruce Momjian committed
604 605
			 * and save a copy of the command status string to return as
			 * our result tuple
606 607 608
			 */
			sql_cmd_status = PQcmdStatus(res);
			funcctx->max_calls = 1;
609 610
		}
		else
611
			funcctx->max_calls = PQntuples(res);
612

613 614
		/* got results, keep track of them */
		funcctx->user_fctx = res;
615

616 617 618
		/* if needed, close the connection to the database and cleanup */
		if (freeconn && PG_NARGS() == 2)
			PQfinish(conn);
619 620 621

		/* fast track when no results */
		if (funcctx->max_calls < 1)
Bruce Momjian's avatar
Bruce Momjian committed
622
			SRF_RETURN_DONE(funcctx);
623 624 625 626 627 628 629 630 631 632

		/* check typtype to see if we have a predetermined return type */
		functypeid = get_func_rettype(funcid);
		functyptype = get_typtype(functypeid);

		if (!is_sql_cmd)
		{
			if (functyptype == 'c')
				tupdesc = TypeGetTupleDesc(functypeid, NIL);
			else if (functyptype == 'p' && functypeid == RECORDOID)
633 634 635 636 637 638 639 640 641 642
			{
				if (!rsinfo || !IsA(rsinfo, ReturnSetInfo))
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("function returning record called in context "
									"that cannot accept type record")));

				/* get the requested return tuple description */
				tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
			}
643
			else
644 645
				/* shouldn't happen */
				elog(ERROR, "return type must be a row type");
646 647 648 649 650 651 652 653 654
		}

		/* store needed metadata for subsequent calls */
		slot = TupleDescGetSlot(tupdesc);
		funcctx->slot = slot;
		attinmeta = TupleDescGetAttInMetadata(tupdesc);
		funcctx->attinmeta = attinmeta;

		MemoryContextSwitchTo(oldcontext);
Bruce Momjian's avatar
Bruce Momjian committed
655
	}
656 657

	/* stuff done on every call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
658
	funcctx = SRF_PERCALL_SETUP();
659 660 661 662 663 664 665 666 667 668 669 670 671 672

	/*
	 * initialize per-call variables
	 */
	call_cntr = funcctx->call_cntr;
	max_calls = funcctx->max_calls;

	slot = funcctx->slot;

	res = (PGresult *) funcctx->user_fctx;
	attinmeta = funcctx->attinmeta;
	tupdesc = attinmeta->tupdesc;

	if (call_cntr < max_calls)	/* do when there is more left to send */
Bruce Momjian's avatar
Bruce Momjian committed
673
	{
674 675 676 677 678 679
		char	  **values;
		HeapTuple	tuple;
		Datum		result;

		if (!is_sql_cmd)
		{
Bruce Momjian's avatar
Bruce Momjian committed
680 681
			int			i;
			int			nfields = PQnfields(res);
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

			values = (char **) palloc(nfields * sizeof(char *));
			for (i = 0; i < nfields; i++)
			{
				if (PQgetisnull(res, call_cntr, i) == 0)
					values[i] = PQgetvalue(res, call_cntr, i);
				else
					values[i] = NULL;
			}
		}
		else
		{
			values = (char **) palloc(1 * sizeof(char *));
			values[0] = sql_cmd_status;
		}

		/* build the tuple */
		tuple = BuildTupleFromCStrings(attinmeta, values);

		/* make the tuple into a datum */
		result = TupleGetDatum(slot, tuple);

Bruce Momjian's avatar
Bruce Momjian committed
704
		SRF_RETURN_NEXT(funcctx, result);
705
	}
Bruce Momjian's avatar
Bruce Momjian committed
706
	else
707
	{
708
		/* do when there is no more left */
709
		PQclear(res);
Bruce Momjian's avatar
Bruce Momjian committed
710
		SRF_RETURN_DONE(funcctx);
711 712 713 714 715 716 717 718 719 720
	}
}

/*
 * Execute an SQL non-SELECT command
 */
PG_FUNCTION_INFO_V1(dblink_exec);
Datum
dblink_exec(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
721 722
	char	   *msg;
	PGresult   *res = NULL;
723
	text	   *sql_cmd_status = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
724 725 726 727
	TupleDesc	tupdesc = NULL;
	PGconn	   *conn = NULL;
	char	   *connstr = NULL;
	char	   *sql = NULL;
728
	char	   *conname = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
729
	remoteConn *rcon = NULL;
730
	bool		freeconn = true;
731

732
	if (PG_NARGS() == 2)
733
	{
734
		DBLINK_GET_CONN;
735 736
		sql = GET_STR(PG_GETARG_TEXT_P(1));
	}
737
	else if (PG_NARGS() == 1)
738
	{
739
		conn = persistent_conn;
740 741 742
		sql = GET_STR(PG_GETARG_TEXT_P(0));
	}
	else
743 744
		/* shouldn't happen */
		elog(ERROR, "wrong number of arguments");
745

Bruce Momjian's avatar
Bruce Momjian committed
746
	if (!conn)
747
		DBLINK_CONN_NOT_AVAIL;
748 749

	res = PQexec(conn, sql);
750 751 752
	if (!res ||
		(PQresultStatus(res) != PGRES_COMMAND_OK &&
		 PQresultStatus(res) != PGRES_TUPLES_OK))
753
		DBLINK_RES_ERROR("sql error");
754 755

	if (PQresultStatus(res) == PGRES_COMMAND_OK)
756
	{
757 758 759 760
		/* need a tuple descriptor representing one TEXT column */
		tupdesc = CreateTemplateTupleDesc(1, false);
		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
						   TEXTOID, -1, 0, false);
761

762
		/*
Bruce Momjian's avatar
Bruce Momjian committed
763 764
		 * and save a copy of the command status string to return as our
		 * result tuple
765 766
		 */
		sql_cmd_status = GET_TEXT(PQcmdStatus(res));
767 768
	}
	else
769
		ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
770 771
			  (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
			   errmsg("statement returning results not allowed")));
772 773 774 775

	PQclear(res);

	/* if needed, close the connection to the database and cleanup */
776
	if (freeconn && fcinfo->nargs == 2)
777 778
		PQfinish(conn);

779
	PG_RETURN_TEXT_P(sql_cmd_status);
780 781
}

782

783 784
/*
 * dblink_get_pkey
Bruce Momjian's avatar
Bruce Momjian committed
785
 *
786
 * Return list of primary key fields for the supplied relation,
787 788 789 790 791 792
 * or NULL if none exists.
 */
PG_FUNCTION_INFO_V1(dblink_get_pkey);
Datum
dblink_get_pkey(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
793 794 795 796 797 798 799 800 801
	int16		numatts;
	Oid			relid;
	char	  **results;
	FuncCallContext *funcctx;
	int32		call_cntr;
	int32		max_calls;
	TupleTableSlot *slot;
	AttInMetadata *attinmeta;
	MemoryContext oldcontext;
802 803

	/* stuff done only on the first call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
804 805 806
	if (SRF_IS_FIRSTCALL())
	{
		TupleDesc	tupdesc = NULL;
807 808

		/* create a function context for cross-call persistence */
Bruce Momjian's avatar
Bruce Momjian committed
809
		funcctx = SRF_FIRSTCALL_INIT();
810

Bruce Momjian's avatar
Bruce Momjian committed
811 812 813 814
		/*
		 * switch to memory context appropriate for multiple function
		 * calls
		 */
815 816 817 818 819
		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

		/* convert relname to rel Oid */
		relid = get_relid_from_relname(PG_GETARG_TEXT_P(0));
		if (!OidIsValid(relid))
820 821 822 823
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_TABLE),
					 errmsg("relation \"%s\" does not exist",
							GET_STR(PG_GETARG_TEXT_P(0)))));
Bruce Momjian's avatar
Bruce Momjian committed
824

Bruce Momjian's avatar
Bruce Momjian committed
825 826 827 828
		/*
		 * need a tuple descriptor representing one INT and one TEXT
		 * column
		 */
829
		tupdesc = CreateTemplateTupleDesc(2, false);
830 831 832 833
		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
						   INT4OID, -1, 0, false);
		TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
						   TEXTOID, -1, 0, false);
834

835 836
		/* allocate a slot for a tuple with this tupdesc */
		slot = TupleDescGetSlot(tupdesc);
837

838 839
		/* assign slot to function context */
		funcctx->slot = slot;
840 841

		/*
Bruce Momjian's avatar
Bruce Momjian committed
842 843
		 * Generate attribute metadata needed later to produce tuples from
		 * raw C strings
844
		 */
845 846 847 848 849
		attinmeta = TupleDescGetAttInMetadata(tupdesc);
		funcctx->attinmeta = attinmeta;

		/* get an array of attnums */
		results = get_pkey_attnames(relid, &numatts);
850

851
		if ((results != NULL) && (numatts > 0))
852
		{
853
			funcctx->max_calls = numatts;
854

855 856 857
			/* got results, keep track of them */
			funcctx->user_fctx = results;
		}
Bruce Momjian's avatar
Bruce Momjian committed
858
		else
859
			/* fast track when no results */
Bruce Momjian's avatar
Bruce Momjian committed
860
			SRF_RETURN_DONE(funcctx);
861

862
		MemoryContextSwitchTo(oldcontext);
Bruce Momjian's avatar
Bruce Momjian committed
863
	}
864

865
	/* stuff done on every call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
866
	funcctx = SRF_PERCALL_SETUP();
867

868 869 870 871 872
	/*
	 * initialize per-call variables
	 */
	call_cntr = funcctx->call_cntr;
	max_calls = funcctx->max_calls;
873

874
	slot = funcctx->slot;
875

876 877
	results = (char **) funcctx->user_fctx;
	attinmeta = funcctx->attinmeta;
878

879
	if (call_cntr < max_calls)	/* do when there is more left to send */
Bruce Momjian's avatar
Bruce Momjian committed
880
	{
881 882 883
		char	  **values;
		HeapTuple	tuple;
		Datum		result;
884

885
		values = (char **) palloc(2 * sizeof(char *));
Bruce Momjian's avatar
Bruce Momjian committed
886
		values[0] = (char *) palloc(12);		/* sign, 10 digits, '\0' */
887

888
		sprintf(values[0], "%d", call_cntr + 1);
889

890
		values[1] = results[call_cntr];
891

892 893
		/* build the tuple */
		tuple = BuildTupleFromCStrings(attinmeta, values);
894

895 896 897
		/* make the tuple into a datum */
		result = TupleGetDatum(slot, tuple);

Bruce Momjian's avatar
Bruce Momjian committed
898
		SRF_RETURN_NEXT(funcctx, result);
899
	}
Bruce Momjian's avatar
Bruce Momjian committed
900
	else
901
	{
902 903
		/* do when there is no more left */
		SRF_RETURN_DONE(funcctx);
904 905 906 907
	}
}


908 909 910
#ifndef SHRT_MAX
#define SHRT_MAX (0x7FFF)
#endif
911 912
/*
 * dblink_build_sql_insert
Bruce Momjian's avatar
Bruce Momjian committed
913
 *
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
 * Used to generate an SQL insert statement
 * based on an existing tuple in a local relation.
 * This is useful for selectively replicating data
 * to another server via dblink.
 *
 * API:
 * <relname> - name of local table of interest
 * <pkattnums> - an int2vector of attnums which will be used
 * to identify the local tuple of interest
 * <pknumatts> - number of attnums in pkattnums
 * <src_pkattvals_arry> - text array of key values which will be used
 * to identify the local tuple of interest
 * <tgt_pkattvals_arry> - text array of key values which will be used
 * to build the string for execution remotely. These are substituted
 * for their counterparts in src_pkattvals_arry
 */
PG_FUNCTION_INFO_V1(dblink_build_sql_insert);
Datum
dblink_build_sql_insert(PG_FUNCTION_ARGS)
{
	Oid			relid;
935 936
	text	   *relname_text;
	int16	   *pkattnums;
937 938
	int			pknumatts_tmp;
	int16		pknumatts = 0;
939 940 941 942
	char	  **src_pkattvals;
	char	  **tgt_pkattvals;
	ArrayType  *src_pkattvals_arry;
	ArrayType  *tgt_pkattvals_arry;
943
	int			src_ndim;
944
	int		   *src_dim;
945 946
	int			src_nitems;
	int			tgt_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
947
	int		   *tgt_dim;
948 949
	int			tgt_nitems;
	int			i;
950 951 952 953 954
	char	   *ptr;
	char	   *sql;
	int16		typlen;
	bool		typbyval;
	char		typalign;
955

956
	relname_text = PG_GETARG_TEXT_P(0);
957 958 959 960

	/*
	 * Convert relname to rel OID.
	 */
961
	relid = get_relid_from_relname(relname_text);
962
	if (!OidIsValid(relid))
963 964 965 966
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_TABLE),
				 errmsg("relation \"%s\" does not exist",
						GET_STR(relname_text))));
967 968

	pkattnums = (int16 *) PG_GETARG_POINTER(1);
969 970 971 972
	pknumatts_tmp = PG_GETARG_INT32(2);
	if (pknumatts_tmp <= SHRT_MAX)
		pknumatts = pknumatts_tmp;
	else
973 974 975 976
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("input for number of primary key " \
						"attributes too large")));
Bruce Momjian's avatar
Bruce Momjian committed
977

978 979 980 981
	/*
	 * There should be at least one key attribute
	 */
	if (pknumatts == 0)
982 983 984
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("number of key attributes must be > 0")));
985 986 987 988 989

	src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
	tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
990 991
	 * Source array is made up of key values that will be used to locate
	 * the tuple of interest from the local system.
992 993 994 995 996 997 998 999 1000
	 */
	src_ndim = ARR_NDIM(src_pkattvals_arry);
	src_dim = ARR_DIMS(src_pkattvals_arry);
	src_nitems = ArrayGetNItems(src_ndim, src_dim);

	/*
	 * There should be one source array key value for each key attnum
	 */
	if (src_nitems != pknumatts)
1001 1002
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1003 1004
			 errmsg("source key array length must match number of key " \
					"attributes")));
1005 1006 1007 1008

	/*
	 * get array of pointers to c-strings from the input source array
	 */
1009
	Assert(ARR_ELEMTYPE(src_pkattvals_arry) == TEXTOID);
1010
	get_typlenbyvalalign(ARR_ELEMTYPE(src_pkattvals_arry),
Bruce Momjian's avatar
Bruce Momjian committed
1011
						 &typlen, &typbyval, &typalign);
1012

1013 1014 1015 1016 1017
	src_pkattvals = (char **) palloc(src_nitems * sizeof(char *));
	ptr = ARR_DATA_PTR(src_pkattvals_arry);
	for (i = 0; i < src_nitems; i++)
	{
		src_pkattvals[i] = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(ptr)));
1018 1019
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1020 1021 1022
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1023 1024
	 * Target array is made up of key values that will be used to build
	 * the SQL string for use on the remote system.
1025 1026 1027 1028 1029 1030 1031 1032 1033
	 */
	tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
	tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
	tgt_nitems = ArrayGetNItems(tgt_ndim, tgt_dim);

	/*
	 * There should be one target array key value for each key attnum
	 */
	if (tgt_nitems != pknumatts)
1034 1035
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1036 1037
			 errmsg("target key array length must match number of key " \
					"attributes")));
1038 1039 1040 1041

	/*
	 * get array of pointers to c-strings from the input target array
	 */
1042
	Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
1043
	get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
Bruce Momjian's avatar
Bruce Momjian committed
1044
						 &typlen, &typbyval, &typalign);
1045

1046 1047 1048 1049 1050
	tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
	ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
	for (i = 0; i < tgt_nitems; i++)
	{
		tgt_pkattvals[i] = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(ptr)));
1051 1052
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
	}

	/*
	 * Prep work is finally done. Go get the SQL string.
	 */
	sql = get_sql_insert(relid, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);

	/*
	 * And send it
	 */
1063
	PG_RETURN_TEXT_P(GET_TEXT(sql));
1064 1065 1066 1067 1068
}


/*
 * dblink_build_sql_delete
Bruce Momjian's avatar
Bruce Momjian committed
1069
 *
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
 * Used to generate an SQL delete statement.
 * This is useful for selectively replicating a
 * delete to another server via dblink.
 *
 * API:
 * <relname> - name of remote table of interest
 * <pkattnums> - an int2vector of attnums which will be used
 * to identify the remote tuple of interest
 * <pknumatts> - number of attnums in pkattnums
 * <tgt_pkattvals_arry> - text array of key values which will be used
 * to build the string for execution remotely.
 */
PG_FUNCTION_INFO_V1(dblink_build_sql_delete);
Datum
dblink_build_sql_delete(PG_FUNCTION_ARGS)
{
	Oid			relid;
Bruce Momjian's avatar
Bruce Momjian committed
1087 1088
	text	   *relname_text;
	int16	   *pkattnums;
1089 1090
	int			pknumatts_tmp;
	int16		pknumatts = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1091 1092
	char	  **tgt_pkattvals;
	ArrayType  *tgt_pkattvals_arry;
1093
	int			tgt_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1094
	int		   *tgt_dim;
1095 1096
	int			tgt_nitems;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1097 1098
	char	   *ptr;
	char	   *sql;
1099 1100 1101
	int16		typlen;
	bool		typbyval;
	char		typalign;
1102

1103
	relname_text = PG_GETARG_TEXT_P(0);
1104 1105 1106 1107

	/*
	 * Convert relname to rel OID.
	 */
1108
	relid = get_relid_from_relname(relname_text);
1109
	if (!OidIsValid(relid))
1110 1111 1112 1113
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_TABLE),
				 errmsg("relation \"%s\" does not exist",
						GET_STR(relname_text))));
1114 1115

	pkattnums = (int16 *) PG_GETARG_POINTER(1);
1116 1117 1118 1119
	pknumatts_tmp = PG_GETARG_INT32(2);
	if (pknumatts_tmp <= SHRT_MAX)
		pknumatts = pknumatts_tmp;
	else
1120 1121 1122 1123
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("input for number of primary key " \
						"attributes too large")));
Bruce Momjian's avatar
Bruce Momjian committed
1124

1125 1126 1127 1128
	/*
	 * There should be at least one key attribute
	 */
	if (pknumatts == 0)
1129 1130 1131
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("number of key attributes must be > 0")));
1132 1133 1134 1135

	tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1136 1137
	 * Target array is made up of key values that will be used to build
	 * the SQL string for use on the remote system.
1138 1139 1140 1141 1142 1143 1144 1145 1146
	 */
	tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
	tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
	tgt_nitems = ArrayGetNItems(tgt_ndim, tgt_dim);

	/*
	 * There should be one target array key value for each key attnum
	 */
	if (tgt_nitems != pknumatts)
1147 1148
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1149 1150
			 errmsg("target key array length must match number of key " \
					"attributes")));
1151 1152 1153 1154

	/*
	 * get array of pointers to c-strings from the input target array
	 */
1155
	Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
1156
	get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
Bruce Momjian's avatar
Bruce Momjian committed
1157
						 &typlen, &typbyval, &typalign);
1158

1159 1160 1161 1162 1163
	tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
	ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
	for (i = 0; i < tgt_nitems; i++)
	{
		tgt_pkattvals[i] = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(ptr)));
1164 1165
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
	}

	/*
	 * Prep work is finally done. Go get the SQL string.
	 */
	sql = get_sql_delete(relid, pkattnums, pknumatts, tgt_pkattvals);

	/*
	 * And send it
	 */
1176
	PG_RETURN_TEXT_P(GET_TEXT(sql));
1177 1178 1179 1180 1181
}


/*
 * dblink_build_sql_update
Bruce Momjian's avatar
Bruce Momjian committed
1182
 *
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
 * Used to generate an SQL update statement
 * based on an existing tuple in a local relation.
 * This is useful for selectively replicating data
 * to another server via dblink.
 *
 * API:
 * <relname> - name of local table of interest
 * <pkattnums> - an int2vector of attnums which will be used
 * to identify the local tuple of interest
 * <pknumatts> - number of attnums in pkattnums
 * <src_pkattvals_arry> - text array of key values which will be used
 * to identify the local tuple of interest
 * <tgt_pkattvals_arry> - text array of key values which will be used
 * to build the string for execution remotely. These are substituted
 * for their counterparts in src_pkattvals_arry
 */
PG_FUNCTION_INFO_V1(dblink_build_sql_update);
Datum
dblink_build_sql_update(PG_FUNCTION_ARGS)
{
	Oid			relid;
Bruce Momjian's avatar
Bruce Momjian committed
1204 1205
	text	   *relname_text;
	int16	   *pkattnums;
1206 1207
	int			pknumatts_tmp;
	int16		pknumatts = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1208 1209 1210 1211
	char	  **src_pkattvals;
	char	  **tgt_pkattvals;
	ArrayType  *src_pkattvals_arry;
	ArrayType  *tgt_pkattvals_arry;
1212
	int			src_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1213
	int		   *src_dim;
1214 1215
	int			src_nitems;
	int			tgt_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1216
	int		   *tgt_dim;
1217 1218
	int			tgt_nitems;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1219 1220
	char	   *ptr;
	char	   *sql;
1221 1222 1223
	int16		typlen;
	bool		typbyval;
	char		typalign;
1224

1225
	relname_text = PG_GETARG_TEXT_P(0);
1226 1227 1228 1229

	/*
	 * Convert relname to rel OID.
	 */
1230
	relid = get_relid_from_relname(relname_text);
1231
	if (!OidIsValid(relid))
1232 1233 1234 1235
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_TABLE),
				 errmsg("relation \"%s\" does not exist",
						GET_STR(relname_text))));
1236 1237

	pkattnums = (int16 *) PG_GETARG_POINTER(1);
1238 1239 1240 1241
	pknumatts_tmp = PG_GETARG_INT32(2);
	if (pknumatts_tmp <= SHRT_MAX)
		pknumatts = pknumatts_tmp;
	else
1242 1243 1244 1245
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("input for number of primary key " \
						"attributes too large")));
Bruce Momjian's avatar
Bruce Momjian committed
1246

1247 1248 1249 1250
	/*
	 * There should be one source array key values for each key attnum
	 */
	if (pknumatts == 0)
1251 1252 1253
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("number of key attributes must be > 0")));
1254 1255 1256 1257 1258

	src_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);
	tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(4);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1259 1260
	 * Source array is made up of key values that will be used to locate
	 * the tuple of interest from the local system.
1261 1262 1263 1264 1265 1266 1267 1268 1269
	 */
	src_ndim = ARR_NDIM(src_pkattvals_arry);
	src_dim = ARR_DIMS(src_pkattvals_arry);
	src_nitems = ArrayGetNItems(src_ndim, src_dim);

	/*
	 * There should be one source array key value for each key attnum
	 */
	if (src_nitems != pknumatts)
1270 1271
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1272 1273
			 errmsg("source key array length must match number of key " \
					"attributes")));
1274 1275 1276 1277

	/*
	 * get array of pointers to c-strings from the input source array
	 */
1278
	Assert(ARR_ELEMTYPE(src_pkattvals_arry) == TEXTOID);
1279
	get_typlenbyvalalign(ARR_ELEMTYPE(src_pkattvals_arry),
Bruce Momjian's avatar
Bruce Momjian committed
1280
						 &typlen, &typbyval, &typalign);
1281

1282 1283 1284 1285 1286
	src_pkattvals = (char **) palloc(src_nitems * sizeof(char *));
	ptr = ARR_DATA_PTR(src_pkattvals_arry);
	for (i = 0; i < src_nitems; i++)
	{
		src_pkattvals[i] = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(ptr)));
1287 1288
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1289 1290 1291
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1292 1293
	 * Target array is made up of key values that will be used to build
	 * the SQL string for use on the remote system.
1294 1295 1296 1297 1298 1299 1300 1301 1302
	 */
	tgt_ndim = ARR_NDIM(tgt_pkattvals_arry);
	tgt_dim = ARR_DIMS(tgt_pkattvals_arry);
	tgt_nitems = ArrayGetNItems(tgt_ndim, tgt_dim);

	/*
	 * There should be one target array key value for each key attnum
	 */
	if (tgt_nitems != pknumatts)
1303 1304
		ereport(ERROR,
				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
1305 1306
			 errmsg("target key array length must match number of key " \
					"attributes")));
1307 1308 1309 1310

	/*
	 * get array of pointers to c-strings from the input target array
	 */
1311
	Assert(ARR_ELEMTYPE(tgt_pkattvals_arry) == TEXTOID);
1312
	get_typlenbyvalalign(ARR_ELEMTYPE(tgt_pkattvals_arry),
Bruce Momjian's avatar
Bruce Momjian committed
1313
						 &typlen, &typbyval, &typalign);
1314

1315 1316 1317 1318 1319
	tgt_pkattvals = (char **) palloc(tgt_nitems * sizeof(char *));
	ptr = ARR_DATA_PTR(tgt_pkattvals_arry);
	for (i = 0; i < tgt_nitems; i++)
	{
		tgt_pkattvals[i] = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(ptr)));
1320 1321
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1322
	}
1323 1324 1325 1326 1327 1328 1329 1330 1331

	/*
	 * Prep work is finally done. Go get the SQL string.
	 */
	sql = get_sql_update(relid, pkattnums, pknumatts, src_pkattvals, tgt_pkattvals);

	/*
	 * And send it
	 */
1332
	PG_RETURN_TEXT_P(GET_TEXT(sql));
1333 1334 1335
}

/*
1336 1337 1338 1339 1340 1341 1342 1343 1344
 * dblink_current_query
 * return the current query string
 * to allow its use in (among other things)
 * rewrite rules
 */
PG_FUNCTION_INFO_V1(dblink_current_query);
Datum
dblink_current_query(PG_FUNCTION_ARGS)
{
1345
	PG_RETURN_TEXT_P(GET_TEXT(debug_query_string));
1346 1347 1348 1349
}


/*************************************************************
1350 1351 1352 1353
 * internal functions
 */


1354 1355
/*
 * get_pkey_attnames
Bruce Momjian's avatar
Bruce Momjian committed
1356
 *
1357 1358 1359
 * Get the primary key attnames for the given relation.
 * Return NULL, and set numatts = 0, if no primary key exists.
 */
1360
static char **
1361 1362
get_pkey_attnames(Oid relid, int16 *numatts)
{
Bruce Momjian's avatar
Bruce Momjian committed
1363 1364 1365 1366 1367 1368 1369 1370
	Relation	indexRelation;
	ScanKeyData entry;
	HeapScanDesc scan;
	HeapTuple	indexTuple;
	int			i;
	char	  **result = NULL;
	Relation	rel;
	TupleDesc	tupdesc;
1371

1372
	/* open relation using relid, get tupdesc */
1373 1374 1375
	rel = relation_open(relid, AccessShareLock);
	tupdesc = rel->rd_att;

1376
	/* initialize numatts to 0 in case no primary key exists */
1377 1378
	*numatts = 0;

1379
	/* use relid to get all related indexes */
1380
	indexRelation = heap_openr(IndexRelationName, AccessShareLock);
1381 1382 1383 1384
	ScanKeyInit(&entry,
				Anum_pg_index_indrelid,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(relid));
1385
	scan = heap_beginscan(indexRelation, SnapshotNow, 1, &entry);
1386

1387
	while ((indexTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1388
	{
Bruce Momjian's avatar
Bruce Momjian committed
1389
		Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
1390

1391
		/* we're only interested if it is the primary key */
1392 1393
		if (index->indisprimary == TRUE)
		{
1394 1395 1396 1397
			i = 0;
			while (index->indkey[i++] != 0)
				(*numatts)++;

1398 1399 1400
			if (*numatts > 0)
			{
				result = (char **) palloc(*numatts * sizeof(char *));
1401

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
				for (i = 0; i < *numatts; i++)
					result[i] = SPI_fname(tupdesc, index->indkey[i]);
			}
			break;
		}
	}
	heap_endscan(scan);
	heap_close(indexRelation, AccessShareLock);
	relation_close(rel, AccessShareLock);

	return result;
}

1415
static char *
1416 1417
get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
	Relation	rel;
	char	   *relname;
	HeapTuple	tuple;
	TupleDesc	tupdesc;
	int			natts;
	StringInfo	str = makeStringInfo();
	char	   *sql;
	char	   *val;
	int16		key;
	int			i;
	bool		needComma;
1429

1430 1431 1432
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1433 1434 1435 1436 1437 1438 1439 1440
	/*
	 * Open relation using relid
	 */
	rel = relation_open(relid, AccessShareLock);
	tupdesc = rel->rd_att;
	natts = tupdesc->natts;

	tuple = get_tuple_of_interest(relid, pkattnums, pknumatts, src_pkattvals);
1441
	if (!tuple)
1442 1443 1444
		ereport(ERROR,
				(errcode(ERRCODE_CARDINALITY_VIOLATION),
				 errmsg("source row not found")));
1445

1446
	appendStringInfo(str, "INSERT INTO %s(", relname);
1447 1448

	needComma = false;
1449 1450
	for (i = 0; i < natts; i++)
	{
1451 1452 1453 1454
		if (tupdesc->attrs[i]->attisdropped)
			continue;

		if (needComma)
1455 1456
			appendStringInfo(str, ",");

1457
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1458
				  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
1459
		needComma = true;
1460 1461 1462 1463 1464 1465 1466
	}

	appendStringInfo(str, ") VALUES(");

	/*
	 * remember attvals are 1 based
	 */
1467
	needComma = false;
1468 1469
	for (i = 0; i < natts; i++)
	{
1470 1471 1472 1473
		if (tupdesc->attrs[i]->attisdropped)
			continue;

		if (needComma)
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
			appendStringInfo(str, ",");

		if (tgt_pkattvals != NULL)
			key = get_attnum_pk_pos(pkattnums, pknumatts, i + 1);
		else
			key = -1;

		if (key > -1)
			val = pstrdup(tgt_pkattvals[key]);
		else
			val = SPI_getvalue(tuple, tupdesc, i + 1);

		if (val != NULL)
		{
1488
			appendStringInfo(str, "%s", quote_literal_cstr(val));
1489 1490 1491 1492
			pfree(val);
		}
		else
			appendStringInfo(str, "NULL");
1493
		needComma = true;
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
	}
	appendStringInfo(str, ")");

	sql = pstrdup(str->data);
	pfree(str->data);
	pfree(str);
	relation_close(rel, AccessShareLock);

	return (sql);
}

1505
static char *
1506 1507
get_sql_delete(Oid relid, int16 *pkattnums, int16 pknumatts, char **tgt_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1508 1509 1510 1511 1512 1513
	Relation	rel;
	char	   *relname;
	TupleDesc	tupdesc;
	int			natts;
	StringInfo	str = makeStringInfo();
	char	   *sql;
1514
	char	   *val = NULL;
Bruce Momjian's avatar
Bruce Momjian committed
1515
	int			i;
1516

1517 1518 1519
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1520 1521 1522 1523 1524 1525 1526
	/*
	 * Open relation using relid
	 */
	rel = relation_open(relid, AccessShareLock);
	tupdesc = rel->rd_att;
	natts = tupdesc->natts;

1527
	appendStringInfo(str, "DELETE FROM %s WHERE ", relname);
1528 1529
	for (i = 0; i < pknumatts; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1530
		int16		pkattnum = pkattnums[i];
1531 1532 1533 1534

		if (i > 0)
			appendStringInfo(str, " AND ");

1535
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1536
		quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
1537 1538 1539 1540

		if (tgt_pkattvals != NULL)
			val = pstrdup(tgt_pkattvals[i]);
		else
1541 1542
			/* internal error */
			elog(ERROR, "target key array must not be NULL");
1543 1544 1545

		if (val != NULL)
		{
1546
			appendStringInfo(str, " = %s", quote_literal_cstr(val));
1547 1548 1549
			pfree(val);
		}
		else
1550
			appendStringInfo(str, " IS NULL");
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
	}

	sql = pstrdup(str->data);
	pfree(str->data);
	pfree(str);
	relation_close(rel, AccessShareLock);

	return (sql);
}

1561
static char *
1562 1563
get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
	Relation	rel;
	char	   *relname;
	HeapTuple	tuple;
	TupleDesc	tupdesc;
	int			natts;
	StringInfo	str = makeStringInfo();
	char	   *sql;
	char	   *val;
	int16		key;
	int			i;
	bool		needComma;
1575

1576 1577 1578
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1579 1580 1581 1582 1583 1584 1585 1586
	/*
	 * Open relation using relid
	 */
	rel = relation_open(relid, AccessShareLock);
	tupdesc = rel->rd_att;
	natts = tupdesc->natts;

	tuple = get_tuple_of_interest(relid, pkattnums, pknumatts, src_pkattvals);
1587
	if (!tuple)
1588 1589 1590
		ereport(ERROR,
				(errcode(ERRCODE_CARDINALITY_VIOLATION),
				 errmsg("source row not found")));
1591

1592
	appendStringInfo(str, "UPDATE %s SET ", relname);
1593

1594
	needComma = false;
1595 1596
	for (i = 0; i < natts; i++)
	{
1597 1598 1599 1600 1601
		if (tupdesc->attrs[i]->attisdropped)
			continue;

		if (needComma)
			appendStringInfo(str, ", ");
1602

1603
		appendStringInfo(str, "%s = ",
Bruce Momjian's avatar
Bruce Momjian committed
1604
				  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

		if (tgt_pkattvals != NULL)
			key = get_attnum_pk_pos(pkattnums, pknumatts, i + 1);
		else
			key = -1;

		if (key > -1)
			val = pstrdup(tgt_pkattvals[key]);
		else
			val = SPI_getvalue(tuple, tupdesc, i + 1);

		if (val != NULL)
		{
1618
			appendStringInfo(str, "%s", quote_literal_cstr(val));
1619 1620 1621 1622
			pfree(val);
		}
		else
			appendStringInfo(str, "NULL");
1623
		needComma = true;
1624 1625 1626 1627 1628 1629
	}

	appendStringInfo(str, " WHERE ");

	for (i = 0; i < pknumatts; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1630
		int16		pkattnum = pkattnums[i];
1631 1632 1633 1634

		if (i > 0)
			appendStringInfo(str, " AND ");

1635
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1636
		quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
1637 1638 1639 1640 1641 1642 1643 1644

		if (tgt_pkattvals != NULL)
			val = pstrdup(tgt_pkattvals[i]);
		else
			val = SPI_getvalue(tuple, tupdesc, pkattnum);

		if (val != NULL)
		{
1645
			appendStringInfo(str, " = %s", quote_literal_cstr(val));
1646 1647 1648
			pfree(val);
		}
		else
1649
			appendStringInfo(str, " IS NULL");
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
	}

	sql = pstrdup(str->data);
	pfree(str->data);
	pfree(str);
	relation_close(rel, AccessShareLock);

	return (sql);
}

/*
 * Return a properly quoted literal value.
 * Uses quote_literal in quote.c
 */
static char *
quote_literal_cstr(char *rawstr)
{
Bruce Momjian's avatar
Bruce Momjian committed
1667 1668 1669
	text	   *rawstr_text;
	text	   *result_text;
	char	   *result;
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684

	rawstr_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(rawstr)));
	result_text = DatumGetTextP(DirectFunctionCall1(quote_literal, PointerGetDatum(rawstr_text)));
	result = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(result_text)));

	return result;
}

/*
 * Return a properly quoted identifier.
 * Uses quote_ident in quote.c
 */
static char *
quote_ident_cstr(char *rawstr)
{
Bruce Momjian's avatar
Bruce Momjian committed
1685 1686 1687
	text	   *rawstr_text;
	text	   *result_text;
	char	   *result;
1688 1689 1690 1691 1692 1693 1694 1695

	rawstr_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(rawstr)));
	result_text = DatumGetTextP(DirectFunctionCall1(quote_ident, PointerGetDatum(rawstr_text)));
	result = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(result_text)));

	return result;
}

1696
static int16
1697 1698
get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key)
{
Bruce Momjian's avatar
Bruce Momjian committed
1699
	int			i;
1700 1701

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1702
	 * Not likely a long list anyway, so just scan for the value
1703 1704 1705 1706 1707 1708 1709 1710
	 */
	for (i = 0; i < pknumatts; i++)
		if (key == pkattnums[i])
			return i;

	return -1;
}

1711
static HeapTuple
1712 1713
get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1714 1715 1716 1717 1718 1719 1720 1721 1722
	Relation	rel;
	char	   *relname;
	TupleDesc	tupdesc;
	StringInfo	str = makeStringInfo();
	char	   *sql = NULL;
	int			ret;
	HeapTuple	tuple;
	int			i;
	char	   *val = NULL;
1723

1724 1725 1726
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1727 1728 1729 1730
	/*
	 * Open relation using relid
	 */
	rel = relation_open(relid, AccessShareLock);
1731 1732
	tupdesc = CreateTupleDescCopy(rel->rd_att);
	relation_close(rel, AccessShareLock);
1733 1734 1735 1736 1737

	/*
	 * Connect to SPI manager
	 */
	if ((ret = SPI_connect()) < 0)
1738 1739
		/* internal error */
		elog(ERROR, "SPI connect failure - returned %d", ret);
1740 1741

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1742 1743
	 * Build sql statement to look up tuple of interest Use src_pkattvals
	 * as the criteria.
1744
	 */
1745
	appendStringInfo(str, "SELECT * FROM %s WHERE ", relname);
1746 1747 1748

	for (i = 0; i < pknumatts; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1749
		int16		pkattnum = pkattnums[i];
1750 1751 1752 1753

		if (i > 0)
			appendStringInfo(str, " AND ");

1754
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1755
		quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
1756 1757 1758 1759

		val = pstrdup(src_pkattvals[i]);
		if (val != NULL)
		{
1760
			appendStringInfo(str, " = %s", quote_literal_cstr(val));
1761 1762 1763
			pfree(val);
		}
		else
1764
			appendStringInfo(str, " IS NULL");
1765 1766 1767 1768 1769
	}

	sql = pstrdup(str->data);
	pfree(str->data);
	pfree(str);
Bruce Momjian's avatar
Bruce Momjian committed
1770

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
	/*
	 * Retrieve the desired tuple
	 */
	ret = SPI_exec(sql, 0);
	pfree(sql);

	/*
	 * Only allow one qualifying tuple
	 */
	if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
1781 1782 1783 1784
		ereport(ERROR,
				(errcode(ERRCODE_CARDINALITY_VIOLATION),
				 errmsg("source criteria matched more than one record")));

1785 1786 1787
	else if (ret == SPI_OK_SELECT && SPI_processed == 1)
	{
		SPITupleTable *tuptable = SPI_tuptable;
Bruce Momjian's avatar
Bruce Momjian committed
1788

1789
		tuple = SPI_copytuple(tuptable->vals[0]);
1790
		SPI_finish();
1791 1792 1793 1794 1795 1796 1797 1798

		return tuple;
	}
	else
	{
		/*
		 * no qualifying tuples
		 */
1799 1800
		SPI_finish();

1801 1802 1803 1804 1805 1806 1807 1808 1809
		return NULL;
	}

	/*
	 * never reached, but keep compiler quiet
	 */
	return NULL;
}

1810 1811
static Oid
get_relid_from_relname(text *relname_text)
1812
{
1813 1814 1815
	RangeVar   *relvar;
	Relation	rel;
	Oid			relid;
1816

1817 1818 1819 1820
	relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text, "get_relid_from_relname"));
	rel = heap_openrv(relvar, AccessShareLock);
	relid = RelationGetRelid(rel);
	relation_close(rel, AccessShareLock);
1821 1822 1823 1824

	return relid;
}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
/*
 * generate_relation_name - copied from ruleutils.c
 *		Compute the name to display for a relation specified by OID
 *
 * The result includes all necessary quoting and schema-prefixing.
 */
static char *
generate_relation_name(Oid relid)
{
	HeapTuple	tp;
	Form_pg_class reltup;
	char	   *nspname;
	char	   *result;

	tp = SearchSysCache(RELOID,
						ObjectIdGetDatum(relid),
						0, 0, 0);
	if (!HeapTupleIsValid(tp))
1843 1844
		elog(ERROR, "cache lookup failed for relation %u", relid);

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
	reltup = (Form_pg_class) GETSTRUCT(tp);

	/* Qualify the name if not visible in search path */
	if (RelationIsVisible(relid))
		nspname = NULL;
	else
		nspname = get_namespace_name(reltup->relnamespace);

	result = quote_qualified_identifier(nspname, NameStr(reltup->relname));

	ReleaseSysCache(tp);

	return result;
}
1859 1860 1861 1862 1863


static remoteConn *
getConnectionByName(const char *name)
{
Bruce Momjian's avatar
Bruce Momjian committed
1864 1865
	remoteConnHashEnt *hentry;
	char		key[NAMEDATALEN];
1866

Bruce Momjian's avatar
Bruce Momjian committed
1867 1868
	if (!remoteConnHash)
		remoteConnHash = createConnHash();
1869 1870 1871

	MemSet(key, 0, NAMEDATALEN);
	snprintf(key, NAMEDATALEN - 1, "%s", name);
Bruce Momjian's avatar
Bruce Momjian committed
1872 1873
	hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
											   key, HASH_FIND, NULL);
1874

Bruce Momjian's avatar
Bruce Momjian committed
1875 1876
	if (hentry)
		return (hentry->rcon);
1877

Bruce Momjian's avatar
Bruce Momjian committed
1878
	return (NULL);
1879 1880 1881 1882 1883
}

static HTAB *
createConnHash(void)
{
Bruce Momjian's avatar
Bruce Momjian committed
1884 1885
	HASHCTL		ctl;
	HTAB	   *ptr;
1886 1887 1888 1889

	ctl.keysize = NAMEDATALEN;
	ctl.entrysize = sizeof(remoteConnHashEnt);

Bruce Momjian's avatar
Bruce Momjian committed
1890
	ptr = hash_create("Remote Con hash", NUMCONN, &ctl, HASH_ELEM);
1891

Bruce Momjian's avatar
Bruce Momjian committed
1892
	if (!ptr)
1893 1894 1895
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));
1896

Bruce Momjian's avatar
Bruce Momjian committed
1897
	return (ptr);
1898 1899
}

1900
static void
Bruce Momjian's avatar
Bruce Momjian committed
1901
createNewConnection(const char *name, remoteConn * con)
1902
{
Bruce Momjian's avatar
Bruce Momjian committed
1903 1904 1905
	remoteConnHashEnt *hentry;
	bool		found;
	char		key[NAMEDATALEN];
1906

Bruce Momjian's avatar
Bruce Momjian committed
1907
	if (!remoteConnHash)
1908
		remoteConnHash = createConnHash();
1909 1910 1911 1912 1913 1914

	MemSet(key, 0, NAMEDATALEN);
	snprintf(key, NAMEDATALEN - 1, "%s", name);
	hentry = (remoteConnHashEnt *) hash_search(remoteConnHash, key,
											   HASH_ENTER, &found);

Bruce Momjian's avatar
Bruce Momjian committed
1915
	if (!hentry)
1916 1917 1918
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory")));
1919

Bruce Momjian's avatar
Bruce Momjian committed
1920
	if (found)
1921 1922 1923
		ereport(ERROR,
				(errcode(ERRCODE_DUPLICATE_OBJECT),
				 errmsg("duplicate connection name")));
1924 1925 1926 1927 1928 1929 1930 1931

	hentry->rcon = con;
	strncpy(hentry->name, name, NAMEDATALEN - 1);
}

static void
deleteConnection(const char *name)
{
Bruce Momjian's avatar
Bruce Momjian committed
1932 1933 1934
	remoteConnHashEnt *hentry;
	bool		found;
	char		key[NAMEDATALEN];
1935

Bruce Momjian's avatar
Bruce Momjian committed
1936 1937
	if (!remoteConnHash)
		remoteConnHash = createConnHash();
1938 1939 1940 1941 1942 1943 1944

	MemSet(key, 0, NAMEDATALEN);
	snprintf(key, NAMEDATALEN - 1, "%s", name);

	hentry = (remoteConnHashEnt *) hash_search(remoteConnHash,
											   key, HASH_REMOVE, &found);

Bruce Momjian's avatar
Bruce Momjian committed
1945
	if (!hentry)
1946 1947 1948 1949
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("undefined connection name")));

1950
}