ri_triggers.c 85.6 KB
Newer Older
1 2 3 4 5 6 7 8
/* ----------
 * ri_triggers.c
 *
 *	Generic trigger procedures for referential integrity constraint
 *	checks.
 *
 *	1999 Jan Wieck
 *
9
 * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.15 2000/05/29 01:59:08 tgl Exp $
10 11 12 13
 *
 * ----------
 */

Jan Wieck's avatar
Jan Wieck committed
14 15 16 17

/* ----------
 * Internal TODO:
 *
Jan Wieck's avatar
Jan Wieck committed
18
 *		Add MATCH PARTIAL logic.
Jan Wieck's avatar
Jan Wieck committed
19 20 21
 * ----------
 */

22 23 24
#include "postgres.h"

#include "access/heapam.h"
25 26
#include "catalog/pg_operator.h"
#include "catalog/catname.h"
27 28
#include "commands/trigger.h"
#include "executor/spi.h"
29
#include "executor/spi_priv.h"
30 31
#include "fmgr.h"
#include "lib/hasht.h"
32
#include "utils/builtins.h"
33
#include "utils/mcxt.h"
34
#include "utils/syscache.h"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63


/* ----------
 * Local definitions
 * ----------
 */
#define RI_CONSTRAINT_NAME_ARGNO		0
#define RI_FK_RELNAME_ARGNO				1
#define RI_PK_RELNAME_ARGNO				2
#define RI_MATCH_TYPE_ARGNO				3
#define RI_FIRST_ATTNAME_ARGNO			4

#define RI_MAX_NUMKEYS					16
#define RI_MAX_ARGUMENTS		(RI_FIRST_ATTNAME_ARGNO + (RI_MAX_NUMKEYS * 2))
#define RI_KEYPAIR_FK_IDX				0
#define RI_KEYPAIR_PK_IDX				1

#define RI_INIT_QUERYHASHSIZE			128
#define RI_INIT_OPREQHASHSIZE			128

#define RI_MATCH_TYPE_UNSPECIFIED		0
#define RI_MATCH_TYPE_FULL				1
#define RI_MATCH_TYPE_PARTIAL			2

#define RI_KEYS_ALL_NULL				0
#define RI_KEYS_SOME_NULL				1
#define RI_KEYS_NONE_NULL				2


Jan Wieck's avatar
Jan Wieck committed
64 65 66 67
#define RI_PLAN_CHECK_LOOKUPPK_NOCOLS	1
#define RI_PLAN_CHECK_LOOKUPPK			2
#define RI_PLAN_CASCADE_DEL_DODELETE	1
#define RI_PLAN_CASCADE_UPD_DOUPDATE	1
68 69
#define RI_PLAN_NOACTION_DEL_CHECKREF	1
#define RI_PLAN_NOACTION_UPD_CHECKREF	1
Jan Wieck's avatar
Jan Wieck committed
70 71
#define RI_PLAN_RESTRICT_DEL_CHECKREF	1
#define RI_PLAN_RESTRICT_UPD_CHECKREF	1
Jan Wieck's avatar
Jan Wieck committed
72 73
#define RI_PLAN_SETNULL_DEL_DOUPDATE	1
#define RI_PLAN_SETNULL_UPD_DOUPDATE	1
74 75 76 77 78 79 80 81


/* ----------
 * RI_QueryKey
 *
 *	The key identifying a prepared SPI plan in our private hashtable
 * ----------
 */
82 83 84 85 86 87 88 89 90
typedef struct RI_QueryKey
{
	int32		constr_type;
	Oid			constr_id;
	int32		constr_queryno;
	Oid			fk_relid;
	Oid			pk_relid;
	int32		nkeypairs;
	int16		keypair[RI_MAX_NUMKEYS][2];
91 92 93 94 95 96 97
} RI_QueryKey;


/* ----------
 * RI_QueryHashEntry
 * ----------
 */
98 99 100 101
typedef struct RI_QueryHashEntry
{
	RI_QueryKey key;
	void	   *plan;
102 103 104
} RI_QueryHashEntry;


105 106 107 108
typedef struct RI_OpreqHashEntry
{
	Oid			typeid;
	FmgrInfo	oprfmgrinfo;
109 110 111 112 113 114 115 116
} RI_OpreqHashEntry;



/* ----------
 * Local data
 * ----------
 */
117 118
static HTAB *ri_query_cache = (HTAB *) NULL;
static HTAB *ri_opreq_cache = (HTAB *) NULL;
119 120 121 122 123 124


/* ----------
 * Local function prototypes
 * ----------
 */
125 126 127
static int	ri_DetermineMatchType(char *str);
static int ri_NullCheck(Relation rel, HeapTuple tup,
			 RI_QueryKey *key, int pairidx);
128
static void ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id,
129 130 131 132 133 134 135
					 int32 constr_queryno,
					 Relation fk_rel, Relation pk_rel,
					 int argc, char **argv);
static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
			 RI_QueryKey *key, int pairidx);
static bool ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
				  RI_QueryKey *key, int pairidx);
136
static bool ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup,
137
			   HeapTuple newtup, RI_QueryKey *key, int pairidx);
138 139 140 141 142 143 144 145 146 147 148
static bool ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue);

static void ri_InitHashTables(void);
static void *ri_FetchPreparedPlan(RI_QueryKey *key);
static void ri_HashPreparedPlan(RI_QueryKey *key, void *plan);



/* ----------
 * RI_FKey_check -
 *
149
 *	Check foreign key existence (combined for INSERT and UPDATE).
150 151
 * ----------
 */
152 153
static Datum
RI_FKey_check(PG_FUNCTION_ARGS)
154
{
155
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
156 157 158 159 160 161 162 163 164 165 166 167 168 169
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		check_values[RI_MAX_NUMKEYS];
	char		check_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
	int			match_type;

170
	ReferentialIntegritySnapshotOverride = true;
171 172 173 174 175

	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
176
	if (!CALLED_AS_TRIGGER(fcinfo))
177
		elog(ERROR, "RI_FKey_check() not fired by trigger manager");
178 179
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
180 181
		elog(ERROR, "RI_FKey_check() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) &&
182
		!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
183 184 185
		elog(ERROR, "RI_FKey_check() must be fired for INSERT or UPDATE");

	/* ----------
186
	 * Check for the correct # of call arguments
187 188 189
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
190
	tgargs = trigdata->tg_trigger->tgargs;
191 192 193 194
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_check()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_check()",
195
			 RI_MAX_NUMKEYS);
196 197 198 199 200 201

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the new tuple.
	 * ----------
	 */
202 203
	fk_rel = trigdata->tg_relation;
	pk_rel = heap_openr(tgargs[RI_PK_RELNAME_ARGNO], NoLock);
204 205 206 207
	if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
	{
		old_row = trigdata->tg_trigtuple;
		new_row = trigdata->tg_newtuple;
208 209 210
	}
	else
	{
211 212 213 214 215 216 217 218 219
		old_row = NULL;
		new_row = trigdata->tg_trigtuple;
	}

	/* ----------
	 * SQL3 11.9 <referential constraint definition>
	 *	Gereral rules 2) a):
	 *		If Rf and Rt are empty (no columns to compare given)
	 *		constraint is true if 0 < (SELECT COUNT(*) FROM T)
Jan Wieck's avatar
Jan Wieck committed
220 221 222 223
	 *
	 *	Note: The special case that no columns are given cannot
	 *		occur up to now in Postgres, it's just there for
	 *		future enhancements.
224 225
	 * ----------
	 */
226 227
	if (tgnargs == 4)
	{
Jan Wieck's avatar
Jan Wieck committed
228
		ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
229 230 231
							 RI_PLAN_CHECK_LOOKUPPK_NOCOLS,
							 fk_rel, pk_rel,
							 tgnargs, tgargs);
232 233 234 235 236 237 238

		if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
		{
			char		querystr[8192];

			/* ----------
			 * The query string built is
239
			 *	SELECT oid FROM <pktable>
240 241
			 * ----------
			 */
242 243 244
			sprintf(querystr, "SELECT oid FROM \"%s\" FOR UPDATE OF \"%s\"",
					tgargs[RI_PK_RELNAME_ARGNO],
					tgargs[RI_PK_RELNAME_ARGNO]);
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

			/* ----------
			 * Prepare, save and remember the new plan.
			 * ----------
			 */
			qplan = SPI_prepare(querystr, 0, NULL);
			qplan = SPI_saveplan(qplan);
			ri_HashPreparedPlan(&qkey, qplan);
		}
		heap_close(pk_rel, NoLock);

		/* ----------
		 * Execute the plan
		 * ----------
		 */
		if (SPI_connect() != SPI_OK_CONNECT)
			elog(NOTICE, "SPI_connect() failed in RI_FKey_check()");

		if (SPI_execp(qplan, check_values, check_nulls, 1) != SPI_OK_SELECT)
			elog(ERROR, "SPI_execp() failed in RI_FKey_check()");
265

266 267
		if (SPI_processed == 0)
			elog(ERROR, "%s referential integrity violation - "
268 269 270
				 "no rows found in %s",
				 tgargs[RI_CONSTRAINT_NAME_ARGNO],
				 tgargs[RI_PK_RELNAME_ARGNO]);
271 272 273 274

		if (SPI_finish() != SPI_OK_FINISH)
			elog(NOTICE, "SPI_finish() failed in RI_FKey_check()");

275
		return PointerGetDatum(NULL);
276 277 278

	}

279 280 281 282 283
	match_type = ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]);

	if (match_type == RI_MATCH_TYPE_PARTIAL)
	{
		elog(ERROR, "MATCH PARTIAL not yet supported");
284
		return PointerGetDatum(NULL);
285 286 287
	}

	ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
288 289
						 RI_PLAN_CHECK_LOOKUPPK, fk_rel, pk_rel,
						 tgnargs, tgargs);
