aboutsummaryrefslogtreecommitdiff
path: root/src/backend/utils/adt/ri_triggers.c
blob: 6f69479ba35093ee08f428a66e8dad28b41201e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
/* ----------
 * ri_triggers.c
 *
 *	Generic trigger procedures for referential integrity constraint
 *	checks.
 *
 *	1999 Jan Wieck
 *
 * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.2 1999/10/08 12:00:08 wieck Exp $
 *
 * ----------
 */

#include "postgres.h"
#include "fmgr.h"

#include "access/heapam.h"
#include "catalog/pg_operator.h"
#include "catalog/catname.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "utils/builtins.h"
#include "utils/mcxt.h"
#include "utils/syscache.h"
#include "lib/hasht.h"


/* ----------
 * 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


#define RI_PLAN_TYPE_CHECK_FULL			0
#define RI_PLAN_TYPE_CASCADE_DEL_FULL	1


/* ----------
 * RI_QueryKey
 *
 *	The key identifying a prepared SPI plan in our private hashtable
 * ----------
 */
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];
} RI_QueryKey;


/* ----------
 * RI_QueryHashEntry
 * ----------
 */
typedef struct RI_QueryHashEntry {
	RI_QueryKey			key;
	void			   *plan;
} RI_QueryHashEntry;


typedef struct RI_OpreqHashEntry {
	Oid					typeid;
	Oid					oprfnid;
	FmgrInfo			oprfmgrinfo;
} RI_OpreqHashEntry;



/* ----------
 * Local data
 * ----------
 */
static HTAB			   *ri_query_cache = (HTAB *)NULL;
static HTAB			   *ri_opreq_cache = (HTAB *)NULL;


/* ----------
 * Local function prototypes
 * ----------
 */
static int ri_DetermineMatchType(char *str);
static int ri_NullCheck(Relation rel, HeapTuple tup, 
							RI_QueryKey *key, int pairidx);
static void ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id,
							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_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 -
 *
 *	Check foreign key existance (combined for INSERT and UPDATE).
 * ----------
 */
