dblink.c 48.3 KB
Newer Older
1 2 3 4 5
/*
 * dblink.c
 *
 * Functions returning results from a remote database
 *
6 7 8
 * Joe Conway <mail@joeconway.com>
 *
 * Copyright (c) 2001, 2002 by PostgreSQL Global Development Group
9
 * ALL RIGHTS RESERVED;
10
 *
11 12 13 14
 * 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.
15
 *
16 17 18 19 20
 * 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.
21
 *
22 23 24 25 26 27 28
 * 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.
 *
 */
29
#include "postgres.h"
30

31
#include "libpq-fe.h"
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#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"
54

55
#include "dblink.h"
56 57 58 59 60 61 62 63 64 65 66 67 68

/*
 * Internal declarations
 */
static dblink_results *init_dblink_results(MemoryContext fn_mcxt);
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
69
static Oid	get_relid_from_relname(text *relname_text);
70
static dblink_results *get_res_ptr(int32 res_id_index);
Bruce Momjian's avatar
Bruce Momjian committed
71 72
static void append_res_ptr(dblink_results * results);
static void remove_res_ptr(dblink_results * results);
73
static TupleDesc pgresultGetTupleDesc(PGresult *res);
74
static char *generate_relation_name(Oid relid);
75

76
/* Global */
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
List	   *res_id = NIL;
int			res_id_index = 0;
PGconn	   *persistent_conn = NULL;

#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)


/*
 * Create a persistent connection to another database
 */
PG_FUNCTION_INFO_V1(dblink_connect);
Datum
dblink_connect(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
100 101 102 103
	char	   *connstr = GET_STR(PG_GETARG_TEXT_P(0));
	char	   *msg;
	text	   *result_text;
	MemoryContext oldcontext;
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

	if (persistent_conn != NULL)
		PQfinish(persistent_conn);

	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
	persistent_conn = PQconnectdb(connstr);
	MemoryContextSwitchTo(oldcontext);

	if (PQstatus(persistent_conn) == CONNECTION_BAD)
	{
		msg = pstrdup(PQerrorMessage(persistent_conn));
		PQfinish(persistent_conn);
		persistent_conn = NULL;
		elog(ERROR, "dblink_connect: connection error: %s", msg);
	}

	result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum("OK")));
	PG_RETURN_TEXT_P(result_text);
}

/*
 * Clear a persistent connection to another database
 */
PG_FUNCTION_INFO_V1(dblink_disconnect);
Datum
dblink_disconnect(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
131
	text	   *result_text;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

	if (persistent_conn != NULL)
		PQfinish(persistent_conn);

	persistent_conn = NULL;

	result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum("OK")));
	PG_RETURN_TEXT_P(result_text);
}

/*
 * 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
149 150 151 152 153 154 155
	char	   *msg;
	PGresult   *res = NULL;
	PGconn	   *conn = NULL;
	text	   *result_text;
	char	   *curname = GET_STR(PG_GETARG_TEXT_P(0));
	char	   *sql = GET_STR(PG_GETARG_TEXT_P(1));
	StringInfo	str = makeStringInfo();
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

	if (persistent_conn != NULL)
		conn = persistent_conn;
	else
		elog(ERROR, "dblink_open: no connection available");

	res = PQexec(conn, "BEGIN");
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		msg = pstrdup(PQerrorMessage(conn));
		PQclear(res);

		PQfinish(conn);
		persistent_conn = NULL;

		elog(ERROR, "dblink_open: begin error: %s", msg);
	}
	PQclear(res);

175
	appendStringInfo(str, "DECLARE %s CURSOR FOR %s", curname, sql);
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	res = PQexec(conn, str->data);
	if (!res ||
		(PQresultStatus(res) != PGRES_COMMAND_OK &&
		 PQresultStatus(res) != PGRES_TUPLES_OK))
	{
		msg = pstrdup(PQerrorMessage(conn));

		PQclear(res);

		PQfinish(conn);
		persistent_conn = NULL;

		elog(ERROR, "dblink: sql error: %s", msg);
	}

	result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum("OK")));
	PG_RETURN_TEXT_P(result_text);
}
194

195 196 197 198 199 200 201
/*
 * closes a cursor
 */
PG_FUNCTION_INFO_V1(dblink_close);
Datum
dblink_close(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
202 203 204 205 206 207
	PGconn	   *conn = NULL;
	PGresult   *res = NULL;
	char	   *curname = GET_STR(PG_GETARG_TEXT_P(0));
	StringInfo	str = makeStringInfo();
	text	   *result_text;
	char	   *msg;
208 209 210 211 212 213

	if (persistent_conn != NULL)
		conn = persistent_conn;
	else
		elog(ERROR, "dblink_close: no connection available");

214
	appendStringInfo(str, "CLOSE %s", curname);
215 216 217

	/* close the cursor */
	res = PQexec(conn, str->data);
Bruce Momjian's avatar
Bruce Momjian committed
218
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
	{
		msg = pstrdup(PQerrorMessage(conn));
		PQclear(res);

		PQfinish(persistent_conn);
		persistent_conn = NULL;

		elog(ERROR, "dblink_close: sql error: %s", msg);
	}

	PQclear(res);

	/* commit the transaction */
	res = PQexec(conn, "COMMIT");
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		msg = pstrdup(PQerrorMessage(conn));
		PQclear(res);

		PQfinish(persistent_conn);
		persistent_conn = NULL;

		elog(ERROR, "dblink_close: commit error: %s", msg);
	}
	PQclear(res);

	result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum("OK")));
	PG_RETURN_TEXT_P(result_text);
}

/*
 * 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
256 257 258 259 260 261 262 263 264
	FuncCallContext *funcctx;
	TupleDesc	tupdesc = NULL;
	int			call_cntr;
	int			max_calls;
	TupleTableSlot *slot;
	AttInMetadata *attinmeta;
	char	   *msg;
	PGresult   *res = NULL;
	MemoryContext oldcontext;
265 266

	/* stuff done only on the first call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
267 268 269 270 271 272 273 274 275
	if (SRF_IS_FIRSTCALL())
	{
		Oid			functypeid;
		char		functyptype;
		Oid			funcid = fcinfo->flinfo->fn_oid;
		PGconn	   *conn = NULL;
		StringInfo	str = makeStringInfo();
		char	   *curname = GET_STR(PG_GETARG_TEXT_P(0));
		int			howmany = PG_GETARG_INT32(1);
276 277

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

Bruce Momjian's avatar
Bruce Momjian committed
280 281 282 283
		/*
		 * switch to memory context appropriate for multiple function
		 * calls
		 */
