xref: /sqlite-3.40.0/src/trigger.c (revision fd3b2226)
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( pParse->disableTriggers ){
54     return 0;
55   }
56 
57   if( pTmpSchema!=pTab->pSchema ){
58     HashElem *p;
59     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
60       Trigger *pTrig = (Trigger *)sqliteHashData(p);
61       if( pTrig->pTabSchema==pTab->pSchema
62        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
63       ){
64         pTrig->pNext = (pList ? pList : pTab->pTrigger);
65         pList = pTrig;
66       }
67     }
68   }
69 
70   return (pList ? pList : pTab->pTrigger);
71 }
72 
73 /*
74 ** This is called by the parser when it sees a CREATE TRIGGER statement
75 ** up to the point of the BEGIN before the trigger actions.  A Trigger
76 ** structure is generated based on the information available and stored
77 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
78 ** sqlite3FinishTrigger() function is called to complete the trigger
79 ** construction process.
80 */
81 void sqlite3BeginTrigger(
82   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
83   Token *pName1,      /* The name of the trigger */
84   Token *pName2,      /* The name of the trigger */
85   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
86   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
87   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
88   SrcList *pTableName,/* The name of the table/view the trigger applies to */
89   Expr *pWhen,        /* WHEN clause */
90   int isTemp,         /* True if the TEMPORARY keyword is present */
91   int noErr           /* Suppress errors if the trigger already exists */
92 ){
93   Trigger *pTrigger = 0;  /* The new trigger */
94   Table *pTab;            /* Table that the trigger fires off of */
95   char *zName = 0;        /* Name of the trigger */
96   sqlite3 *db = pParse->db;  /* The database connection */
97   int iDb;                /* The database to store the trigger in */
98   Token *pName;           /* The unqualified db name */
99   DbFixer sFix;           /* State vector for the DB fixer */
100   int iTabDb;             /* Index of the database holding pTab */
101 
102   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
103   assert( pName2!=0 );
104   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
105   assert( op>0 && op<0xff );
106   if( isTemp ){
107     /* If TEMP was specified, then the trigger name may not be qualified. */
108     if( pName2->n>0 ){
109       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
110       goto trigger_cleanup;
111     }
112     iDb = 1;
113     pName = pName1;
114   }else{
115     /* Figure out the db that the the trigger will be created in */
116     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
117     if( iDb<0 ){
118       goto trigger_cleanup;
119     }
120   }
121 
122   /* If the trigger name was unqualified, and the table is a temp table,
123   ** then set iDb to 1 to create the trigger in the temporary database.
124   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
125   ** exist, the error is caught by the block below.
126   */
127   if( !pTableName || db->mallocFailed ){
128     goto trigger_cleanup;
129   }
130   pTab = sqlite3SrcListLookup(pParse, pTableName);
131   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
132     iDb = 1;
133   }
134 
135   /* Ensure the table name matches database name and that the table exists */
136   if( db->mallocFailed ) goto trigger_cleanup;
137   assert( pTableName->nSrc==1 );
138   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
139       sqlite3FixSrcList(&sFix, pTableName) ){
140     goto trigger_cleanup;
141   }
142   pTab = sqlite3SrcListLookup(pParse, pTableName);
143   if( !pTab ){
144     /* The table does not exist. */
145     if( db->init.iDb==1 ){
146       /* Ticket #3810.
147       ** Normally, whenever a table is dropped, all associated triggers are
148       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
149       ** and the table is dropped by a different database connection, the
150       ** trigger is not visible to the database connection that does the
151       ** drop so the trigger cannot be dropped.  This results in an
152       ** "orphaned trigger" - a trigger whose associated table is missing.
153       */
154       db->init.orphanTrigger = 1;
155     }
156     goto trigger_cleanup;
157   }
158   if( IsVirtual(pTab) ){
159     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
160     goto trigger_cleanup;
161   }
162 
163   /* Check that the trigger name is not reserved and that no trigger of the
164   ** specified name exists */
165   zName = sqlite3NameFromToken(db, pName);
166   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
167     goto trigger_cleanup;
168   }
169   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
170                       zName, sqlite3Strlen30(zName)) ){
171     if( !noErr ){
172       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
173     }
174     goto trigger_cleanup;
175   }
176 
177   /* Do not create a trigger on a system table */
178   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
179     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
180     pParse->nErr++;
181     goto trigger_cleanup;
182   }
183 
184   /* INSTEAD of triggers are only for views and views only support INSTEAD
185   ** of triggers.
186   */
187   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
188     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
189         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
190     goto trigger_cleanup;
191   }
192   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
193     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
194         " trigger on table: %S", pTableName, 0);
195     goto trigger_cleanup;
196   }
197   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
198 
199 #ifndef SQLITE_OMIT_AUTHORIZATION
200   {
201     int code = SQLITE_CREATE_TRIGGER;
202     const char *zDb = db->aDb[iTabDb].zName;
203     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
204     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
205     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
206       goto trigger_cleanup;
207     }
208     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
209       goto trigger_cleanup;
210     }
211   }
212 #endif
213 
214   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
215   ** cannot appear on views.  So we might as well translate every
216   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
217   ** elsewhere.
218   */
219   if (tr_tm == TK_INSTEAD){
220     tr_tm = TK_BEFORE;
221   }
222 
223   /* Build the Trigger object */
224   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
225   if( pTrigger==0 ) goto trigger_cleanup;
226   pTrigger->zName = zName;
227   zName = 0;
228   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
229   pTrigger->pSchema = db->aDb[iDb].pSchema;
230   pTrigger->pTabSchema = pTab->pSchema;
231   pTrigger->op = (u8)op;
232   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
233   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
234   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
235   assert( pParse->pNewTrigger==0 );
236   pParse->pNewTrigger = pTrigger;
237 
238 trigger_cleanup:
239   sqlite3DbFree(db, zName);
240   sqlite3SrcListDelete(db, pTableName);
241   sqlite3IdListDelete(db, pColumns);
242   sqlite3ExprDelete(db, pWhen);
243   if( !pParse->pNewTrigger ){
244     sqlite3DeleteTrigger(db, pTrigger);
245   }else{
246     assert( pParse->pNewTrigger==pTrigger );
247   }
248 }
249 
250 /*
251 ** This routine is called after all of the trigger actions have been parsed
252 ** in order to complete the process of building the trigger.
253 */
254 void sqlite3FinishTrigger(
255   Parse *pParse,          /* Parser context */
256   TriggerStep *pStepList, /* The triggered program */
257   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
258 ){
259   Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
260   char *zName;                             /* Name of trigger */
261   sqlite3 *db = pParse->db;                /* The database */
262   DbFixer sFix;
263   int iDb;                                 /* Database containing the trigger */
264   Token nameToken;           /* Trigger name for error reporting */
265 
266   pTrig = pParse->pNewTrigger;
267   pParse->pNewTrigger = 0;
268   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
269   zName = pTrig->zName;
270   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
271   pTrig->step_list = pStepList;
272   while( pStepList ){
273     pStepList->pTrig = pTrig;
274     pStepList = pStepList->pNext;
275   }
276   nameToken.z = pTrig->zName;
277   nameToken.n = sqlite3Strlen30(nameToken.z);
278   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
279           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
280     goto triggerfinish_cleanup;
281   }
282 
283   /* if we are not initializing, and this trigger is not on a TEMP table,
284   ** build the sqlite_master entry
285   */
286   if( !db->init.busy ){
287     Vdbe *v;
288     char *z;
289 
290     /* Make an entry in the sqlite_master table */
291     v = sqlite3GetVdbe(pParse);
292     if( v==0 ) goto triggerfinish_cleanup;
293     sqlite3BeginWriteOperation(pParse, 0, iDb);
294     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
295     sqlite3NestedParse(pParse,
296        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
297        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
298        pTrig->table, z);
299     sqlite3DbFree(db, z);
300     sqlite3ChangeCookie(pParse, iDb);
301     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
302         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
303     );
304   }
305 
306   if( db->init.busy ){
307     Trigger *pLink = pTrig;
308     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
309     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
310     if( pTrig ){
311       db->mallocFailed = 1;
312     }else if( pLink->pSchema==pLink->pTabSchema ){
313       Table *pTab;
314       int n = sqlite3Strlen30(pLink->table);
315       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
316       assert( pTab!=0 );
317       pLink->pNext = pTab->pTrigger;
318       pTab->pTrigger = pLink;
319     }
320   }
321 
322 triggerfinish_cleanup:
323   sqlite3DeleteTrigger(db, pTrig);
324   assert( !pParse->pNewTrigger );
325   sqlite3DeleteTriggerStep(db, pStepList);
326 }
327 
328 /*
329 ** Turn a SELECT statement (that the pSelect parameter points to) into
330 ** a trigger step.  Return a pointer to a TriggerStep structure.
331 **
332 ** The parser calls this routine when it finds a SELECT statement in
333 ** body of a TRIGGER.
334 */
335 TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
336   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
337   if( pTriggerStep==0 ) {
338     sqlite3SelectDelete(db, pSelect);
339     return 0;
340   }
341   pTriggerStep->op = TK_SELECT;
342   pTriggerStep->pSelect = pSelect;
343   pTriggerStep->orconf = OE_Default;
344   return pTriggerStep;
345 }
346 
347 /*
348 ** Allocate space to hold a new trigger step.  The allocated space
349 ** holds both the TriggerStep object and the TriggerStep.target.z string.
350 **
351 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
352 */
353 static TriggerStep *triggerStepAllocate(
354   sqlite3 *db,                /* Database connection */
355   u8 op,                      /* Trigger opcode */
356   Token *pName                /* The target name */
357 ){
358   TriggerStep *pTriggerStep;
359 
360   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
361   if( pTriggerStep ){
362     char *z = (char*)&pTriggerStep[1];
363     memcpy(z, pName->z, pName->n);
364     pTriggerStep->target.z = z;
365     pTriggerStep->target.n = pName->n;
366     pTriggerStep->op = op;
367   }
368   return pTriggerStep;
369 }
370 
371 /*
372 ** Build a trigger step out of an INSERT statement.  Return a pointer
373 ** to the new trigger step.
374 **
375 ** The parser calls this routine when it sees an INSERT inside the
376 ** body of a trigger.
377 */
378 TriggerStep *sqlite3TriggerInsertStep(
379   sqlite3 *db,        /* The database connection */
380   Token *pTableName,  /* Name of the table into which we insert */
381   IdList *pColumn,    /* List of columns in pTableName to insert into */
382   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
383   Select *pSelect,    /* A SELECT statement that supplies values */
384   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
385 ){
386   TriggerStep *pTriggerStep;
387 
388   assert(pEList == 0 || pSelect == 0);
389   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
390 
391   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
392   if( pTriggerStep ){
393     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
394     pTriggerStep->pIdList = pColumn;
395     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
396     pTriggerStep->orconf = orconf;
397   }else{
398     sqlite3IdListDelete(db, pColumn);
399   }
400   sqlite3ExprListDelete(db, pEList);
401   sqlite3SelectDelete(db, pSelect);
402 
403   return pTriggerStep;
404 }
405 
406 /*
407 ** Construct a trigger step that implements an UPDATE statement and return
408 ** a pointer to that trigger step.  The parser calls this routine when it
409 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
410 */
411 TriggerStep *sqlite3TriggerUpdateStep(
412   sqlite3 *db,         /* The database connection */
413   Token *pTableName,   /* Name of the table to be updated */
414   ExprList *pEList,    /* The SET clause: list of column and new values */
415   Expr *pWhere,        /* The WHERE clause */
416   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
417 ){
418   TriggerStep *pTriggerStep;
419 
420   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
421   if( pTriggerStep ){
422     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
423     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
424     pTriggerStep->orconf = orconf;
425   }
426   sqlite3ExprListDelete(db, pEList);
427   sqlite3ExprDelete(db, pWhere);
428   return pTriggerStep;
429 }
430 
431 /*
432 ** Construct a trigger step that implements a DELETE statement and return
433 ** a pointer to that trigger step.  The parser calls this routine when it
434 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
435 */
436 TriggerStep *sqlite3TriggerDeleteStep(
437   sqlite3 *db,            /* Database connection */
438   Token *pTableName,      /* The table from which rows are deleted */
439   Expr *pWhere            /* The WHERE clause */
440 ){
441   TriggerStep *pTriggerStep;
442 
443   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
444   if( pTriggerStep ){
445     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
446     pTriggerStep->orconf = OE_Default;
447   }
448   sqlite3ExprDelete(db, pWhere);
449   return pTriggerStep;
450 }
451 
452 /*
453 ** Recursively delete a Trigger structure
454 */
455 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
456   if( pTrigger==0 ) return;
457   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
458   sqlite3DbFree(db, pTrigger->zName);
459   sqlite3DbFree(db, pTrigger->table);
460   sqlite3ExprDelete(db, pTrigger->pWhen);
461   sqlite3IdListDelete(db, pTrigger->pColumns);
462   sqlite3DbFree(db, pTrigger);
463 }
464 
465 /*
466 ** This function is called to drop a trigger from the database schema.
467 **
468 ** This may be called directly from the parser and therefore identifies
469 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
470 ** same job as this routine except it takes a pointer to the trigger
471 ** instead of the trigger name.
472 **/
473 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
474   Trigger *pTrigger = 0;
475   int i;
476   const char *zDb;
477   const char *zName;
478   int nName;
479   sqlite3 *db = pParse->db;
480 
481   if( db->mallocFailed ) goto drop_trigger_cleanup;
482   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
483     goto drop_trigger_cleanup;
484   }
485 
486   assert( pName->nSrc==1 );
487   zDb = pName->a[0].zDatabase;
488   zName = pName->a[0].zName;
489   nName = sqlite3Strlen30(zName);
490   for(i=OMIT_TEMPDB; i<db->nDb; i++){
491     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
492     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
493     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
494     if( pTrigger ) break;
495   }
496   if( !pTrigger ){
497     if( !noErr ){
498       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
499     }
500     goto drop_trigger_cleanup;
501   }
502   sqlite3DropTriggerPtr(pParse, pTrigger);
503 
504 drop_trigger_cleanup:
505   sqlite3SrcListDelete(db, pName);
506 }
507 
508 /*
509 ** Return a pointer to the Table structure for the table that a trigger
510 ** is set on.
511 */
512 static Table *tableOfTrigger(Trigger *pTrigger){
513   int n = sqlite3Strlen30(pTrigger->table);
514   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
515 }
516 
517 
518 /*
519 ** Drop a trigger given a pointer to that trigger.
520 */
521 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
522   Table   *pTable;
523   Vdbe *v;
524   sqlite3 *db = pParse->db;
525   int iDb;
526 
527   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
528   assert( iDb>=0 && iDb<db->nDb );
529   pTable = tableOfTrigger(pTrigger);
530   assert( pTable );
531   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
532 #ifndef SQLITE_OMIT_AUTHORIZATION
533   {
534     int code = SQLITE_DROP_TRIGGER;
535     const char *zDb = db->aDb[iDb].zName;
536     const char *zTab = SCHEMA_TABLE(iDb);
537     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
538     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
539       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
540       return;
541     }
542   }
543 #endif
544 
545   /* Generate code to destroy the database record of the trigger.
546   */
547   assert( pTable!=0 );
548   if( (v = sqlite3GetVdbe(pParse))!=0 ){
549     int base;
550     static const VdbeOpList dropTrigger[] = {
551       { OP_Rewind,     0, ADDR(9),  0},
552       { OP_String8,    0, 1,        0}, /* 1 */
553       { OP_Column,     0, 1,        2},
554       { OP_Ne,         2, ADDR(8),  1},
555       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
556       { OP_Column,     0, 0,        2},
557       { OP_Ne,         2, ADDR(8),  1},
558       { OP_Delete,     0, 0,        0},
559       { OP_Next,       0, ADDR(1),  0}, /* 8 */
560     };
561 
562     sqlite3BeginWriteOperation(pParse, 0, iDb);
563     sqlite3OpenMasterTable(pParse, iDb);
564     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
565     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
566     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
567     sqlite3ChangeCookie(pParse, iDb);
568     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
569     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
570     if( pParse->nMem<3 ){
571       pParse->nMem = 3;
572     }
573   }
574 }
575 
576 /*
577 ** Remove a trigger from the hash tables of the sqlite* pointer.
578 */
579 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
580   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
581   Trigger *pTrigger;
582   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
583   if( ALWAYS(pTrigger) ){
584     if( pTrigger->pSchema==pTrigger->pTabSchema ){
585       Table *pTab = tableOfTrigger(pTrigger);
586       Trigger **pp;
587       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
588       *pp = (*pp)->pNext;
589     }
590     sqlite3DeleteTrigger(db, pTrigger);
591     db->flags |= SQLITE_InternChanges;
592   }
593 }
594 
595 /*
596 ** pEList is the SET clause of an UPDATE statement.  Each entry
597 ** in pEList is of the format <id>=<expr>.  If any of the entries
598 ** in pEList have an <id> which matches an identifier in pIdList,
599 ** then return TRUE.  If pIdList==NULL, then it is considered a
600 ** wildcard that matches anything.  Likewise if pEList==NULL then
601 ** it matches anything so always return true.  Return false only
602 ** if there is no match.
603 */
604 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
605   int e;
606   if( pIdList==0 || NEVER(pEList==0) ) return 1;
607   for(e=0; e<pEList->nExpr; e++){
608     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
609   }
610   return 0;
611 }
612 
613 /*
614 ** Return a list of all triggers on table pTab if there exists at least
615 ** one trigger that must be fired when an operation of type 'op' is
616 ** performed on the table, and, if that operation is an UPDATE, if at
617 ** least one of the columns in pChanges is being modified.
618 */
619 Trigger *sqlite3TriggersExist(
620   Parse *pParse,          /* Parse context */
621   Table *pTab,            /* The table the contains the triggers */
622   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
623   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
624   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
625 ){
626   int mask = 0;
627   Trigger *pList = sqlite3TriggerList(pParse, pTab);
628   Trigger *p;
629   assert( pList==0 || IsVirtual(pTab)==0 );
630   for(p=pList; p; p=p->pNext){
631     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
632       mask |= p->tr_tm;
633     }
634   }
635   if( pMask ){
636     *pMask = mask;
637   }
638   return (mask ? pList : 0);
639 }
640 
641 /*
642 ** Convert the pStep->target token into a SrcList and return a pointer
643 ** to that SrcList.
644 **
645 ** This routine adds a specific database name, if needed, to the target when
646 ** forming the SrcList.  This prevents a trigger in one database from
647 ** referring to a target in another database.  An exception is when the
648 ** trigger is in TEMP in which case it can refer to any other database it
649 ** wants.
650 */
651 static SrcList *targetSrcList(
652   Parse *pParse,       /* The parsing context */
653   TriggerStep *pStep   /* The trigger containing the target token */
654 ){
655   int iDb;             /* Index of the database to use */
656   SrcList *pSrc;       /* SrcList to be returned */
657 
658   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
659   if( pSrc ){
660     assert( pSrc->nSrc>0 );
661     assert( pSrc->a!=0 );
662     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
663     if( iDb==0 || iDb>=2 ){
664       sqlite3 *db = pParse->db;
665       assert( iDb<pParse->db->nDb );
666       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
667     }
668   }
669   return pSrc;
670 }
671 
672 /*
673 ** Generate VDBE code for the statements inside the body of a single
674 ** trigger.
675 */
676 static int codeTriggerProgram(
677   Parse *pParse,            /* The parser context */
678   TriggerStep *pStepList,   /* List of statements inside the trigger body */
679   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
680 ){
681   TriggerStep *pStep;
682   Vdbe *v = pParse->pVdbe;
683   sqlite3 *db = pParse->db;
684 
685   assert( pParse->pTriggerTab && pParse->pToplevel );
686   assert( pStepList );
687   assert( v!=0 );
688   for(pStep=pStepList; pStep; pStep=pStep->pNext){
689     /* Figure out the ON CONFLICT policy that will be used for this step
690     ** of the trigger program. If the statement that caused this trigger
691     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
692     ** the ON CONFLICT policy that was specified as part of the trigger
693     ** step statement. Example:
694     **
695     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
696     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
697     **   END;
698     **
699     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
700     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
701     */
702     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
703 
704     switch( pStep->op ){
705       case TK_UPDATE: {
706         sqlite3Update(pParse,
707           targetSrcList(pParse, pStep),
708           sqlite3ExprListDup(db, pStep->pExprList, 0),
709           sqlite3ExprDup(db, pStep->pWhere, 0),
710           pParse->eOrconf
711         );
712         break;
713       }
714       case TK_INSERT: {
715         sqlite3Insert(pParse,
716           targetSrcList(pParse, pStep),
717           sqlite3ExprListDup(db, pStep->pExprList, 0),
718           sqlite3SelectDup(db, pStep->pSelect, 0),
719           sqlite3IdListDup(db, pStep->pIdList),
720           pParse->eOrconf
721         );
722         break;
723       }
724       case TK_DELETE: {
725         sqlite3DeleteFrom(pParse,
726           targetSrcList(pParse, pStep),
727           sqlite3ExprDup(db, pStep->pWhere, 0)
728         );
729         break;
730       }
731       default: assert( pStep->op==TK_SELECT ); {
732         SelectDest sDest;
733         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
734         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
735         sqlite3Select(pParse, pSelect, &sDest);
736         sqlite3SelectDelete(db, pSelect);
737         break;
738       }
739     }
740     if( pStep->op!=TK_SELECT ){
741       sqlite3VdbeAddOp0(v, OP_ResetCount);
742     }
743   }
744 
745   return 0;
746 }
747 
748 #ifdef SQLITE_DEBUG
749 /*
750 ** This function is used to add VdbeComment() annotations to a VDBE
751 ** program. It is not used in production code, only for debugging.
752 */
753 static const char *onErrorText(int onError){
754   switch( onError ){
755     case OE_Abort:    return "abort";
756     case OE_Rollback: return "rollback";
757     case OE_Fail:     return "fail";
758     case OE_Replace:  return "replace";
759     case OE_Ignore:   return "ignore";
760     case OE_Default:  return "default";
761   }
762   return "n/a";
763 }
764 #endif
765 
766 /*
767 ** Parse context structure pFrom has just been used to create a sub-vdbe
768 ** (trigger program). If an error has occurred, transfer error information
769 ** from pFrom to pTo.
770 */
771 static void transferParseError(Parse *pTo, Parse *pFrom){
772   assert( pFrom->zErrMsg==0 || pFrom->nErr );
773   assert( pTo->zErrMsg==0 || pTo->nErr );
774   if( pTo->nErr==0 ){
775     pTo->zErrMsg = pFrom->zErrMsg;
776     pTo->nErr = pFrom->nErr;
777   }else{
778     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
779   }
780 }
781 
782 /*
783 ** Create and populate a new TriggerPrg object with a sub-program
784 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
785 */
786 static TriggerPrg *codeRowTrigger(
787   Parse *pParse,       /* Current parse context */
788   Trigger *pTrigger,   /* Trigger to code */
789   Table *pTab,         /* The table pTrigger is attached to */
790   int orconf           /* ON CONFLICT policy to code trigger program with */
791 ){
792   Parse *pTop = sqlite3ParseToplevel(pParse);
793   sqlite3 *db = pParse->db;   /* Database handle */
794   TriggerPrg *pPrg;           /* Value to return */
795   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
796   Vdbe *v;                    /* Temporary VM */
797   NameContext sNC;            /* Name context for sub-vdbe */
798   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
799   Parse *pSubParse;           /* Parse context for sub-vdbe */
800   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
801 
802   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
803 
804   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
805   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
806   ** list of the top-level Parse object sooner rather than later.  */
807   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
808   if( !pPrg ) return 0;
809   pPrg->pNext = pTop->pTriggerPrg;
810   pTop->pTriggerPrg = pPrg;
811   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
812   if( !pProgram ) return 0;
813   pProgram->nRef = 1;
814   pPrg->pTrigger = pTrigger;
815   pPrg->orconf = orconf;
816   pPrg->oldmask = 0xffffffff;
817 
818   /* Allocate and populate a new Parse context to use for coding the
819   ** trigger sub-program.  */
820   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
821   if( !pSubParse ) return 0;
822   memset(&sNC, 0, sizeof(sNC));
823   sNC.pParse = pSubParse;
824   pSubParse->db = db;
825   pSubParse->pTriggerTab = pTab;
826   pSubParse->pToplevel = pTop;
827   pSubParse->zAuthContext = pTrigger->zName;
828   pSubParse->eTriggerOp = pTrigger->op;
829 
830   v = sqlite3GetVdbe(pSubParse);
831   if( v ){
832     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
833       pTrigger->zName, onErrorText(orconf),
834       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
835         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
836         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
837         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
838       pTab->zName
839     ));
840 #ifndef SQLITE_OMIT_TRACE
841     sqlite3VdbeChangeP4(v, -1,
842       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
843     );
844 #endif
845 
846     /* If one was specified, code the WHEN clause. If it evaluates to false
847     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
848     ** OP_Halt inserted at the end of the program.  */
849     if( pTrigger->pWhen ){
850       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
851       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
852        && db->mallocFailed==0
853       ){
854         iEndTrigger = sqlite3VdbeMakeLabel(v);
855         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
856       }
857       sqlite3ExprDelete(db, pWhen);
858     }
859 
860     /* Code the trigger program into the sub-vdbe. */
861     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
862 
863     /* Insert an OP_Halt at the end of the sub-program. */
864     if( iEndTrigger ){
865       sqlite3VdbeResolveLabel(v, iEndTrigger);
866     }
867     sqlite3VdbeAddOp0(v, OP_Halt);
868     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
869 
870     transferParseError(pParse, pSubParse);
871     if( db->mallocFailed==0 ){
872       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
873     }
874     pProgram->nMem = pSubParse->nMem;
875     pProgram->nCsr = pSubParse->nTab;
876     pProgram->token = (void *)pTrigger;
877     pPrg->oldmask = pSubParse->oldmask;
878     sqlite3VdbeDelete(v);
879   }
880 
881   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
882   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
883   sqlite3StackFree(db, pSubParse);
884 
885   return pPrg;
886 }
887 
888 /*
889 ** Return a pointer to a TriggerPrg object containing the sub-program for
890 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
891 ** TriggerPrg object exists, a new object is allocated and populated before
892 ** being returned.
893 */
894 static TriggerPrg *getRowTrigger(
895   Parse *pParse,       /* Current parse context */
896   Trigger *pTrigger,   /* Trigger to code */
897   Table *pTab,         /* The table trigger pTrigger is attached to */
898   int orconf           /* ON CONFLICT algorithm. */
899 ){
900   Parse *pRoot = sqlite3ParseToplevel(pParse);
901   TriggerPrg *pPrg;
902 
903   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
904 
905   /* It may be that this trigger has already been coded (or is in the
906   ** process of being coded). If this is the case, then an entry with
907   ** a matching TriggerPrg.pTrigger field will be present somewhere
908   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
909   for(pPrg=pRoot->pTriggerPrg;
910       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
911       pPrg=pPrg->pNext
912   );
913 
914   /* If an existing TriggerPrg could not be located, create a new one. */
915   if( !pPrg ){
916     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
917   }
918 
919   return pPrg;
920 }
921 
922 /*
923 ** Generate code for the trigger program associated with trigger p on
924 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
925 ** function are the same as those described in the header function for
926 ** sqlite3CodeRowTrigger()
927 */
928 void sqlite3CodeRowTriggerDirect(
929   Parse *pParse,       /* Parse context */
930   Trigger *p,          /* Trigger to code */
931   Table *pTab,         /* The table to code triggers from */
932   int reg,             /* Reg array containing OLD.* and NEW.* values */
933   int orconf,          /* ON CONFLICT policy */
934   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
935 ){
936   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
937   TriggerPrg *pPrg;
938   pPrg = getRowTrigger(pParse, p, pTab, orconf);
939   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
940 
941   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
942   ** is a pointer to the sub-vdbe containing the trigger program.  */
943   if( pPrg ){
944     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
945     pPrg->pProgram->nRef++;
946     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
947     VdbeComment(
948         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
949 
950     /* Set the P5 operand of the OP_Program instruction to non-zero if
951     ** recursive invocation of this trigger program is disallowed. Recursive
952     ** invocation is disallowed if (a) the sub-program is really a trigger,
953     ** not a foreign key action, and (b) the flag to enable recursive triggers
954     ** is clear.  */
955     sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
956   }
957 }
958 
959 /*
960 ** This is called to code the required FOR EACH ROW triggers for an operation
961 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
962 ** is given by the op paramater. The tr_tm parameter determines whether the
963 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
964 ** parameter pChanges is passed the list of columns being modified.
965 **
966 ** If there are no triggers that fire at the specified time for the specified
967 ** operation on pTab, this function is a no-op.
968 **
969 ** The reg argument is the address of the first in an array of registers
970 ** that contain the values substituted for the new.* and old.* references
971 ** in the trigger program. If N is the number of columns in table pTab
972 ** (a copy of pTab->nCol), then registers are populated as follows:
973 **
974 **   Register       Contains
975 **   ------------------------------------------------------
976 **   reg+0          OLD.rowid
977 **   reg+1          OLD.* value of left-most column of pTab
978 **   ...            ...
979 **   reg+N          OLD.* value of right-most column of pTab
980 **   reg+N+1        NEW.rowid
981 **   reg+N+2        OLD.* value of left-most column of pTab
982 **   ...            ...
983 **   reg+N+N+1      NEW.* value of right-most column of pTab
984 **
985 ** For ON DELETE triggers, the registers containing the NEW.* values will
986 ** never be accessed by the trigger program, so they are not allocated or
987 ** populated by the caller (there is no data to populate them with anyway).
988 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
989 ** are never accessed, and so are not allocated by the caller. So, for an
990 ** ON INSERT trigger, the value passed to this function as parameter reg
991 ** is not a readable register, although registers (reg+N) through
992 ** (reg+N+N+1) are.
993 **
994 ** Parameter orconf is the default conflict resolution algorithm for the
995 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
996 ** is the instruction that control should jump to if a trigger program
997 ** raises an IGNORE exception.
998 */
999 void sqlite3CodeRowTrigger(
1000   Parse *pParse,       /* Parse context */
1001   Trigger *pTrigger,   /* List of triggers on table pTab */
1002   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1003   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1004   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1005   Table *pTab,         /* The table to code triggers from */
1006   int reg,             /* The first in an array of registers (see above) */
1007   int orconf,          /* ON CONFLICT policy */
1008   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
1009 ){
1010   Trigger *p;          /* Used to iterate through pTrigger list */
1011 
1012   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1013   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1014   assert( (op==TK_UPDATE)==(pChanges!=0) );
1015 
1016   for(p=pTrigger; p; p=p->pNext){
1017 
1018     /* Sanity checking:  The schema for the trigger and for the table are
1019     ** always defined.  The trigger must be in the same schema as the table
1020     ** or else it must be a TEMP trigger. */
1021     assert( p->pSchema!=0 );
1022     assert( p->pTabSchema!=0 );
1023     assert( p->pSchema==p->pTabSchema
1024          || p->pSchema==pParse->db->aDb[1].pSchema );
1025 
1026     /* Determine whether we should code this trigger */
1027     if( p->op==op
1028      && p->tr_tm==tr_tm
1029      && checkColumnOverlap(p->pColumns, pChanges)
1030     ){
1031       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1032     }
1033   }
1034 }
1035 
1036 /*
1037 ** Triggers fired by UPDATE or DELETE statements may access values stored
1038 ** in the old.* pseudo-table. This function returns a 32-bit bitmask
1039 ** indicating which columns of the old.* table actually are used by
1040 ** triggers. This information may be used by the caller to avoid having
1041 ** to load the entire old.* record into memory when executing an UPDATE
1042 ** or DELETE command.
1043 **
1044 ** Bit 0 of the returned mask is set if the left-most column of the
1045 ** table may be accessed using an old.<col> reference. Bit 1 is set if
1046 ** the second leftmost column value is required, and so on. If there
1047 ** are more than 32 columns in the table, and at least one of the columns
1048 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1049 **
1050 ** It is not possible to determine if the old.rowid column is accessed
1051 ** by triggers. The caller must always assume that it is.
1052 **
1053 ** There is no equivalent function for new.* references.
1054 */
1055 u32 sqlite3TriggerOldmask(
1056   Parse *pParse,       /* Parse context */
1057   Trigger *pTrigger,   /* List of triggers on table pTab */
1058   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1059   Table *pTab,         /* The table to code triggers from */
1060   int orconf           /* Default ON CONFLICT policy for trigger steps */
1061 ){
1062   const int op = pChanges ? TK_UPDATE : TK_DELETE;
1063   u32 mask = 0;
1064   Trigger *p;
1065 
1066   for(p=pTrigger; p; p=p->pNext){
1067     if( p->op==op && checkColumnOverlap(p->pColumns,pChanges) ){
1068       TriggerPrg *pPrg;
1069       pPrg = getRowTrigger(pParse, p, pTab, orconf);
1070       if( pPrg ){
1071         mask |= pPrg->oldmask;
1072       }
1073     }
1074   }
1075 
1076   return mask;
1077 }
1078 
1079 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1080