static HeapTuple
RI_FKey_check (FmgrInfo *proinfo)
{
	TriggerData		   *trigdata;
	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;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
	if (trigdata == NULL)
		elog(ERROR, "RI_FKey_check() not fired by trigger manager");
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) || 
				!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
		elog(ERROR, "RI_FKey_check() must be fired AFTER ROW");
	if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) &&
				!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		elog(ERROR, "RI_FKey_check() must be fired for INSERT or UPDATE");

	/* ----------
	 * Check for the correct # of call arguments 
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
	tgargs  = trigdata->tg_trigger->tgargs;
	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()",
						RI_MAX_NUMKEYS);

	/* ----------
	 * Get the relation descriptors of the FK and PK tables and
	 * the new tuple.
	 * ----------
	 */
	fk_rel  = trigdata->tg_relation;
	pk_rel	= heap_openr(tgargs[RI_PK_RELNAME_ARGNO], NoLock);
	if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
	{
		old_row = trigdata->tg_trigtuple;
		new_row = trigdata->tg_newtuple;
	} else {
		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)
	 * ----------
	 */
	if (tgnargs == 4) {
		ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid, 1,
								fk_rel, pk_rel,
								tgnargs, tgargs);

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

			/* ----------
			 * The query string built is
			 *    SELECT oid FROM <pktable>
			 * ----------
			 */
			sprintf(querystr, "SELECT oid FROM \"%s\"", 
								tgargs[RI_PK_RELNAME_ARGNO]);

			/* ----------
			 * 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()");
		
		if (SPI_processed == 0)
			elog(ERROR, "%s referential integrity violation - "
						"no rows found in %s",
					tgargs[RI_CONSTRAINT_NAME_ARGNO],
					tgargs[RI_PK_RELNAME_ARGNO]);

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

		return NULL;

	}

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
		/* ----------
		 * SQL3 11.9 <referential constraint definition>
		 *	Gereral rules 2) b):
		 * 		<match type> is not specified
		 * ----------
		 */
		case RI_MATCH_TYPE_UNSPECIFIED:
			elog(ERROR, "MATCH <unspecified> not yet supported");
			return NULL;

		/* ----------
		 * SQL3 11.9 <referential constraint definition>
		 *	Gereral rules 2) c):
		 * 		MATCH PARTIAL
		 * ----------
		 */
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
			return NULL;

		/* ----------
		 * SQL3 11.9 <referential constraint definition>
		 *	Gereral rules 2) d):
		 * 		MATCH FULL
		 * ----------
		 */
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid, 2,
												fk_rel, pk_rel,
												tgnargs, tgargs);

			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.
					 * ----------
					 */
					heap_close(pk_rel, NoLock);
					return NULL;
					
				case RI_KEYS_SOME_NULL:
					/* ----------
					 * Not allowed - MATCH FULL says either all or none
					 * of the attributes can be NULLs
					 * ----------
					 */
					elog(ERROR, "%s referential integrity violation - "
								"MATCH FULL doesn't allow mixing of NULL "
								"and NON-NULL key values",
								tgargs[RI_CONSTRAINT_NAME_ARGNO]);
					break;

				case RI_KEYS_NONE_NULL:
					/* ----------
					 * Have a full qualified key - continue below
					 * ----------
					 */
					break;
			}
			heap_close(pk_rel, NoLock);

			/* ----------
			 * If we're called on UPDATE, check if there was a change
			 * in the foreign key at all.
			 * ----------
			 */
			if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
			{
				if (ri_KeysEqual(fk_rel, old_row, new_row, &qkey,
														RI_KEYPAIR_FK_IDX))
					return NULL;
			}

			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];
				char		*querysep;
				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 '='.
				 * ----------
				 */
				sprintf(querystr, "SELECT oid FROM \"%s\"", 
									tgargs[RI_PK_RELNAME_ARGNO]);
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
					sprintf(buf, " %s \"%s\" = $%d", querysep, 
										tgargs[5 + i * 2], i + 1);
					strcat(querystr, buf);
					querysep = "AND";
					queryoids[i] = SPI_gettypeid(fk_rel->rd_att,
									qkey.keypair[i][RI_KEYPAIR_FK_IDX]);
				}

				/* ----------
				 * 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++)
			{
				check_values[i] = SPI_getbinval(new_row,
									fk_rel->rd_att,
									qkey.keypair[i][RI_KEYPAIR_FK_IDX],
									&isnull);
				if (isnull) 
					check_nulls[i] = 'n';
				else
					check_nulls[i] = ' ';
			}
			check_nulls[RI_MAX_NUMKEYS] = '\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()");
			
			if (SPI_processed == 0)
				elog(ERROR, "%s referential integrity violation - "
							"key referenced from %s not found in %s",
						tgargs[RI_CONSTRAINT_NAME_ARGNO],
						tgargs[RI_FK_RELNAME_ARGNO],
						tgargs[RI_PK_RELNAME_ARGNO]);

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

			return NULL;
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
	elog(ERROR, "internal error #1 in ri_triggers.c");
	return NULL;
}


/* ----------
 * RI_FKey_check_ins -
 *
 *	Check foreign key existance at insert event on FK table.
 * ----------
 */
HeapTuple
RI_FKey_check_ins (FmgrInfo *proinfo)
{
	return RI_FKey_check(proinfo);
}


/* ----------
 * RI_FKey_check_upd -
 *
 *	Check foreign key existance at update event on FK table.
 * ----------
 */
HeapTuple
RI_FKey_check_upd (FmgrInfo *proinfo)
{
	return RI_FKey_check(proinfo);
}


/* ----------
 * RI_FKey_cascade_del -
 *
 *	Cascaded delete foreign key references at delete event on PK table.
 * ----------
 */