284 285 286 287 288 289 290
		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

		if (persistent_conn != NULL)
			conn = persistent_conn;
		else
			elog(ERROR, "dblink_fetch: no connection available");

291
		appendStringInfo(str, "FETCH %d FROM %s", howmany, curname);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

		res = PQexec(conn, str->data);
		if (!res ||
			(PQresultStatus(res) != PGRES_COMMAND_OK &&
			 PQresultStatus(res) != PGRES_TUPLES_OK))
		{
			msg = pstrdup(PQerrorMessage(conn));
			PQclear(res);

			PQfinish(persistent_conn);
			persistent_conn = NULL;

			elog(ERROR, "dblink_fetch: sql error: %s", msg);
		}
		else if (PQresultStatus(res) == PGRES_COMMAND_OK)
		{
			/* cursor does not exist - closed already or bad name */
			PQclear(res);
310
			elog(ERROR, "dblink_fetch: cursor %s does not exist", curname);
311 312 313 314 315 316 317 318 319
		}

		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
320
			SRF_RETURN_DONE(funcctx);
321 322 323 324 325 326 327 328 329 330

		/* 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)
			tupdesc = pgresultGetTupleDesc(res);
		else
331
			elog(ERROR, "dblink_fetch: return type must be a row type");
332 333 334 335 336 337 338 339

		/* 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
340
	}
341 342

	/* stuff done on every call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
343
	funcctx = SRF_PERCALL_SETUP();
344 345 346 347 348 349 350 351 352 353 354 355 356 357

	/*
	 * 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
358
	{
359 360 361
		char	  **values;
		HeapTuple	tuple;
		Datum		result;
Bruce Momjian's avatar
Bruce Momjian committed
362 363
		int			i;
		int			nfields = PQnfields(res);
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

		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
380
		SRF_RETURN_NEXT(funcctx, result);
381
	}
Bruce Momjian's avatar
Bruce Momjian committed
382 383
	else
/* do when there is no more left */
384 385
	{
		PQclear(res);
Bruce Momjian's avatar
Bruce Momjian committed
386
		SRF_RETURN_DONE(funcctx);
387 388 389 390 391 392 393 394 395 396
	}
}

/*
 * 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
397 398 399 400 401 402 403 404 405 406 407
	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;
408 409

	/* stuff done only on the first call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
410 411 412 413 414 415 416 417
	if (SRF_IS_FIRSTCALL())
	{
		Oid			functypeid;
		char		functyptype;
		Oid			funcid = fcinfo->flinfo->fn_oid;
		PGconn	   *conn = NULL;
		char	   *connstr = NULL;
		char	   *sql = NULL;
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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

		if (fcinfo->nargs == 2)
		{
			connstr = GET_STR(PG_GETARG_TEXT_P(0));
			sql = GET_STR(PG_GETARG_TEXT_P(1));

			conn = PQconnectdb(connstr);
			if (PQstatus(conn) == CONNECTION_BAD)
			{
				msg = pstrdup(PQerrorMessage(conn));
				PQfinish(conn);
				elog(ERROR, "dblink: connection error: %s", msg);
			}
		}
		else if (fcinfo->nargs == 1)
		{
			sql = GET_STR(PG_GETARG_TEXT_P(0));

			if (persistent_conn != NULL)
				conn = persistent_conn;
			else
				elog(ERROR, "dblink: no connection available");
		}
		else
			elog(ERROR, "dblink: wrong number of arguments");

		res = PQexec(conn, sql);
		if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK))
		{
			msg = pstrdup(PQerrorMessage(conn));
			PQclear(res);
			PQfinish(conn);
			if (fcinfo->nargs == 1)
				persistent_conn = NULL;

			elog(ERROR, "dblink: sql error: %s", msg);
		}
		else
		{
			if (PQresultStatus(res) == PGRES_COMMAND_OK)
			{
				is_sql_cmd = true;

				/* need a tuple descriptor representing one TEXT column */
471
				tupdesc = CreateTemplateTupleDesc(1, false);
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
				TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
								   TEXTOID, -1, 0, false);

				/*
				 * and save a copy of the command status string to return
				 * as our result tuple
				 */
				sql_cmd_status = PQcmdStatus(res);
				funcctx->max_calls = 1;
			}
			else
				funcctx->max_calls = PQntuples(res);

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

			/* if needed, close the connection to the database and cleanup */
			if (fcinfo->nargs == 2)
				PQfinish(conn);
		}

		/* fast track when no results */
		if (funcctx->max_calls < 1)
Bruce Momjian's avatar
Bruce Momjian committed
495
			SRF_RETURN_DONE(funcctx);
496 497 498 499 500 501 502 503 504 505 506 507

		/* 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)
				tupdesc = pgresultGetTupleDesc(res);
			else
508
				elog(ERROR, "dblink: return type must be a row type");
509 510 511 512 513 514 515 516 517
		}

		/* 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
518
	}
519 520

	/* stuff done on every call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
521
	funcctx = SRF_PERCALL_SETUP();
522 523 524 525 526 527 528 529 530 531 532 533 534 535

	/*
	 * 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
536
	{
537 538 539 540 541 542
		char	  **values;
		HeapTuple	tuple;
		Datum		result;

		if (!is_sql_cmd)
		{
Bruce Momjian's avatar
Bruce Momjian committed
543 544
			int			i;
			int			nfields = PQnfields(res);
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

			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
567
		SRF_RETURN_NEXT(funcctx, result);
568
	}
Bruce Momjian's avatar
Bruce Momjian committed
569 570
	else
/* do when there is no more left */
571 572
	{
		PQclear(res);
Bruce Momjian's avatar
Bruce Momjian committed
573
		SRF_RETURN_DONE(funcctx);
574 575 576 577 578 579 580 581 582 583
	}
}