290 291 292 293 294 295 296

	switch (ri_NullCheck(fk_rel, new_row, &qkey, RI_KEYPAIR_FK_IDX))
	{
		case RI_KEYS_ALL_NULL:
			/* ----------
			 * No check - if NULLs are allowed at all is
			 * already checked by NOT NULL constraint.
297 298 299
			 *
			 * This is true for MATCH FULL, MATCH PARTIAL, and
			 * MATCH <unspecified>
300 301 302
			 * ----------
			 */
			heap_close(pk_rel, NoLock);
303
			return PointerGetDatum(NULL);
304

305 306 307
		case RI_KEYS_SOME_NULL:
			/* ----------
			 * This is the only case that differs between the
308
			 * three kinds of MATCH.
309 310 311 312 313 314
			 * ----------
			 */
			switch (match_type)
			{
				case RI_MATCH_TYPE_FULL:
					/* ----------
315
					 * Not allowed - MATCH FULL says either all or none
316 317 318 319
					 * of the attributes can be NULLs
					 * ----------
					 */
					elog(ERROR, "%s referential integrity violation - "
320 321 322
						 "MATCH FULL doesn't allow mixing of NULL "
						 "and NON-NULL key values",
						 tgargs[RI_CONSTRAINT_NAME_ARGNO]);
323
					heap_close(pk_rel, NoLock);
324
					return PointerGetDatum(NULL);
325 326 327 328 329 330 331 332

				case RI_MATCH_TYPE_UNSPECIFIED:
					/* ----------
					 * MATCH <unspecified> - if ANY column is null, we
					 * have a match.
					 * ----------
					 */
					heap_close(pk_rel, NoLock);
333
					return PointerGetDatum(NULL);
334 335 336 337 338

				case RI_MATCH_TYPE_PARTIAL:
					/* ----------
					 * MATCH PARTIAL - all non-null columns must match.
					 * (not implemented, can be done by modifying the query
339 340
					 * below to only include non-null columns, or by
					 * writing a special version here)
341 342 343 344
					 * ----------
					 */
					elog(ERROR, "MATCH PARTIAL not yet implemented");
					heap_close(pk_rel, NoLock);
345
					return PointerGetDatum(NULL);
346 347 348 349 350
			}

		case RI_KEYS_NONE_NULL:
			/* ----------
			 * Have a full qualified key - continue below for all three
351
			 * kinds of MATCH.
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
			 * ----------
			 */
			break;
	}
	heap_close(pk_rel, NoLock);

	/* ----------
	 * Note:
	 * We cannot avoid the check on UPDATE, even if old and new
	 * key are the same. Otherwise, someone could DELETE the PK
	 * that consists of the DEFAULT values, and if there are any
	 * references, a ON DELETE SET DEFAULT action would update
	 * the references to exactly these values but we wouldn't see
	 * that weired case (this is the only place to see it).
	 * ----------
	 */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(NOTICE, "SPI_connect() failed in RI_FKey_check()");

	/* ----------
	 * Fetch or prepare a saved plan for the real check
	 * ----------
	 */
	if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
	{
		char		buf[256];
		char		querystr[8192];
379
		char	   *querysep;
380 381 382 383 384 385 386 387 388 389 390
		Oid			queryoids[RI_MAX_NUMKEYS];

		/* ----------
		 * The query string built is
		 *	SELECT oid FROM <pktable> WHERE pkatt1 = $1 [AND ...]
		 * The type id's for the $ parameters are those of the
		 * corresponding FK attributes. Thus, SPI_prepare could
		 * eventually fail if the parser cannot identify some way
		 * how to compare these two types by '='.
		 * ----------
		 */
391 392
		sprintf(querystr, "SELECT oid FROM \"%s\"",
				tgargs[RI_PK_RELNAME_ARGNO]);
393 394 395
		querysep = "WHERE";
		for (i = 0; i < qkey.nkeypairs; i++)
		{
396 397
			sprintf(buf, " %s \"%s\" = $%d", querysep,
					tgargs[5 + i * 2], i + 1);
398 399 400
			strcat(querystr, buf);
			querysep = "AND";
			queryoids[i] = SPI_gettypeid(fk_rel->rd_att,
401
									 qkey.keypair[i][RI_KEYPAIR_FK_IDX]);
402 403
		}
		sprintf(buf, " FOR UPDATE OF \"%s\"",
404
				tgargs[RI_PK_RELNAME_ARGNO]);
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
		strcat(querystr, buf);

		/* ----------
		 * Prepare, save and remember the new plan.
		 * ----------
		 */
		qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
		qplan = SPI_saveplan(qplan);
		ri_HashPreparedPlan(&qkey, qplan);
	}

	/* ----------
	 * We have a plan now. Build up the arguments for SPI_execp()
	 * from the key values in the new FK tuple.
	 * ----------
	 */
	for (i = 0; i < qkey.nkeypairs; i++)
	{
		/* ----------
		 * We can implement MATCH PARTIAL by excluding this column from
425 426 427
		 * the query if it is null.  Simple!  Unfortunately, the
		 * referential actions aren't so I've not bothered to do so
		 * for the moment.
428 429
		 * ----------
		 */
430

431
		check_values[i] = SPI_getbinval(new_row,
432 433 434 435
										fk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_FK_IDX],
										&isnull);
		if (isnull)
436 437 438 439 440 441 442 443 444 445 446 447
			check_nulls[i] = 'n';
		else
			check_nulls[i] = ' ';
	}
	check_nulls[i] = '\0';

	/* ----------
	 * Now check that foreign key exists in PK table
	 * ----------
	 */
	if (SPI_execp(qplan, check_values, check_nulls, 1) != SPI_OK_SELECT)
		elog(ERROR, "SPI_execp() failed in RI_FKey_check()");
448

449 450
	if (SPI_processed == 0)
		elog(ERROR, "%s referential integrity violation - "
451 452 453 454
			 "key referenced from %s not found in %s",
			 tgargs[RI_CONSTRAINT_NAME_ARGNO],
			 tgargs[RI_FK_RELNAME_ARGNO],
			 tgargs[RI_PK_RELNAME_ARGNO]);
455 456 457 458

	if (SPI_finish() != SPI_OK_FINISH)
		elog(NOTICE, "SPI_finish() failed in RI_FKey_check()");

459
	return PointerGetDatum(NULL);
460 461 462 463 464 465

	/* ----------
	 * Never reached
	 * ----------
	 */
	elog(ERROR, "internal error #1 in ri_triggers.c");
466
	return PointerGetDatum(NULL);
467 468 469 470 471 472
}


/* ----------
 * RI_FKey_check_ins -
 *
473
 *	Check foreign key existence at insert event on FK table.
474 475
 * ----------
 */
476 477
Datum
RI_FKey_check_ins(PG_FUNCTION_ARGS)
478
{
479
	return RI_FKey_check(fcinfo);
480 481 482 483 484 485
}


/* ----------
 * RI_FKey_check_upd -
 *
486
 *	Check foreign key existence at update event on FK table.
487 488
 * ----------
 */
489 490
Datum
RI_FKey_check_upd(PG_FUNCTION_ARGS)
491
{
492
	return RI_FKey_check(fcinfo);
493 494 495 496 497 498 499
}


/* ----------
 * RI_FKey_noaction_del -
 *
 *	Give an error and roll back the current transaction if the
500 501
 *	delete has resulted in a violation of the given referential
 *	integrity constraint.
502 503
 * ----------
 */
504 505
Datum
RI_FKey_noaction_del(PG_FUNCTION_ARGS)
506
{
507
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
508 509 510 511 512 513 514 515 516 517 518
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		del_values[RI_MAX_NUMKEYS];
	char		del_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
519 520 521 522 523 524 525

	ReferentialIntegritySnapshotOverride = true;

	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
526
	if (!CALLED_AS_TRIGGER(fcinfo))
527
		elog(ERROR, "RI_FKey_noaction_del() not fired by trigger manager");
528 529
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
530 531 532 533 534
		elog(ERROR, "RI_FKey_noaction_del() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_noaction_del() must be fired for DELETE");

	/* ----------
535
	 * Check for the correct # of call arguments
536 537 538
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
539
	tgargs = trigdata->tg_trigger->tgargs;
540 541 542 543
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_noaction_del()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_noaction_del()",
544
			 RI_MAX_NUMKEYS);
545 546 547 548 549 550

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
551
		return PointerGetDatum(NULL);
552 553 554 555 556 557

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
558 559
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
560 561
	old_row = trigdata->tg_trigtuple;

562 563
	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
564 565 566 567 568 569 570
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) iv):
			 *		MATCH <unspecified> or MATCH FULL
			 *			... ON DELETE CASCADE
			 * ----------
			 */
571
		case RI_MATCH_TYPE_UNSPECIFIED:
572 573
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
574 575 576
								 RI_PLAN_NOACTION_DEL_CHECKREF,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
577 578 579 580 581 582 583 584 585 586 587

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No check - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
588
					return PointerGetDatum(NULL);
589

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_noaction_del()");

			/* ----------
			 * Fetch or prepare a saved plan for the restrict delete
			 * lookup if foreign references exist
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
611
				char	   *querysep;
612 613 614 615 616 617 618 619 620 621 622
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
				 *	SELECT oid FROM <fktable> WHERE fkatt1 = $1 [AND ...]
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
623 624
				sprintf(querystr, "SELECT oid FROM \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
625 626 627
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
628 629
					sprintf(buf, " %s \"%s\" = $%d", querysep,
							tgargs[4 + i * 2], i + 1);
630 631 632
					strcat(querystr, buf);
					querysep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
633
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
634
				}
635 636
				sprintf(buf, " FOR UPDATE OF \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
				strcat(querystr, buf);

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the deleted PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				del_values[i] = SPI_getbinval(old_row,
656 657 658 659
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
660 661 662 663 664 665 666 667 668 669 670 671
					del_nulls[i] = 'n';
				else
					del_nulls[i] = ' ';
			}
			del_nulls[i] = '\0';

			/* ----------
			 * Now check for existing references
			 * ----------
			 */
			if (SPI_execp(qplan, del_values, del_nulls, 1) != SPI_OK_SELECT)
				elog(ERROR, "SPI_execp() failed in RI_FKey_noaction_del()");
672

673 674
			if (SPI_processed > 0)
				elog(ERROR, "%s referential integrity violation - "
675 676 677 678
					 "key in %s still referenced from %s",
					 tgargs[RI_CONSTRAINT_NAME_ARGNO],
					 tgargs[RI_PK_RELNAME_ARGNO],
					 tgargs[RI_FK_RELNAME_ARGNO]);
679 680 681 682

			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_noaction_del()");

683
			return PointerGetDatum(NULL);
684

685 686 687 688
			/* ----------
			 * Handle MATCH PARTIAL restrict delete.
			 * ----------
			 */
689 690
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
691
			return PointerGetDatum(NULL);
692 693 694 695 696 697 698
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
	elog(ERROR, "internal error #2 in ri_triggers.c");
699
	return PointerGetDatum(NULL);
700 701 702 703 704 705 706
}


/* ----------
 * RI_FKey_noaction_upd -
 *
 *	Give an error and roll back the current transaction if the
707 708
 *	update has resulted in a violation of the given referential
 *	integrity constraint.
709 710
 * ----------
 */
711 712
Datum
RI_FKey_noaction_upd(PG_FUNCTION_ARGS)
713
{
714
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
715 716 717 718 719 720 721 722 723 724 725 726
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS];
	char		upd_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
727 728 729 730 731 732 733

	ReferentialIntegritySnapshotOverride = true;

	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
734
	if (!CALLED_AS_TRIGGER(fcinfo))
735
		elog(ERROR, "RI_FKey_noaction_upd() not fired by trigger manager");
736 737
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
738 739 740 741 742
		elog(ERROR, "RI_FKey_noaction_upd() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_noaction_upd() must be fired for UPDATE");

	/* ----------
743
	 * Check for the correct # of call arguments
744 745 746
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
747
	tgargs = trigdata->tg_trigger->tgargs;
748 749 750 751
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_noaction_upd()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_noaction_upd()",
752
			 RI_MAX_NUMKEYS);
753 754 755 756 757 758

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
759
		return PointerGetDatum(NULL);
760 761 762 763 764 765

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the new and old tuple.
	 * ----------
	 */
766 767
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
768 769
	new_row = trigdata->tg_newtuple;
	old_row = trigdata->tg_trigtuple;
770

771 772
	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
