~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to contrib/spi/refint.c

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * refint.c --  set of functions to define referential integrity
 
3
 *              constraints using general triggers.
 
4
 */
 
5
 
 
6
#include "executor/spi.h"               /* this is what you need to work with SPI */
 
7
#include "commands/trigger.h"   /* -"- and triggers */
 
8
#include <ctype.h>
 
9
 
 
10
 
 
11
extern Datum check_primary_key(PG_FUNCTION_ARGS);
 
12
extern Datum check_foreign_key(PG_FUNCTION_ARGS);
 
13
 
 
14
 
 
15
typedef struct
 
16
{
 
17
        char       *ident;
 
18
        int                     nplans;
 
19
        void      **splan;
 
20
}       EPlan;
 
21
 
 
22
static EPlan *FPlans = NULL;
 
23
static int      nFPlans = 0;
 
24
static EPlan *PPlans = NULL;
 
25
static int      nPPlans = 0;
 
26
 
 
27
static EPlan *find_plan(char *ident, EPlan ** eplan, int *nplans);
 
28
 
 
29
/*
 
30
 * check_primary_key () -- check that key in tuple being inserted/updated
 
31
 *                       references existing tuple in "primary" table.
 
32
 * Though it's called without args You have to specify referenced
 
33
 * table/keys while creating trigger:  key field names in triggered table,
 
34
 * referenced table name, referenced key field names:
 
35
 * EXECUTE PROCEDURE
 
36
 * check_primary_key ('Fkey1', 'Fkey2', 'Ptable', 'Pkey1', 'Pkey2').
 
37
 */
 
38
 
 
39
PG_FUNCTION_INFO_V1(check_primary_key);
 
40
 
 
41
Datum
 
42
check_primary_key(PG_FUNCTION_ARGS)
 