/*
 * 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
584 585 586 587 588 589 590 591
	char	   *msg;
	PGresult   *res = NULL;
	char	   *sql_cmd_status = NULL;
	TupleDesc	tupdesc = NULL;
	text	   *result_text;
	PGconn	   *conn = NULL;
	char	   *connstr = NULL;
	char	   *sql = NULL;
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

	if (fcinfo->nargs == 2)
	{
		connstr = GET_STR(PG_GETARG_TEXT_P(0));
		sql = GET_STR(PG_GETARG_TEXT_P(1));

		conn = PQconnectdb(connstr);
		if (PQstatus(conn) == CONNECTION_BAD)
		{
			msg = pstrdup(PQerrorMessage(conn));
			PQfinish(conn);
			elog(ERROR, "dblink_exec: connection error: %s", msg);
		}
	}
	else if (fcinfo->nargs == 1)
	{
		sql = GET_STR(PG_GETARG_TEXT_P(0));

		if (persistent_conn != NULL)
			conn = persistent_conn;
		else
			elog(ERROR, "dblink_exec: no connection available");
	}
	else
		elog(ERROR, "dblink_exec: wrong number of arguments");


	res = PQexec(conn, sql);
	if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK))
	{
		msg = pstrdup(PQerrorMessage(conn));
		PQclear(res);
		PQfinish(conn);
		if (fcinfo->nargs == 1)
			persistent_conn = NULL;

		elog(ERROR, "dblink_exec: sql error: %s", msg);
	}
	else
	{
		if (PQresultStatus(res) == PGRES_COMMAND_OK)
		{
			/* need a tuple descriptor representing one TEXT column */
635
			tupdesc = CreateTemplateTupleDesc(1, false);
636 637 638 639
			TupleDescInitEntry(tupdesc, (AttrNumber) 1, "status",
							   TEXTOID, -1, 0, false);

			/*
Bruce Momjian's avatar
Bruce Momjian committed
640 641
			 * and save a copy of the command status string to return as
			 * our result tuple
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
			 */
			sql_cmd_status = PQcmdStatus(res);
		}
		else
			elog(ERROR, "dblink_exec: queries returning results not allowed");
	}
	PQclear(res);

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

	result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(sql_cmd_status)));
	PG_RETURN_TEXT_P(result_text);
}

/*
 * Note: this original version of dblink is DEPRECATED;
 * it *will* be removed in favor of the new version on next release
 */
662 663 664 665
PG_FUNCTION_INFO_V1(dblink);
Datum
dblink(PG_FUNCTION_ARGS)
{
Bruce Momjian's avatar
Bruce Momjian committed
666 667 668 669 670 671 672 673 674
	PGconn	   *conn = NULL;
	PGresult   *res = NULL;
	dblink_results *results;
	char	   *optstr;
	char	   *sqlstatement;
	char	   *execstatement;
	char	   *msg;
	int			ntuples = 0;
	ReturnSetInfo *rsi;
675

676
	if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
677 678 679 680 681
		elog(ERROR, "dblink: function called in context that does not accept a set result");

	optstr = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(PG_GETARG_TEXT_P(0))));
	sqlstatement = DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(PG_GETARG_TEXT_P(1))));

682 683
	if (fcinfo->flinfo->fn_extra == NULL)
	{
684 685 686 687

		conn = PQconnectdb(optstr);
		if (PQstatus(conn) == CONNECTION_BAD)
		{
688
			msg = pstrdup(PQerrorMessage(conn));
689 690 691 692
			PQfinish(conn);
			elog(ERROR, "dblink: connection error: %s", msg);
		}

693
		execstatement = (char *) palloc(strlen(sqlstatement) + 1);
694 695
		if (execstatement != NULL)
		{
696
			strcpy(execstatement, sqlstatement);
697 698
			strcat(execstatement, "\0");
		}
699 700
		else
			elog(ERROR, "dblink: insufficient memory");
701 702 703 704

		res = PQexec(conn, execstatement);
		if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK))
		{
705
			msg = pstrdup(PQerrorMessage(conn));
706 707 708
			PQclear(res);
			PQfinish(conn);
			elog(ERROR, "dblink: sql error: %s", msg);
709 710 711
		}
		else
		{
712 713 714 715 716
			/*
			 * got results, start fetching them
			 */
			ntuples = PQntuples(res);

717 718 719 720
			/*
			 * increment resource index
			 */
			res_id_index++;
721

722 723 724 725
			results = init_dblink_results(fcinfo->flinfo->fn_mcxt);
			results->tup_num = 0;
			results->res_id_index = res_id_index;
			results->res = res;
726

727
			/*
Bruce Momjian's avatar
Bruce Momjian committed
728 729
			 * Append node to res_id to hold pointer to results. Needed by
			 * dblink_tok to access the data
730 731
			 */
			append_res_ptr(results);
732

733 734 735 736
			/*
			 * save pointer to results for the next function manager call
			 */
			fcinfo->flinfo->fn_extra = (void *) results;
737

738 739
			/* close the connection to the database and cleanup */
			PQfinish(conn);
740

741 742
			rsi = (ReturnSetInfo *) fcinfo->resultinfo;
			rsi->isDone = ExprMultipleResult;
743

744
			PG_RETURN_INT32(res_id_index);
745
		}
746 747 748
	}
	else
	{
749 750 751 752
		/*
		 * check for more results
		 */
		results = fcinfo->flinfo->fn_extra;
753

754
		results->tup_num++;
755
		res_id_index = results->res_id_index;
756 757
		ntuples = PQntuples(results->res);

758 759
		if (results->tup_num < ntuples)
		{
760 761 762 763
			/*
			 * fetch them if available
			 */

764
			rsi = (ReturnSetInfo *) fcinfo->resultinfo;
765 766
			rsi->isDone = ExprMultipleResult;

767
			PG_RETURN_INT32(res_id_index);
768 769 770
		}
		else
		{
771 772 773 774 775
			/*
			 * or if no more, clean things up
			 */
			results = fcinfo->flinfo->fn_extra;

776
			remove_res_ptr(results);
777
			PQclear(results->res);
778 779
			pfree(results);
			fcinfo->flinfo->fn_extra = NULL;
780

781 782
			rsi = (ReturnSetInfo *) fcinfo->resultinfo;
			rsi->isDone = ExprEndResult;
783 784 785 786 787 788 789 790

			PG_RETURN_NULL();
		}
	}
	PG_RETURN_NULL();
}

