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