43
{
 
44
        TriggerData *trigdata = (TriggerData *) fcinfo->context;
 
45
        Trigger    *trigger;            /* to get trigger name */
 
46
        int                     nargs;                  /* # of args specified in CREATE TRIGGER */
 
47
        char      **args;                       /* arguments: column names and table name */
 
48
        int                     nkeys;                  /* # of key columns (= nargs / 2) */
 
49
        Datum      *kvals;                      /* key values */
 
50
        char       *relname;            /* referenced relation name */
 
51
        Relation        rel;                    /* triggered relation */
 
52
        HeapTuple       tuple = NULL;   /* tuple to return */
 
53
        TupleDesc       tupdesc;                /* tuple description */
 
54
        EPlan      *plan;                       /* prepared plan */
 
55
        Oid                *argtypes = NULL;    /* key types to prepare execution plan */
 
56
        bool            isnull;                 /* to know is some column NULL or not */
 
57
        char            ident[2 * NAMEDATALEN]; /* to identify myself */
 
58
        int                     ret;
 
59
        int                     i;
 
60
 
 
61
#ifdef  DEBUG_QUERY
 
62
        elog(DEBUG4, "check_primary_key: Enter Function");
 
63
#endif
 
64
 
 
65
        /*
 
66
         * Some checks first...
 
67
         */
 
68
 
 
69
        /* Called by trigger manager ? */
 
70
        if (!CALLED_AS_TRIGGER(fcinfo))
 
71
                /* internal error */
 
72
                elog(ERROR, "check_primary_key: not fired by trigger manager");
 
73
 
 
74
        /* Should be called for ROW trigger */
 
75
        if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
 
76
                /* internal error */
 
77
                elog(ERROR, "check_primary_key: can't process STATEMENT events");
 
78
 
 
79
        /* If INSERTion then must check Tuple to being inserted */
 
80
        if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
 
81
                tuple = trigdata->tg_trigtuple;
 
82
 
 
83
        /* Not should be called for DELETE */
 
84
        else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
 
85
                /* internal error */
 
86
                elog(ERROR, "check_primary_key: can't process DELETE events");
 
87
 
 
88
        /* If UPDATion the must check new Tuple, not old one */
 
89
        else
 
90
                tuple = trigdata->tg_newtuple;
 
91
 
 
92
        trigger = trigdata->tg_trigger;
 
93
        nargs = trigger->tgnargs;
 
94
        args = trigger->tgargs;
 
95
 
 
96
        if (nargs % 2 != 1)                     /* odd number of arguments! */
 
97
                /* internal error */
 
98
                elog(ERROR, "check_primary_key: odd number of arguments should be specified");
 
99
 
 
100
        nkeys = nargs / 2;
 
101
        relname = args[nkeys];
 
102
        rel = trigdata->tg_relation;
 
103
        tupdesc = rel->rd_att;
 
104
 
 
105
        /* Connect to SPI manager */
 
106
        if ((ret = SPI_connect()) < 0)
 
107
                /* internal error */
 
108
                elog(ERROR, "check_primary_key: SPI_connect returned %d", ret);
 
109
 
 
110
        /*
 
111
         * We use SPI plan preparation feature, so allocate space to place key
 
112
         * values.
 
113
         */
 
114
        kvals = (Datum *) palloc(nkeys * sizeof(Datum));
 
115
 
 
116
        /*
 
117
         * Construct ident string as TriggerName $ TriggeredRelationId and try
 
118
         * to find prepared execution plan.
 
119
         */
 
120
        snprintf(ident, sizeof(ident), "%s$%u", trigger->tgname, rel->rd_id);
 
121
        plan = find_plan(ident, &PPlans, &nPPlans);
 
122
 
 
123
        /* if there is no plan then allocate argtypes for preparation */
 
124
        if (plan->nplans <= 0)
 
125
                argtypes = (Oid *) palloc(nkeys * sizeof(Oid));
 
126
 
 
127
        /* For each column in key ... */
 
128
        for (i = 0; i < nkeys; i++)
 
129
        {
 
130
                /* get index of column in tuple */
 
131
                int                     fnumber = SPI_fnumber(tupdesc, args[i]);
 
132
 
 
133
                /* Bad guys may give us un-existing column in CREATE TRIGGER */
 
134
                if (fnumber < 0)
 
135
                        ereport(ERROR,
 
136
                                        (errcode(ERRCODE_UNDEFINED_COLUMN),
 
137
                                errmsg("there is no attribute \"%s\" in relation \"%s\"",
 
138
                                           args[i], SPI_getrelname(rel))));
 
139
 
 
140
                /* Well, get binary (in internal format) value of column */
 
141
                kvals[i] = SPI_getbinval(tuple, tupdesc, fnumber, &isnull);
 
142
 
 
143
                /*
 
144
                 * If it's NULL then nothing to do! DON'T FORGET call SPI_finish
 
145
                 * ()! DON'T FORGET return tuple! Executor inserts tuple you're
 
146
                 * returning! If you return NULL then nothing will be inserted!
 
147
                 */
 
148
                if (isnull)
 
149
                {
 
150
                        SPI_finish();
 
151
                        return PointerGetDatum(tuple);
 
152
                }
 
153
 
 
154
                if (plan->nplans <= 0)  /* Get typeId of column */
 
155
                        argtypes[i] = SPI_gettypeid(tupdesc, fnumber);
 
156
        }
 
157
 
 
158
        /*
 
159
         * If we have to prepare plan ...
 
160
         */
 
161
        if (plan->nplans <= 0)
 
162
        {
 
163
                void       *pplan;
 
164
                char            sql[8192];
 
165
 
 
166
                /*
 
167
                 * Construct query: SELECT 1 FROM _referenced_relation_ WHERE
 
168
                 * Pkey1 = $1 [AND Pkey2 = $2 [...]]
 
169
                 */
 
170
                snprintf(sql, sizeof(sql), "select 1 from %s where ", relname);
 
171
                for (i = 0; i < nkeys; i++)
 
172
                {
 
173
                        snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "%s = $%d %s",
 
174
                          args[i + nkeys + 1], i + 1, (i < nkeys - 1) ? "and " : "");
 
175
                }
 
176
 
 
177
                /* Prepare plan for query */
 
178
                pplan = SPI_prepare(sql, nkeys, argtypes);
 
179
                if (pplan == NULL)
 
180
                        /* internal error */
 
181
                        elog(ERROR, "check_primary_key: SPI_prepare returned %d", SPI_result);
 
182
 
 
183
                /*
 
184
                 * Remember that SPI_prepare places plan in current memory context
 
185
                 * - so, we have to save plan in Top memory context for latter
 
186
                 * use.
 
187
                 */
 
188
                pplan = SPI_saveplan(pplan);
 
189
                if (pplan == NULL)
 
190
                        /* internal error */
 
191
                        elog(ERROR, "check_primary_key: SPI_saveplan returned %d", SPI_result);
 
192
                plan->splan = (void **) malloc(sizeof(void *));
 
193
                *(plan->splan) = pplan;
 
194
                plan->nplans = 1;
 
195
        }
 