/*
791 792 793
 * Note: dblink_tok is DEPRECATED;
 * it *will* be removed in favor of the new version on next release
 *
794 795 796 797 798 799 800 801 802
 * dblink_tok
 * parse dblink output string
 * return fldnum item (0 based)
 * based on provided field separator
 */
PG_FUNCTION_INFO_V1(dblink_tok);
Datum
dblink_tok(PG_FUNCTION_ARGS)
{
803
	dblink_results *results;
Bruce Momjian's avatar
Bruce Momjian committed
804 805 806 807 808
	int			fldnum;
	text	   *result_text;
	char	   *result;
	int			nfields = 0;
	int			text_len = 0;
809

810
	results = get_res_ptr(PG_GETARG_INT32(0));
811
	if (results == NULL)
812 813 814 815 816 817 818 819 820 821
	{
		if (res_id != NIL)
		{
			freeList(res_id);
			res_id = NIL;
			res_id_index = 0;
		}

		elog(ERROR, "dblink_tok: function called with invalid resource id");
	}
822 823

	fldnum = PG_GETARG_INT32(1);
824
	if (fldnum < 0)
825
		elog(ERROR, "dblink_tok: field number < 0 not permitted");
826 827

	nfields = PQnfields(results->res);
828
	if (fldnum > (nfields - 1))
829
		elog(ERROR, "dblink_tok: field number %d does not exist", fldnum);
830

831
	if (PQgetisnull(results->res, results->tup_num, fldnum) == 1)
832
		PG_RETURN_NULL();
833 834
	else
	{
835 836 837
		text_len = PQgetlength(results->res, results->tup_num, fldnum);

		result = (char *) palloc(text_len + 1);
838

839 840
		if (result != NULL)
		{
841 842 843
			strcpy(result, PQgetvalue(results->res, results->tup_num, fldnum));
			strcat(result, "\0");
		}
844 845
		else
			elog(ERROR, "dblink: insufficient memory");
846 847 848 849

		result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(result)));

		PG_RETURN_TEXT_P(result_text);
850 851
	}
}
852

853 854
/*
 * dblink_get_pkey
Bruce Momjian's avatar
Bruce Momjian committed
855
 *
856
 * Return list of primary key fields for the supplied relation,
857 858 859 860 861 862
 * 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
863 864 865 866 867 868 869 870 871
	int16		numatts;
	Oid			relid;
	char	  **results;
	FuncCallContext *funcctx;
	int32		call_cntr;
	int32		max_calls;
	TupleTableSlot *slot;
	AttInMetadata *attinmeta;
	MemoryContext oldcontext;
872 873

	/* stuff done only on the first call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
874 875 876
	if (SRF_IS_FIRSTCALL())
	{
		TupleDesc	tupdesc = NULL;
877 878

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

Bruce Momjian's avatar
Bruce Momjian committed
881 882 883 884
		/*
		 * switch to memory context appropriate for multiple function
		 * calls
		 */
885 886 887 888 889 890
		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))
			elog(ERROR, "dblink_get_pkey: relation does not exist");
891

Bruce Momjian's avatar
Bruce Momjian committed
892 893 894 895
		/*
		 * need a tuple descriptor representing one INT and one TEXT
		 * column
		 */
896
		tupdesc = CreateTemplateTupleDesc(2, false);
897 898 899 900
		TupleDescInitEntry(tupdesc, (AttrNumber) 1, "position",
						   INT4OID, -1, 0, false);
		TupleDescInitEntry(tupdesc, (AttrNumber) 2, "colname",
						   TEXTOID, -1, 0, false);
901

902 903
		/* allocate a slot for a tuple with this tupdesc */
		slot = TupleDescGetSlot(tupdesc);
904

905 906
		/* assign slot to function context */
		funcctx->slot = slot;
907 908

		/*
Bruce Momjian's avatar
Bruce Momjian committed
909 910
		 * Generate attribute metadata needed later to produce tuples from
		 * raw C strings
911
		 */
912 913 914 915 916
		attinmeta = TupleDescGetAttInMetadata(tupdesc);
		funcctx->attinmeta = attinmeta;

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

918
		if ((results != NULL) && (numatts > 0))
919
		{
920
			funcctx->max_calls = numatts;
921

922 923 924
			/* got results, keep track of them */
			funcctx->user_fctx = results;
		}
Bruce Momjian's avatar
Bruce Momjian committed
925 926 927
		else
/* fast track when no results */
			SRF_RETURN_DONE(funcctx);
928

929
		MemoryContextSwitchTo(oldcontext);
Bruce Momjian's avatar
Bruce Momjian committed
930
	}
931

932
	/* stuff done on every call of the function */
Bruce Momjian's avatar
Bruce Momjian committed
933
	funcctx = SRF_PERCALL_SETUP();
934

935 936 937 938 939
	/*
	 * initialize per-call variables
	 */
	call_cntr = funcctx->call_cntr;
	max_calls = funcctx->max_calls;
940

941
	slot = funcctx->slot;
942

943 944
	results = (char **) funcctx->user_fctx;
	attinmeta = funcctx->attinmeta;
945

946
	if (call_cntr < max_calls)	/* do when there is more left to send */
Bruce Momjian's avatar
Bruce Momjian committed
947
	{
948 949 950
		char	  **values;
		HeapTuple	tuple;
		Datum		result;
951

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

955
		sprintf(values[0], "%d", call_cntr + 1);
956

957
		values[1] = results[call_cntr];
958

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

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

Bruce Momjian's avatar
Bruce Momjian committed
965
		SRF_RETURN_NEXT(funcctx, result);
966
	}
Bruce Momjian's avatar
Bruce Momjian committed
967 968 969
	else
