LCOV - code coverage report
Current view: top level - contrib/spi - refint.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 154 207 74.4 %
Date: 2020-06-05 19:06:29 Functions: 6 6 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13