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