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