196
 
 
197
        /*
 
198
         * Ok, execute prepared plan.
 
199
         */
 
200
        ret = SPI_execp(*(plan->splan), kvals, NULL, 1);
 
201
        /* we have no NULLs - so we pass   ^^^^   here */
 
202
 
 
203
        if (ret < 0)
 
204
                /* internal error */
 
205
                elog(ERROR, "check_primary_key: SPI_execp returned %d", ret);
 
206
 
 
207
        /*
 
208
         * If there are no tuples returned by SELECT then ...
 
209
         */
 
210
        if (SPI_processed == 0)
 
211
                ereport(ERROR,
 
212
                                (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
 
213
                                 errmsg("tuple references non-existent key"),
 
214
                                 errdetail("Trigger \"%s\" found tuple referencing non-existent key in \"%s\".", trigger->tgname, relname)));
 
215
 
 
216
        SPI_finish();
 
217
 
 
218
        return PointerGetDatum(tuple);
 
219
}
 
220
 
 
221
/*
 
222
 * check_foreign_key () -- check that key in tuple being deleted/updated
 
223
 *                       is not referenced by tuples in "foreign" table(s).
 
224
 * Though it's called without args You have to specify (while creating trigger):
 
225
 * number of references, action to do if key referenced
 
226
 * ('restrict' | 'setnull' | 'cascade'), key field names in triggered
 
227
 * ("primary") table and referencing table(s)/keys:
 
228
 * EXECUTE PROCEDURE
 
229
 * check_foreign_key (2, 'restrict', 'Pkey1', 'Pkey2',
 
230
 * 'Ftable1', 'Fkey11', 'Fkey12', 'Ftable2', 'Fkey21', 'Fkey22').
 
231
 */
 
232
 
 
233
PG_FUNCTION_INFO_V1(check_foreign_key);
 
234
 
 
235
Datum
 
236
check_foreign_key(PG_FUNCTION_ARGS)
 