773 774 775 776 777 778 779
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) iv):
			 *		MATCH <unspecified> or MATCH FULL
			 *			... ON DELETE CASCADE
			 * ----------
			 */
780
		case RI_MATCH_TYPE_UNSPECIFIED:
781
		case RI_MATCH_TYPE_FULL:
Jan Wieck's avatar
Jan Wieck committed
782
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
783 784 785
								 RI_PLAN_NOACTION_UPD_CHECKREF,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
786

787
			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
788 789
			{
				case RI_KEYS_ALL_NULL:
790
				case RI_KEYS_SOME_NULL:
791
					/* ----------
792 793
					 * No check - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
794 795
					 * ----------
					 */
796
					heap_close(fk_rel, NoLock);
797
					return PointerGetDatum(NULL);
798

799 800 801 802 803 804 805
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
806
			heap_close(fk_rel, NoLock);
807 808

			/* ----------
809
			 * No need to check anything if old and new keys are equal
810 811
			 * ----------
			 */
812
			if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
813
							 RI_KEYPAIR_PK_IDX))
814
				return PointerGetDatum(NULL);
815

816
			if (SPI_connect() != SPI_OK_CONNECT)
817
				elog(NOTICE, "SPI_connect() failed in RI_FKey_noaction_upd()");
818 819

			/* ----------
820 821
			 * Fetch or prepare a saved plan for the noaction update
			 * lookup if foreign references exist
822 823 824 825 826 827
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
828
				char	   *querysep;
829 830 831 832
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
833
				 *	SELECT oid FROM <fktable> WHERE fkatt1 = $1 [AND ...]
834
				 * The type id's for the $ parameters are those of the
835
				 * corresponding PK attributes. Thus, SPI_prepare could
836 837 838 839
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
840 841
				sprintf(querystr, "SELECT oid FROM \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
842 843 844
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
845 846
					sprintf(buf, " %s \"%s\" = $%d", querysep,
							tgargs[4 + i * 2], i + 1);
847 848
					strcat(querystr, buf);
					querysep = "AND";
849
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
850
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
851
				}
852 853
				sprintf(buf, " FOR UPDATE OF \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
854
				strcat(querystr, buf);
855 856 857 858 859 860 861 862 863 864 865 866

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
867
			 * from the key values in the updated PK tuple.
868 869 870 871
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
872
				upd_values[i] = SPI_getbinval(old_row,
873 874 875 876
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
877
					upd_nulls[i] = 'n';
878
				else
879
					upd_nulls[i] = ' ';
880
			}
881
			upd_nulls[i] = '\0';
882 883

			/* ----------
884
			 * Now check for existing references
885 886
			 * ----------
			 */
887 888
			if (SPI_execp(qplan, upd_values, upd_nulls, 1) != SPI_OK_SELECT)
				elog(ERROR, "SPI_execp() failed in RI_FKey_noaction_upd()");
889

890
			if (SPI_processed > 0)
891
				elog(ERROR, "%s referential integrity violation - "
892 893 894 895
					 "key in %s still referenced from %s",
					 tgargs[RI_CONSTRAINT_NAME_ARGNO],
					 tgargs[RI_PK_RELNAME_ARGNO],
					 tgargs[RI_FK_RELNAME_ARGNO]);
896 897

			if (SPI_finish() != SPI_OK_FINISH)
898 899
				elog(NOTICE, "SPI_finish() failed in RI_FKey_noaction_upd()");

900
			return PointerGetDatum(NULL);
901

902 903 904 905
			/* ----------
			 * Handle MATCH PARTIAL noaction update.
			 * ----------
			 */
906 907
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
908
			return PointerGetDatum(NULL);
909 910 911 912 913 914
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
915
	elog(ERROR, "internal error #3 in ri_triggers.c");
916
	return PointerGetDatum(NULL);
917 918 919
}


920 921 922 923 924 925
/* ----------
 * RI_FKey_cascade_del -
 *
 *	Cascaded delete foreign key references at delete event on PK table.
 * ----------
 */
926 927
Datum
RI_FKey_cascade_del(PG_FUNCTION_ARGS)
928
{
929
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
930 931 932 933 934 935 936 937 938 939 940
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		del_values[RI_MAX_NUMKEYS];
	char		del_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
941

942
	ReferentialIntegritySnapshotOverride = true;
943

944 945 946 947
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
948
	if (!CALLED_AS_TRIGGER(fcinfo))
949
		elog(ERROR, "RI_FKey_cascade_del() not fired by trigger manager");
950 951
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
952 953 954 955 956
		elog(ERROR, "RI_FKey_cascade_del() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_cascade_del() must be fired for DELETE");

	/* ----------
957
	 * Check for the correct # of call arguments
958 959 960
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
961
	tgargs = trigdata->tg_trigger->tgargs;
962 963 964 965
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_cascade_del()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_cascade_del()",
966
			 RI_MAX_NUMKEYS);
967 968 969 970 971 972

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
973
		return PointerGetDatum(NULL);
974 975 976 977 978 979

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
980 981
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
982 983 984 985
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
986 987 988 989 990 991 992
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) i):
			 *		MATCH <unspecified> or MATCH FULL
			 *			... ON DELETE CASCADE
			 * ----------
			 */
993 994
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
Jan Wieck's avatar
Jan Wieck committed
995
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
996 997 998
								 RI_PLAN_CASCADE_DEL_DODELETE,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No check - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
1010
					return PointerGetDatum(NULL);
1011

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			if (SPI_connect() != SPI_OK_CONNECT)
Jan Wieck's avatar
Jan Wieck committed
1022
				elog(NOTICE, "SPI_connect() failed in RI_FKey_cascade_del()");
1023 1024 1025 1026 1027 1028 1029 1030 1031

			/* ----------
			 * Fetch or prepare a saved plan for the cascaded delete
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
1032
				char	   *querysep;
1033 1034 1035 1036
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
1037
				 *	DELETE FROM <fktable> WHERE fkatt1 = $1 [AND ...]
1038 1039 1040 1041 1042 1043
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
1044 1045
				sprintf(querystr, "DELETE FROM \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
1046 1047 1048
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
1049 1050
					sprintf(buf, " %s \"%s\" = $%d", querysep,
							tgargs[4 + i * 2], i + 1);
1051 1052 1053
					strcat(querystr, buf);
					querysep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
1054
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
				}

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the deleted PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				del_values[i] = SPI_getbinval(old_row,
1074 1075 1076 1077
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
1078 1079 1080 1081
					del_nulls[i] = 'n';
				else
					del_nulls[i] = ' ';
			}
Jan Wieck's avatar
Jan Wieck committed
1082
			del_nulls[i] = '\0';
1083 1084 1085 1086 1087

			/* ----------
			 * Now delete constraint
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1088
			if (SPI_execp(qplan, del_values, del_nulls, 0) != SPI_OK_DELETE)
1089
				elog(ERROR, "SPI_execp() failed in RI_FKey_cascade_del()");
1090

1091 1092 1093
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_cascade_del()");

1094
			return PointerGetDatum(NULL);
1095

1096 1097 1098 1099
			/* ----------
			 * Handle MATCH PARTIAL cascaded delete.
			 * ----------
			 */
1100 1101
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
1102
			return PointerGetDatum(NULL);
1103 1104 1105 1106 1107 1108
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
1109
	elog(ERROR, "internal error #4 in ri_triggers.c");
1110
	return PointerGetDatum(NULL);
1111 1112 1113 1114 1115 1116 1117 1118 1119
}


/* ----------
 * RI_FKey_cascade_upd -
 *
 *	Cascaded update/delete foreign key references at update event on PK table.
 * ----------
 */
1120 1121
Datum
RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
1122
{
1123
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS * 2];
	char		upd_nulls[RI_MAX_NUMKEYS * 2 + 1];
	bool		isnull;
	int			i;
	int			j;
1137

1138
	ReferentialIntegritySnapshotOverride = true;
1139

Jan Wieck's avatar
Jan Wieck committed
1140 1141 1142 1143
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
1144
	if (!CALLED_AS_TRIGGER(fcinfo))
Jan Wieck's avatar
Jan Wieck committed
1145
		elog(ERROR, "RI_FKey_cascade_upd() not fired by trigger manager");
1146 1147
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
Jan Wieck's avatar
Jan Wieck committed
1148 1149 1150 1151 1152
		elog(ERROR, "RI_FKey_cascade_upd() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_cascade_upd() must be fired for UPDATE");

	/* ----------
1153
	 * Check for the correct # of call arguments
Jan Wieck's avatar
Jan Wieck committed
1154 1155 1156
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
1157
	tgargs = trigdata->tg_trigger->tgargs;
Jan Wieck's avatar
Jan Wieck committed
1158 1159 1160 1161
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_cascade_upd()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_cascade_upd()",
1162
			 RI_MAX_NUMKEYS);
Jan Wieck's avatar
Jan Wieck committed
1163 1164 1165 1166 1167 1168

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
1169
		return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1170 1171 1172

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
Jan Wieck's avatar
Jan Wieck committed
1173
	 * the new and old tuple.
Jan Wieck's avatar
Jan Wieck committed
1174 1175
	 * ----------
	 */
1176 1177
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
Jan Wieck's avatar
Jan Wieck committed
1178 1179 1180 1181 1182
	new_row = trigdata->tg_newtuple;
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
1183 1184 1185 1186 1187 1188 1189
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 7) a) i):
			 *		MATCH <unspecified> or MATCH FULL
			 *			... ON UPDATE CASCADE
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1190 1191 1192
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
1193 1194 1195
								 RI_PLAN_CASCADE_UPD_DOUPDATE,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
Jan Wieck's avatar
Jan Wieck committed
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No update - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
1207
					return PointerGetDatum(NULL);
1208

Jan Wieck's avatar
Jan Wieck committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			/* ----------
			 * No need to do anything if old and new keys are equal
			 * ----------
			 */
			if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
1223
							 RI_KEYPAIR_PK_IDX))
1224
				return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1225 1226

			if (SPI_connect() != SPI_OK_CONNECT)
Jan Wieck's avatar
Jan Wieck committed
1227
				elog(NOTICE, "SPI_connect() failed in RI_FKey_cascade_upd()");
