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