237
{
 
238
        TriggerData *trigdata = (TriggerData *) fcinfo->context;
 
239
        Trigger    *trigger;            /* to get trigger name */
 
240
        int                     nargs;                  /* # of args specified in CREATE TRIGGER */
 
241
        char      **args;                       /* arguments: as described above */
 
242
        char      **args_temp;
 
243
        int                     nrefs;                  /* number of references (== # of plans) */
 
244
        char            action;                 /* 'R'estrict | 'S'etnull | 'C'ascade */
 
245
        int                     nkeys;                  /* # of key columns */
 
246
        Datum      *kvals;                      /* key values */
 
247
        char       *relname;            /* referencing relation name */
 
248
        Relation        rel;                    /* triggered relation */
 
249
        HeapTuple       trigtuple = NULL;               /* tuple to being changed */
 
250
        HeapTuple       newtuple = NULL;        /* tuple to return */
 
251
        TupleDesc       tupdesc;                /* tuple description */
 
252
        EPlan      *plan;                       /* prepared plan(s) */
 
253
        Oid                *argtypes = NULL;    /* key types to prepare execution plan */
 
254
        bool            isnull;                 /* to know is some column NULL or not */
 
255
        bool            isequal = true; /* are keys in both tuples equal (in
 
256
                                                                 * UPDATE) */
 
257
        char            ident[2 * NAMEDATALEN]; /* to identify myself */
 
258
        int                     is_update = 0;
 
259
        int                     ret;
 
260
        int                     i,
 
261
                                r;
 
262
 
 
263
#ifdef DEBUG_QUERY
 
264
        elog(DEBUG4, "check_foreign_key: Enter Function");
 
265
#endif
 
266
 
 
267
        /*
 
268
         * Some checks first...
 
269
         */
 
270
 
 
271
        /* Called by trigger manager ? */
 
272
        if (!CALLED_AS_TRIGGER(fcinfo))
 
273
                /* internal error */
 
274
                elog(ERROR, "check_foreign_key: not fired by trigger manager");
 
275
 
 
276
        /* Should be called for ROW trigger */
 
277
        if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
 
278
                /* internal error */
 
279
                elog(ERROR, "check_foreign_key: can't process STATEMENT events");
 
280
 
 
281
        /* Not should be called for INSERT */
 
282
        if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
 
283
                /* internal error */
 
284
                elog(ERROR, "check_foreign_key: can't process INSERT events");
 
285
 
 
286
        /* Have to check tg_trigtuple - tuple being deleted */
 
287
        trigtuple = trigdata->tg_trigtuple;
 
288
 
 
289
        /*
 
290
         * But if this is UPDATE then we have to return tg_newtuple. Also, if
 
291
         * key in tg_newtuple is the same as in tg_trigtuple then nothing to
 
292
         * do.
 
293
         */
 
294
        is_update = 0;
 
295
        if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
 
296
        {
 
297
                newtuple = trigdata->tg_newtuple;
 
298
                is_update = 1;
 
299
        }
 
300
        trigger = trigdata->tg_trigger;
 
301
        nargs = trigger->tgnargs;
 
302
        args = trigger->tgargs;
 
303
 
 
304
        if (nargs < 5)                          /* nrefs, action, key, Relation, key - at
 
305
                                                                 * least */
 
306
                /* internal error */
 
307
                elog(ERROR, "check_foreign_key: too short %d (< 5) list of arguments", nargs);
 
308
 
 
309
        nrefs = pg_atoi(args[0], sizeof(int), 0);
 
310
        if (nrefs < 1)
 
311
                /* internal error */
 
312
                elog(ERROR, "check_foreign_key: %d (< 1) number of references specified", nrefs);
 
313
        action = tolower((unsigned char) *(args[1]));
 
314
        if (action != 'r' && action != 'c' && action != 's')
 
315
                /* internal error */
 
316
                elog(ERROR, "check_foreign_key: invalid action %s", args[1]);
 
317
        nargs -= 2;
 
318
        args += 2;
 
319
        nkeys = (nargs - nrefs) / (nrefs + 1);
 
320
        if (nkeys <= 0 || nargs != (nrefs + nkeys * (nrefs + 1)))
 
321
                /* internal error */
 
322
                elog(ERROR, "check_foreign_key: invalid number of arguments %d for %d references",
 
323
                         nargs + 2, nrefs);
 
324
 
 
325
        rel = trigdata->tg_relation;
 
326
        tupdesc = rel->rd_att;
 
327
 
 
328
        /* Connect to SPI manager */
 
329
        if ((ret = SPI_connect()) < 0)
 
330
                /* internal error */
 
331
                elog(ERROR, "check_foreign_key: SPI_connect returned %d", ret);
 
332
 
 
333
        /*
 
334
         * We use SPI plan preparation feature, so allocate space to place key
 
335
         * values.
 
336
         */
 
337
        kvals = (Datum *) palloc(nkeys * sizeof(Datum));
 
338
 
 
339
        /*
 
340
         * Construct ident string as TriggerName $ TriggeredRelationId and try
 
341
         * to find prepared execution plan(s).
 
342
         */
 
343
        snprintf(ident, sizeof(ident), "%s$%u", trigger->tgname, rel->rd_id);
 
344
        plan = find_plan(ident, &FPlans, &nFPlans);
 
345
 
 
346
        /* if there is no plan(s) then allocate argtypes for preparation */
 
347
        if (plan->nplans <= 0)
 
348
                argtypes = (Oid *) palloc(nkeys * sizeof(Oid));
 
349
 
 
350
        /*
 
351
         * else - check that we have exactly nrefs plan(s) ready
 
352
         */
 
353
        else if (plan->nplans != nrefs)
 
354
                /* internal error */
 
355
                elog(ERROR, "%s: check_foreign_key: # of plans changed in meantime",
 
356
                         trigger->tgname);
 
357
 
 
358
        /* For each column in key ... */
 
359
        for (i = 0; i < nkeys; i++)
 
360
        {
 
361
                /* get index of column in tuple */
 
362
                int                     fnumber = SPI_fnumber(tupdesc, args[i]);
 
363
 
 
364
                /* Bad guys may give us un-existing column in CREATE TRIGGER */
 
365
                if (fnumber < 0)
 
366
                        ereport(ERROR,
 
367
                                        (errcode(ERRCODE_UNDEFINED_COLUMN),
 
368
                                errmsg("there is no attribute \"%s\" in relation \"%s\"",
 
369
                                           args[i], SPI_getrelname(rel))));
 
370
 
 
371
                /* Well, get binary (in internal format) value of column */
 
372
                kvals[i] = SPI_getbinval(trigtuple, tupdesc, fnumber, &isnull);
 
373
 
 
374
                /*
 
375
                 * If it's NULL then nothing to do! DON'T FORGET call SPI_finish
 
376
                 * ()! DON'T FORGET return tuple! Executor inserts tuple you're
 
377
                 * returning! If you return NULL then nothing will be inserted!
 
378
                 */
 
379
                if (isnull)
 
380
                {
 
381
                        SPI_finish();
 
382
                        return PointerGetDatum((newtuple == NULL) ? trigtuple : newtuple);
 
383
                }
 
384
 
 
385
                /*
 
386
                 * If UPDATE then get column value from new tuple being inserted
 
387
                 * and compare is this the same as old one. For the moment we use
 
388
                 * string presentation of values...
 
389
                 */
 
390
                if (newtuple != NULL)
 
391
                {
 
392
                        char       *oldval = SPI_getvalue(trigtuple, tupdesc, fnumber);
 
393
                        char       *newval;
 
394
 
 
395
                        /* this shouldn't happen! SPI_ERROR_NOOUTFUNC ? */
 
396
                        if (oldval == NULL)
 
397
                                /* internal error */
 
398
                                elog(ERROR, "check_foreign_key: SPI_getvalue returned %d", SPI_result);
 
399
                        newval = SPI_getvalue(newtuple, tupdesc, fnumber);
 
400
                        if (newval == NULL || strcmp(oldval, newval) != 0)
 
401
                                isequal = false;
 
402
                }
 
403
 
 
404
                if (plan->nplans <= 0)  /* Get typeId of column */
 
405
                        argtypes[i] = SPI_gettypeid(tupdesc, fnumber);
 
406
        }
 
407
        args_temp = args;
 
408
        nargs -= nkeys;
 
409
        args += nkeys;
 
410
 
 
411
        /*
 
412
         * If we have to prepare plans ...
 
413
         */
 
414
        if (plan->nplans <= 0)
 
415
        {
 
416
                void       *pplan;
 
417
                char            sql[8192];
 
418
                char      **args2 = args;
 
419
 
 
420
                plan->splan = (void **) malloc(nrefs * sizeof(void *));
 
421
 
 
422
                for (r = 0; r < nrefs; r++)
 
423
                {
 
424
                        relname = args2[0];
 
425
 
 
426
                        /*---------
 
427
                         * For 'R'estrict action we construct SELECT query:
 
428
                         *
 
429
                         *      SELECT 1
 
430
                         *      FROM _referencing_relation_
 
431
                         *      WHERE Fkey1 = $1 [AND Fkey2 = $2 [...]]
 
432
                         *
 
433
                         *      to check is tuple referenced or not.
 
434
                         *---------
 
435
                         */
 
436
                        if (action == 'r')
 
437
 
 
438
                                snprintf(sql, sizeof(sql), "select 1 from %s where ", relname);
 
439
 
 
440
                        /*---------
 
441
                         * For 'C'ascade action we construct DELETE query
 
442
                         *
 
443
                         *      DELETE
 
444
                         *      FROM _referencing_relation_
 
445
                         *      WHERE Fkey1 = $1 [AND Fkey2 = $2 [...]]
 
446
                         *
 
447
                         * to delete all referencing tuples.
 
448
                         *---------
 
449
                         */
 
450
 
 
451
                        /*
 
452
                         * Max : Cascade with UPDATE query i create update query that
 
453
                         * updates new key values in referenced tables
 
454
                         */
 
455
 
 
456
 
 
457
                        else if (action == 'c')
 
458
                        {
 
459
                                if (is_update == 1)
 
460
                                {
 
461
                                        int                     fn;
 
462
                                        char       *nv;
 
463
                                        int                     k;
 
464
 
 
465
                                        snprintf(sql, sizeof(sql), "update %s set ", relname);
 
466
                                        for (k = 1; k <= nkeys; k++)
 
467
                                        {
 
468
                                                int                     is_char_type = 0;
 
469
                                                char       *type;
 
470
 
 
471
                                                fn = SPI_fnumber(tupdesc, args_temp[k - 1]);
 
472
                                                nv = SPI_getvalue(newtuple, tupdesc, fn);
 
473
                                                type = SPI_gettype(tupdesc, fn);
 
474
 
 
475
                                                if ((strcmp(type, "text") && strcmp(type, "varchar") &&
 
476
                                                strcmp(type, "char") && strcmp(type, "bpchar") &&
 
477
                                                         strcmp(type, "date") && strcmp(type, "timestamp")) == 0)
 
478
                                                        is_char_type = 1;
 
479
#ifdef  DEBUG_QUERY
 
480
                                                elog(DEBUG4, "check_foreign_key Debug value %s type %s %d",
 
481
                                                         nv, type, is_char_type);
 
482
#endif
 
483
 
 
484
                                                /*
 
485
                                                 * is_char_type =1 i set ' ' for define a new
 
486
                                                 * value
 
487
                                                 */
 
488
                                                snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql),
 
489
                                                                 " %s = %s%s%s %s ",
 
490
                                                                 args2[k], (is_char_type > 0) ? "'" : "",
 
491
                                                                 nv, (is_char_type > 0) ? "'" : "", (k < nkeys) ? ", " : "");
 
492
                                                is_char_type = 0;
 
493
                                        }
 
494
                                        strcat(sql, " where ");
 
495
 
 
496
                                }
 
497
                                else
 
498
                                        /* DELETE */
 
499
                                        snprintf(sql, sizeof(sql), "delete from %s where ", relname);
 
500
 
 
501
                        }
 
502
 
 
503
                        /*
 
504
                         * For 'S'etnull action we construct UPDATE query - UPDATE
 
505
                         * _referencing_relation_ SET Fkey1 null [, Fkey2 null [...]]
 
506
                         * WHERE Fkey1 = $1 [AND Fkey2 = $2 [...]] - to set key
 
507
                         * columns in all referencing tuples to NULL.
 
508
                         */
 
509
                        else if (action == 's')
 
510
                        {
 
511
                                snprintf(sql, sizeof(sql), "update %s set ", relname);
 
512
                                for (i = 1; i <= nkeys; i++)
 
513
                                {
 
514
                                        snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql),
 
515
                                                         "%s = null%s",
 
516
                                                         args2[i], (i < nkeys) ? ", " : "");
 
517
                                }
 