Jan Wieck's avatar
Jan Wieck committed
1228 1229

			/* ----------
Jan Wieck's avatar
Jan Wieck committed
1230 1231
			 * Fetch or prepare a saved plan for the cascaded update
			 * of foreign references
Jan Wieck's avatar
Jan Wieck committed
1232 1233 1234 1235 1236 1237 1238
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
				char		qualstr[8192];
1239 1240
				char	   *querysep;
				char	   *qualsep;
Jan Wieck's avatar
Jan Wieck committed
1241 1242 1243 1244
				Oid			queryoids[RI_MAX_NUMKEYS * 2];

				/* ----------
				 * The query string built is
1245
				 *	UPDATE <fktable> SET fkatt1 = $1 [, ...]
Jan Wieck's avatar
Jan Wieck committed
1246 1247 1248 1249 1250 1251 1252
				 *			WHERE fkatt1 = $n [AND ...]
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
1253 1254
				sprintf(querystr, "UPDATE \"%s\" SET",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1255 1256 1257 1258 1259
				qualstr[0] = '\0';
				querysep = "";
				qualsep = "WHERE";
				for (i = 0, j = qkey.nkeypairs; i < qkey.nkeypairs; i++, j++)
				{
1260 1261
					sprintf(buf, "%s \"%s\" = $%d", querysep,
							tgargs[4 + i * 2], i + 1);
Jan Wieck's avatar
Jan Wieck committed
1262 1263
					strcat(querystr, buf);
					sprintf(buf, " %s \"%s\" = $%d", qualsep,
1264
							tgargs[4 + i * 2], j + 1);
Jan Wieck's avatar
Jan Wieck committed
1265 1266 1267 1268
					strcat(qualstr, buf);
					querysep = ",";
					qualsep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
1269
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
Jan Wieck's avatar
Jan Wieck committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
					queryoids[j] = queryoids[i];
				}
				strcat(querystr, qualstr);

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs * 2, queryoids);
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the updated PK tuple.
			 * ----------
			 */
			for (i = 0, j = qkey.nkeypairs; i < qkey.nkeypairs; i++, j++)
			{
				upd_values[i] = SPI_getbinval(new_row,
1291 1292 1293 1294
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
Jan Wieck's avatar
Jan Wieck committed
1295 1296 1297 1298 1299
					upd_nulls[i] = 'n';
				else
					upd_nulls[i] = ' ';

				upd_values[j] = SPI_getbinval(old_row,
1300 1301 1302 1303
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
Jan Wieck's avatar
Jan Wieck committed
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
					upd_nulls[j] = 'n';
				else
					upd_nulls[j] = ' ';
			}
			upd_nulls[j] = '\0';

			/* ----------
			 * Now update the existing references
			 * ----------
			 */
			if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
				elog(ERROR, "SPI_execp() failed in RI_FKey_cascade_upd()");
1316

Jan Wieck's avatar
Jan Wieck committed
1317 1318 1319
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_cascade_upd()");

1320
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1321

1322 1323 1324 1325
			/* ----------
			 * Handle MATCH PARTIAL cascade update.
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1326 1327
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
1328
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1329 1330 1331 1332 1333 1334
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
1335
	elog(ERROR, "internal error #5 in ri_triggers.c");
1336
	return PointerGetDatum(NULL);
1337 1338 1339 1340 1341 1342 1343
}


/* ----------
 * RI_FKey_restrict_del -
 *
 *	Restrict delete from PK table to rows unreferenced by foreign key.
1344
 *
1345 1346 1347
 *	SQL3 intends that this referential action occur BEFORE the
 *	update is performed, rather than after.  This appears to be
 *	the only difference between "NO ACTION" and "RESTRICT".
1348
 *
1349 1350
 *	For now, however, we treat "RESTRICT" and "NO ACTION" as
 *	equivalent.
1351 1352
 * ----------
 */
1353 1354
Datum
RI_FKey_restrict_del(PG_FUNCTION_ARGS)
1355
{
1356
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		del_values[RI_MAX_NUMKEYS];
	char		del_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
1368

1369
	ReferentialIntegritySnapshotOverride = true;
1370

Jan Wieck's avatar
Jan Wieck committed
1371 1372 1373 1374
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
1375
	if (!CALLED_AS_TRIGGER(fcinfo))
Jan Wieck's avatar
Jan Wieck committed
1376
		elog(ERROR, "RI_FKey_restrict_del() not fired by trigger manager");
1377 1378
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
Jan Wieck's avatar
Jan Wieck committed
1379 1380 1381 1382 1383
		elog(ERROR, "RI_FKey_restrict_del() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_restrict_del() must be fired for DELETE");

	/* ----------
1384
	 * Check for the correct # of call arguments
Jan Wieck's avatar
Jan Wieck committed
1385 1386 1387
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
1388
	tgargs = trigdata->tg_trigger->tgargs;
Jan Wieck's avatar
Jan Wieck committed
1389 1390 1391 1392
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_restrict_del()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_restrict_del()",
1393
			 RI_MAX_NUMKEYS);
Jan Wieck's avatar
Jan Wieck committed
1394 1395 1396 1397 1398 1399

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
1400
		return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1401 1402 1403 1404 1405 1406

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
1407 1408
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
Jan Wieck's avatar
Jan Wieck committed
1409 1410 1411 1412
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
1413 1414 1415 1416 1417 1418 1419
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) iv):
			 *		MATCH <unspecified> or MATCH FULL
			 *			... ON DELETE CASCADE
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1420 1421 1422
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
1423 1424 1425
								 RI_PLAN_RESTRICT_DEL_CHECKREF,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
Jan Wieck's avatar
Jan Wieck committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No check - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
1437
					return PointerGetDatum(NULL);
1438

Jan Wieck's avatar
Jan Wieck committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_restrict_del()");

			/* ----------
			 * Fetch or prepare a saved plan for the restrict delete
Jan Wieck's avatar
Jan Wieck committed
1453
			 * lookup if foreign references exist
Jan Wieck's avatar
Jan Wieck committed
1454 1455 1456 1457 1458 1459
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
1460
				char	   *querysep;
Jan Wieck's avatar
Jan Wieck committed
1461 1462 1463 1464
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
1465
				 *	SELECT oid FROM <fktable> WHERE fkatt1 = $1 [AND ...]
Jan Wieck's avatar
Jan Wieck committed
1466 1467 1468 1469 1470 1471
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
1472 1473
				sprintf(querystr, "SELECT oid FROM \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1474 1475 1476
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
1477 1478
					sprintf(buf, " %s \"%s\" = $%d", querysep,
							tgargs[4 + i * 2], i + 1);
Jan Wieck's avatar
Jan Wieck committed
1479 1480 1481
					strcat(querystr, buf);
					querysep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
1482
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
Jan Wieck's avatar
Jan Wieck committed
1483
				}
1484 1485
				sprintf(buf, " FOR UPDATE OF \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1486
				strcat(querystr, buf);
Jan Wieck's avatar
Jan Wieck committed
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the deleted PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				del_values[i] = SPI_getbinval(old_row,
1505 1506 1507 1508
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
Jan Wieck's avatar
Jan Wieck committed
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
					del_nulls[i] = 'n';
				else
					del_nulls[i] = ' ';
			}
			del_nulls[i] = '\0';

			/* ----------
			 * Now check for existing references
			 * ----------
			 */
			if (SPI_execp(qplan, del_values, del_nulls, 1) != SPI_OK_SELECT)
				elog(ERROR, "SPI_execp() failed in RI_FKey_restrict_del()");
1521

Jan Wieck's avatar
Jan Wieck committed
1522 1523
			if (SPI_processed > 0)
				elog(ERROR, "%s referential integrity violation - "
1524 1525 1526 1527
					 "key in %s still referenced from %s",
					 tgargs[RI_CONSTRAINT_NAME_ARGNO],
					 tgargs[RI_PK_RELNAME_ARGNO],
					 tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1528 1529 1530 1531

			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_restrict_del()");

1532
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1533

1534 1535 1536 1537
			/* ----------
			 * Handle MATCH PARTIAL restrict delete.
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1538 1539
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
1540
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1541 1542 1543 1544 1545 1546
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
1547
	elog(ERROR, "internal error #6 in ri_triggers.c");
1548
	return PointerGetDatum(NULL);
1549 1550 1551 1552 1553 1554 1555
}


/* ----------
 * RI_FKey_restrict_upd -
 *
 *	Restrict update of PK to rows unreferenced by foreign key.
1556
 *
1557 1558 1559
 *	SQL3 intends that this referential action occur BEFORE the
 *	update is performed, rather than after.  This appears to be
 *	the only difference between "NO ACTION" and "RESTRICT".
1560
 *
1561 1562
 *	For now, however, we treat "RESTRICT" and "NO ACTION" as
 *	equivalent.
1563 1564
 * ----------
 */
1565 1566
Datum
RI_FKey_restrict_upd(PG_FUNCTION_ARGS)
1567
{
1568
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS];
	char		upd_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
1581

1582
	ReferentialIntegritySnapshotOverride = true;
1583

Jan Wieck's avatar
Jan Wieck committed
1584 1585 1586 1587
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
1588
	if (!CALLED_AS_TRIGGER(fcinfo))
Jan Wieck's avatar
Jan Wieck committed
1589
		elog(ERROR, "RI_FKey_restrict_upd() not fired by trigger manager");
1590 1591
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
Jan Wieck's avatar
Jan Wieck committed
1592 1593 1594 1595 1596
		elog(ERROR, "RI_FKey_restrict_upd() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_restrict_upd() must be fired for UPDATE");

	/* ----------
1597
	 * Check for the correct # of call arguments
Jan Wieck's avatar
Jan Wieck committed
1598 1599 1600
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
1601
	tgargs = trigdata->tg_trigger->tgargs;
Jan Wieck's avatar
Jan Wieck committed
1602 1603 1604 1605
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_restrict_upd()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_restrict_upd()",
1606
			 RI_MAX_NUMKEYS);
Jan Wieck's avatar
Jan Wieck committed
1607 1608 1609 1610 1611 1612

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
1613
		return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1614 1615 1616

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
Jan Wieck's avatar
Jan Wieck committed
1617
	 * the new and old tuple.
Jan Wieck's avatar
Jan Wieck committed
1618 1619
	 * ----------
	 */
1620 1621
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
Jan Wieck's avatar
Jan Wieck committed
1622 1623 1624 1625 1626
	new_row = trigdata->tg_newtuple;
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
1627 1628 1629 1630 1631 1632 1633
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) iv):
			 *		MATCH <unspecified> or MATCH FULL
			 *			... ON DELETE CASCADE
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1634 1635 1636
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
1637 1638 1639
								 RI_PLAN_RESTRICT_UPD_CHECKREF,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
Jan Wieck's avatar
Jan Wieck committed
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No check - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
1651
					return PointerGetDatum(NULL);
1652

Jan Wieck's avatar
Jan Wieck committed
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			/* ----------
			 * No need to check anything if old and new keys are equal
			 * ----------
			 */
			if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
1667
							 RI_KEYPAIR_PK_IDX))
1668
				return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1669 1670 1671 1672 1673

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_restrict_upd()");

			/* ----------
Jan Wieck's avatar
Jan Wieck committed
1674 1675
			 * Fetch or prepare a saved plan for the restrict update
			 * lookup if foreign references exist
Jan Wieck's avatar
Jan Wieck committed
1676 1677 1678 1679 1680 1681
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
1682
				char	   *querysep;
Jan Wieck's avatar
Jan Wieck committed
1683 1684 1685 1686
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
1687
				 *	SELECT oid FROM <fktable> WHERE fkatt1 = $1 [AND ...]
Jan Wieck's avatar
Jan Wieck committed
1688 1689 1690 1691 1692 1693
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
1694 1695
				sprintf(querystr, "SELECT oid FROM \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1696 1697 1698
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
1699 1700
					sprintf(buf, " %s \"%s\" = $%d", querysep,
							tgargs[4 + i * 2], i + 1);
Jan Wieck's avatar
Jan Wieck committed
1701 1702 1703
					strcat(querystr, buf);
					querysep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
1704
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
Jan Wieck's avatar
Jan Wieck committed
1705
				}
1706 1707
				sprintf(buf, " FOR UPDATE OF \"%s\"",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1708
				strcat(querystr, buf);
Jan Wieck's avatar
Jan Wieck committed
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the updated PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				upd_values[i] = SPI_getbinval(old_row,
1727 1728 1729 1730
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
Jan Wieck's avatar
Jan Wieck committed
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
					upd_nulls[i] = 'n';
				else
					upd_nulls[i] = ' ';
			}
			upd_nulls[i] = '\0';

			/* ----------
			 * Now check for existing references
			 * ----------
			 */
			if (SPI_execp(qplan, upd_values, upd_nulls, 1) != SPI_OK_SELECT)
				elog(ERROR, "SPI_execp() failed in RI_FKey_restrict_upd()");
