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