/* do when there is no more left */
		SRF_RETURN_DONE(funcctx);
970 971 972
}

/*
973 974 975
 * Note: dblink_last_oid is DEPRECATED;
 * it *will* be removed on next release
 *
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
 * dblink_last_oid
 * return last inserted oid
 */
PG_FUNCTION_INFO_V1(dblink_last_oid);
Datum
dblink_last_oid(PG_FUNCTION_ARGS)
{
	dblink_results *results;

	results = get_res_ptr(PG_GETARG_INT32(0));
	if (results == NULL)
	{
		if (res_id != NIL)
		{
			freeList(res_id);
			res_id = NIL;
			res_id_index = 0;
		}

		elog(ERROR, "dblink_tok: function called with invalid resource id");
	}

	PG_RETURN_OID(PQoidValue(results->res));
}


1002 1003 1004
#ifndef SHRT_MAX
#define SHRT_MAX (0x7FFF)
#endif
1005 1006
/*
 * dblink_build_sql_insert
Bruce Momjian's avatar
Bruce Momjian committed
1007
 *
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
 * 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;
1029 1030
	text	   *relname_text;
	int16	   *pkattnums;
1031 1032
	int			pknumatts_tmp;
	int16		pknumatts = 0;
1033 1034 1035 1036
	char	  **src_pkattvals;
	char	  **tgt_pkattvals;
	ArrayType  *src_pkattvals_arry;
	ArrayType  *tgt_pkattvals_arry;
1037
	int			src_ndim;
1038
	int		   *src_dim;
1039 1040
	int			src_nitems;
	int			tgt_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1041
	int		   *tgt_dim;
1042 1043
	int			tgt_nitems;
	int			i;
1044 1045 1046 1047 1048 1049
	char	   *ptr;
	char	   *sql;
	text	   *sql_text;
	int16		typlen;
	bool		typbyval;
	char		typalign;
1050

1051
	relname_text = PG_GETARG_TEXT_P(0);
1052 1053 1054 1055

	/*
	 * Convert relname to rel OID.
	 */
1056
	relid = get_relid_from_relname(relname_text);
1057
	if (!OidIsValid(relid))
1058
		elog(ERROR, "dblink_build_sql_insert: relation does not exist");
1059 1060

	pkattnums = (int16 *) PG_GETARG_POINTER(1);
1061 1062 1063 1064 1065
	pknumatts_tmp = PG_GETARG_INT32(2);
	if (pknumatts_tmp <= SHRT_MAX)
		pknumatts = pknumatts_tmp;
	else
		elog(ERROR, "Bad input value for pknumatts; too large");
Bruce Momjian's avatar
Bruce Momjian committed
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
	/*
	 * There should be at least one key attribute
	 */
	if (pknumatts == 0)
		elog(ERROR, "dblink_build_sql_insert: number of key attributes must be > 0.");

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

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1077 1078
	 * Source array is made up of key values that will be used to locate
	 * the tuple of interest from the local system.
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	 */
	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)
		elog(ERROR, "dblink_build_sql_insert: source key array length does not match number of key attributes.");

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

1097 1098 1099 1100 1101
	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)));
1102 1103
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1104 1105 1106
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1107 1108
	 * Target array is made up of key values that will be used to build
	 * the SQL string for use on the remote system.
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
	 */
	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)
		elog(ERROR, "dblink_build_sql_insert: target key array length does not match number of key attributes.");

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

1127 1128 1129 1130 1131
	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)));
1132 1133
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	}

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

	/*
	 * Make it into TEXT for return to the client
	 */
	sql_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(sql)));

	/*
	 * And send it
	 */
	PG_RETURN_TEXT_P(sql_text);
}


/*
 * dblink_build_sql_delete
Bruce Momjian's avatar
Bruce Momjian committed
1155
 *
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
 * 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
1173 1174
	text	   *relname_text;
	int16	   *pkattnums;
1175 1176
	int			pknumatts_tmp;
	int16		pknumatts = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1177 1178
	char	  **tgt_pkattvals;
	ArrayType  *tgt_pkattvals_arry;
1179
	int			tgt_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1180
	int		   *tgt_dim;
1181 1182
	int			tgt_nitems;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1183 1184 1185
	char	   *ptr;
	char	   *sql;
	text	   *sql_text;
1186 1187 1188
	int16		typlen;
	bool		typbyval;
	char		typalign;
1189

1190
	relname_text = PG_GETARG_TEXT_P(0);
1191 1192 1193 1194

	/*
	 * Convert relname to rel OID.
	 */
1195
	relid = get_relid_from_relname(relname_text);
1196
	if (!OidIsValid(relid))
1197
		elog(ERROR, "dblink_build_sql_delete: relation does not exist");
1198 1199

	pkattnums = (int16 *) PG_GETARG_POINTER(1);
1200 1201 1202 1203 1204
	pknumatts_tmp = PG_GETARG_INT32(2);
	if (pknumatts_tmp <= SHRT_MAX)
		pknumatts = pknumatts_tmp;
	else
		elog(ERROR, "Bad input value for pknumatts; too large");
Bruce Momjian's avatar
Bruce Momjian committed
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214
	/*
	 * There should be at least one key attribute
	 */
	if (pknumatts == 0)
		elog(ERROR, "dblink_build_sql_insert: number of key attributes must be > 0.");

	tgt_pkattvals_arry = PG_GETARG_ARRAYTYPE_P(3);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1215 1216
	 * Target array is made up of key values that will be used to build
	 * the SQL string for use on the remote system.
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
	 */
	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)
		elog(ERROR, "dblink_build_sql_insert: target key array length does not match number of key attributes.");

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

1235 1236 1237 1238 1239
	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)));
1240 1241
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
	}

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

	/*
	 * Make it into TEXT for return to the client
	 */
	sql_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(sql)));

	/*
	 * And send it
	 */
	PG_RETURN_TEXT_P(sql_text);
}