518
                                strcat(sql, " where ");
 
519
                        }
 
520
 
 
521
                        /* Construct WHERE qual */
 
522
                        for (i = 1; i <= nkeys; i++)
 
523
                        {
 
524
                                snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "%s = $%d %s",
 
525
                                                 args2[i], i, (i < nkeys) ? "and " : "");
 
526
                        }
 
527
 
 
528
                        /* Prepare plan for query */
 
529
                        pplan = SPI_prepare(sql, nkeys, argtypes);
 
530
                        if (pplan == NULL)
 
531
                                /* internal error */
 
532
                                elog(ERROR, "check_foreign_key: SPI_prepare returned %d", SPI_result);
 
533
 
 
534
                        /*
 
535
                         * Remember that SPI_prepare places plan in current memory
 
536
                         * context - so, we have to save plan in Top memory context
 
537
                         * for latter use.
 
538
                         */
 
539
                        pplan = SPI_saveplan(pplan);
 
540
                        if (pplan == NULL)
 
541
                                /* internal error */
 
542
                                elog(ERROR, "check_foreign_key: SPI_saveplan returned %d", SPI_result);
 
543
 
 
544
                        plan->splan[r] = pplan;
 
545
 
 
546
                        args2 += nkeys + 1; /* to the next relation */
 