HeapTuple
RI_FKey_cascade_del (FmgrInfo *proinfo)
{
	TriggerData		   *trigdata;
	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;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	/* ----------
	 * Check that this is a valid trigger call on the right time and event.
	 * ----------
	 */
	if (trigdata == NULL)
		elog(ERROR, "RI_FKey_cascade_del() not fired by trigger manager");
	if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) || 
				!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
		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");

	/* ----------
	 * Check for the correct # of call arguments 
	 * ----------
	 */
	tgnargs = trigdata->tg_trigger->tgnargs;
	tgargs  = trigdata->tg_trigger->tgargs;
	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()",
						RI_MAX_NUMKEYS);

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

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

	switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
	{
		/* ----------
		 * SQL3 11.9 <referential constraint definition>
		 *	Gereral rules 6) a) i):
		 * 		MATCH <unspecified> or MATCH FULL
		 *			... ON DELETE CASCADE
		 * ----------
		 */
		case RI_MATCH_TYPE_UNSPECIFIED:
		case RI_MATCH_TYPE_FULL:
			ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid, 1,
												fk_rel, pk_rel,
												tgnargs, tgargs);

			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);
					return NULL;
					
				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_check()");

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

				/* ----------
				 * The query string built is
				 *    DELETE 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 '='.
				 * ----------
				 */
				sprintf(querystr, "DELETE FROM \"%s\"", 
									tgargs[RI_FK_RELNAME_ARGNO]);
				querysep = "WHERE";
				for (i = 0; i < qkey.nkeypairs; i++)
				{
					sprintf(buf, " %s \"%s\" = $%d", querysep, 
										tgargs[4 + i * 2], i + 1);
					strcat(querystr, buf);
					querysep = "AND";
					queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
									qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
				}

				/* ----------
				 * 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,
									pk_rel->rd_att,
									qkey.keypair[i][RI_KEYPAIR_PK_IDX],
									&isnull);
				if (isnull) 
					del_nulls[i] = 'n';
				else
					del_nulls[i] = ' ';
			}
			del_nulls[RI_MAX_NUMKEYS] = '\0';

			/* ----------
			 * Now delete constraint
			 * ----------
			 */
			if (SPI_execp(qplan, del_values, del_nulls, 1) != SPI_OK_DELETE)
				elog(ERROR, "SPI_execp() failed in RI_FKey_cascade_del()");
			
			if (SPI_finish() != SPI_OK_FINISH)
				elog(NOTICE, "SPI_finish() failed in RI_FKey_cascade_del()");

			return NULL;

		/* ----------
		 * Handle MATCH PARTIAL cascaded delete.
		 * ----------
		 */
		case RI_MATCH_TYPE_PARTIAL:
			elog(ERROR, "MATCH PARTIAL not yet supported");
			return NULL;
	}

	/* ----------
	 * Never reached
	 * ----------
	 */
	elog(ERROR, "internal error #2 in ri_triggers.c");
	return NULL;
}


/* ----------
 * RI_FKey_cascade_upd -
 *
 *	Cascaded update/delete foreign key references at update event on PK table.
 * ----------
 */
HeapTuple
RI_FKey_cascade_upd (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_cascade_upd() called\n");
	return NULL;
}


/* ----------
 * RI_FKey_restrict_del -
 *
 *	Restrict delete from PK table to rows unreferenced by foreign key.
 * ----------
 */
HeapTuple
RI_FKey_restrict_del (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_restrict_del() called\n");
	return NULL;
}


/* ----------
 * RI_FKey_restrict_upd -
 *
 *	Restrict update of PK to rows unreferenced by foreign key.
 * ----------
 */
HeapTuple
RI_FKey_restrict_upd (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_restrict_upd() called\n");
	return NULL;
}


/* ----------
 * RI_FKey_setnull_del -
 *
 *	Set foreign key references to NULL values at delete event on PK table.
 * ----------
 */
HeapTuple
RI_FKey_setnull_del (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_setnull_del() called\n");
	return NULL;
}


/* ----------
 * RI_FKey_setnull_upd -
 *
 *	Set foreign key references to NULL at update event on PK table.
 * ----------
 */
HeapTuple
RI_FKey_setnull_upd (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_setnull_upd() called\n");
	return NULL;
}


/* ----------
 * RI_FKey_setdefault_del -
 *
 *	Set foreign key references to defaults at delete event on PK table.
 * ----------
 */