/*
 * dblink_build_sql_update
Bruce Momjian's avatar
Bruce Momjian committed
1263
 *
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
 * 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
1285 1286
	text	   *relname_text;
	int16	   *pkattnums;
1287 1288
	int			pknumatts_tmp;
	int16		pknumatts = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1289 1290 1291 1292
	char	  **src_pkattvals;
	char	  **tgt_pkattvals;
	ArrayType  *src_pkattvals_arry;
	ArrayType  *tgt_pkattvals_arry;
1293
	int			src_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1294
	int		   *src_dim;
1295 1296
	int			src_nitems;
	int			tgt_ndim;
Bruce Momjian's avatar
Bruce Momjian committed
1297
	int		   *tgt_dim;
1298 1299
	int			tgt_nitems;
	int			i;
Bruce Momjian's avatar
Bruce Momjian committed
1300 1301 1302
	char	   *ptr;
	char	   *sql;
	text	   *sql_text;
1303 1304 1305
	int16		typlen;
	bool		typbyval;
	char		typalign;
1306

1307
	relname_text = PG_GETARG_TEXT_P(0);
1308 1309 1310 1311

	/*
	 * Convert relname to rel OID.
	 */
1312
	relid = get_relid_from_relname(relname_text);
1313
	if (!OidIsValid(relid))
1314
		elog(ERROR, "dblink_build_sql_update: relation does not exist");
1315 1316

	pkattnums = (int16 *) PG_GETARG_POINTER(1);
1317 1318 1319 1320 1321
	pknumatts_tmp = PG_GETARG_INT32(2);
	if (pknumatts_tmp <= SHRT_MAX)
		pknumatts = pknumatts_tmp;
	else
		elog(ERROR, "Bad input value for pknumatts; too large");
Bruce Momjian's avatar
Bruce Momjian committed
1322

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
	/*
	 * There should be one source array key values for each key attnum
	 */
	if (pknumatts == 0)
		elog(ERROR, "dblink_build_sql_insert: number of key attributes must be > 0.");

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

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1333 1334
	 * Source array is made up of key values that will be used to locate
	 * the tuple of interest from the local system.
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
	 */
	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)
		elog(ERROR, "dblink_build_sql_insert: source key array length does not match number of key attributes.");

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

1353 1354 1355 1356 1357
	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)));
1358 1359
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1360 1361 1362
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1363 1364
	 * Target array is made up of key values that will be used to build
	 * the SQL string for use on the remote system.
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
	 */
	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)
		elog(ERROR, "dblink_build_sql_insert: target key array length does not match number of key attributes.");

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

1383 1384 1385 1386 1387
	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)));
1388 1389
		ptr = att_addlength(ptr, typlen, PointerGetDatum(ptr));
		ptr = (char *) att_align(ptr, typalign);
1390
	}
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405

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

	/*
	 * Make it into TEXT for return to the client
	 */
	sql_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(sql)));

	/*
	 * And send it
	 */
	PG_RETURN_TEXT_P(sql_text);
1406 1407 1408
}

/*
1409 1410 1411 1412 1413 1414 1415 1416 1417
 * 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)
{
Bruce Momjian's avatar
Bruce Momjian committed
1418
	text	   *result_text;
1419 1420 1421 1422 1423 1424 1425

	result_text = DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(debug_query_string)));
	PG_RETURN_TEXT_P(result_text);
}


/*************************************************************
1426 1427 1428 1429 1430 1431 1432 1433
 * internal functions
 */


/*
 * init_dblink_results
 *	 - create an empty dblink_results data structure
 */
1434
static dblink_results *
1435 1436
init_dblink_results(MemoryContext fn_mcxt)
{
1437 1438
	MemoryContext oldcontext;
	dblink_results *retval;
1439 1440 1441

	oldcontext = MemoryContextSwitchTo(fn_mcxt);

1442
	retval = (dblink_results *) palloc0(sizeof(dblink_results));
1443 1444

	retval->tup_num = -1;
Bruce Momjian's avatar
Bruce Momjian committed
1445
	retval->res_id_index = -1;
1446 1447 1448 1449 1450 1451
	retval->res = NULL;

	MemoryContextSwitchTo(oldcontext);

	return retval;
}
1452 1453 1454

/*
 * get_pkey_attnames
Bruce Momjian's avatar
Bruce Momjian committed
1455
 *
1456 1457 1458
 * Get the primary key attnames for the given relation.
 * Return NULL, and set numatts = 0, if no primary key exists.
 */