547
                }
 
548
                plan->nplans = nrefs;
 
549
#ifdef  DEBUG_QUERY
 
550
                elog(DEBUG4, "check_foreign_key Debug Query is :  %s ", sql);
 
551
#endif
 
552
        }
 
553
 
 
554
        /*
 
555
         * If UPDATE and key is not changed ...
 
556
         */
 
557
        if (newtuple != NULL && isequal)
 
558
        {
 
559
                SPI_finish();
 
560
                return PointerGetDatum(newtuple);
 
561
        }
 
562
 
 
563
        /*
 
564
         * Ok, execute prepared plan(s).
 
565
         */
 
566
        for (r = 0; r < nrefs; r++)
 
567
        {
 
568
                /*
 
569
                 * For 'R'estrict we may to execute plan for one tuple only, for
 
570
                 * other actions - for all tuples.
 
571
                 */
 
572
                int                     tcount = (action == 'r') ? 1 : 0;
 
573
 
 
574
                relname = args[0];
 
575
 
 
576
                snprintf(ident, sizeof(ident), "%s$%u", trigger->tgname, rel->rd_id);
 
577
                plan = find_plan(ident, &FPlans, &nFPlans);
 
578
                ret = SPI_execp(plan->splan[r], kvals, NULL, tcount);
 
579
                /* we have no NULLs - so we pass   ^^^^  here */
 
580
 
 
581
                if (ret < 0)
 
582
                        ereport(ERROR,
 
583
                                        (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
 
584
                                         errmsg("SPI_execp returned %d", ret)));
 
585
 
 
586
                /* If action is 'R'estrict ... */
 
587
                if (action == 'r')
 
588
                {
 
589
                        /* If there is tuple returned by SELECT then ... */
 
590
                        if (SPI_processed > 0)
 
591
                                ereport(ERROR,
 
592
                                                (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION),
 
593
                                                 errmsg("\"%s\": tuple is referenced in \"%s\"",
 
594
                                                                trigger->tgname, relname)));
 
595
                }
 