1743

Jan Wieck's avatar
Jan Wieck committed
1744 1745
			if (SPI_processed > 0)
				elog(ERROR, "%s referential integrity violation - "
1746 1747 1748 1749
					 "key in %s still referenced from %s",
					 tgargs[RI_CONSTRAINT_NAME_ARGNO],
					 tgargs[RI_PK_RELNAME_ARGNO],
					 tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1750 1751 1752 1753

			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_restrict_upd()");

1754
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1755

1756 1757 1758 1759
			/* ----------
			 * Handle MATCH PARTIAL restrict update.
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1760 1761
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
1762
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1763 1764 1765 1766 1767 1768
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
1769
	elog(ERROR, "internal error #7 in ri_triggers.c");
1770
	return PointerGetDatum(NULL);
1771 1772 1773 1774 1775 1776 1777 1778 1779
}


/* ----------
 * RI_FKey_setnull_del -
 *
 *	Set foreign key references to NULL values at delete event on PK table.
 * ----------
 */
1780 1781
Datum
RI_FKey_setnull_del(PG_FUNCTION_ARGS)
1782
{
1783
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS];
	char		upd_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
1795

1796
	ReferentialIntegritySnapshotOverride = true;
1797

Jan Wieck's avatar
Jan Wieck committed
1798 1799 1800 1801
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
1802
	if (!CALLED_AS_TRIGGER(fcinfo))
Jan Wieck's avatar
Jan Wieck committed
1803
		elog(ERROR, "RI_FKey_setnull_del() not fired by trigger manager");
1804 1805
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
Jan Wieck's avatar
Jan Wieck committed
1806 1807 1808 1809 1810
		elog(ERROR, "RI_FKey_setnull_del() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_setnull_del() must be fired for DELETE");

	/* ----------
1811
	 * Check for the correct # of call arguments
Jan Wieck's avatar
Jan Wieck committed
1812 1813 1814
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
1815
	tgargs = trigdata->tg_trigger->tgargs;
Jan Wieck's avatar
Jan Wieck committed
1816 1817 1818 1819
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_setnull_del()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_setnull_del()",
1820
			 RI_MAX_NUMKEYS);
Jan Wieck's avatar
Jan Wieck committed
1821 1822 1823 1824 1825 1826

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
1827
		return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1828 1829 1830 1831 1832 1833

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
1834 1835
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
Jan Wieck's avatar
Jan Wieck committed
1836 1837 1838 1839
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
1840 1841 1842 1843 1844 1845 1846
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) ii):
			 *		MATCH <UNSPECIFIED> or MATCH FULL
			 *			... ON DELETE SET NULL
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1847 1848 1849
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
1850 1851 1852
								 RI_PLAN_SETNULL_DEL_DOUPDATE,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
Jan Wieck's avatar
Jan Wieck committed
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No update - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
1864
					return PointerGetDatum(NULL);
1865

Jan Wieck's avatar
Jan Wieck committed
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_setnull_del()");

			/* ----------
			 * Fetch or prepare a saved plan for the set null delete
			 * operation
			 * ----------
			 */
			if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
			{
				char		buf[256];
				char		querystr[8192];
				char		qualstr[8192];
1888 1889
				char	   *querysep;
				char	   *qualsep;
Jan Wieck's avatar
Jan Wieck committed
1890 1891 1892 1893
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
1894
				 *	UPDATE <fktable> SET fkatt1 = NULL [, ...]
Jan Wieck's avatar
Jan Wieck committed
1895 1896 1897 1898 1899 1900 1901
				 *			WHERE fkatt1 = $1 [AND ...]
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
1902 1903
				sprintf(querystr, "UPDATE \"%s\" SET",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
1904 1905 1906 1907 1908
				qualstr[0] = '\0';
				querysep = "";
				qualsep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
1909 1910
					sprintf(buf, "%s \"%s\" = NULL", querysep,
							tgargs[4 + i * 2]);
Jan Wieck's avatar
Jan Wieck committed
1911 1912
					strcat(querystr, buf);
					sprintf(buf, " %s \"%s\" = $%d", qualsep,
1913
							tgargs[4 + i * 2], i + 1);
Jan Wieck's avatar
Jan Wieck committed
1914 1915 1916 1917
					strcat(qualstr, buf);
					querysep = ",";
					qualsep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
1918
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
Jan Wieck's avatar
Jan Wieck committed
1919 1920 1921 1922 1923 1924 1925
				}
				strcat(querystr, qualstr);

				/* ----------
				 * Prepare, save and remember the new plan.
				 * ----------
				 */
1926
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
Jan Wieck's avatar
Jan Wieck committed
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
				qplan = SPI_saveplan(qplan);
				ri_HashPreparedPlan(&qkey, qplan);
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the updated PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				upd_values[i] = SPI_getbinval(old_row,
1939 1940 1941 1942
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
Jan Wieck's avatar
Jan Wieck committed
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
					upd_nulls[i] = 'n';
				else
					upd_nulls[i] = ' ';
			}
			upd_nulls[i] = '\0';

			/* ----------
			 * Now update the existing references
			 * ----------
			 */
			if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
				elog(ERROR, "SPI_execp() failed in RI_FKey_setnull_del()");
1955

Jan Wieck's avatar
Jan Wieck committed
1956 1957 1958
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_setnull_del()");

1959
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1960

1961 1962 1963 1964
			/* ----------
			 * Handle MATCH PARTIAL set null delete.
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
1965 1966
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
1967
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
1968 1969 1970 1971 1972 1973
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
1974
	elog(ERROR, "internal error #8 in ri_triggers.c");
1975
	return PointerGetDatum(NULL);
1976 1977 1978 1979 1980 1981 1982 1983 1984
}


/* ----------
 * RI_FKey_setnull_upd -
 *
 *	Set foreign key references to NULL at update event on PK table.
 * ----------
 */
1985 1986
Datum
RI_FKey_setnull_upd(PG_FUNCTION_ARGS)
1987
{
1988
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS];
	char		upd_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
	int			match_type;
	bool		use_cached_query;
2003

2004
	ReferentialIntegritySnapshotOverride = true;
2005

Jan Wieck's avatar
Jan Wieck committed
2006 2007 2008 2009
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
2010
	if (!CALLED_AS_TRIGGER(fcinfo))
Jan Wieck's avatar
Jan Wieck committed
2011
		elog(ERROR, "RI_FKey_setnull_upd() not fired by trigger manager");
2012 2013
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
Jan Wieck's avatar
Jan Wieck committed
2014 2015 2016 2017 2018
		elog(ERROR, "RI_FKey_setnull_upd() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_setnull_upd() must be fired for UPDATE");

	/* ----------
2019
	 * Check for the correct # of call arguments
Jan Wieck's avatar
Jan Wieck committed
2020 2021 2022
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
2023
	tgargs = trigdata->tg_trigger->tgargs;
Jan Wieck's avatar
Jan Wieck committed
2024 2025 2026 2027
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_setnull_upd()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_setnull_upd()",
2028
			 RI_MAX_NUMKEYS);
Jan Wieck's avatar
Jan Wieck committed
2029 2030 2031 2032 2033 2034

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
2035
		return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
2036 2037 2038 2039 2040 2041

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
2042 2043
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
Jan Wieck's avatar
Jan Wieck committed
2044 2045
	new_row = trigdata->tg_newtuple;
	old_row = trigdata->tg_trigtuple;
2046
	match_type = ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
2047

2048
	switch (match_type)
Jan Wieck's avatar
Jan Wieck committed
2049
	{
2050 2051 2052 2053 2054 2055 2056
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 7) a) ii) 2):
			 *		MATCH FULL
			 *			... ON UPDATE SET NULL
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
2057 2058 2059
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
2060 2061 2062
								 RI_PLAN_SETNULL_UPD_DOUPDATE,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
Jan Wieck's avatar
Jan Wieck committed
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No update - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
2074
					return PointerGetDatum(NULL);
2075

Jan Wieck's avatar
Jan Wieck committed
2076 2077 2078 2079 2080 2081 2082 2083 2084
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

2085

Jan Wieck's avatar
Jan Wieck committed
2086 2087 2088 2089 2090
			/* ----------
			 * No need to do anything if old and new keys are equal
			 * ----------
			 */
			if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
2091
							 RI_KEYPAIR_PK_IDX))
2092
				return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
2093 2094 2095 2096

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_setnull_upd()");

2097 2098 2099 2100 2101 2102 2103 2104 2105
			/*
			 * "MATCH <unspecified>" only changes columns corresponding to
			 * the referenced columns that have changed in pk_rel.	This
			 * means the "SET attrn=NULL [, attrn=NULL]" string will be
			 * change as well.	In this case, we need to build a temporary
			 * plan rather than use our cached plan, unless the update
			 * happens to change all columns in the key.  Fortunately, for
			 * the most common case of a single-column foreign key, this
			 * will be true.
2106 2107 2108 2109 2110 2111
			 *
			 * In case you're wondering, the inequality check works because
			 * we know that the old key value has no NULLs (see above).
			 */

			use_cached_query = match_type == RI_MATCH_TYPE_FULL ||
2112 2113
				ri_AllKeysUnequal(pk_rel, old_row, new_row,
								  &qkey, RI_KEYPAIR_PK_IDX);
2114

Jan Wieck's avatar
Jan Wieck committed
2115 2116
			/* ----------
			 * Fetch or prepare a saved plan for the set null update
2117
			 * operation if possible, or build a temporary plan if not.
Jan Wieck's avatar
Jan Wieck committed
2118 2119
			 * ----------
			 */