HeapTuple
RI_FKey_setdefault_del (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_setdefault_del() called\n");
	return NULL;
}


/* ----------
 * RI_FKey_setdefault_upd -
 *
 *	Set foreign key references to defaults at update event on PK table.
 * ----------
 */
HeapTuple
RI_FKey_setdefault_upd (FmgrInfo *proinfo)
{
	TriggerData			*trigdata;

	trigdata = CurrentTriggerData;
	CurrentTriggerData	= NULL;

	elog(NOTICE, "RI_FKey_setdefault_upd() called\n");
	return NULL;
}





/* ----------
 * 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.
 * ----------
 */
static void 
ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id, int32 constr_queryno,
							Relation fk_rel, Relation pk_rel,
							int argc, char **argv)
{
	int 				i;
	int					j;
	int					fno;

	/* ----------
	 * Initialize the key and fill in type, oid's and number of keypairs
	 * ----------
	 */
	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;

	/* ----------
	 * 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",
					argv[RI_CONSTRAINT_NAME_ARGNO],
					argv[RI_FK_RELNAME_ARGNO],
					argv[j]);
		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",
					argv[RI_CONSTRAINT_NAME_ARGNO],
					argv[RI_PK_RELNAME_ARGNO],
					argv[j + 1]);
		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.
 * ----------
 */
static int 
ri_NullCheck(Relation rel, HeapTuple tup, RI_QueryKey *key, int pairidx)
{
	int				i;
	bool			isnull;
	bool			allnull  = true;
	bool			nonenull = true;

	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));
	ctl.keysize		= sizeof(RI_QueryKey);
	ctl.datasize	= sizeof(void *);
	ri_query_cache = hash_create(RI_INIT_QUERYHASHSIZE, &ctl, HASH_ELEM);

	memset(&ctl, 0, sizeof(ctl));
	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);
}


/* ----------
 * 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)
{
	RI_QueryHashEntry  *entry;
	bool				found;

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

	/* ----------
	 * Lookup for the key
	 * ----------
	 */
	entry = (RI_QueryHashEntry *)hash_search(ri_query_cache, 
										(char *)key, HASH_FIND, &found);
	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)
{
	RI_QueryHashEntry  *entry;
	bool				found;

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

	/* ----------
	 * Add the new plan.
	 * ----------
	 */
	entry = (RI_QueryHashEntry *)hash_search(ri_query_cache, 
										(char *)key, HASH_ENTER, &found);
	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
ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup, 
							RI_QueryKey *key, int pairidx)
{
	int				i;
	Oid				typeid;
	Datum			oldvalue;
	Datum			newvalue;
	bool			isnull;

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

		/* ----------
		 * Get one attributes oldvalue. If it is NULL - they're not equal.
		 * ----------
		 */
		newvalue = SPI_getbinval(newtup, rel->rd_att, 
									key->keypair[i][pairidx], &isnull);
		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;
}


/* ----------
 * ri_AttributesEqual -
 *
 *	Call the type specific '=' operator comparision function
 *	for two values.
 * ----------
 */
static bool
ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue)
{
	RI_OpreqHashEntry	   *entry;
	bool					found;
	Datum					result;

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

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

	/* ----------
	 * If not found, lookup the OPRNAME system cache for it
	 * and remember that info.
	 * ----------
	 */
	if (!found)
	{
		HeapTuple			opr_tup;
		Form_pg_operator	opr_struct;

		opr_tup = SearchSysCacheTuple(OPRNAME,
							PointerGetDatum("="),
							ObjectIdGetDatum(typeid),
							ObjectIdGetDatum(typeid),
							CharGetDatum('b'));

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

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

		entry->oprfnid = opr_struct->oprcode;
		memset(&(entry->oprfmgrinfo), 0, sizeof(FmgrInfo));
	}

	/* ----------
	 * Call the type specific '=' function
	 * ----------
	 */
	fmgr_info(entry->oprfnid, &(entry->oprfmgrinfo));
	result = (Datum)(*fmgr_faddr(&(entry->oprfmgrinfo)))(oldvalue, newvalue);
	return (bool)result;
}