596
                else
 
597
                {
 
598
#ifdef REFINT_VERBOSE
 
599
                        elog(NOTICE, "%s: %d tuple(s) of %s are %s",
 
600
                                 trigger->tgname, SPI_processed, relname,
 
601
                                 (action == 'c') ? "deleted" : "set to null");
 
602
#endif
 
603
                }
 
604
                args += nkeys + 1;              /* to the next relation */
 
605
        }
 
606
 
 
607
        SPI_finish();
 
608
 
 
609
        return PointerGetDatum((newtuple == NULL) ? trigtuple : newtuple);
 
610
}
 
611
 
 
612
static EPlan *
 
613
find_plan(char *ident, EPlan ** eplan, int *nplans)
 
614
{
 
615
        EPlan      *newp;
 
616
        int                     i;
 
617
 
 
618
        if (*nplans > 0)
 
619
        {
 
620
                for (i = 0; i < *nplans; i++)
 
621
                {
 
622
                        if (strcmp((*eplan)[i].ident, ident) == 0)
 
623
                                break;
 
624
                }
 
625
                if (i != *nplans)
 
626
                        return (*eplan + i);
 
627
                *eplan = (EPlan *) realloc(*eplan, (i + 1) * sizeof(EPlan));
 
628
                newp = *eplan + i;
 
629
        }
 
630
        else
 
631
        {
 
632
                newp = *eplan = (EPlan *) malloc(sizeof(EPlan));
 
633
                (*nplans) = i = 0;
 
634
        }
 
635
 
 
636
        newp->ident = (char *) malloc(strlen(ident) + 1);
 
637
        strcpy(newp->ident, ident);
 
638
        newp->nplans = 0;
 
639
        newp->splan = NULL;
 
640
        (*nplans)++;
 
641
 
 
642
        return (newp);
 
643
}