xref: /sqlite-3.40.0/src/trigger.c (revision 5d00d0a8)
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 ** $Id: trigger.c,v 1.143 2009/08/10 03:57:58 shane Exp $
14 */
15 #include "sqliteInt.h"
16 
17 #ifndef SQLITE_OMIT_TRIGGER
18 /*
19 ** Delete a linked list of TriggerStep structures.
20 */
21 void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
22   while( pTriggerStep ){
23     TriggerStep * pTmp = pTriggerStep;
24     pTriggerStep = pTriggerStep->pNext;
25 
26     sqlite3ExprDelete(db, pTmp->pWhere);
27     sqlite3ExprListDelete(db, pTmp->pExprList);
28     sqlite3SelectDelete(db, pTmp->pSelect);
29     sqlite3IdListDelete(db, pTmp->pIdList);
30 
31     sqlite3DbFree(db, pTmp);
32   }
33 }
34 
35 /*
36 ** Given table pTab, return a list of all the triggers attached to
37 ** the table. The list is connected by Trigger.pNext pointers.
38 **
39 ** All of the triggers on pTab that are in the same database as pTab
40 ** are already attached to pTab->pTrigger.  But there might be additional
41 ** triggers on pTab in the TEMP schema.  This routine prepends all
42 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
43 ** and returns the combined list.
44 **
45 ** To state it another way:  This routine returns a list of all triggers
46 ** that fire off of pTab.  The list will include any TEMP triggers on
47 ** pTab as well as the triggers lised in pTab->pTrigger.
48 */
49 Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
50   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
51   Trigger *pList = 0;                  /* List of triggers to return */
52 
53   if( pTmpSchema!=pTab->pSchema ){
54     HashElem *p;
55     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
56       Trigger *pTrig = (Trigger *)sqliteHashData(p);
57       if( pTrig->pTabSchema==pTab->pSchema
58        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
59       ){
60         pTrig->pNext = (pList ? pList : pTab->pTrigger);
61         pList = pTrig;
62       }
63     }
64   }
65 
66   return (pList ? pList : pTab->pTrigger);
67 }
68 
69 /*
70 ** This is called by the parser when it sees a CREATE TRIGGER statement
71 ** up to the point of the BEGIN before the trigger actions.  A Trigger
72 ** structure is generated based on the information available and stored
73 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
74 ** sqlite3FinishTrigger() function is called to complete the trigger
75 ** construction process.
76 */
77 void sqlite3BeginTrigger(
78   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
79   Token *pName1,      /* The name of the trigger */
80   Token *pName2,      /* The name of the trigger */
81   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
82   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
83   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
84   SrcList *pTableName,/* The name of the table/view the trigger applies to */
85   Expr *pWhen,        /* WHEN clause */
86   int isTemp,         /* True if the TEMPORARY keyword is present */
87   int noErr           /* Suppress errors if the trigger already exists */
88 ){
89   Trigger *pTrigger = 0;  /* The new trigger */
90   Table *pTab;            /* Table that the trigger fires off of */
91   char *zName = 0;        /* Name of the trigger */
92   sqlite3 *db = pParse->db;  /* The database connection */
93   int iDb;                /* The database to store the trigger in */
94   Token *pName;           /* The unqualified db name */
95   DbFixer sFix;           /* State vector for the DB fixer */
96   int iTabDb;             /* Index of the database holding pTab */
97 
98   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99   assert( pName2!=0 );
100   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
101   assert( op>0 && op<0xff );
102   if( isTemp ){
103     /* If TEMP was specified, then the trigger name may not be qualified. */
104     if( pName2->n>0 ){
105       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
106       goto trigger_cleanup;
107     }
108     iDb = 1;
109     pName = pName1;
110   }else{
111     /* Figure out the db that the the trigger will be created in */
112     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
113     if( iDb<0 ){
114       goto trigger_cleanup;
115     }
116   }
117 
118   /* If the trigger name was unqualified, and the table is a temp table,
119   ** then set iDb to 1 to create the trigger in the temporary database.
120   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
121   ** exist, the error is caught by the block below.
122   */
123   if( !pTableName || db->mallocFailed ){
124     goto trigger_cleanup;
125   }
126   pTab = sqlite3SrcListLookup(pParse, pTableName);
127   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
128     iDb = 1;
129   }
130 
131   /* Ensure the table name matches database name and that the table exists */
132   if( db->mallocFailed ) goto trigger_cleanup;
133   assert( pTableName->nSrc==1 );
134   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
135       sqlite3FixSrcList(&sFix, pTableName) ){
136     goto trigger_cleanup;
137   }
138   pTab = sqlite3SrcListLookup(pParse, pTableName);
139   if( !pTab ){
140     /* The table does not exist. */
141     if( db->init.iDb==1 ){
142       /* Ticket #3810.
143       ** Normally, whenever a table is dropped, all associated triggers are
144       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
145       ** and the table is dropped by a different database connection, the
146       ** trigger is not visible to the database connection that does the
147       ** drop so the trigger cannot be dropped.  This results in an
148       ** "orphaned trigger" - a trigger whose associated table is missing.
149       */
150       db->init.orphanTrigger = 1;
151     }
152     goto trigger_cleanup;
153   }
154   if( IsVirtual(pTab) ){
155     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
156     goto trigger_cleanup;
157   }
158 
159   /* Check that the trigger name is not reserved and that no trigger of the
160   ** specified name exists */
161   zName = sqlite3NameFromToken(db, pName);
162   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
163     goto trigger_cleanup;
164   }
165   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
166                       zName, sqlite3Strlen30(zName)) ){
167     if( !noErr ){
168       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
169     }
170     goto trigger_cleanup;
171   }
172 
173   /* Do not create a trigger on a system table */
174   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
175     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
176     pParse->nErr++;
177     goto trigger_cleanup;
178   }
179 
180   /* INSTEAD of triggers are only for views and views only support INSTEAD
181   ** of triggers.
182   */
183   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
184     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
185         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
186     goto trigger_cleanup;
187   }
188   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
189     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
190         " trigger on table: %S", pTableName, 0);
191     goto trigger_cleanup;
192   }
193   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
194 
195 #ifndef SQLITE_OMIT_AUTHORIZATION
196   {
197     int code = SQLITE_CREATE_TRIGGER;
198     const char *zDb = db->aDb[iTabDb].zName;
199     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
200     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
201     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
202       goto trigger_cleanup;
203     }
204     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
205       goto trigger_cleanup;
206     }
207   }
208 #endif
209 
210   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
211   ** cannot appear on views.  So we might as well translate every
212   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
213   ** elsewhere.
214   */
215   if (tr_tm == TK_INSTEAD){
216     tr_tm = TK_BEFORE;
217   }
218 
219   /* Build the Trigger object */
220   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
221   if( pTrigger==0 ) goto trigger_cleanup;
222   pTrigger->name = zName;
223   zName = 0;
224   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
225   pTrigger->pSchema = db->aDb[iDb].pSchema;
226   pTrigger->pTabSchema = pTab->pSchema;
227   pTrigger->op = (u8)op;
228   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
229   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
230   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
231   assert( pParse->pNewTrigger==0 );
232   pParse->pNewTrigger = pTrigger;
233 
234 trigger_cleanup:
235   sqlite3DbFree(db, zName);
236   sqlite3SrcListDelete(db, pTableName);
237   sqlite3IdListDelete(db, pColumns);
238   sqlite3ExprDelete(db, pWhen);
239   if( !pParse->pNewTrigger ){
240     sqlite3DeleteTrigger(db, pTrigger);
241   }else{
242     assert( pParse->pNewTrigger==pTrigger );
243   }
244 }
245 
246 /*
247 ** This routine is called after all of the trigger actions have been parsed
248 ** in order to complete the process of building the trigger.
249 */
250 void sqlite3FinishTrigger(
251   Parse *pParse,          /* Parser context */
252   TriggerStep *pStepList, /* The triggered program */
253   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
254 ){
255   Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
256   char *zName;                             /* Name of trigger */
257   sqlite3 *db = pParse->db;                /* The database */
258   DbFixer sFix;
259   int iDb;                                 /* Database containing the trigger */
260   Token nameToken;           /* Trigger name for error reporting */
261 
262   pTrig = pParse->pNewTrigger;
263   pParse->pNewTrigger = 0;
264   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
265   zName = pTrig->name;
266   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
267   pTrig->step_list = pStepList;
268   while( pStepList ){
269     pStepList->pTrig = pTrig;
270     pStepList = pStepList->pNext;
271   }
272   nameToken.z = pTrig->name;
273   nameToken.n = sqlite3Strlen30(nameToken.z);
274   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
275           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
276     goto triggerfinish_cleanup;
277   }
278 
279   /* if we are not initializing, and this trigger is not on a TEMP table,
280   ** build the sqlite_master entry
281   */
282   if( !db->init.busy ){
283     Vdbe *v;
284     char *z;
285 
286     /* Make an entry in the sqlite_master table */
287     v = sqlite3GetVdbe(pParse);
288     if( v==0 ) goto triggerfinish_cleanup;
289     sqlite3BeginWriteOperation(pParse, 0, iDb);
290     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
291     sqlite3NestedParse(pParse,
292        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
293        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
294        pTrig->table, z);
295     sqlite3DbFree(db, z);
296     sqlite3ChangeCookie(pParse, iDb);
297     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
298         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
299     );
300   }
301 
302   if( db->init.busy ){
303     Trigger *pLink = pTrig;
304     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
305     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
306     if( pTrig ){
307       db->mallocFailed = 1;
308     }else if( pLink->pSchema==pLink->pTabSchema ){
309       Table *pTab;
310       int n = sqlite3Strlen30(pLink->table);
311       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
312       assert( pTab!=0 );
313       pLink->pNext = pTab->pTrigger;
314       pTab->pTrigger = pLink;
315     }
316   }
317 
318 triggerfinish_cleanup:
319   sqlite3DeleteTrigger(db, pTrig);
320   assert( !pParse->pNewTrigger );
321   sqlite3DeleteTriggerStep(db, pStepList);
322 }
323 
324 /*
325 ** Turn a SELECT statement (that the pSelect parameter points to) into
326 ** a trigger step.  Return a pointer to a TriggerStep structure.
327 **
328 ** The parser calls this routine when it finds a SELECT statement in
329 ** body of a TRIGGER.
330 */
331 TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
332   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
333   if( pTriggerStep==0 ) {
334     sqlite3SelectDelete(db, pSelect);
335     return 0;
336   }
337   pTriggerStep->op = TK_SELECT;
338   pTriggerStep->pSelect = pSelect;
339   pTriggerStep->orconf = OE_Default;
340   return pTriggerStep;
341 }
342 
343 /*
344 ** Allocate space to hold a new trigger step.  The allocated space
345 ** holds both the TriggerStep object and the TriggerStep.target.z string.
346 **
347 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
348 */
349 static TriggerStep *triggerStepAllocate(
350   sqlite3 *db,                /* Database connection */
351   u8 op,                      /* Trigger opcode */
352   Token *pName                /* The target name */
353 ){
354   TriggerStep *pTriggerStep;
355 
356   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
357   if( pTriggerStep ){
358     char *z = (char*)&pTriggerStep[1];
359     memcpy(z, pName->z, pName->n);
360     pTriggerStep->target.z = z;
361     pTriggerStep->target.n = pName->n;
362     pTriggerStep->op = op;
363   }
364   return pTriggerStep;
365 }
366 
367 /*
368 ** Build a trigger step out of an INSERT statement.  Return a pointer
369 ** to the new trigger step.
370 **
371 ** The parser calls this routine when it sees an INSERT inside the
372 ** body of a trigger.
373 */
374 TriggerStep *sqlite3TriggerInsertStep(
375   sqlite3 *db,        /* The database connection */
376   Token *pTableName,  /* Name of the table into which we insert */
377   IdList *pColumn,    /* List of columns in pTableName to insert into */
378   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
379   Select *pSelect,    /* A SELECT statement that supplies values */
380   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
381 ){
382   TriggerStep *pTriggerStep;
383 
384   assert(pEList == 0 || pSelect == 0);
385   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
386 
387   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
388   if( pTriggerStep ){
389     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
390     pTriggerStep->pIdList = pColumn;
391     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
392     pTriggerStep->orconf = orconf;
393   }else{
394     sqlite3IdListDelete(db, pColumn);
395   }
396   sqlite3ExprListDelete(db, pEList);
397   sqlite3SelectDelete(db, pSelect);
398 
399   return pTriggerStep;
400 }
401 
402 /*
403 ** Construct a trigger step that implements an UPDATE statement and return
404 ** a pointer to that trigger step.  The parser calls this routine when it
405 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
406 */
407 TriggerStep *sqlite3TriggerUpdateStep(
408   sqlite3 *db,         /* The database connection */
409   Token *pTableName,   /* Name of the table to be updated */
410   ExprList *pEList,    /* The SET clause: list of column and new values */
411   Expr *pWhere,        /* The WHERE clause */
412   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
413 ){
414   TriggerStep *pTriggerStep;
415 
416   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
417   if( pTriggerStep ){
418     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
419     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
420     pTriggerStep->orconf = orconf;
421   }
422   sqlite3ExprListDelete(db, pEList);
423   sqlite3ExprDelete(db, pWhere);
424   return pTriggerStep;
425 }
426 
427 /*
428 ** Construct a trigger step that implements a DELETE statement and return
429 ** a pointer to that trigger step.  The parser calls this routine when it
430 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
431 */
432 TriggerStep *sqlite3TriggerDeleteStep(
433   sqlite3 *db,            /* Database connection */
434   Token *pTableName,      /* The table from which rows are deleted */
435   Expr *pWhere            /* The WHERE clause */
436 ){
437   TriggerStep *pTriggerStep;
438 
439   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
440   if( pTriggerStep ){
441     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
442     pTriggerStep->orconf = OE_Default;
443   }
444   sqlite3ExprDelete(db, pWhere);
445   return pTriggerStep;
446 }
447 
448 /*
449 ** Recursively delete a Trigger structure
450 */
451 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
452   if( pTrigger==0 ) return;
453   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
454   sqlite3DbFree(db, pTrigger->name);
455   sqlite3DbFree(db, pTrigger->table);
456   sqlite3ExprDelete(db, pTrigger->pWhen);
457   sqlite3IdListDelete(db, pTrigger->pColumns);
458   sqlite3DbFree(db, pTrigger);
459 }
460 
461 /*
462 ** This function is called to drop a trigger from the database schema.
463 **
464 ** This may be called directly from the parser and therefore identifies
465 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
466 ** same job as this routine except it takes a pointer to the trigger
467 ** instead of the trigger name.
468 **/
469 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
470   Trigger *pTrigger = 0;
471   int i;
472   const char *zDb;
473   const char *zName;
474   int nName;
475   sqlite3 *db = pParse->db;
476 
477   if( db->mallocFailed ) goto drop_trigger_cleanup;
478   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
479     goto drop_trigger_cleanup;
480   }
481 
482   assert( pName->nSrc==1 );
483   zDb = pName->a[0].zDatabase;
484   zName = pName->a[0].zName;
485   nName = sqlite3Strlen30(zName);
486   for(i=OMIT_TEMPDB; i<db->nDb; i++){
487     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
488     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
489     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
490     if( pTrigger ) break;
491   }
492   if( !pTrigger ){
493     if( !noErr ){
494       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
495     }
496     goto drop_trigger_cleanup;
497   }
498   sqlite3DropTriggerPtr(pParse, pTrigger);
499 
500 drop_trigger_cleanup:
501   sqlite3SrcListDelete(db, pName);
502 }
503 
504 /*
505 ** Return a pointer to the Table structure for the table that a trigger
506 ** is set on.
507 */
508 static Table *tableOfTrigger(Trigger *pTrigger){
509   int n = sqlite3Strlen30(pTrigger->table);
510   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
511 }
512 
513 
514 /*
515 ** Drop a trigger given a pointer to that trigger.
516 */
517 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
518   Table   *pTable;
519   Vdbe *v;
520   sqlite3 *db = pParse->db;
521   int iDb;
522 
523   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
524   assert( iDb>=0 && iDb<db->nDb );
525   pTable = tableOfTrigger(pTrigger);
526   assert( pTable );
527   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
528 #ifndef SQLITE_OMIT_AUTHORIZATION
529   {
530     int code = SQLITE_DROP_TRIGGER;
531     const char *zDb = db->aDb[iDb].zName;
532     const char *zTab = SCHEMA_TABLE(iDb);
533     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
534     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
535       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
536       return;
537     }
538   }
539 #endif
540 
541   /* Generate code to destroy the database record of the trigger.
542   */
543   assert( pTable!=0 );
544   if( (v = sqlite3GetVdbe(pParse))!=0 ){
545     int base;
546     static const VdbeOpList dropTrigger[] = {
547       { OP_Rewind,     0, ADDR(9),  0},
548       { OP_String8,    0, 1,        0}, /* 1 */
549       { OP_Column,     0, 1,        2},
550       { OP_Ne,         2, ADDR(8),  1},
551       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
552       { OP_Column,     0, 0,        2},
553       { OP_Ne,         2, ADDR(8),  1},
554       { OP_Delete,     0, 0,        0},
555       { OP_Next,       0, ADDR(1),  0}, /* 8 */
556     };
557 
558     sqlite3BeginWriteOperation(pParse, 0, iDb);
559     sqlite3OpenMasterTable(pParse, iDb);
560     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
561     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
562     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
563     sqlite3ChangeCookie(pParse, iDb);
564     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
565     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
566     if( pParse->nMem<3 ){
567       pParse->nMem = 3;
568     }
569   }
570 }
571 
572 /*
573 ** Remove a trigger from the hash tables of the sqlite* pointer.
574 */
575 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
576   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
577   Trigger *pTrigger;
578   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
579   if( ALWAYS(pTrigger) ){
580     if( pTrigger->pSchema==pTrigger->pTabSchema ){
581       Table *pTab = tableOfTrigger(pTrigger);
582       Trigger **pp;
583       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
584       *pp = (*pp)->pNext;
585     }
586     sqlite3DeleteTrigger(db, pTrigger);
587     db->flags |= SQLITE_InternChanges;
588   }
589 }
590 
591 /*
592 ** pEList is the SET clause of an UPDATE statement.  Each entry
593 ** in pEList is of the format <id>=<expr>.  If any of the entries
594 ** in pEList have an <id> which matches an identifier in pIdList,
595 ** then return TRUE.  If pIdList==NULL, then it is considered a
596 ** wildcard that matches anything.  Likewise if pEList==NULL then
597 ** it matches anything so always return true.  Return false only
598 ** if there is no match.
599 */
600 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
601   int e;
602   if( pIdList==0 || NEVER(pEList==0) ) return 1;
603   for(e=0; e<pEList->nExpr; e++){
604     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
605   }
606   return 0;
607 }
608 
609 /*
610 ** Return a list of all triggers on table pTab if there exists at least
611 ** one trigger that must be fired when an operation of type 'op' is
612 ** performed on the table, and, if that operation is an UPDATE, if at
613 ** least one of the columns in pChanges is being modified.
614 */
615 Trigger *sqlite3TriggersExist(
616   Parse *pParse,          /* Parse context */
617   Table *pTab,            /* The table the contains the triggers */
618   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
619   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
620   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
621 ){
622   int mask = 0;
623   Trigger *pList = sqlite3TriggerList(pParse, pTab);
624   Trigger *p;
625   assert( pList==0 || IsVirtual(pTab)==0 );
626   for(p=pList; p; p=p->pNext){
627     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
628       mask |= p->tr_tm;
629     }
630   }
631   if( pMask ){
632     *pMask = mask;
633   }
634   return (mask ? pList : 0);
635 }
636 
637 /*
638 ** Convert the pStep->target token into a SrcList and return a pointer
639 ** to that SrcList.
640 **
641 ** This routine adds a specific database name, if needed, to the target when
642 ** forming the SrcList.  This prevents a trigger in one database from
643 ** referring to a target in another database.  An exception is when the
644 ** trigger is in TEMP in which case it can refer to any other database it
645 ** wants.
646 */
647 static SrcList *targetSrcList(
648   Parse *pParse,       /* The parsing context */
649   TriggerStep *pStep   /* The trigger containing the target token */
650 ){
651   int iDb;             /* Index of the database to use */
652   SrcList *pSrc;       /* SrcList to be returned */
653 
654   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
655   if( pSrc ){
656     assert( pSrc->nSrc>0 );
657     assert( pSrc->a!=0 );
658     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
659     if( iDb==0 || iDb>=2 ){
660       sqlite3 *db = pParse->db;
661       assert( iDb<pParse->db->nDb );
662       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
663     }
664   }
665   return pSrc;
666 }
667 
668 /*
669 ** Generate VDBE code for zero or more statements inside the body of a
670 ** trigger.
671 */
672 static int codeTriggerProgram(
673   Parse *pParse,            /* The parser context */
674   TriggerStep *pStepList,   /* List of statements inside the trigger body */
675   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */
676 ){
677   TriggerStep * pTriggerStep = pStepList;
678   int orconf;
679   Vdbe *v = pParse->pVdbe;
680   sqlite3 *db = pParse->db;
681 
682   assert( pTriggerStep!=0 );
683   assert( v!=0 );
684   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
685   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
686   while( pTriggerStep ){
687     sqlite3ExprCacheClear(pParse);
688     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
689     pParse->trigStack->orconf = orconf;
690     switch( pTriggerStep->op ){
691       case TK_UPDATE: {
692         SrcList *pSrc;
693         pSrc = targetSrcList(pParse, pTriggerStep);
694         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
695         sqlite3Update(pParse, pSrc,
696                 sqlite3ExprListDup(db, pTriggerStep->pExprList, 0),
697                 sqlite3ExprDup(db, pTriggerStep->pWhere, 0), orconf);
698         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
699         break;
700       }
701       case TK_INSERT: {
702         SrcList *pSrc;
703         pSrc = targetSrcList(pParse, pTriggerStep);
704         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
705         sqlite3Insert(pParse, pSrc,
706           sqlite3ExprListDup(db, pTriggerStep->pExprList, 0),
707           sqlite3SelectDup(db, pTriggerStep->pSelect, 0),
708           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
709         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
710         break;
711       }
712       case TK_DELETE: {
713         SrcList *pSrc;
714         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
715         pSrc = targetSrcList(pParse, pTriggerStep);
716         sqlite3DeleteFrom(pParse, pSrc,
717                           sqlite3ExprDup(db, pTriggerStep->pWhere, 0));
718         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
719         break;
720       }
721       default: assert( pTriggerStep->op==TK_SELECT ); {
722         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0);
723         if( ss ){
724           SelectDest dest;
725 
726           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
727           sqlite3Select(pParse, ss, &dest);
728           sqlite3SelectDelete(db, ss);
729         }
730         break;
731       }
732     }
733     pTriggerStep = pTriggerStep->pNext;
734   }
735   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
736   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
737 
738   return 0;
739 }
740 
741 /*
742 ** This is called to code FOR EACH ROW triggers.
743 **
744 ** When the code that this function generates is executed, the following
745 ** must be true:
746 **
747 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
748 **    can be indices of cursors in temporary tables.  See below.)
749 **
750 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
751 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
752 **    a row containing values to be substituted for new.* expressions in the
753 **    trigger program(s).
754 **
755 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
756 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
757 **    a row containing values to be substituted for old.* expressions in the
758 **    trigger program(s).
759 **
760 ** If they are not NULL, the piOldColMask and piNewColMask output variables
761 ** are set to values that describe the columns used by the trigger program
762 ** in the OLD.* and NEW.* tables respectively. If column N of the
763 ** pseudo-table is read at least once, the corresponding bit of the output
764 ** mask is set. If a column with an index greater than 32 is read, the
765 ** output mask is set to the special value 0xffffffff.
766 **
767 */
768 int sqlite3CodeRowTrigger(
769   Parse *pParse,       /* Parse context */
770   Trigger *pTrigger,   /* List of triggers on table pTab */
771   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
772   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
773   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
774   Table *pTab,         /* The table to code triggers from */
775   int newIdx,          /* The indice of the "new" row to access */
776   int oldIdx,          /* The indice of the "old" row to access */
777   int orconf,          /* ON CONFLICT policy */
778   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
779   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
780   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
781 ){
782   Trigger *p;
783   sqlite3 *db = pParse->db;
784   TriggerStack trigStackEntry;
785 
786   trigStackEntry.oldColMask = 0;
787   trigStackEntry.newColMask = 0;
788 
789   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
790   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
791 
792   assert(newIdx != -1 || oldIdx != -1);
793 
794   for(p=pTrigger; p; p=p->pNext){
795     int fire_this = 0;
796 
797     /* Sanity checking:  The schema for the trigger and for the table are
798     ** always defined.  The trigger must be in the same schema as the table
799     ** or else it must be a TEMP trigger. */
800     assert( p->pSchema!=0 );
801     assert( p->pTabSchema!=0 );
802     assert( p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema );
803 
804     /* Determine whether we should code this trigger */
805     if(
806       p->op==op &&
807       p->tr_tm==tr_tm &&
808       checkColumnOverlap(p->pColumns,pChanges)
809     ){
810       TriggerStack *pS;      /* Pointer to trigger-stack entry */
811       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
812       if( !pS ){
813         fire_this = 1;
814       }
815 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
816       else{
817         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
818             p->name);
819         return SQLITE_ERROR;
820       }
821 #endif
822     }
823 
824     if( fire_this ){
825       int endTrigger;
826       Expr * whenExpr;
827       AuthContext sContext;
828       NameContext sNC;
829 
830 #ifndef SQLITE_OMIT_TRACE
831       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
832                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
833                         P4_DYNAMIC);
834 #endif
835       memset(&sNC, 0, sizeof(sNC));
836       sNC.pParse = pParse;
837 
838       /* Push an entry on to the trigger stack */
839       trigStackEntry.pTrigger = p;
840       trigStackEntry.newIdx = newIdx;
841       trigStackEntry.oldIdx = oldIdx;
842       trigStackEntry.pTab = pTab;
843       trigStackEntry.pNext = pParse->trigStack;
844       trigStackEntry.ignoreJump = ignoreJump;
845       pParse->trigStack = &trigStackEntry;
846       sqlite3AuthContextPush(pParse, &sContext, p->name);
847 
848       /* code the WHEN clause */
849       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
850       whenExpr = sqlite3ExprDup(db, p->pWhen, 0);
851       if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
852         pParse->trigStack = trigStackEntry.pNext;
853         sqlite3ExprDelete(db, whenExpr);
854         return 1;
855       }
856       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
857       sqlite3ExprDelete(db, whenExpr);
858 
859       sqlite3ExprCachePush(pParse);
860       codeTriggerProgram(pParse, p->step_list, orconf);
861       sqlite3ExprCachePop(pParse, 1);
862 
863       /* Pop the entry off the trigger stack */
864       pParse->trigStack = trigStackEntry.pNext;
865       sqlite3AuthContextPop(&sContext);
866 
867       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
868     }
869   }
870   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
871   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
872   return 0;
873 }
874 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
875