2120 2121
			if (!use_cached_query ||
				(qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
Jan Wieck's avatar
Jan Wieck committed
2122 2123 2124 2125
			{
				char		buf[256];
				char		querystr[8192];
				char		qualstr[8192];
2126 2127
				char	   *querysep;
				char	   *qualsep;
Jan Wieck's avatar
Jan Wieck committed
2128 2129 2130 2131
				Oid			queryoids[RI_MAX_NUMKEYS];

				/* ----------
				 * The query string built is
2132
				 *	UPDATE <fktable> SET fkatt1 = NULL [, ...]
Jan Wieck's avatar
Jan Wieck committed
2133 2134 2135 2136 2137 2138 2139
				 *			WHERE fkatt1 = $1 [AND ...]
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
2140 2141
				sprintf(querystr, "UPDATE \"%s\" SET",
						tgargs[RI_FK_RELNAME_ARGNO]);
Jan Wieck's avatar
Jan Wieck committed
2142 2143 2144 2145 2146
				qualstr[0] = '\0';
				querysep = "";
				qualsep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
2147 2148 2149 2150

					/*
					 * MATCH <unspecified> - only change columns
					 * corresponding to changed columns in pk_rel's key
2151 2152
					 */
					if (match_type == RI_MATCH_TYPE_FULL ||
2153 2154
					  !ri_OneKeyEqual(pk_rel, i, old_row, new_row, &qkey,
									  RI_KEYPAIR_PK_IDX))
2155
					{
2156 2157
						sprintf(buf, "%s \"%s\" = NULL", querysep,
								tgargs[4 + i * 2]);
2158 2159 2160
						strcat(querystr, buf);
						querysep = ",";
					}
Jan Wieck's avatar
Jan Wieck committed
2161
					sprintf(buf, " %s \"%s\" = $%d", qualsep,
2162
							tgargs[4 + i * 2], i + 1);
Jan Wieck's avatar
Jan Wieck committed
2163 2164 2165
					strcat(qualstr, buf);
					qualsep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
2166
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
Jan Wieck's avatar
Jan Wieck committed
2167 2168 2169 2170
				}
				strcat(querystr, qualstr);

				/* ----------
2171
				 * Prepare the new plan.
Jan Wieck's avatar
Jan Wieck committed
2172 2173
				 * ----------
				 */
2174
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
2175

2176 2177 2178
				/*
				 * Save and remember the plan if we're building the
				 * "standard" plan.
2179 2180 2181 2182 2183 2184
				 */
				if (use_cached_query)
				{
					qplan = SPI_saveplan(qplan);
					ri_HashPreparedPlan(&qkey, qplan);
				}
Jan Wieck's avatar
Jan Wieck committed
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the updated PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				upd_values[i] = SPI_getbinval(old_row,
2195 2196 2197 2198
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
Jan Wieck's avatar
Jan Wieck committed
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
					upd_nulls[i] = 'n';
				else
					upd_nulls[i] = ' ';
			}
			upd_nulls[i] = '\0';

			/* ----------
			 * Now update the existing references
			 * ----------
			 */
			if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
				elog(ERROR, "SPI_execp() failed in RI_FKey_setnull_upd()");
2211

Jan Wieck's avatar
Jan Wieck committed
2212 2213 2214
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_setnull_upd()");

2215
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
2216

2217 2218 2219 2220
			/* ----------
			 * Handle MATCH PARTIAL set null update.
			 * ----------
			 */
Jan Wieck's avatar
Jan Wieck committed
2221 2222
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
2223
			return PointerGetDatum(NULL);
Jan Wieck's avatar
Jan Wieck committed
2224 2225 2226 2227 2228 2229
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
2230
	elog(ERROR, "internal error #9 in ri_triggers.c");
2231
	return PointerGetDatum(NULL);
2232 2233 2234 2235 2236 2237 2238 2239 2240
}


/* ----------
 * RI_FKey_setdefault_del -
 *
 *	Set foreign key references to defaults at delete event on PK table.
 * ----------
 */
2241 2242
Datum
RI_FKey_setdefault_del(PG_FUNCTION_ARGS)
2243
{
2244
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS];
	char		upd_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
2256

2257
	ReferentialIntegritySnapshotOverride = true;
2258

2259 2260 2261 2262
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
2263
	if (!CALLED_AS_TRIGGER(fcinfo))
2264
		elog(ERROR, "RI_FKey_setdefault_del() not fired by trigger manager");
2265 2266
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2267 2268 2269 2270 2271
		elog(ERROR, "RI_FKey_setdefault_del() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_setdefault_del() must be fired for DELETE");

	/* ----------
2272
	 * Check for the correct # of call arguments
2273 2274 2275
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
2276
	tgargs = trigdata->tg_trigger->tgargs;
2277 2278 2279 2280
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_setdefault_del()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_setdefault_del()",
2281
			 RI_MAX_NUMKEYS);
2282 2283 2284 2285 2286 2287

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
2288
		return PointerGetDatum(NULL);
2289 2290 2291 2292 2293 2294

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
2295 2296
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
2297 2298 2299 2300
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
2301 2302 2303 2304 2305 2306 2307
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 6) a) iii):
			 *		MATCH <UNSPECIFIED> or MATCH FULL
			 *			... ON DELETE SET DEFAULT
			 * ----------
			 */
2308 2309 2310
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
2311 2312 2313
								 RI_PLAN_SETNULL_DEL_DOUPDATE,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No update - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
2325
					return PointerGetDatum(NULL);
2326

2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_setdefault_del()");

			/* ----------
			 * Prepare a plan for the set defalt delete operation.
			 * Unfortunately we need to do it on every invocation
			 * because the default value could potentially change
			 * between calls.
			 * ----------
			 */
			{
				char		buf[256];
				char		querystr[8192];
				char		qualstr[8192];
2350 2351
				char	   *querysep;
				char	   *qualsep;
2352
				Oid			queryoids[RI_MAX_NUMKEYS];
2353 2354 2355 2356 2357
				Plan	   *spi_plan;
				AttrDefault *defval;
				TargetEntry *spi_qptle;
				int			i,
							j;
2358 2359 2360

				/* ----------
				 * The query string built is
2361
				 *	UPDATE <fktable> SET fkatt1 = NULL [, ...]
2362 2363 2364 2365 2366 2367 2368
				 *			WHERE fkatt1 = $1 [AND ...]
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
2369 2370
				sprintf(querystr, "UPDATE \"%s\" SET",
						tgargs[RI_FK_RELNAME_ARGNO]);
2371 2372 2373 2374 2375
				qualstr[0] = '\0';
				querysep = "";
				qualsep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
2376 2377
					sprintf(buf, "%s \"%s\" = NULL", querysep,
							tgargs[4 + i * 2]);
2378 2379
					strcat(querystr, buf);
					sprintf(buf, " %s \"%s\" = $%d", qualsep,
2380
							tgargs[4 + i * 2], i + 1);
2381 2382 2383 2384
					strcat(qualstr, buf);
					querysep = ",";
					qualsep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
2385
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
				}
				strcat(querystr, qualstr);

				/* ----------
				 * Prepare the plan
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);

				/* ----------
2396 2397 2398 2399 2400 2401
				 * Here now follows very ugly code depending on internals
				 * of the SPI manager.
				 *
				 * EVIL EVIL EVIL (but must be - Jan)
				 *
				 * We replace the CONST NULL targetlist expressions
2402 2403 2404 2405
				 * in the generated plan by (any) default values found
				 * in the tuple constructor.
				 * ----------
				 */
2406
				spi_plan = (Plan *) lfirst(((_SPI_plan *) qplan)->ptlist);
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
				if (fk_rel->rd_att->constr != NULL)
					defval = fk_rel->rd_att->constr->defval;
				else
					defval = NULL;
				for (i = 0; i < qkey.nkeypairs && defval != NULL; i++)
				{
					/* ----------
					 * For each key attribute lookup the tuple constructor
					 * for a corresponding default value
					 * ----------
					 */
					for (j = 0; j < fk_rel->rd_att->constr->num_defval; j++)
					{
2420 2421
						if (defval[j].adnum ==
							qkey.keypair[i][RI_KEYPAIR_FK_IDX])
2422 2423 2424 2425 2426 2427 2428
						{
							/* ----------
							 * That's the one - push the expression
							 * from defval.adbin into the plan's targetlist
							 * ----------
							 */
							spi_qptle = (TargetEntry *)
2429 2430
								nth(defval[j].adnum - 1,
									spi_plan->targetlist);
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
							spi_qptle->expr = stringToNode(defval[j].adbin);

							break;
						}
					}
				}
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the deleted PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				upd_values[i] = SPI_getbinval(old_row,
2447 2448 2449 2450
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
					upd_nulls[i] = 'n';
				else
					upd_nulls[i] = ' ';
			}
			upd_nulls[i] = '\0';

			/* ----------
			 * Now update the existing references
			 * ----------
			 */
			if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
				elog(ERROR, "SPI_execp() failed in RI_FKey_setdefault_del()");
2463

2464 2465 2466
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_setdefault_del()");

2467
			return PointerGetDatum(NULL);
2468

2469 2470 2471 2472
			/* ----------
			 * Handle MATCH PARTIAL set null delete.
			 * ----------
			 */
2473 2474
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
2475
			return PointerGetDatum(NULL);
2476 2477 2478 2479 2480 2481
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
2482
	elog(ERROR, "internal error #10 in ri_triggers.c");
2483
	return PointerGetDatum(NULL);
2484 2485 2486 2487 2488 2489 2490 2491 2492
}


/* ----------
 * RI_FKey_setdefault_upd -
 *
 *	Set foreign key references to defaults at update event on PK table.
 * ----------
 */
2493 2494
Datum
RI_FKey_setdefault_upd(PG_FUNCTION_ARGS)
2495
{
2496
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
	void	   *qplan;
	Datum		upd_values[RI_MAX_NUMKEYS];
	char		upd_nulls[RI_MAX_NUMKEYS + 1];
	bool		isnull;
	int			i;
	int			match_type;
2510

2511
	ReferentialIntegritySnapshotOverride = true;
2512

2513 2514 2515 2516
	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
2517
	if (!CALLED_AS_TRIGGER(fcinfo))
2518
		elog(ERROR, "RI_FKey_setdefault_upd() not fired by trigger manager");
2519 2520
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
		!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
2521 2522 2523 2524 2525
		elog(ERROR, "RI_FKey_setdefault_upd() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_setdefault_upd() must be fired for UPDATE");

	/* ----------
2526
	 * Check for the correct # of call arguments
2527 2528 2529
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
2530
	tgargs = trigdata->tg_trigger->tgargs;
2531 2532 2533 2534
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_setdefault_upd()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_setdefault_upd()",
2535
			 RI_MAX_NUMKEYS);
2536 2537 2538 2539 2540 2541

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
2542
		return PointerGetDatum(NULL);
2543 2544 2545 2546 2547 2548

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the old tuple.
	 * ----------
	 */
2549 2550
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
2551 2552 2553
	new_row = trigdata->tg_newtuple;
	old_row = trigdata->tg_trigtuple;

2554 2555 2556
	match_type = ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]);

	switch (match_type)
2557
	{
2558 2559 2560 2561 2562 2563 2564
			/* ----------
			 * SQL3 11.9 <referential constraint definition>
			 *	Gereral rules 7) a) iii):
			 *		MATCH <UNSPECIFIED> or MATCH FULL
			 *			... ON UPDATE SET DEFAULT
			 * ----------
			 */
2565 2566 2567
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
2568 2569 2570
								 RI_PLAN_SETNULL_DEL_DOUPDATE,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581

			switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
			{
				case RI_KEYS_ALL_NULL:
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * No update - MATCH FULL means there cannot be any
					 * reference to old key if it contains NULL
					 * ----------
					 */
					heap_close(fk_rel, NoLock);
2582
					return PointerGetDatum(NULL);
2583

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(fk_rel, NoLock);

			/* ----------
			 * No need to do anything if old and new keys are equal
			 * ----------
			 */
			if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
2598
							 RI_KEYPAIR_PK_IDX))
