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