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