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