2599
				return PointerGetDatum(NULL);
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614

			if (SPI_connect() != SPI_OK_CONNECT)
				elog(NOTICE, "SPI_connect() failed in RI_FKey_setdefault_upd()");

			/* ----------
			 * Prepare a plan for the set defalt delete operation.
			 * Unfortunately we need to do it on every invocation
			 * because the default value could potentially change
			 * between calls.
			 * ----------
			 */
			{
				char		buf[256];
				char		querystr[8192];
				char		qualstr[8192];
2615 2616
				char	   *querysep;
				char	   *qualsep;
2617
				Oid			queryoids[RI_MAX_NUMKEYS];
2618 2619 2620 2621 2622
				Plan	   *spi_plan;
				AttrDefault *defval;
				TargetEntry *spi_qptle;
				int			i,
							j;
2623 2624 2625

				/* ----------
				 * The query string built is
2626
				 *	UPDATE <fktable> SET fkatt1 = NULL [, ...]
2627 2628 2629 2630 2631 2632 2633
				 *			WHERE fkatt1 = $1 [AND ...]
				 * The type id's for the $ parameters are those of the
				 * corresponding PK attributes. Thus, SPI_prepare could
				 * eventually fail if the parser cannot identify some way
				 * how to compare these two types by '='.
				 * ----------
				 */
2634 2635
				sprintf(querystr, "UPDATE \"%s\" SET",
						tgargs[RI_FK_RELNAME_ARGNO]);
2636 2637 2638 2639 2640
				qualstr[0] = '\0';
				querysep = "";
				qualsep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
2641 2642 2643 2644

					/*
					 * MATCH <unspecified> - only change columns
					 * corresponding to changed columns in pk_rel's key
2645 2646 2647
					 */
					if (match_type == RI_MATCH_TYPE_FULL ||
						!ri_OneKeyEqual(pk_rel, i, old_row,
2648
									  new_row, &qkey, RI_KEYPAIR_PK_IDX))
2649
					{
2650 2651
						sprintf(buf, "%s \"%s\" = NULL", querysep,
								tgargs[4 + i * 2]);
2652 2653 2654
						strcat(querystr, buf);
						querysep = ",";
					}
2655
					sprintf(buf, " %s \"%s\" = $%d", qualsep,
2656
							tgargs[4 + i * 2], i + 1);
2657 2658 2659
					strcat(qualstr, buf);
					qualsep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
2660
									 qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
				}
				strcat(querystr, qualstr);

				/* ----------
				 * Prepare the plan
				 * ----------
				 */
				qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);

				/* ----------
				 * Now replace the CONST NULL targetlist expressions
				 * in the generated plan by (any) default values found
				 * in the tuple constructor.
				 * ----------
				 */
2676
				spi_plan = (Plan *) lfirst(((_SPI_plan *) qplan)->ptlist);
2677 2678 2679 2680 2681 2682
				if (fk_rel->rd_att->constr != NULL)
					defval = fk_rel->rd_att->constr->defval;
				else
					defval = NULL;
				for (i = 0; i < qkey.nkeypairs && defval != NULL; i++)
				{
2683 2684 2685 2686 2687 2688

					/*
					 * MATCH <unspecified> - only change columns
					 * corresponding to changed columns in pk_rel's key.
					 * This conditional must match the one in the loop
					 * above that built the SET attrn=NULL list.
2689
					 */
2690 2691
					if (match_type == RI_MATCH_TYPE_FULL ||
						!ri_OneKeyEqual(pk_rel, i, old_row,
2692
									  new_row, &qkey, RI_KEYPAIR_PK_IDX))
2693
					{
2694 2695 2696 2697 2698 2699
						/* ----------
						 * For each key attribute lookup the tuple constructor
						 * for a corresponding default value
						 * ----------
						 */
						for (j = 0; j < fk_rel->rd_att->constr->num_defval; j++)
2700
						{
2701 2702
							if (defval[j].adnum ==
								qkey.keypair[i][RI_KEYPAIR_FK_IDX])
2703 2704 2705 2706 2707 2708 2709
							{
								/* ----------
								 * That's the one - push the expression
								 * from defval.adbin into the plan's targetlist
								 * ----------
								 */
								spi_qptle = (TargetEntry *)
2710
									nth(defval[j].adnum - 1,
2711
										spi_plan->targetlist);
2712
								spi_qptle->expr = stringToNode(defval[j].adbin);
2713

2714
								break;
2715
							}
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
						}
					}
				}
			}

			/* ----------
			 * We have a plan now. Build up the arguments for SPI_execp()
			 * from the key values in the deleted PK tuple.
			 * ----------
			 */
			for (i = 0; i < qkey.nkeypairs; i++)
			{
				upd_values[i] = SPI_getbinval(old_row,
2729 2730 2731 2732
											  pk_rel->rd_att,
									  qkey.keypair[i][RI_KEYPAIR_PK_IDX],
											  &isnull);
				if (isnull)
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
					upd_nulls[i] = 'n';
				else
					upd_nulls[i] = ' ';
			}
			upd_nulls[i] = '\0';

			/* ----------
			 * Now update the existing references
			 * ----------
			 */
			if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
				elog(ERROR, "SPI_execp() failed in RI_FKey_setdefault_upd()");
2745

2746 2747 2748
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_setdefault_upd()");

2749
			return PointerGetDatum(NULL);
2750

2751 2752 2753 2754
			/* ----------
			 * Handle MATCH PARTIAL set null delete.
			 * ----------
			 */
2755 2756
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
2757
			return PointerGetDatum(NULL);
2758 2759 2760 2761 2762 2763
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
2764
	elog(ERROR, "internal error #11 in ri_triggers.c");
2765
	return PointerGetDatum(NULL);
2766 2767 2768
}


2769 2770 2771 2772 2773
/* ----------
 * RI_FKey_keyequal_upd -
 *
 *	Check if we have a key change on update.
 *
2774
 *	This is not a real trigger procedure. It is used by the deferred
2775 2776 2777 2778
 *	trigger queue manager to detect "triggered data change violation".
 * ----------
 */
bool
2779
RI_FKey_keyequal_upd(TriggerData *trigdata)
2780
{
2781 2782 2783 2784 2785 2786 2787
	int			tgnargs;
	char	  **tgargs;
	Relation	fk_rel;
	Relation	pk_rel;
	HeapTuple	new_row;
	HeapTuple	old_row;
	RI_QueryKey qkey;
2788 2789

	/* ----------
2790
	 * Check for the correct # of call arguments
2791 2792 2793
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
2794
	tgargs = trigdata->tg_trigger->tgargs;
2795 2796 2797 2798
	if (tgnargs < 4 || (tgnargs % 2) != 0)
		elog(ERROR, "wrong # of arguments in call to RI_FKey_keyequal_upd()");
	if (tgnargs > RI_MAX_ARGUMENTS)
		elog(ERROR, "too many keys (%d max) in call to RI_FKey_keyequal_upd()",
2799
			 RI_MAX_NUMKEYS);
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812

	/* ----------
	 * Nothing to do if no column names to compare given
	 * ----------
	 */
	if (tgnargs == 4)
		return true;

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the new and old tuple.
	 * ----------
	 */
2813 2814
	fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
	pk_rel = trigdata->tg_relation;
2815 2816 2817 2818 2819
	new_row = trigdata->tg_newtuple;
	old_row = trigdata->tg_trigtuple;

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
2820 2821 2822 2823
			/* ----------
			 * MATCH <UNSPECIFIED>
			 * ----------
			 */
2824 2825 2826
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
2827 2828 2829
								 0,
								 fk_rel, pk_rel,
								 tgnargs, tgargs);
2830 2831 2832 2833 2834 2835 2836
			heap_close(fk_rel, NoLock);

			/* ----------
			 * Return if key's are equal
			 * ----------
			 */
			return ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
2837
								RI_KEYPAIR_PK_IDX);
2838

2839 2840 2841 2842
			/* ----------
			 * Handle MATCH PARTIAL set null delete.
			 * ----------
			 */
2843 2844 2845 2846 2847 2848 2849 2850 2851
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
			break;
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
2852
	elog(ERROR, "internal error #12 in ri_triggers.c");
2853 2854 2855 2856
	return false;
}


2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906



/* ----------
 * Local functions below
 * ----------
 */





/* ----------
 * ri_DetermineMatchType -
 *
 *	Convert the MATCH TYPE string into a switchable int
 * ----------
 */
static int
ri_DetermineMatchType(char *str)
{
	if (!strcmp(str, "UNSPECIFIED"))
		return RI_MATCH_TYPE_UNSPECIFIED;
	if (!strcmp(str, "FULL"))
		return RI_MATCH_TYPE_FULL;
	if (!strcmp(str, "PARTIAL"))
		return RI_MATCH_TYPE_PARTIAL;

	elog(ERROR, "unrecognized referential integrity MATCH type '%s'", str);
	return 0;
}


/* ----------
 * ri_BuildQueryKeyFull -
 *
 *	Build up a new hashtable key for a prepared SPI plan of a
 *	constraint trigger of MATCH FULL. The key consists of:
 *
 *		constr_type is FULL
 *		constr_id is the OID of the pg_trigger row that invoked us
 *		constr_queryno is an internal number of the query inside the proc
 *		fk_relid is the OID of referencing relation
 *		pk_relid is the OID of referenced relation
 *		nkeypairs is the number of keypairs
 *		following are the attribute number keypairs of the trigger invocation
 *
 *	At least for MATCH FULL this builds a unique key per plan.
 * ----------
 */
2907
static void
2908
ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id, int32 constr_queryno,
2909 2910
					 Relation fk_rel, Relation pk_rel,
					 int argc, char **argv)
2911
{
2912 2913 2914
	int			i;
	int			j;
	int			fno;
2915 2916 2917 2918 2919

	/* ----------
	 * Initialize the key and fill in type, oid's and number of keypairs
	 * ----------
	 */
2920 2921 2922 2923 2924 2925 2926
	memset((void *) key, 0, sizeof(RI_QueryKey));
	key->constr_type = RI_MATCH_TYPE_FULL;
	key->constr_id = constr_id;
	key->constr_queryno = constr_queryno;
	key->fk_relid = fk_rel->rd_id;
	key->pk_relid = pk_rel->rd_id;
	key->nkeypairs = (argc - RI_FIRST_ATTNAME_ARGNO) / 2;
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937

	/* ----------
	 * Lookup the attribute numbers of the arguments to the trigger call
	 * and fill in the keypairs.
	 * ----------
	 */
	for (i = 0, j = RI_FIRST_ATTNAME_ARGNO; j < argc; i++, j += 2)
	{
		fno = SPI_fnumber(fk_rel->rd_att, argv[j]);
		if (fno == SPI_ERROR_NOATTRIBUTE)
			elog(ERROR, "constraint %s: table %s does not have an attribute %s",
2938 2939 2940
				 argv[RI_CONSTRAINT_NAME_ARGNO],
				 argv[RI_FK_RELNAME_ARGNO],
				 argv[j]);
2941 2942 2943 2944 2945
		key->keypair[i][RI_KEYPAIR_FK_IDX] = fno;

		fno = SPI_fnumber(pk_rel->rd_att, argv[j + 1]);
		if (fno == SPI_ERROR_NOATTRIBUTE)
			elog(ERROR, "constraint %s: table %s does not have an attribute %s",
2946 2947 2948
				 argv[RI_CONSTRAINT_NAME_ARGNO],
				 argv[RI_PK_RELNAME_ARGNO],
				 argv[j + 1]);
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
		key->keypair[i][RI_KEYPAIR_PK_IDX] = fno;
	}

	return;
}


