xref: /sqlite-3.40.0/src/trigger.c (revision a3fdec71)
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 ** This file contains the implementation for TRIGGERs
12 */
13 #include "sqliteInt.h"
14 
15 #ifndef SQLITE_OMIT_TRIGGER
16 /*
17 ** Delete a linked list of TriggerStep structures.
18 */
19 void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
20   while( pTriggerStep ){
21     TriggerStep * pTmp = pTriggerStep;
22     pTriggerStep = pTriggerStep->pNext;
23 
24     sqlite3ExprDelete(db, pTmp->pWhere);
25     sqlite3ExprListDelete(db, pTmp->pExprList);
26     sqlite3SelectDelete(db, pTmp->pSelect);
27     sqlite3IdListDelete(db, pTmp->pIdList);
28 
29     sqlite3DbFree(db, pTmp);
30   }
31 }
32 
33 /*
34 ** Given table pTab, return a list of all the triggers attached to
35 ** the table. The list is connected by Trigger.pNext pointers.
36 **
37 ** All of the triggers on pTab that are in the same database as pTab
38 ** are already attached to pTab->pTrigger.  But there might be additional
39 ** triggers on pTab in the TEMP schema.  This routine prepends all
40 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
41 ** and returns the combined list.
42 **
43 ** To state it another way:  This routine returns a list of all triggers
44 ** that fire off of pTab.  The list will include any TEMP triggers on
45 ** pTab as well as the triggers lised in pTab->pTrigger.
46 */
47 Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
48   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
49   Trigger *pList = 0;                  /* List of triggers to return */
50 
51   if( pParse->disableTriggers ){
52     return 0;
53   }
54 
55   if( pTmpSchema!=pTab->pSchema ){
56     HashElem *p;
57     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
58     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
59       Trigger *pTrig = (Trigger *)sqliteHashData(p);
60       if( pTrig->pTabSchema==pTab->pSchema
61        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
62       ){
63         pTrig->pNext = (pList ? pList : pTab->pTrigger);
64         pList = pTrig;
65       }
66     }
67   }
68 
69   return (pList ? pList : pTab->pTrigger);
70 }
71 
72 /*
73 ** This is called by the parser when it sees a CREATE TRIGGER statement
74 ** up to the point of the BEGIN before the trigger actions.  A Trigger
75 ** structure is generated based on the information available and stored
76 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
77 ** sqlite3FinishTrigger() function is called to complete the trigger
78 ** construction process.
79 */
80 void sqlite3BeginTrigger(
81   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
82   Token *pName1,      /* The name of the trigger */
83   Token *pName2,      /* The name of the trigger */
84   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
85   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
86   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
87   SrcList *pTableName,/* The name of the table/view the trigger applies to */
88   Expr *pWhen,        /* WHEN clause */
89   int isTemp,         /* True if the TEMPORARY keyword is present */
90   int noErr           /* Suppress errors if the trigger already exists */
91 ){
92   Trigger *pTrigger = 0;  /* The new trigger */
93   Table *pTab;            /* Table that the trigger fires off of */
94   char *zName = 0;        /* Name of the trigger */
95   sqlite3 *db = pParse->db;  /* The database connection */
96   int iDb;                /* The database to store the trigger in */
97   Token *pName;           /* The unqualified db name */
98   DbFixer sFix;           /* State vector for the DB fixer */
99   int iTabDb;             /* Index of the database holding pTab */
100 
101   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
102   assert( pName2!=0 );
103   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
104   assert( op>0 && op<0xff );
105   if( isTemp ){
106     /* If TEMP was specified, then the trigger name may not be qualified. */
107     if( pName2->n>0 ){
108       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
109       goto trigger_cleanup;
110     }
111     iDb = 1;
112     pName = pName1;
113   }else{
114     /* Figure out the db that the trigger will be created in */
115     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
116     if( iDb<0 ){
117       goto trigger_cleanup;
118     }
119   }
120   if( !pTableName || db->mallocFailed ){
121     goto trigger_cleanup;
122   }
123 
124   /* A long-standing parser bug is that this syntax was allowed:
125   **
126   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
127   **                                                 ^^^^^^^^
128   **
129   ** To maintain backwards compatibility, ignore the database
130   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
131   */
132   if( db->init.busy && iDb!=1 ){
133     sqlite3DbFree(db, pTableName->a[0].zDatabase);
134     pTableName->a[0].zDatabase = 0;
135   }
136 
137   /* If the trigger name was unqualified, and the table is a temp table,
138   ** then set iDb to 1 to create the trigger in the temporary database.
139   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
140   ** exist, the error is caught by the block below.
141   */
142   pTab = sqlite3SrcListLookup(pParse, pTableName);
143   if( db->init.busy==0 && pName2->n==0 && pTab
144         && pTab->pSchema==db->aDb[1].pSchema ){
145     iDb = 1;
146   }
147 
148   /* Ensure the table name matches database name and that the table exists */
149   if( db->mallocFailed ) goto trigger_cleanup;
150   assert( pTableName->nSrc==1 );
151   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
152   if( sqlite3FixSrcList(&sFix, pTableName) ){
153     goto trigger_cleanup;
154   }
155   pTab = sqlite3SrcListLookup(pParse, pTableName);
156   if( !pTab ){
157     /* The table does not exist. */
158     if( db->init.iDb==1 ){
159       /* Ticket #3810.
160       ** Normally, whenever a table is dropped, all associated triggers are
161       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
162       ** and the table is dropped by a different database connection, the
163       ** trigger is not visible to the database connection that does the
164       ** drop so the trigger cannot be dropped.  This results in an
165       ** "orphaned trigger" - a trigger whose associated table is missing.
166       */
167       db->init.orphanTrigger = 1;
168     }
169     goto trigger_cleanup;
170   }
171   if( IsVirtual(pTab) ){
172     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
173     goto trigger_cleanup;
174   }
175 
176   /* Check that the trigger name is not reserved and that no trigger of the
177   ** specified name exists */
178   zName = sqlite3NameFromToken(db, pName);
179   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
180     goto trigger_cleanup;
181   }
182   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
183   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
184                       zName, sqlite3Strlen30(zName)) ){
185     if( !noErr ){
186       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
187     }else{
188       assert( !db->init.busy );
189       sqlite3CodeVerifySchema(pParse, iDb);
190     }
191     goto trigger_cleanup;
192   }
193 
194   /* Do not create a trigger on a system table */
195   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
196     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
197     pParse->nErr++;
198     goto trigger_cleanup;
199   }
200 
201   /* INSTEAD of triggers are only for views and views only support INSTEAD
202   ** of triggers.
203   */
204   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
205     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
206         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
207     goto trigger_cleanup;
208   }
209   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
210     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
211         " trigger on table: %S", pTableName, 0);
212     goto trigger_cleanup;
213   }
214   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
215 
216 #ifndef SQLITE_OMIT_AUTHORIZATION
217   {
218     int code = SQLITE_CREATE_TRIGGER;
219     const char *zDb = db->aDb[iTabDb].zName;
220     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
221     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
222     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
223       goto trigger_cleanup;
224     }
225     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
226       goto trigger_cleanup;
227     }
228   }
229 #endif
230 
231   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
232   ** cannot appear on views.  So we might as well translate every
233   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
234   ** elsewhere.
235   */
236   if (tr_tm == TK_INSTEAD){
237     tr_tm = TK_BEFORE;
238   }
239 
240   /* Build the Trigger object */
241   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
242   if( pTrigger==0 ) goto trigger_cleanup;
243   pTrigger->zName = zName;
244   zName = 0;
245   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
246   pTrigger->pSchema = db->aDb[iDb].pSchema;
247   pTrigger->pTabSchema = pTab->pSchema;
248   pTrigger->op = (u8)op;
249   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
250   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
251   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
252   assert( pParse->pNewTrigger==0 );
253   pParse->pNewTrigger = pTrigger;
254 
255 trigger_cleanup:
256   sqlite3DbFree(db, zName);
257   sqlite3SrcListDelete(db, pTableName);
258   sqlite3IdListDelete(db, pColumns);
259   sqlite3ExprDelete(db, pWhen);
260   if( !pParse->pNewTrigger ){
261     sqlite3DeleteTrigger(db, pTrigger);
262   }else{
263     assert( pParse->pNewTrigger==pTrigger );
264   }
265 }
266 
267 /*
268 ** This routine is called after all of the trigger actions have been parsed
269 ** in order to complete the process of building the trigger.
270 */
271 void sqlite3FinishTrigger(
272   Parse *pParse,          /* Parser context */
273   TriggerStep *pStepList, /* The triggered program */
274   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
275 ){
276   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
277   char *zName;                            /* Name of trigger */
278   sqlite3 *db = pParse->db;               /* The database */
279   DbFixer sFix;                           /* Fixer object */
280   int iDb;                                /* Database containing the trigger */
281   Token nameToken;                        /* Trigger name for error reporting */
282 
283   pParse->pNewTrigger = 0;
284   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
285   zName = pTrig->zName;
286   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
287   pTrig->step_list = pStepList;
288   while( pStepList ){
289     pStepList->pTrig = pTrig;
290     pStepList = pStepList->pNext;
291   }
292   nameToken.z = pTrig->zName;
293   nameToken.n = sqlite3Strlen30(nameToken.z);
294   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
295   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
296    || sqlite3FixExpr(&sFix, pTrig->pWhen)
297   ){
298     goto triggerfinish_cleanup;
299   }
300 
301   /* if we are not initializing,
302   ** build the sqlite_master entry
303   */
304   if( !db->init.busy ){
305     Vdbe *v;
306     char *z;
307 
308     /* Make an entry in the sqlite_master table */
309     v = sqlite3GetVdbe(pParse);
310     if( v==0 ) goto triggerfinish_cleanup;
311     sqlite3BeginWriteOperation(pParse, 0, iDb);
312     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
313     sqlite3NestedParse(pParse,
314        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
315        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
316        pTrig->table, z);
317     sqlite3DbFree(db, z);
318     sqlite3ChangeCookie(pParse, iDb);
319     sqlite3VdbeAddParseSchemaOp(v, iDb,
320         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
321   }
322 
323   if( db->init.busy ){
324     Trigger *pLink = pTrig;
325     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
326     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
327     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
328     if( pTrig ){
329       db->mallocFailed = 1;
330     }else if( pLink->pSchema==pLink->pTabSchema ){
331       Table *pTab;
332       int n = sqlite3Strlen30(pLink->table);
333       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
334       assert( pTab!=0 );
335       pLink->pNext = pTab->pTrigger;
336       pTab->pTrigger = pLink;
337     }
338   }
339 
340 triggerfinish_cleanup:
341   sqlite3DeleteTrigger(db, pTrig);
342   assert( !pParse->pNewTrigger );
343   sqlite3DeleteTriggerStep(db, pStepList);
344 }
345 
346 /*
347 ** Turn a SELECT statement (that the pSelect parameter points to) into
348 ** a trigger step.  Return a pointer to a TriggerStep structure.
349 **
350 ** The parser calls this routine when it finds a SELECT statement in
351 ** body of a TRIGGER.
352 */
353 TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
354   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
355   if( pTriggerStep==0 ) {
356     sqlite3SelectDelete(db, pSelect);
357     return 0;
358   }
359   pTriggerStep->op = TK_SELECT;
360   pTriggerStep->pSelect = pSelect;
361   pTriggerStep->orconf = OE_Default;
362   return pTriggerStep;
363 }
364 
365 /*
366 ** Allocate space to hold a new trigger step.  The allocated space
367 ** holds both the TriggerStep object and the TriggerStep.target.z string.
368 **
369 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
370 */
371 static TriggerStep *triggerStepAllocate(
372   sqlite3 *db,                /* Database connection */
373   u8 op,                      /* Trigger opcode */
374   Token *pName                /* The target name */
375 ){
376   TriggerStep *pTriggerStep;
377 
378   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
379   if( pTriggerStep ){
380     char *z = (char*)&pTriggerStep[1];
381     memcpy(z, pName->z, pName->n);
382     pTriggerStep->target.z = z;
383     pTriggerStep->target.n = pName->n;
384     pTriggerStep->op = op;
385   }
386   return pTriggerStep;
387 }
388 
389 /*
390 ** Build a trigger step out of an INSERT statement.  Return a pointer
391 ** to the new trigger step.
392 **
393 ** The parser calls this routine when it sees an INSERT inside the
394 ** body of a trigger.
395 */
396 TriggerStep *sqlite3TriggerInsertStep(
397   sqlite3 *db,        /* The database connection */
398   Token *pTableName,  /* Name of the table into which we insert */
399   IdList *pColumn,    /* List of columns in pTableName to insert into */
400   Select *pSelect,    /* A SELECT statement that supplies values */
401   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
402 ){
403   TriggerStep *pTriggerStep;
404 
405   assert(pSelect != 0 || db->mallocFailed);
406 
407   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
408   if( pTriggerStep ){
409     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
410     pTriggerStep->pIdList = pColumn;
411     pTriggerStep->orconf = orconf;
412   }else{
413     sqlite3IdListDelete(db, pColumn);
414   }
415   sqlite3SelectDelete(db, pSelect);
416 
417   return pTriggerStep;
418 }
419 
420 /*
421 ** Construct a trigger step that implements an UPDATE statement and return
422 ** a pointer to that trigger step.  The parser calls this routine when it
423 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
424 */
425 TriggerStep *sqlite3TriggerUpdateStep(
426   sqlite3 *db,         /* The database connection */
427   Token *pTableName,   /* Name of the table to be updated */
428   ExprList *pEList,    /* The SET clause: list of column and new values */
429   Expr *pWhere,        /* The WHERE clause */
430   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
431 ){
432   TriggerStep *pTriggerStep;
433 
434   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
435   if( pTriggerStep ){
436     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
437     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
438     pTriggerStep->orconf = orconf;
439   }
440   sqlite3ExprListDelete(db, pEList);
441   sqlite3ExprDelete(db, pWhere);
442   return pTriggerStep;
443 }
444 
445 /*
446 ** Construct a trigger step that implements a DELETE statement and return
447 ** a pointer to that trigger step.  The parser calls this routine when it
448 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
449 */
450 TriggerStep *sqlite3TriggerDeleteStep(
451   sqlite3 *db,            /* Database connection */
452   Token *pTableName,      /* The table from which rows are deleted */
453   Expr *pWhere            /* The WHERE clause */
454 ){
455   TriggerStep *pTriggerStep;
456 
457   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
458   if( pTriggerStep ){
459     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
460     pTriggerStep->orconf = OE_Default;
461   }
462   sqlite3ExprDelete(db, pWhere);
463   return pTriggerStep;
464 }
465 
466 /*
467 ** Recursively delete a Trigger structure
468 */
469 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
470   if( pTrigger==0 ) return;
471   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
472   sqlite3DbFree(db, pTrigger->zName);
473   sqlite3DbFree(db, pTrigger->table);
474   sqlite3ExprDelete(db, pTrigger->pWhen);
475   sqlite3IdListDelete(db, pTrigger->pColumns);
476   sqlite3DbFree(db, pTrigger);
477 }
478 
479 /*
480 ** This function is called to drop a trigger from the database schema.
481 **
482 ** This may be called directly from the parser and therefore identifies
483 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
484 ** same job as this routine except it takes a pointer to the trigger
485 ** instead of the trigger name.
486 **/
487 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
488   Trigger *pTrigger = 0;
489   int i;
490   const char *zDb;
491   const char *zName;
492   int nName;
493   sqlite3 *db = pParse->db;
494 
495   if( db->mallocFailed ) goto drop_trigger_cleanup;
496   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
497     goto drop_trigger_cleanup;
498   }
499 
500   assert( pName->nSrc==1 );
501   zDb = pName->a[0].zDatabase;
502   zName = pName->a[0].zName;
503   nName = sqlite3Strlen30(zName);
504   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
505   for(i=OMIT_TEMPDB; i<db->nDb; i++){
506     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
507     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
508     assert( sqlite3SchemaMutexHeld(db, j, 0) );
509     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
510     if( pTrigger ) break;
511   }
512   if( !pTrigger ){
513     if( !noErr ){
514       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
515     }else{
516       sqlite3CodeVerifyNamedSchema(pParse, zDb);
517     }
518     pParse->checkSchema = 1;
519     goto drop_trigger_cleanup;
520   }
521   sqlite3DropTriggerPtr(pParse, pTrigger);
522 
523 drop_trigger_cleanup:
524   sqlite3SrcListDelete(db, pName);
525 }
526 
527 /*
528 ** Return a pointer to the Table structure for the table that a trigger
529 ** is set on.
530 */
531 static Table *tableOfTrigger(Trigger *pTrigger){
532   int n = sqlite3Strlen30(pTrigger->table);
533   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
534 }
535 
536 
537 /*
538 ** Drop a trigger given a pointer to that trigger.
539 */
540 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
541   Table   *pTable;
542   Vdbe *v;
543   sqlite3 *db = pParse->db;
544   int iDb;
545 
546   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
547   assert( iDb>=0 && iDb<db->nDb );
548   pTable = tableOfTrigger(pTrigger);
549   assert( pTable );
550   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
551 #ifndef SQLITE_OMIT_AUTHORIZATION
552   {
553     int code = SQLITE_DROP_TRIGGER;
554     const char *zDb = db->aDb[iDb].zName;
555     const char *zTab = SCHEMA_TABLE(iDb);
556     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
557     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
558       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
559       return;
560     }
561   }
562 #endif
563 
564   /* Generate code to destroy the database record of the trigger.
565   */
566   assert( pTable!=0 );
567   if( (v = sqlite3GetVdbe(pParse))!=0 ){
568     int base;
569     static const VdbeOpList dropTrigger[] = {
570       { OP_Rewind,     0, ADDR(9),  0},
571       { OP_String8,    0, 1,        0}, /* 1 */
572       { OP_Column,     0, 1,        2},
573       { OP_Ne,         2, ADDR(8),  1},
574       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
575       { OP_Column,     0, 0,        2},
576       { OP_Ne,         2, ADDR(8),  1},
577       { OP_Delete,     0, 0,        0},
578       { OP_Next,       0, ADDR(1),  0}, /* 8 */
579     };
580 
581     sqlite3BeginWriteOperation(pParse, 0, iDb);
582     sqlite3OpenMasterTable(pParse, iDb);
583     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
584     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
585     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
586     sqlite3ChangeCookie(pParse, iDb);
587     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
588     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
589     if( pParse->nMem<3 ){
590       pParse->nMem = 3;
591     }
592   }
593 }
594 
595 /*
596 ** Remove a trigger from the hash tables of the sqlite* pointer.
597 */
598 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
599   Trigger *pTrigger;
600   Hash *pHash;
601 
602   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
603   pHash = &(db->aDb[iDb].pSchema->trigHash);
604   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
605   if( ALWAYS(pTrigger) ){
606     if( pTrigger->pSchema==pTrigger->pTabSchema ){
607       Table *pTab = tableOfTrigger(pTrigger);
608       Trigger **pp;
609       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
610       *pp = (*pp)->pNext;
611     }
612     sqlite3DeleteTrigger(db, pTrigger);
613     db->flags |= SQLITE_InternChanges;
614   }
615 }
616 
617 /*
618 ** pEList is the SET clause of an UPDATE statement.  Each entry
619 ** in pEList is of the format <id>=<expr>.  If any of the entries
620 ** in pEList have an <id> which matches an identifier in pIdList,
621 ** then return TRUE.  If pIdList==NULL, then it is considered a
622 ** wildcard that matches anything.  Likewise if pEList==NULL then
623 ** it matches anything so always return true.  Return false only
624 ** if there is no match.
625 */
626 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
627   int e;
628   if( pIdList==0 || NEVER(pEList==0) ) return 1;
629   for(e=0; e<pEList->nExpr; e++){
630     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
631   }
632   return 0;
633 }
634 
635 /*
636 ** Return a list of all triggers on table pTab if there exists at least
637 ** one trigger that must be fired when an operation of type 'op' is
638 ** performed on the table, and, if that operation is an UPDATE, if at
639 ** least one of the columns in pChanges is being modified.
640 */
641 Trigger *sqlite3TriggersExist(
642   Parse *pParse,          /* Parse context */
643   Table *pTab,            /* The table the contains the triggers */
644   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
645   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
646   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
647 ){
648   int mask = 0;
649   Trigger *pList = 0;
650   Trigger *p;
651 
652   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
653     pList = sqlite3TriggerList(pParse, pTab);
654   }
655   assert( pList==0 || IsVirtual(pTab)==0 );
656   for(p=pList; p; p=p->pNext){
657     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
658       mask |= p->tr_tm;
659     }
660   }
661   if( pMask ){
662     *pMask = mask;
663   }
664   return (mask ? pList : 0);
665 }
666 
667 /*
668 ** Convert the pStep->target token into a SrcList and return a pointer
669 ** to that SrcList.
670 **
671 ** This routine adds a specific database name, if needed, to the target when
672 ** forming the SrcList.  This prevents a trigger in one database from
673 ** referring to a target in another database.  An exception is when the
674 ** trigger is in TEMP in which case it can refer to any other database it
675 ** wants.
676 */
677 static SrcList *targetSrcList(
678   Parse *pParse,       /* The parsing context */
679   TriggerStep *pStep   /* The trigger containing the target token */
680 ){
681   int iDb;             /* Index of the database to use */
682   SrcList *pSrc;       /* SrcList to be returned */
683 
684   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
685   if( pSrc ){
686     assert( pSrc->nSrc>0 );
687     assert( pSrc->a!=0 );
688     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
689     if( iDb==0 || iDb>=2 ){
690       sqlite3 *db = pParse->db;
691       assert( iDb<pParse->db->nDb );
692       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
693     }
694   }
695   return pSrc;
696 }
697 
698 /*
699 ** Generate VDBE code for the statements inside the body of a single
700 ** trigger.
701 */
702 static int codeTriggerProgram(
703   Parse *pParse,            /* The parser context */
704   TriggerStep *pStepList,   /* List of statements inside the trigger body */
705   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
706 ){
707   TriggerStep *pStep;
708   Vdbe *v = pParse->pVdbe;
709   sqlite3 *db = pParse->db;
710 
711   assert( pParse->pTriggerTab && pParse->pToplevel );
712   assert( pStepList );
713   assert( v!=0 );
714   for(pStep=pStepList; pStep; pStep=pStep->pNext){
715     /* Figure out the ON CONFLICT policy that will be used for this step
716     ** of the trigger program. If the statement that caused this trigger
717     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
718     ** the ON CONFLICT policy that was specified as part of the trigger
719     ** step statement. Example:
720     **
721     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
722     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
723     **   END;
724     **
725     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
726     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
727     */
728     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
729 
730     /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
731     ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
732     ** that it is not safe to refactor constants (this happens after the
733     ** start of the first loop in the SQL statement is coded - at that
734     ** point code may be conditionally executed, so it is no longer safe to
735     ** initialize constant register values).  */
736     assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
737     pParse->cookieGoto = 0;
738 
739     switch( pStep->op ){
740       case TK_UPDATE: {
741         sqlite3Update(pParse,
742           targetSrcList(pParse, pStep),
743           sqlite3ExprListDup(db, pStep->pExprList, 0),
744           sqlite3ExprDup(db, pStep->pWhere, 0),
745           pParse->eOrconf
746         );
747         break;
748       }
749       case TK_INSERT: {
750         sqlite3Insert(pParse,
751           targetSrcList(pParse, pStep),
752           sqlite3SelectDup(db, pStep->pSelect, 0),
753           sqlite3IdListDup(db, pStep->pIdList),
754           pParse->eOrconf
755         );
756         break;
757       }
758       case TK_DELETE: {
759         sqlite3DeleteFrom(pParse,
760           targetSrcList(pParse, pStep),
761           sqlite3ExprDup(db, pStep->pWhere, 0)
762         );
763         break;
764       }
765       default: assert( pStep->op==TK_SELECT ); {
766         SelectDest sDest;
767         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
768         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
769         sqlite3Select(pParse, pSelect, &sDest);
770         sqlite3SelectDelete(db, pSelect);
771         break;
772       }
773     }
774     if( pStep->op!=TK_SELECT ){
775       sqlite3VdbeAddOp0(v, OP_ResetCount);
776     }
777   }
778 
779   return 0;
780 }
781 
782 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
783 /*
784 ** This function is used to add VdbeComment() annotations to a VDBE
785 ** program. It is not used in production code, only for debugging.
786 */
787 static const char *onErrorText(int onError){
788   switch( onError ){
789     case OE_Abort:    return "abort";
790     case OE_Rollback: return "rollback";
791     case OE_Fail:     return "fail";
792     case OE_Replace:  return "replace";
793     case OE_Ignore:   return "ignore";
794     case OE_Default:  return "default";
795   }
796   return "n/a";
797 }
798 #endif
799 
800 /*
801 ** Parse context structure pFrom has just been used to create a sub-vdbe
802 ** (trigger program). If an error has occurred, transfer error information
803 ** from pFrom to pTo.
804 */
805 static void transferParseError(Parse *pTo, Parse *pFrom){
806   assert( pFrom->zErrMsg==0 || pFrom->nErr );
807   assert( pTo->zErrMsg==0 || pTo->nErr );
808   if( pTo->nErr==0 ){
809     pTo->zErrMsg = pFrom->zErrMsg;
810     pTo->nErr = pFrom->nErr;
811   }else{
812     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
813   }
814 }
815 
816 /*
817 ** Create and populate a new TriggerPrg object with a sub-program
818 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
819 */
820 static TriggerPrg *codeRowTrigger(
821   Parse *pParse,       /* Current parse context */
822   Trigger *pTrigger,   /* Trigger to code */
823   Table *pTab,         /* The table pTrigger is attached to */
824   int orconf           /* ON CONFLICT policy to code trigger program with */
825 ){
826   Parse *pTop = sqlite3ParseToplevel(pParse);
827   sqlite3 *db = pParse->db;   /* Database handle */
828   TriggerPrg *pPrg;           /* Value to return */
829   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
830   Vdbe *v;                    /* Temporary VM */
831   NameContext sNC;            /* Name context for sub-vdbe */
832   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
833   Parse *pSubParse;           /* Parse context for sub-vdbe */
834   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
835 
836   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
837   assert( pTop->pVdbe );
838 
839   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
840   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
841   ** list of the top-level Parse object sooner rather than later.  */
842   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
843   if( !pPrg ) return 0;
844   pPrg->pNext = pTop->pTriggerPrg;
845   pTop->pTriggerPrg = pPrg;
846   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
847   if( !pProgram ) return 0;
848   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
849   pPrg->pTrigger = pTrigger;
850   pPrg->orconf = orconf;
851   pPrg->aColmask[0] = 0xffffffff;
852   pPrg->aColmask[1] = 0xffffffff;
853 
854   /* Allocate and populate a new Parse context to use for coding the
855   ** trigger sub-program.  */
856   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
857   if( !pSubParse ) return 0;
858   memset(&sNC, 0, sizeof(sNC));
859   sNC.pParse = pSubParse;
860   pSubParse->db = db;
861   pSubParse->pTriggerTab = pTab;
862   pSubParse->pToplevel = pTop;
863   pSubParse->zAuthContext = pTrigger->zName;
864   pSubParse->eTriggerOp = pTrigger->op;
865   pSubParse->nQueryLoop = pParse->nQueryLoop;
866 
867   v = sqlite3GetVdbe(pSubParse);
868   if( v ){
869     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
870       pTrigger->zName, onErrorText(orconf),
871       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
872         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
873         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
874         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
875       pTab->zName
876     ));
877 #ifndef SQLITE_OMIT_TRACE
878     sqlite3VdbeChangeP4(v, -1,
879       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
880     );
881 #endif
882 
883     /* If one was specified, code the WHEN clause. If it evaluates to false
884     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
885     ** OP_Halt inserted at the end of the program.  */
886     if( pTrigger->pWhen ){
887       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
888       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
889        && db->mallocFailed==0
890       ){
891         iEndTrigger = sqlite3VdbeMakeLabel(v);
892         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
893       }
894       sqlite3ExprDelete(db, pWhen);
895     }
896 
897     /* Code the trigger program into the sub-vdbe. */
898     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
899 
900     /* Insert an OP_Halt at the end of the sub-program. */
901     if( iEndTrigger ){
902       sqlite3VdbeResolveLabel(v, iEndTrigger);
903     }
904     sqlite3VdbeAddOp0(v, OP_Halt);
905     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
906 
907     transferParseError(pParse, pSubParse);
908     if( db->mallocFailed==0 ){
909       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
910     }
911     pProgram->nMem = pSubParse->nMem;
912     pProgram->nCsr = pSubParse->nTab;
913     pProgram->nOnce = pSubParse->nOnce;
914     pProgram->token = (void *)pTrigger;
915     pPrg->aColmask[0] = pSubParse->oldmask;
916     pPrg->aColmask[1] = pSubParse->newmask;
917     sqlite3VdbeDelete(v);
918   }
919 
920   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
921   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
922   sqlite3ParserReset(pSubParse);
923   sqlite3StackFree(db, pSubParse);
924 
925   return pPrg;
926 }
927 
928 /*
929 ** Return a pointer to a TriggerPrg object containing the sub-program for
930 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
931 ** TriggerPrg object exists, a new object is allocated and populated before
932 ** being returned.
933 */
934 static TriggerPrg *getRowTrigger(
935   Parse *pParse,       /* Current parse context */
936   Trigger *pTrigger,   /* Trigger to code */
937   Table *pTab,         /* The table trigger pTrigger is attached to */
938   int orconf           /* ON CONFLICT algorithm. */
939 ){
940   Parse *pRoot = sqlite3ParseToplevel(pParse);
941   TriggerPrg *pPrg;
942 
943   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
944 
945   /* It may be that this trigger has already been coded (or is in the
946   ** process of being coded). If this is the case, then an entry with
947   ** a matching TriggerPrg.pTrigger field will be present somewhere
948   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
949   for(pPrg=pRoot->pTriggerPrg;
950       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
951       pPrg=pPrg->pNext
952   );
953 
954   /* If an existing TriggerPrg could not be located, create a new one. */
955   if( !pPrg ){
956     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
957   }
958 
959   return pPrg;
960 }
961 
962 /*
963 ** Generate code for the trigger program associated with trigger p on
964 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
965 ** function are the same as those described in the header function for
966 ** sqlite3CodeRowTrigger()
967 */
968 void sqlite3CodeRowTriggerDirect(
969   Parse *pParse,       /* Parse context */
970   Trigger *p,          /* Trigger to code */
971   Table *pTab,         /* The table to code triggers from */
972   int reg,             /* Reg array containing OLD.* and NEW.* values */
973   int orconf,          /* ON CONFLICT policy */
974   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
975 ){
976   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
977   TriggerPrg *pPrg;
978   pPrg = getRowTrigger(pParse, p, pTab, orconf);
979   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
980 
981   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
982   ** is a pointer to the sub-vdbe containing the trigger program.  */
983   if( pPrg ){
984     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
985 
986     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
987     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
988     VdbeComment(
989         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
990 
991     /* Set the P5 operand of the OP_Program instruction to non-zero if
992     ** recursive invocation of this trigger program is disallowed. Recursive
993     ** invocation is disallowed if (a) the sub-program is really a trigger,
994     ** not a foreign key action, and (b) the flag to enable recursive triggers
995     ** is clear.  */
996     sqlite3VdbeChangeP5(v, (u8)bRecursive);
997   }
998 }
999 
1000 /*
1001 ** This is called to code the required FOR EACH ROW triggers for an operation
1002 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
1003 ** is given by the op parameter. The tr_tm parameter determines whether the
1004 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
1005 ** parameter pChanges is passed the list of columns being modified.
1006 **
1007 ** If there are no triggers that fire at the specified time for the specified
1008 ** operation on pTab, this function is a no-op.
1009 **
1010 ** The reg argument is the address of the first in an array of registers
1011 ** that contain the values substituted for the new.* and old.* references
1012 ** in the trigger program. If N is the number of columns in table pTab
1013 ** (a copy of pTab->nCol), then registers are populated as follows:
1014 **
1015 **   Register       Contains
1016 **   ------------------------------------------------------
1017 **   reg+0          OLD.rowid
1018 **   reg+1          OLD.* value of left-most column of pTab
1019 **   ...            ...
1020 **   reg+N          OLD.* value of right-most column of pTab
1021 **   reg+N+1        NEW.rowid
1022 **   reg+N+2        OLD.* value of left-most column of pTab
1023 **   ...            ...
1024 **   reg+N+N+1      NEW.* value of right-most column of pTab
1025 **
1026 ** For ON DELETE triggers, the registers containing the NEW.* values will
1027 ** never be accessed by the trigger program, so they are not allocated or
1028 ** populated by the caller (there is no data to populate them with anyway).
1029 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1030 ** are never accessed, and so are not allocated by the caller. So, for an
1031 ** ON INSERT trigger, the value passed to this function as parameter reg
1032 ** is not a readable register, although registers (reg+N) through
1033 ** (reg+N+N+1) are.
1034 **
1035 ** Parameter orconf is the default conflict resolution algorithm for the
1036 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1037 ** is the instruction that control should jump to if a trigger program
1038 ** raises an IGNORE exception.
1039 */
1040 void sqlite3CodeRowTrigger(
1041   Parse *pParse,       /* Parse context */
1042   Trigger *pTrigger,   /* List of triggers on table pTab */
1043   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1044   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1045   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1046   Table *pTab,         /* The table to code triggers from */
1047   int reg,             /* The first in an array of registers (see above) */
1048   int orconf,          /* ON CONFLICT policy */
1049   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
1050 ){
1051   Trigger *p;          /* Used to iterate through pTrigger list */
1052 
1053   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1054   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1055   assert( (op==TK_UPDATE)==(pChanges!=0) );
1056 
1057   for(p=pTrigger; p; p=p->pNext){
1058 
1059     /* Sanity checking:  The schema for the trigger and for the table are
1060     ** always defined.  The trigger must be in the same schema as the table
1061     ** or else it must be a TEMP trigger. */
1062     assert( p->pSchema!=0 );
1063     assert( p->pTabSchema!=0 );
1064     assert( p->pSchema==p->pTabSchema
1065          || p->pSchema==pParse->db->aDb[1].pSchema );
1066 
1067     /* Determine whether we should code this trigger */
1068     if( p->op==op
1069      && p->tr_tm==tr_tm
1070      && checkColumnOverlap(p->pColumns, pChanges)
1071     ){
1072       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1073     }
1074   }
1075 }
1076 
1077 /*
1078 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1079 ** This function returns a 32-bit bitmask indicating which columns of the
1080 ** old.* or new.* tables actually are used by triggers. This information
1081 ** may be used by the caller, for example, to avoid having to load the entire
1082 ** old.* record into memory when executing an UPDATE or DELETE command.
1083 **
1084 ** Bit 0 of the returned mask is set if the left-most column of the
1085 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1086 ** the second leftmost column value is required, and so on. If there
1087 ** are more than 32 columns in the table, and at least one of the columns
1088 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1089 **
1090 ** It is not possible to determine if the old.rowid or new.rowid column is
1091 ** accessed by triggers. The caller must always assume that it is.
1092 **
1093 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1094 ** applies to the old.* table. If 1, the new.* table.
1095 **
1096 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1097 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1098 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1099 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1100 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1101 */
1102 u32 sqlite3TriggerColmask(
1103   Parse *pParse,       /* Parse context */
1104   Trigger *pTrigger,   /* List of triggers on table pTab */
1105   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1106   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
1107   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1108   Table *pTab,         /* The table to code triggers from */
1109   int orconf           /* Default ON CONFLICT policy for trigger steps */
1110 ){
1111   const int op = pChanges ? TK_UPDATE : TK_DELETE;
1112   u32 mask = 0;
1113   Trigger *p;
1114 
1115   assert( isNew==1 || isNew==0 );
1116   for(p=pTrigger; p; p=p->pNext){
1117     if( p->op==op && (tr_tm&p->tr_tm)
1118      && checkColumnOverlap(p->pColumns,pChanges)
1119     ){
1120       TriggerPrg *pPrg;
1121       pPrg = getRowTrigger(pParse, p, pTab, orconf);
1122       if( pPrg ){
1123         mask |= pPrg->aColmask[isNew];
1124       }
1125     }
1126   }
1127 
1128   return mask;
1129 }
1130 
1131 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1132