1459
static char **
1460 1461
get_pkey_attnames(Oid relid, int16 *numatts)
{
Bruce Momjian's avatar
Bruce Momjian committed
1462 1463 1464 1465 1466 1467 1468 1469
	Relation	indexRelation;
	ScanKeyData entry;
	HeapScanDesc scan;
	HeapTuple	indexTuple;
	int			i;
	char	  **result = NULL;
	Relation	rel;
	TupleDesc	tupdesc;
1470

1471
	/* open relation using relid, get tupdesc */
1472 1473 1474
	rel = relation_open(relid, AccessShareLock);
	tupdesc = rel->rd_att;

1475
	/* initialize numatts to 0 in case no primary key exists */
1476 1477
	*numatts = 0;

1478
	/* use relid to get all related indexes */
1479 1480 1481
	indexRelation = heap_openr(IndexRelationName, AccessShareLock);
	ScanKeyEntryInitialize(&entry, 0, Anum_pg_index_indrelid,
						   F_OIDEQ, ObjectIdGetDatum(relid));
1482
	scan = heap_beginscan(indexRelation, SnapshotNow, 1, &entry);
1483

1484
	while ((indexTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1485
	{
Bruce Momjian's avatar
Bruce Momjian committed
1486
		Form_pg_index index = (Form_pg_index) GETSTRUCT(indexTuple);
1487

1488
		/* we're only interested if it is the primary key */
1489 1490
		if (index->indisprimary == TRUE)
		{
1491
			*numatts = index->indnatts;
1492 1493 1494
			if (*numatts > 0)
			{
				result = (char **) palloc(*numatts * sizeof(char *));
1495

1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
				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;
}

1509
static char *
1510 1511
get_sql_insert(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
	Relation	rel;
	char	   *relname;
	HeapTuple	tuple;
	TupleDesc	tupdesc;
	int			natts;
	StringInfo	str = makeStringInfo();
	char	   *sql;
	char	   *val;
	int16		key;
	int			i;
	bool		needComma;
1523

1524 1525 1526
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1527 1528 1529 1530 1531 1532 1533 1534
	/*
	 * 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);
1535 1536
	if (!tuple)
		elog(ERROR, "dblink_build_sql_insert: row not found");
1537

1538
	appendStringInfo(str, "INSERT INTO %s(", relname);
1539 1540

	needComma = false;
1541 1542
	for (i = 0; i < natts; i++)
	{
1543 1544 1545 1546
		if (tupdesc->attrs[i]->attisdropped)
			continue;

		if (needComma)
1547 1548
			appendStringInfo(str, ",");

1549
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1550
				  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
1551
		needComma = true;
1552 1553 1554 1555 1556 1557 1558
	}

	appendStringInfo(str, ") VALUES(");

	/*
	 * remember attvals are 1 based
	 */
1559
	needComma = false;
1560 1561
	for (i = 0; i < natts; i++)
	{
1562 1563 1564 1565
		if (tupdesc->attrs[i]->attisdropped)
			continue;

		if (needComma)
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
			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)
		{
1580
			appendStringInfo(str, "%s", quote_literal_cstr(val));
1581 1582 1583 1584
			pfree(val);
		}
		else
			appendStringInfo(str, "NULL");
1585
		needComma = true;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
	}
	appendStringInfo(str, ")");

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

	return (sql);
}

1597
static char *
1598 1599
get_sql_delete(Oid relid, int16 *pkattnums, int16 pknumatts, char **tgt_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1600 1601 1602 1603 1604 1605 1606 1607
	Relation	rel;
	char	   *relname;
	TupleDesc	tupdesc;
	int			natts;
	StringInfo	str = makeStringInfo();
	char	   *sql;
	char	   *val;
	int			i;
1608

1609 1610 1611
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1612 1613 1614 1615 1616 1617 1618
	/*
	 * Open relation using relid
	 */
	rel = relation_open(relid, AccessShareLock);
	tupdesc = rel->rd_att;
	natts = tupdesc->natts;

1619
	appendStringInfo(str, "DELETE FROM %s WHERE ", relname);
1620 1621
	for (i = 0; i < pknumatts; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1622
		int16		pkattnum = pkattnums[i];
1623 1624 1625 1626

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

1627
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1628
		quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
1629 1630 1631 1632

		if (tgt_pkattvals != NULL)
			val = pstrdup(tgt_pkattvals[i]);
		else
1633
		{
1634
			elog(ERROR, "Target key array must not be NULL");
1635 1636
			val = NULL;			/* keep compiler quiet */
		}
1637 1638 1639

		if (val != NULL)
		{
1640
			appendStringInfo(str, " = %s", quote_literal_cstr(val));
1641 1642 1643
			pfree(val);
		}
		else
1644
			appendStringInfo(str, " IS NULL");
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
	}

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

	return (sql);
}

1655
static char *
1656 1657
get_sql_update(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals, char **tgt_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
	Relation	rel;
	char	   *relname;
	HeapTuple	tuple;
	TupleDesc	tupdesc;
	int			natts;
	StringInfo	str = makeStringInfo();
	char	   *sql;
	char	   *val;
	int16		key;
	int			i;
	bool		needComma;
1669

1670 1671 1672
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1673 1674 1675 1676 1677 1678 1679 1680
	/*
	 * 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);
1681 1682
	if (!tuple)
		elog(ERROR, "dblink_build_sql_update: row not found");
1683

1684
	appendStringInfo(str, "UPDATE %s SET ", relname);
1685

1686
	needComma = false;
1687 1688
	for (i = 0; i < natts; i++)
	{
1689 1690 1691 1692 1693
		if (tupdesc->attrs[i]->attisdropped)
			continue;

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

1695
		appendStringInfo(str, "%s = ",
Bruce Momjian's avatar
Bruce Momjian committed
1696
				  quote_ident_cstr(NameStr(tupdesc->attrs[i]->attname)));
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709

		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)
		{
1710
			appendStringInfo(str, "%s", quote_literal_cstr(val));
1711 1712 1713 1714
			pfree(val);
		}
		else
			appendStringInfo(str, "NULL");
1715
		needComma = true;
1716 1717 1718 1719 1720 1721
	}

	appendStringInfo(str, " WHERE ");

	for (i = 0; i < pknumatts; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1722
		int16		pkattnum = pkattnums[i];
1723 1724 1725 1726

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

1727
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1728
		quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
1729 1730 1731 1732 1733 1734 1735 1736

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

		if (val != NULL)
		{
1737
			appendStringInfo(str, " = %s", quote_literal_cstr(val));
1738 1739 1740
			pfree(val);
		}
		else
1741
			appendStringInfo(str, " IS NULL");
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
	}

	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
1759 1760 1761
	text	   *rawstr_text;
	text	   *result_text;
	char	   *result;
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776

	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
1777 1778 1779
	text	   *rawstr_text;
	text	   *result_text;
	char	   *result;
1780 1781 1782 1783 1784 1785 1786 1787

	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;
}

1788
static int16
1789 1790
get_attnum_pk_pos(int16 *pkattnums, int16 pknumatts, int16 key)
{
Bruce Momjian's avatar
Bruce Momjian committed
1791
	int			i;
1792 1793

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1794
	 * Not likely a long list anyway, so just scan for the value
1795 1796 1797 1798 1799 1800 1801 1802
	 */
	for (i = 0; i < pknumatts; i++)
		if (key == pkattnums[i])
			return i;

	return -1;
}

1803
static HeapTuple
1804 1805
get_tuple_of_interest(Oid relid, int16 *pkattnums, int16 pknumatts, char **src_pkattvals)
{
Bruce Momjian's avatar
Bruce Momjian committed
1806 1807 1808 1809 1810 1811 1812 1813 1814
	Relation	rel;
	char	   *relname;
	TupleDesc	tupdesc;
	StringInfo	str = makeStringInfo();
	char	   *sql = NULL;
	int			ret;
	HeapTuple	tuple;
	int			i;
	char	   *val = NULL;
1815

1816 1817 1818
	/* get relation name including any needed schema prefix and quoting */
	relname = generate_relation_name(relid);

1819 1820 1821 1822
	/*
	 * Open relation using relid
	 */
	rel = relation_open(relid, AccessShareLock);
1823 1824
	tupdesc = CreateTupleDescCopy(rel->rd_att);
	relation_close(rel, AccessShareLock);
1825 1826 1827 1828 1829 1830 1831 1832

	/*
	 * Connect to SPI manager
	 */
	if ((ret = SPI_connect()) < 0)
		elog(ERROR, "get_tuple_of_interest: SPI_connect returned %d", ret);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1833 1834
	 * Build sql statement to look up tuple of interest Use src_pkattvals
	 * as the criteria.
1835
	 */
1836
	appendStringInfo(str, "SELECT * FROM %s WHERE ", relname);
1837 1838 1839

	for (i = 0; i < pknumatts; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1840
		int16		pkattnum = pkattnums[i];
1841 1842 1843 1844

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

1845
		appendStringInfo(str, "%s",
Bruce Momjian's avatar
Bruce Momjian committed
1846
		quote_ident_cstr(NameStr(tupdesc->attrs[pkattnum - 1]->attname)));
1847 1848 1849 1850

		val = pstrdup(src_pkattvals[i]);
		if (val != NULL)
		{
1851
			appendStringInfo(str, " = %s", quote_literal_cstr(val));
1852 1853 1854
			pfree(val);
		}
		else
1855
			appendStringInfo(str, " IS NULL");
1856 1857 1858 1859 1860
	}

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

1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
	/*
	 * Retrieve the desired tuple
	 */
	ret = SPI_exec(sql, 0);
	pfree(sql);

	/*
	 * Only allow one qualifying tuple
	 */
	if ((ret == SPI_OK_SELECT) && (SPI_processed > 1))
		elog(ERROR, "get_tuple_of_interest: Source criteria may not match more than one record.");
	else if (ret == SPI_OK_SELECT && SPI_processed == 1)
	{
		SPITupleTable *tuptable = SPI_tuptable;
Bruce Momjian's avatar
Bruce Momjian committed
1876

1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
		tuple = SPI_copytuple(tuptable->vals[0]);

		return tuple;
	}
	else
	{
		/*
		 * no qualifying tuples
		 */
		return NULL;
	}

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

1895 1896
static Oid
get_relid_from_relname(text *relname_text)
1897
{
1898 1899 1900
	RangeVar   *relvar;
	Relation	rel;
	Oid			relid;
1901

1902 1903 1904 1905
	relvar = makeRangeVarFromNameList(textToQualifiedNameList(relname_text, "get_relid_from_relname"));
	rel = heap_openrv(relvar, AccessShareLock);
	relid = RelationGetRelid(rel);
	relation_close(rel, AccessShareLock);
1906 1907 1908 1909

	return relid;
}

Bruce Momjian's avatar
Bruce Momjian committed
1910
static dblink_results *
1911 1912
get_res_ptr(int32 res_id_index)
{
Bruce Momjian's avatar
Bruce Momjian committed
1913
	List	   *ptr;
1914 1915 1916 1917

	/*
	 * short circuit empty list
	 */
Bruce Momjian's avatar
Bruce Momjian committed
1918
	if (res_id == NIL)
1919 1920 1921 1922 1923 1924 1925
		return NULL;

	/*
	 * OK, should be good to go
	 */
	foreach(ptr, res_id)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1926 1927
		dblink_results *this_res_id = (dblink_results *) lfirst(ptr);

1928 1929 1930 1931 1932 1933 1934 1935 1936
		if (this_res_id->res_id_index == res_id_index)
			return this_res_id;
	}
	return NULL;
}

/*
 * Add node to global List res_id
 */
1937
static void
Bruce Momjian's avatar
Bruce Momjian committed
1938
append_res_ptr(dblink_results * results)
1939 1940 1941 1942 1943 1944 1945 1946
{
	res_id = lappend(res_id, results);
}

/*
 * Remove node from global List
 * using res_id_index
 */
1947
static void
Bruce Momjian's avatar
Bruce Momjian committed
1948
remove_res_ptr(dblink_results * results)
1949 1950 1951 1952 1953 1954 1955
{
	res_id = lremove(results, res_id);

	if (res_id == NIL)
		res_id_index = 0;
}

1956 1957 1958
static TupleDesc
pgresultGetTupleDesc(PGresult *res)
{
Bruce Momjian's avatar
Bruce Momjian committed
1959 1960 1961 1962 1963 1964 1965 1966 1967
	int			natts;
	AttrNumber	attnum;
	TupleDesc	desc;
	char	   *attname;
	int32		atttypmod;
	int			attdim;
	bool		attisset;
	Oid			atttypid;
	int			i;
1968 1969 1970 1971 1972 1973 1974 1975

	/*
	 * allocate a new tuple descriptor
	 */
	natts = PQnfields(res);
	if (natts < 1)
		elog(ERROR, "cannot create a description for empty results");

1976
	desc = CreateTemplateTupleDesc(natts, false);
1977 1978 1979 1980 1981 1982

	attnum = 0;

	for (i = 0; i < natts; i++)
	{
		/*
Bruce Momjian's avatar
Bruce Momjian committed
1983 1984
		 * for each field, get the name and type information from the
		 * query result and have TupleDescInitEntry fill in the attribute
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
		 * information we need.
		 */
		attnum++;

		attname = PQfname(res, i);
		atttypid = PQftype(res, i);
		atttypmod = PQfmod(res, i);

		if (PQfsize(res, i) != get_typlen(atttypid))
			elog(ERROR, "Size of remote field \"%s\" does not match size "
Bruce Momjian's avatar
Bruce Momjian committed
1995 1996 1997
				 "of local type \"%s\"",
				 attname,
				 format_type_with_typemod(atttypid, atttypmod));
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007

		attdim = 0;
		attisset = false;

		TupleDescInitEntry(desc, attnum, attname, atttypid,
						   atttypmod, attdim, attisset);
	}

	return desc;
}
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041

/*
 * 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))
		elog(ERROR, "cache lookup of relation %u failed", relid);
	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;
}