xref: /titanic_51/usr/src/lib/libsqlite/src/trigger.c (revision 1e49577a7fcde812700ded04431b49d67cc57d6d)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 **
6 ** The author disclaims copyright to this source code.  In place of
7 ** a legal notice, here is a blessing:
8 **
9 **    May you do good and not evil.
10 **    May you find forgiveness for yourself and forgive others.
11 **    May you share freely, never taking more than you give.
12 **
13 *************************************************************************
14 *
15 */
16 #include "sqliteInt.h"
17 
18 /*
19 ** Delete a linked list of TriggerStep structures.
20 */
21 void sqliteDeleteTriggerStep(TriggerStep *pTriggerStep){
22   while( pTriggerStep ){
23     TriggerStep * pTmp = pTriggerStep;
24     pTriggerStep = pTriggerStep->pNext;
25 
26     if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
27     sqliteExprDelete(pTmp->pWhere);
28     sqliteExprListDelete(pTmp->pExprList);
29     sqliteSelectDelete(pTmp->pSelect);
30     sqliteIdListDelete(pTmp->pIdList);
31 
32     sqliteFree(pTmp);
33   }
34 }
35 
36 /*
37 ** This is called by the parser when it sees a CREATE TRIGGER statement
38 ** up to the point of the BEGIN before the trigger actions.  A Trigger
39 ** structure is generated based on the information available and stored
40 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
41 ** sqliteFinishTrigger() function is called to complete the trigger
42 ** construction process.
43 */
44 void sqliteBeginTrigger(
45   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
46   Token *pName,       /* The name of the trigger */
47   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
48   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
49   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
50   SrcList *pTableName,/* The name of the table/view the trigger applies to */
51   int foreach,        /* One of TK_ROW or TK_STATEMENT */
52   Expr *pWhen,        /* WHEN clause */
53   int isTemp          /* True if the TEMPORARY keyword is present */
54 ){
55   Trigger *nt;
56   Table   *tab;
57   char *zName = 0;        /* Name of the trigger */
58   sqlite *db = pParse->db;
59   int iDb;                /* When database to store the trigger in */
60   DbFixer sFix;
61 
62   /* Check that:
63   ** 1. the trigger name does not already exist.
64   ** 2. the table (or view) does exist in the same database as the trigger.
65   ** 3. that we are not trying to create a trigger on the sqlite_master table
66   ** 4. That we are not trying to create an INSTEAD OF trigger on a table.
67   ** 5. That we are not trying to create a BEFORE or AFTER trigger on a view.
68   */
69   if( sqlite_malloc_failed ) goto trigger_cleanup;
70   assert( pTableName->nSrc==1 );
71   if( db->init.busy
72    && sqliteFixInit(&sFix, pParse, db->init.iDb, "trigger", pName)
73    && sqliteFixSrcList(&sFix, pTableName)
74   ){
75     goto trigger_cleanup;
76   }
77   tab = sqliteSrcListLookup(pParse, pTableName);
78   if( !tab ){
79     goto trigger_cleanup;
80   }
81   iDb = isTemp ? 1 : tab->iDb;
82   if( iDb>=2 && !db->init.busy ){
83     sqliteErrorMsg(pParse, "triggers may not be added to auxiliary "
84        "database %s", db->aDb[tab->iDb].zName);
85     goto trigger_cleanup;
86   }
87 
88   zName = sqliteStrNDup(pName->z, pName->n);
89   sqliteDequote(zName);
90   if( sqliteHashFind(&(db->aDb[iDb].trigHash), zName,pName->n+1) ){
91     sqliteErrorMsg(pParse, "trigger %T already exists", pName);
92     goto trigger_cleanup;
93   }
94   if( sqliteStrNICmp(tab->zName, "sqlite_", 7)==0 ){
95     sqliteErrorMsg(pParse, "cannot create trigger on system table");
96     pParse->nErr++;
97     goto trigger_cleanup;
98   }
99   if( tab->pSelect && tr_tm != TK_INSTEAD ){
100     sqliteErrorMsg(pParse, "cannot create %s trigger on view: %S",
101         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
102     goto trigger_cleanup;
103   }
104   if( !tab->pSelect && tr_tm == TK_INSTEAD ){
105     sqliteErrorMsg(pParse, "cannot create INSTEAD OF"
106         " trigger on table: %S", pTableName, 0);
107     goto trigger_cleanup;
108   }
109 #ifndef SQLITE_OMIT_AUTHORIZATION
110   {
111     int code = SQLITE_CREATE_TRIGGER;
112     const char *zDb = db->aDb[tab->iDb].zName;
113     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
114     if( tab->iDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
115     if( sqliteAuthCheck(pParse, code, zName, tab->zName, zDbTrig) ){
116       goto trigger_cleanup;
117     }
118     if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(tab->iDb), 0, zDb)){
119       goto trigger_cleanup;
120     }
121   }
122 #endif
123 
124   /* INSTEAD OF triggers can only appear on views and BEGIN triggers
125   ** cannot appear on views.  So we might as well translate every
126   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
127   ** elsewhere.
128   */
129   if (tr_tm == TK_INSTEAD){
130     tr_tm = TK_BEFORE;
131   }
132 
133   /* Build the Trigger object */
134   nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
135   if( nt==0 ) goto trigger_cleanup;
136   nt->name = zName;
137   zName = 0;
138   nt->table = sqliteStrDup(pTableName->a[0].zName);
139   if( sqlite_malloc_failed ) goto trigger_cleanup;
140   nt->iDb = iDb;
141   nt->iTabDb = tab->iDb;
142   nt->op = op;
143   nt->tr_tm = tr_tm;
144   nt->pWhen = sqliteExprDup(pWhen);
145   nt->pColumns = sqliteIdListDup(pColumns);
146   nt->foreach = foreach;
147   sqliteTokenCopy(&nt->nameToken,pName);
148   assert( pParse->pNewTrigger==0 );
149   pParse->pNewTrigger = nt;
150 
151 trigger_cleanup:
152   sqliteFree(zName);
153   sqliteSrcListDelete(pTableName);
154   sqliteIdListDelete(pColumns);
155   sqliteExprDelete(pWhen);
156 }
157 
158 /*
159 ** This routine is called after all of the trigger actions have been parsed
160 ** in order to complete the process of building the trigger.
161 */
162 void sqliteFinishTrigger(
163   Parse *pParse,          /* Parser context */
164   TriggerStep *pStepList, /* The triggered program */
165   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
166 ){
167   Trigger *nt = 0;          /* The trigger whose construction is finishing up */
168   sqlite *db = pParse->db;  /* The database */
169   DbFixer sFix;
170 
171   if( pParse->nErr || pParse->pNewTrigger==0 ) goto triggerfinish_cleanup;
172   nt = pParse->pNewTrigger;
173   pParse->pNewTrigger = 0;
174   nt->step_list = pStepList;
175   while( pStepList ){
176     pStepList->pTrig = nt;
177     pStepList = pStepList->pNext;
178   }
179   if( sqliteFixInit(&sFix, pParse, nt->iDb, "trigger", &nt->nameToken)
180           && sqliteFixTriggerStep(&sFix, nt->step_list) ){
181     goto triggerfinish_cleanup;
182   }
183 
184   /* if we are not initializing, and this trigger is not on a TEMP table,
185   ** build the sqlite_master entry
186   */
187   if( !db->init.busy ){
188     static VdbeOpList insertTrig[] = {
189       { OP_NewRecno,   0, 0,  0          },
190       { OP_String,     0, 0,  "trigger"  },
191       { OP_String,     0, 0,  0          },  /* 2: trigger name */
192       { OP_String,     0, 0,  0          },  /* 3: table name */
193       { OP_Integer,    0, 0,  0          },
194       { OP_String,     0, 0,  0          },  /* 5: SQL */
195       { OP_MakeRecord, 5, 0,  0          },
196       { OP_PutIntKey,  0, 0,  0          },
197     };
198     int addr;
199     Vdbe *v;
200 
201     /* Make an entry in the sqlite_master table */
202     v = sqliteGetVdbe(pParse);
203     if( v==0 ) goto triggerfinish_cleanup;
204     sqliteBeginWriteOperation(pParse, 0, 0);
205     sqliteOpenMasterTable(v, nt->iDb);
206     addr = sqliteVdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
207     sqliteVdbeChangeP3(v, addr+2, nt->name, 0);
208     sqliteVdbeChangeP3(v, addr+3, nt->table, 0);
209     sqliteVdbeChangeP3(v, addr+5, pAll->z, pAll->n);
210     if( nt->iDb==0 ){
211       sqliteChangeCookie(db, v);
212     }
213     sqliteVdbeAddOp(v, OP_Close, 0, 0);
214     sqliteEndWriteOperation(pParse);
215   }
216 
217   if( !pParse->explain ){
218     Table *pTab;
219     sqliteHashInsert(&db->aDb[nt->iDb].trigHash,
220                      nt->name, strlen(nt->name)+1, nt);
221     pTab = sqliteLocateTable(pParse, nt->table, db->aDb[nt->iTabDb].zName);
222     assert( pTab!=0 );
223     nt->pNext = pTab->pTrigger;
224     pTab->pTrigger = nt;
225     nt = 0;
226   }
227 
228 triggerfinish_cleanup:
229   sqliteDeleteTrigger(nt);
230   sqliteDeleteTrigger(pParse->pNewTrigger);
231   pParse->pNewTrigger = 0;
232   sqliteDeleteTriggerStep(pStepList);
233 }
234 
235 /*
236 ** Make a copy of all components of the given trigger step.  This has
237 ** the effect of copying all Expr.token.z values into memory obtained
238 ** from sqliteMalloc().  As initially created, the Expr.token.z values
239 ** all point to the input string that was fed to the parser.  But that
240 ** string is ephemeral - it will go away as soon as the sqlite_exec()
241 ** call that started the parser exits.  This routine makes a persistent
242 ** copy of all the Expr.token.z strings so that the TriggerStep structure
243 ** will be valid even after the sqlite_exec() call returns.
244 */
245 static void sqlitePersistTriggerStep(TriggerStep *p){
246   if( p->target.z ){
247     p->target.z = sqliteStrNDup(p->target.z, p->target.n);
248     p->target.dyn = 1;
249   }
250   if( p->pSelect ){
251     Select *pNew = sqliteSelectDup(p->pSelect);
252     sqliteSelectDelete(p->pSelect);
253     p->pSelect = pNew;
254   }
255   if( p->pWhere ){
256     Expr *pNew = sqliteExprDup(p->pWhere);
257     sqliteExprDelete(p->pWhere);
258     p->pWhere = pNew;
259   }
260   if( p->pExprList ){
261     ExprList *pNew = sqliteExprListDup(p->pExprList);
262     sqliteExprListDelete(p->pExprList);
263     p->pExprList = pNew;
264   }
265   if( p->pIdList ){
266     IdList *pNew = sqliteIdListDup(p->pIdList);
267     sqliteIdListDelete(p->pIdList);
268     p->pIdList = pNew;
269   }
270 }
271 
272 /*
273 ** Turn a SELECT statement (that the pSelect parameter points to) into
274 ** a trigger step.  Return a pointer to a TriggerStep structure.
275 **
276 ** The parser calls this routine when it finds a SELECT statement in
277 ** body of a TRIGGER.
278 */
279 TriggerStep *sqliteTriggerSelectStep(Select *pSelect){
280   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
281   if( pTriggerStep==0 ) return 0;
282 
283   pTriggerStep->op = TK_SELECT;
284   pTriggerStep->pSelect = pSelect;
285   pTriggerStep->orconf = OE_Default;
286   sqlitePersistTriggerStep(pTriggerStep);
287 
288   return pTriggerStep;
289 }
290 
291 /*
292 ** Build a trigger step out of an INSERT statement.  Return a pointer
293 ** to the new trigger step.
294 **
295 ** The parser calls this routine when it sees an INSERT inside the
296 ** body of a trigger.
297 */
298 TriggerStep *sqliteTriggerInsertStep(
299   Token *pTableName,  /* Name of the table into which we insert */
300   IdList *pColumn,    /* List of columns in pTableName to insert into */
301   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
302   Select *pSelect,    /* A SELECT statement that supplies values */
303   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
304 ){
305   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
306   if( pTriggerStep==0 ) return 0;
307 
308   assert(pEList == 0 || pSelect == 0);
309   assert(pEList != 0 || pSelect != 0);
310 
311   pTriggerStep->op = TK_INSERT;
312   pTriggerStep->pSelect = pSelect;
313   pTriggerStep->target  = *pTableName;
314   pTriggerStep->pIdList = pColumn;
315   pTriggerStep->pExprList = pEList;
316   pTriggerStep->orconf = orconf;
317   sqlitePersistTriggerStep(pTriggerStep);
318 
319   return pTriggerStep;
320 }
321 
322 /*
323 ** Construct a trigger step that implements an UPDATE statement and return
324 ** a pointer to that trigger step.  The parser calls this routine when it
325 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
326 */
327 TriggerStep *sqliteTriggerUpdateStep(
328   Token *pTableName,   /* Name of the table to be updated */
329   ExprList *pEList,    /* The SET clause: list of column and new values */
330   Expr *pWhere,        /* The WHERE clause */
331   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
332 ){
333   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
334   if( pTriggerStep==0 ) return 0;
335 
336   pTriggerStep->op = TK_UPDATE;
337   pTriggerStep->target  = *pTableName;
338   pTriggerStep->pExprList = pEList;
339   pTriggerStep->pWhere = pWhere;
340   pTriggerStep->orconf = orconf;
341   sqlitePersistTriggerStep(pTriggerStep);
342 
343   return pTriggerStep;
344 }
345 
346 /*
347 ** Construct a trigger step that implements a DELETE statement and return
348 ** a pointer to that trigger step.  The parser calls this routine when it
349 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
350 */
351 TriggerStep *sqliteTriggerDeleteStep(Token *pTableName, Expr *pWhere){
352   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
353   if( pTriggerStep==0 ) return 0;
354 
355   pTriggerStep->op = TK_DELETE;
356   pTriggerStep->target  = *pTableName;
357   pTriggerStep->pWhere = pWhere;
358   pTriggerStep->orconf = OE_Default;
359   sqlitePersistTriggerStep(pTriggerStep);
360 
361   return pTriggerStep;
362 }
363 
364 /*
365 ** Recursively delete a Trigger structure
366 */
367 void sqliteDeleteTrigger(Trigger *pTrigger){
368   if( pTrigger==0 ) return;
369   sqliteDeleteTriggerStep(pTrigger->step_list);
370   sqliteFree(pTrigger->name);
371   sqliteFree(pTrigger->table);
372   sqliteExprDelete(pTrigger->pWhen);
373   sqliteIdListDelete(pTrigger->pColumns);
374   if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
375   sqliteFree(pTrigger);
376 }
377 
378 /*
379  * This function is called to drop a trigger from the database schema.
380  *
381  * This may be called directly from the parser and therefore identifies
382  * the trigger by name.  The sqliteDropTriggerPtr() routine does the
383  * same job as this routine except it take a spointer to the trigger
384  * instead of the trigger name.
385  *
386  * Note that this function does not delete the trigger entirely. Instead it
387  * removes it from the internal schema and places it in the trigDrop hash
388  * table. This is so that the trigger can be restored into the database schema
389  * if the transaction is rolled back.
390  */
391 void sqliteDropTrigger(Parse *pParse, SrcList *pName){
392   Trigger *pTrigger;
393   int i;
394   const char *zDb;
395   const char *zName;
396   int nName;
397   sqlite *db = pParse->db;
398 
399   if( sqlite_malloc_failed ) goto drop_trigger_cleanup;
400   assert( pName->nSrc==1 );
401   zDb = pName->a[0].zDatabase;
402   zName = pName->a[0].zName;
403   nName = strlen(zName);
404   for(i=0; i<db->nDb; i++){
405     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
406     if( zDb && sqliteStrICmp(db->aDb[j].zName, zDb) ) continue;
407     pTrigger = sqliteHashFind(&(db->aDb[j].trigHash), zName, nName+1);
408     if( pTrigger ) break;
409   }
410   if( !pTrigger ){
411     sqliteErrorMsg(pParse, "no such trigger: %S", pName, 0);
412     goto drop_trigger_cleanup;
413   }
414   sqliteDropTriggerPtr(pParse, pTrigger, 0);
415 
416 drop_trigger_cleanup:
417   sqliteSrcListDelete(pName);
418 }
419 
420 /*
421 ** Drop a trigger given a pointer to that trigger.  If nested is false,
422 ** then also generate code to remove the trigger from the SQLITE_MASTER
423 ** table.
424 */
425 void sqliteDropTriggerPtr(Parse *pParse, Trigger *pTrigger, int nested){
426   Table   *pTable;
427   Vdbe *v;
428   sqlite *db = pParse->db;
429 
430   assert( pTrigger->iDb<db->nDb );
431   if( pTrigger->iDb>=2 ){
432     sqliteErrorMsg(pParse, "triggers may not be removed from "
433        "auxiliary database %s", db->aDb[pTrigger->iDb].zName);
434     return;
435   }
436   pTable = sqliteFindTable(db, pTrigger->table,db->aDb[pTrigger->iTabDb].zName);
437   assert(pTable);
438   assert( pTable->iDb==pTrigger->iDb || pTrigger->iDb==1 );
439 #ifndef SQLITE_OMIT_AUTHORIZATION
440   {
441     int code = SQLITE_DROP_TRIGGER;
442     const char *zDb = db->aDb[pTrigger->iDb].zName;
443     const char *zTab = SCHEMA_TABLE(pTrigger->iDb);
444     if( pTrigger->iDb ) code = SQLITE_DROP_TEMP_TRIGGER;
445     if( sqliteAuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
446       sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
447       return;
448     }
449   }
450 #endif
451 
452   /* Generate code to destroy the database record of the trigger.
453   */
454   if( pTable!=0 && !nested && (v = sqliteGetVdbe(pParse))!=0 ){
455     int base;
456     static VdbeOpList dropTrigger[] = {
457       { OP_Rewind,     0, ADDR(9),  0},
458       { OP_String,     0, 0,        0}, /* 1 */
459       { OP_Column,     0, 1,        0},
460       { OP_Ne,         0, ADDR(8),  0},
461       { OP_String,     0, 0,        "trigger"},
462       { OP_Column,     0, 0,        0},
463       { OP_Ne,         0, ADDR(8),  0},
464       { OP_Delete,     0, 0,        0},
465       { OP_Next,       0, ADDR(1),  0}, /* 8 */
466     };
467 
468     sqliteBeginWriteOperation(pParse, 0, 0);
469     sqliteOpenMasterTable(v, pTrigger->iDb);
470     base = sqliteVdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
471     sqliteVdbeChangeP3(v, base+1, pTrigger->name, 0);
472     if( pTrigger->iDb==0 ){
473       sqliteChangeCookie(db, v);
474     }
475     sqliteVdbeAddOp(v, OP_Close, 0, 0);
476     sqliteEndWriteOperation(pParse);
477   }
478 
479   /*
480    * If this is not an "explain", then delete the trigger structure.
481    */
482   if( !pParse->explain ){
483     const char *zName = pTrigger->name;
484     int nName = strlen(zName);
485     if( pTable->pTrigger == pTrigger ){
486       pTable->pTrigger = pTrigger->pNext;
487     }else{
488       Trigger *cc = pTable->pTrigger;
489       while( cc ){
490         if( cc->pNext == pTrigger ){
491           cc->pNext = cc->pNext->pNext;
492           break;
493         }
494         cc = cc->pNext;
495       }
496       assert(cc);
497     }
498     sqliteHashInsert(&(db->aDb[pTrigger->iDb].trigHash), zName, nName+1, 0);
499     sqliteDeleteTrigger(pTrigger);
500   }
501 }
502 
503 /*
504 ** pEList is the SET clause of an UPDATE statement.  Each entry
505 ** in pEList is of the format <id>=<expr>.  If any of the entries
506 ** in pEList have an <id> which matches an identifier in pIdList,
507 ** then return TRUE.  If pIdList==NULL, then it is considered a
508 ** wildcard that matches anything.  Likewise if pEList==NULL then
509 ** it matches anything so always return true.  Return false only
510 ** if there is no match.
511 */
512 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
513   int e;
514   if( !pIdList || !pEList ) return 1;
515   for(e=0; e<pEList->nExpr; e++){
516     if( sqliteIdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
517   }
518   return 0;
519 }
520 
521 /* A global variable that is TRUE if we should always set up temp tables for
522  * for triggers, even if there are no triggers to code. This is used to test
523  * how much overhead the triggers algorithm is causing.
524  *
525  * This flag can be set or cleared using the "trigger_overhead_test" pragma.
526  * The pragma is not documented since it is not really part of the interface
527  * to SQLite, just the test procedure.
528 */
529 int always_code_trigger_setup = 0;
530 
531 /*
532  * Returns true if a trigger matching op, tr_tm and foreach that is NOT already
533  * on the Parse objects trigger-stack (to prevent recursive trigger firing) is
534  * found in the list specified as pTrigger.
535  */
536 int sqliteTriggersExist(
537   Parse *pParse,          /* Used to check for recursive triggers */
538   Trigger *pTrigger,      /* A list of triggers associated with a table */
539   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
540   int tr_tm,              /* one of TK_BEFORE, TK_AFTER */
541   int foreach,            /* one of TK_ROW or TK_STATEMENT */
542   ExprList *pChanges      /* Columns that change in an UPDATE statement */
543 ){
544   Trigger * pTriggerCursor;
545 
546   if( always_code_trigger_setup ){
547     return 1;
548   }
549 
550   pTriggerCursor = pTrigger;
551   while( pTriggerCursor ){
552     if( pTriggerCursor->op == op &&
553 	pTriggerCursor->tr_tm == tr_tm &&
554 	pTriggerCursor->foreach == foreach &&
555 	checkColumnOverLap(pTriggerCursor->pColumns, pChanges) ){
556       TriggerStack * ss;
557       ss = pParse->trigStack;
558       while( ss && ss->pTrigger != pTrigger ){
559 	ss = ss->pNext;
560       }
561       if( !ss )return 1;
562     }
563     pTriggerCursor = pTriggerCursor->pNext;
564   }
565 
566   return 0;
567 }
568 
569 /*
570 ** Convert the pStep->target token into a SrcList and return a pointer
571 ** to that SrcList.
572 **
573 ** This routine adds a specific database name, if needed, to the target when
574 ** forming the SrcList.  This prevents a trigger in one database from
575 ** referring to a target in another database.  An exception is when the
576 ** trigger is in TEMP in which case it can refer to any other database it
577 ** wants.
578 */
579 static SrcList *targetSrcList(
580   Parse *pParse,       /* The parsing context */
581   TriggerStep *pStep   /* The trigger containing the target token */
582 ){
583   Token sDb;           /* Dummy database name token */
584   int iDb;             /* Index of the database to use */
585   SrcList *pSrc;       /* SrcList to be returned */
586 
587   iDb = pStep->pTrig->iDb;
588   if( iDb==0 || iDb>=2 ){
589     assert( iDb<pParse->db->nDb );
590     sDb.z = pParse->db->aDb[iDb].zName;
591     sDb.n = strlen(sDb.z);
592     pSrc = sqliteSrcListAppend(0, &sDb, &pStep->target);
593   } else {
594     pSrc = sqliteSrcListAppend(0, &pStep->target, 0);
595   }
596   return pSrc;
597 }
598 
599 /*
600 ** Generate VDBE code for zero or more statements inside the body of a
601 ** trigger.
602 */
603 static int codeTriggerProgram(
604   Parse *pParse,            /* The parser context */
605   TriggerStep *pStepList,   /* List of statements inside the trigger body */
606   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */
607 ){
608   TriggerStep * pTriggerStep = pStepList;
609   int orconf;
610 
611   while( pTriggerStep ){
612     int saveNTab = pParse->nTab;
613 
614     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
615     pParse->trigStack->orconf = orconf;
616     switch( pTriggerStep->op ){
617       case TK_SELECT: {
618 	Select * ss = sqliteSelectDup(pTriggerStep->pSelect);
619 	assert(ss);
620 	assert(ss->pSrc);
621 	sqliteSelect(pParse, ss, SRT_Discard, 0, 0, 0, 0);
622 	sqliteSelectDelete(ss);
623 	break;
624       }
625       case TK_UPDATE: {
626         SrcList *pSrc;
627         pSrc = targetSrcList(pParse, pTriggerStep);
628         sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
629         sqliteUpdate(pParse, pSrc,
630 		sqliteExprListDup(pTriggerStep->pExprList),
631 		sqliteExprDup(pTriggerStep->pWhere), orconf);
632         sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
633         break;
634       }
635       case TK_INSERT: {
636         SrcList *pSrc;
637         pSrc = targetSrcList(pParse, pTriggerStep);
638         sqliteInsert(pParse, pSrc,
639           sqliteExprListDup(pTriggerStep->pExprList),
640           sqliteSelectDup(pTriggerStep->pSelect),
641           sqliteIdListDup(pTriggerStep->pIdList), orconf);
642         break;
643       }
644       case TK_DELETE: {
645         SrcList *pSrc;
646         sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
647         pSrc = targetSrcList(pParse, pTriggerStep);
648         sqliteDeleteFrom(pParse, pSrc, sqliteExprDup(pTriggerStep->pWhere));
649         sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
650         break;
651       }
652       default:
653         assert(0);
654     }
655     pParse->nTab = saveNTab;
656     pTriggerStep = pTriggerStep->pNext;
657   }
658 
659   return 0;
660 }
661 
662 /*
663 ** This is called to code FOR EACH ROW triggers.
664 **
665 ** When the code that this function generates is executed, the following
666 ** must be true:
667 **
668 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
669 **    can be indices of cursors in temporary tables.  See below.)
670 **
671 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
672 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
673 **    a row containing values to be substituted for new.* expressions in the
674 **    trigger program(s).
675 **
676 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
677 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
678 **    a row containing values to be substituted for old.* expressions in the
679 **    trigger program(s).
680 **
681 */
682 int sqliteCodeRowTrigger(
683   Parse *pParse,       /* Parse context */
684   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
685   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
686   int tr_tm,           /* One of TK_BEFORE, TK_AFTER */
687   Table *pTab,         /* The table to code triggers from */
688   int newIdx,          /* The indice of the "new" row to access */
689   int oldIdx,          /* The indice of the "old" row to access */
690   int orconf,          /* ON CONFLICT policy */
691   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
692 ){
693   Trigger * pTrigger;
694   TriggerStack * pTriggerStack;
695 
696   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
697   assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER );
698 
699   assert(newIdx != -1 || oldIdx != -1);
700 
701   pTrigger = pTab->pTrigger;
702   while( pTrigger ){
703     int fire_this = 0;
704 
705     /* determine whether we should code this trigger */
706     if( pTrigger->op == op && pTrigger->tr_tm == tr_tm &&
707         pTrigger->foreach == TK_ROW ){
708       fire_this = 1;
709       pTriggerStack = pParse->trigStack;
710       while( pTriggerStack ){
711         if( pTriggerStack->pTrigger == pTrigger ){
712 	  fire_this = 0;
713 	}
714         pTriggerStack = pTriggerStack->pNext;
715       }
716       if( op == TK_UPDATE && pTrigger->pColumns &&
717           !checkColumnOverLap(pTrigger->pColumns, pChanges) ){
718         fire_this = 0;
719       }
720     }
721 
722     if( fire_this && (pTriggerStack = sqliteMalloc(sizeof(TriggerStack)))!=0 ){
723       int endTrigger;
724       SrcList dummyTablist;
725       Expr * whenExpr;
726       AuthContext sContext;
727 
728       dummyTablist.nSrc = 0;
729 
730       /* Push an entry on to the trigger stack */
731       pTriggerStack->pTrigger = pTrigger;
732       pTriggerStack->newIdx = newIdx;
733       pTriggerStack->oldIdx = oldIdx;
734       pTriggerStack->pTab = pTab;
735       pTriggerStack->pNext = pParse->trigStack;
736       pTriggerStack->ignoreJump = ignoreJump;
737       pParse->trigStack = pTriggerStack;
738       sqliteAuthContextPush(pParse, &sContext, pTrigger->name);
739 
740       /* code the WHEN clause */
741       endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
742       whenExpr = sqliteExprDup(pTrigger->pWhen);
743       if( sqliteExprResolveIds(pParse, &dummyTablist, 0, whenExpr) ){
744         pParse->trigStack = pParse->trigStack->pNext;
745         sqliteFree(pTriggerStack);
746         sqliteExprDelete(whenExpr);
747         return 1;
748       }
749       sqliteExprIfFalse(pParse, whenExpr, endTrigger, 1);
750       sqliteExprDelete(whenExpr);
751 
752       sqliteVdbeAddOp(pParse->pVdbe, OP_ContextPush, 0, 0);
753       codeTriggerProgram(pParse, pTrigger->step_list, orconf);
754       sqliteVdbeAddOp(pParse->pVdbe, OP_ContextPop, 0, 0);
755 
756       /* Pop the entry off the trigger stack */
757       pParse->trigStack = pParse->trigStack->pNext;
758       sqliteAuthContextPop(&sContext);
759       sqliteFree(pTriggerStack);
760 
761       sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
762     }
763     pTrigger = pTrigger->pNext;
764   }
765 
766   return 0;
767 }
768