/* ----------
 * ri_NullCheck -
 *
 *	Determine the NULL state of all key values in a tuple
 *
 *	Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
 * ----------
 */
2964
static int
2965 2966
ri_NullCheck(Relation rel, HeapTuple tup, RI_QueryKey *key, int pairidx)
{
2967 2968 2969 2970
	int			i;
	bool		isnull;
	bool		allnull = true;
	bool		nonenull = true;
2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004

	for (i = 0; i < key->nkeypairs; i++)
	{
		isnull = false;
		SPI_getbinval(tup, rel->rd_att, key->keypair[i][pairidx], &isnull);
		if (isnull)
			nonenull = false;
		else
			allnull = false;
	}

	if (allnull)
		return RI_KEYS_ALL_NULL;

	if (nonenull)
		return RI_KEYS_NONE_NULL;

	return RI_KEYS_SOME_NULL;
}


/* ----------
 * ri_InitHashTables -
 *
 *	Initialize our internal hash tables for prepared
 *	query plans and equal operators.
 * ----------
 */
static void
ri_InitHashTables(void)
{
	HASHCTL		ctl;

	memset(&ctl, 0, sizeof(ctl));
3005 3006
	ctl.keysize = sizeof(RI_QueryKey);
	ctl.datasize = sizeof(void *);
3007 3008 3009
	ri_query_cache = hash_create(RI_INIT_QUERYHASHSIZE, &ctl, HASH_ELEM);

	memset(&ctl, 0, sizeof(ctl));
3010 3011 3012 3013 3014
	ctl.keysize = sizeof(Oid);
	ctl.datasize = sizeof(Oid) + sizeof(FmgrInfo);
	ctl.hash = tag_hash;
	ri_opreq_cache = hash_create(RI_INIT_OPREQHASHSIZE, &ctl,
								 HASH_ELEM | HASH_FUNCTION);
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
}


/* ----------
 * ri_FetchPreparedPlan -
 *
 *	Lookup for a query key in our private hash table of prepared
 *	and saved SPI execution plans. Return the plan if found or NULL.
 * ----------
 */
static void *
ri_FetchPreparedPlan(RI_QueryKey *key)
{
3028 3029
	RI_QueryHashEntry *entry;
	bool		found;
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041

	/* ----------
	 * On the first call initialize the hashtable
	 * ----------
	 */
	if (!ri_query_cache)
		ri_InitHashTables();

	/* ----------
	 * Lookup for the key
	 * ----------
	 */
3042 3043
	entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
										(char *) key, HASH_FIND, &found);
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
	if (entry == NULL)
		elog(FATAL, "error in RI plan cache");
	if (!found)
		return NULL;
	return entry->plan;
}


/* ----------
 * ri_HashPreparedPlan -
 *
 *	Add another plan to our private SPI query plan hashtable.
 * ----------
 */
static void
ri_HashPreparedPlan(RI_QueryKey *key, void *plan)
{
3061 3062
	RI_QueryHashEntry *entry;
	bool		found;
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074

	/* ----------
	 * On the first call initialize the hashtable
	 * ----------
	 */
	if (!ri_query_cache)
		ri_InitHashTables();

	/* ----------
	 * Add the new plan.
	 * ----------
	 */
3075 3076
	entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
									   (char *) key, HASH_ENTER, &found);
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
	if (entry == NULL)
		elog(FATAL, "can't insert into RI plan cache");
	entry->plan = plan;
}


/* ----------
 * ri_KeysEqual -
 *
 *	Check if all key values in OLD and NEW are equal.
 * ----------
 */
static bool
3090 3091
ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
			 RI_QueryKey *key, int pairidx)
3092
{
3093 3094 3095 3096 3097
	int			i;
	Oid			typeid;
	Datum		oldvalue;
	Datum		newvalue;
	bool		isnull;
3098 3099 3100 3101 3102 3103 3104

	for (i = 0; i < key->nkeypairs; i++)
	{
		/* ----------
		 * Get one attributes oldvalue. If it is NULL - they're not equal.
		 * ----------
		 */
3105 3106
		oldvalue = SPI_getbinval(oldtup, rel->rd_att,
								 key->keypair[i][pairidx], &isnull);
3107 3108 3109 3110 3111 3112 3113
		if (isnull)
			return false;

		/* ----------
		 * Get one attributes oldvalue. If it is NULL - they're not equal.
		 * ----------
		 */
3114 3115
		newvalue = SPI_getbinval(newtup, rel->rd_att,
								 key->keypair[i][pairidx], &isnull);
3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
		if (isnull)
			return false;

		/* ----------
		 * Get the attributes type OID and call the '=' operator
		 * to compare the values.
		 * ----------
		 */
		typeid = SPI_gettypeid(rel->rd_att, key->keypair[i][pairidx]);
		if (!ri_AttributesEqual(typeid, oldvalue, newvalue))
			return false;
	}

	return true;
}


3133 3134 3135 3136 3137 3138 3139
/* ----------
 * ri_AllKeysUnequal -
 *
 *	Check if all key values in OLD and NEW are not equal.
 * ----------
 */
static bool
3140 3141
ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
				  RI_QueryKey *key, int pairidx)
3142
{
3143 3144 3145 3146 3147 3148
	int			i;
	Oid			typeid;
	Datum		oldvalue;
	Datum		newvalue;
	bool		isnull;
	bool		keys_unequal;
3149 3150 3151 3152 3153 3154 3155 3156

	keys_unequal = true;
	for (i = 0; keys_unequal && i < key->nkeypairs; i++)
	{
		/* ----------
		 * Get one attributes oldvalue. If it is NULL - they're not equal.
		 * ----------
		 */
3157 3158
		oldvalue = SPI_getbinval(oldtup, rel->rd_att,
								 key->keypair[i][pairidx], &isnull);
3159 3160 3161 3162 3163 3164 3165
		if (isnull)
			continue;

		/* ----------
		 * Get one attributes oldvalue. If it is NULL - they're not equal.
		 * ----------
		 */
3166 3167
		newvalue = SPI_getbinval(newtup, rel->rd_att,
								 key->keypair[i][pairidx], &isnull);
3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
		if (isnull)
			continue;

		/* ----------
		 * Get the attributes type OID and call the '=' operator
		 * to compare the values.
		 * ----------
		 */
		typeid = SPI_gettypeid(rel->rd_att, key->keypair[i][pairidx]);
		if (!ri_AttributesEqual(typeid, oldvalue, newvalue))
			continue;
		keys_unequal = false;
	}

	return keys_unequal;
}


/* ----------
 * ri_OneKeyEqual -
 *
 *	Check if one key value in OLD and NEW is equal.
 *
3191 3192
 *	ri_KeysEqual could call this but would run a bit slower.  For
 *	now, let's duplicate the code.
3193 3194 3195
 * ----------
 */
static bool
3196 3197
ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup,
			   RI_QueryKey *key, int pairidx)
3198
{
3199 3200 3201 3202
	Oid			typeid;
	Datum		oldvalue;
	Datum		newvalue;
	bool		isnull;
3203 3204 3205 3206 3207

	/* ----------
	 * Get one attributes oldvalue. If it is NULL - they're not equal.
	 * ----------
	 */
3208 3209
	oldvalue = SPI_getbinval(oldtup, rel->rd_att,
							 key->keypair[column][pairidx], &isnull);
3210 3211 3212 3213 3214 3215 3216
	if (isnull)
		return false;

	/* ----------
	 * Get one attributes oldvalue. If it is NULL - they're not equal.
	 * ----------
	 */
3217 3218
	newvalue = SPI_getbinval(newtup, rel->rd_att,
							 key->keypair[column][pairidx], &isnull);
3219 3220 3221 3222 3223 3224 3225 3226 3227 3228
	if (isnull)
		return false;

	/* ----------
	 * Get the attributes type OID and call the '=' operator
	 * to compare the values.
	 * ----------
	 */
	typeid = SPI_gettypeid(rel->rd_att, key->keypair[column][pairidx]);
	if (!ri_AttributesEqual(typeid, oldvalue, newvalue))
3229
		return false;
3230 3231 3232 3233 3234

	return true;
}


3235 3236 3237
/* ----------
 * ri_AttributesEqual -
 *
3238
 *	Call the type specific '=' operator comparison function
3239
 *	for two values.
3240 3241
 *
 *	NB: we have already checked that neither value is null.
3242 3243 3244 3245 3246
 * ----------
 */
static bool
ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue)
{
3247 3248
	RI_OpreqHashEntry *entry;
	bool		found;
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260

	/* ----------
	 * On the first call initialize the hashtable
	 * ----------
	 */
	if (!ri_query_cache)
		ri_InitHashTables();

	/* ----------
	 * Try to find the '=' operator for this type in our cache
	 * ----------
	 */
3261 3262
	entry = (RI_OpreqHashEntry *) hash_search(ri_opreq_cache,
									(char *) &typeid, HASH_FIND, &found);
3263 3264 3265 3266
	if (entry == NULL)
		elog(FATAL, "error in RI operator cache");

	/* ----------
3267
	 * If not found, lookup the OPERNAME system cache for it
3268
	 * to get the func OID, then do the function manager lookup,
3269 3270 3271 3272 3273
	 * and remember that info.
	 * ----------
	 */
	if (!found)
	{
3274 3275
		HeapTuple	opr_tup;
		Form_pg_operator opr_struct;
3276

3277
		opr_tup = SearchSysCacheTuple(OPERNAME,
3278 3279 3280 3281
									  PointerGetDatum("="),
									  ObjectIdGetDatum(typeid),
									  ObjectIdGetDatum(typeid),
									  CharGetDatum('b'));
3282 3283 3284

		if (!HeapTupleIsValid(opr_tup))
			elog(ERROR, "ri_AttributesEqual(): cannot find '=' operator "
3285
				 "for type %u", typeid);
3286 3287
		opr_struct = (Form_pg_operator) GETSTRUCT(opr_tup);

3288 3289
		entry = (RI_OpreqHashEntry *) hash_search(ri_opreq_cache,
								   (char *) &typeid, HASH_ENTER, &found);
3290 3291 3292
		if (entry == NULL)
			elog(FATAL, "can't insert into RI operator cache");

3293 3294
		entry->typeid = typeid;
		fmgr_info(opr_struct->oprcode, &(entry->oprfmgrinfo));
3295 3296 3297 3298 3299 3300
	}

	/* ----------
	 * Call the type specific '=' function
	 * ----------
	 */
3301 3302
	return DatumGetBool(FunctionCall2(&(entry->oprfmgrinfo),
									  oldvalue, newvalue));
3303
}