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