xref: /sqlite-3.40.0/src/trigger.c (revision 067b92ba)
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 the schema table
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_schema entry
322   */
323   if( !db->init.busy ){
324     Vdbe *v;
325     char *z;
326 
327     /* Make an entry in the sqlite_schema 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." DFLT_SCHEMA_TABLE
335        " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
336        db->aDb[iDb].zDbSName, zName,
337        pTrig->table, z);
338     sqlite3DbFree(db, z);
339     sqlite3ChangeCookie(pParse, iDb);
340     sqlite3VdbeAddParseSchemaOp(v, iDb,
341         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
342   }
343 
344   if( db->init.busy ){
345     Trigger *pLink = pTrig;
346     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
347     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
348     assert( pLink!=0 );
349     pTrig = sqlite3HashInsert(pHash, zName, pTrig);
350     if( pTrig ){
351       sqlite3OomFault(db);
352     }else if( pLink->pSchema==pLink->pTabSchema ){
353       Table *pTab;
354       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
355       assert( pTab!=0 );
356       pLink->pNext = pTab->pTrigger;
357       pTab->pTrigger = pLink;
358     }
359   }
360 
361 triggerfinish_cleanup:
362   sqlite3DeleteTrigger(db, pTrig);
363   assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
364   sqlite3DeleteTriggerStep(db, pStepList);
365 }
366 
367 /*
368 ** Duplicate a range of text from an SQL statement, then convert all
369 ** whitespace characters into ordinary space characters.
370 */
371 static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
372   char *z = sqlite3DbSpanDup(db, zStart, zEnd);
373   int i;
374   if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
375   return z;
376 }
377 
378 /*
379 ** Turn a SELECT statement (that the pSelect parameter points to) into
380 ** a trigger step.  Return a pointer to a TriggerStep structure.
381 **
382 ** The parser calls this routine when it finds a SELECT statement in
383 ** body of a TRIGGER.
384 */
385 TriggerStep *sqlite3TriggerSelectStep(
386   sqlite3 *db,                /* Database connection */
387   Select *pSelect,            /* The SELECT statement */
388   const char *zStart,         /* Start of SQL text */
389   const char *zEnd            /* End of SQL text */
390 ){
391   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
392   if( pTriggerStep==0 ) {
393     sqlite3SelectDelete(db, pSelect);
394     return 0;
395   }
396   pTriggerStep->op = TK_SELECT;
397   pTriggerStep->pSelect = pSelect;
398   pTriggerStep->orconf = OE_Default;
399   pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
400   return pTriggerStep;
401 }
402 
403 /*
404 ** Allocate space to hold a new trigger step.  The allocated space
405 ** holds both the TriggerStep object and the TriggerStep.target.z string.
406 **
407 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
408 */
409 static TriggerStep *triggerStepAllocate(
410   Parse *pParse,              /* Parser context */
411   u8 op,                      /* Trigger opcode */
412   Token *pName,               /* The target name */
413   const char *zStart,         /* Start of SQL text */
414   const char *zEnd            /* End of SQL text */
415 ){
416   sqlite3 *db = pParse->db;
417   TriggerStep *pTriggerStep;
418 
419   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
420   if( pTriggerStep ){
421     char *z = (char*)&pTriggerStep[1];
422     memcpy(z, pName->z, pName->n);
423     sqlite3Dequote(z);
424     pTriggerStep->zTarget = z;
425     pTriggerStep->op = op;
426     pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
427     if( IN_RENAME_OBJECT ){
428       sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
429     }
430   }
431   return pTriggerStep;
432 }
433 
434 /*
435 ** Build a trigger step out of an INSERT statement.  Return a pointer
436 ** to the new trigger step.
437 **
438 ** The parser calls this routine when it sees an INSERT inside the
439 ** body of a trigger.
440 */
441 TriggerStep *sqlite3TriggerInsertStep(
442   Parse *pParse,      /* Parser */
443   Token *pTableName,  /* Name of the table into which we insert */
444   IdList *pColumn,    /* List of columns in pTableName to insert into */
445   Select *pSelect,    /* A SELECT statement that supplies values */
446   u8 orconf,          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
447   Upsert *pUpsert,    /* ON CONFLICT clauses for upsert */
448   const char *zStart, /* Start of SQL text */
449   const char *zEnd    /* End of SQL text */
450 ){
451   sqlite3 *db = pParse->db;
452   TriggerStep *pTriggerStep;
453 
454   assert(pSelect != 0 || db->mallocFailed);
455 
456   pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
457   if( pTriggerStep ){
458     if( IN_RENAME_OBJECT ){
459       pTriggerStep->pSelect = pSelect;
460       pSelect = 0;
461     }else{
462       pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
463     }
464     pTriggerStep->pIdList = pColumn;
465     pTriggerStep->pUpsert = pUpsert;
466     pTriggerStep->orconf = orconf;
467     if( pUpsert ){
468       sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
469     }
470   }else{
471     testcase( pColumn );
472     sqlite3IdListDelete(db, pColumn);
473     testcase( pUpsert );
474     sqlite3UpsertDelete(db, pUpsert);
475   }
476   sqlite3SelectDelete(db, pSelect);
477 
478   return pTriggerStep;
479 }
480 
481 /*
482 ** Construct a trigger step that implements an UPDATE statement and return
483 ** a pointer to that trigger step.  The parser calls this routine when it
484 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
485 */
486 TriggerStep *sqlite3TriggerUpdateStep(
487   Parse *pParse,          /* Parser */
488   Token *pTableName,   /* Name of the table to be updated */
489   ExprList *pEList,    /* The SET clause: list of column and new values */
490   Expr *pWhere,        /* The WHERE clause */
491   u8 orconf,           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
492   const char *zStart,  /* Start of SQL text */
493   const char *zEnd     /* End of SQL text */
494 ){
495   sqlite3 *db = pParse->db;
496   TriggerStep *pTriggerStep;
497 
498   pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
499   if( pTriggerStep ){
500     if( IN_RENAME_OBJECT ){
501       pTriggerStep->pExprList = pEList;
502       pTriggerStep->pWhere = pWhere;
503       pEList = 0;
504       pWhere = 0;
505     }else{
506       pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
507       pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
508     }
509     pTriggerStep->orconf = orconf;
510   }
511   sqlite3ExprListDelete(db, pEList);
512   sqlite3ExprDelete(db, pWhere);
513   return pTriggerStep;
514 }
515 
516 /*
517 ** Construct a trigger step that implements a DELETE statement and return
518 ** a pointer to that trigger step.  The parser calls this routine when it
519 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
520 */
521 TriggerStep *sqlite3TriggerDeleteStep(
522   Parse *pParse,          /* Parser */
523   Token *pTableName,      /* The table from which rows are deleted */
524   Expr *pWhere,           /* The WHERE clause */
525   const char *zStart,     /* Start of SQL text */
526   const char *zEnd        /* End of SQL text */
527 ){
528   sqlite3 *db = pParse->db;
529   TriggerStep *pTriggerStep;
530 
531   pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
532   if( pTriggerStep ){
533     if( IN_RENAME_OBJECT ){
534       pTriggerStep->pWhere = pWhere;
535       pWhere = 0;
536     }else{
537       pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
538     }
539     pTriggerStep->orconf = OE_Default;
540   }
541   sqlite3ExprDelete(db, pWhere);
542   return pTriggerStep;
543 }
544 
545 /*
546 ** Recursively delete a Trigger structure
547 */
548 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
549   if( pTrigger==0 ) return;
550   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
551   sqlite3DbFree(db, pTrigger->zName);
552   sqlite3DbFree(db, pTrigger->table);
553   sqlite3ExprDelete(db, pTrigger->pWhen);
554   sqlite3IdListDelete(db, pTrigger->pColumns);
555   sqlite3DbFree(db, pTrigger);
556 }
557 
558 /*
559 ** This function is called to drop a trigger from the database schema.
560 **
561 ** This may be called directly from the parser and therefore identifies
562 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
563 ** same job as this routine except it takes a pointer to the trigger
564 ** instead of the trigger name.
565 **/
566 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
567   Trigger *pTrigger = 0;
568   int i;
569   const char *zDb;
570   const char *zName;
571   sqlite3 *db = pParse->db;
572 
573   if( db->mallocFailed ) goto drop_trigger_cleanup;
574   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
575     goto drop_trigger_cleanup;
576   }
577 
578   assert( pName->nSrc==1 );
579   zDb = pName->a[0].zDatabase;
580   zName = pName->a[0].zName;
581   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
582   for(i=OMIT_TEMPDB; i<db->nDb; i++){
583     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
584     if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
585     assert( sqlite3SchemaMutexHeld(db, j, 0) );
586     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
587     if( pTrigger ) break;
588   }
589   if( !pTrigger ){
590     if( !noErr ){
591       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
592     }else{
593       sqlite3CodeVerifyNamedSchema(pParse, zDb);
594     }
595     pParse->checkSchema = 1;
596     goto drop_trigger_cleanup;
597   }
598   sqlite3DropTriggerPtr(pParse, pTrigger);
599 
600 drop_trigger_cleanup:
601   sqlite3SrcListDelete(db, pName);
602 }
603 
604 /*
605 ** Return a pointer to the Table structure for the table that a trigger
606 ** is set on.
607 */
608 static Table *tableOfTrigger(Trigger *pTrigger){
609   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
610 }
611 
612 
613 /*
614 ** Drop a trigger given a pointer to that trigger.
615 */
616 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
617   Table   *pTable;
618   Vdbe *v;
619   sqlite3 *db = pParse->db;
620   int iDb;
621 
622   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
623   assert( iDb>=0 && iDb<db->nDb );
624   pTable = tableOfTrigger(pTrigger);
625   assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
626 #ifndef SQLITE_OMIT_AUTHORIZATION
627   if( pTable ){
628     int code = SQLITE_DROP_TRIGGER;
629     const char *zDb = db->aDb[iDb].zDbSName;
630     const char *zTab = SCHEMA_TABLE(iDb);
631     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
632     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
633       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
634       return;
635     }
636   }
637 #endif
638 
639   /* Generate code to destroy the database record of the trigger.
640   */
641   if( (v = sqlite3GetVdbe(pParse))!=0 ){
642     sqlite3NestedParse(pParse,
643        "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
644        db->aDb[iDb].zDbSName, pTrigger->zName
645     );
646     sqlite3ChangeCookie(pParse, iDb);
647     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
648   }
649 }
650 
651 /*
652 ** Remove a trigger from the hash tables of the sqlite* pointer.
653 */
654 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
655   Trigger *pTrigger;
656   Hash *pHash;
657 
658   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
659   pHash = &(db->aDb[iDb].pSchema->trigHash);
660   pTrigger = sqlite3HashInsert(pHash, zName, 0);
661   if( ALWAYS(pTrigger) ){
662     if( pTrigger->pSchema==pTrigger->pTabSchema ){
663       Table *pTab = tableOfTrigger(pTrigger);
664       if( pTab ){
665         Trigger **pp;
666         for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
667           if( *pp==pTrigger ){
668             *pp = (*pp)->pNext;
669             break;
670           }
671         }
672       }
673     }
674     sqlite3DeleteTrigger(db, pTrigger);
675     db->mDbFlags |= DBFLAG_SchemaChange;
676   }
677 }
678 
679 /*
680 ** pEList is the SET clause of an UPDATE statement.  Each entry
681 ** in pEList is of the format <id>=<expr>.  If any of the entries
682 ** in pEList have an <id> which matches an identifier in pIdList,
683 ** then return TRUE.  If pIdList==NULL, then it is considered a
684 ** wildcard that matches anything.  Likewise if pEList==NULL then
685 ** it matches anything so always return true.  Return false only
686 ** if there is no match.
687 */
688 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
689   int e;
690   if( pIdList==0 || NEVER(pEList==0) ) return 1;
691   for(e=0; e<pEList->nExpr; e++){
692     if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
693   }
694   return 0;
695 }
696 
697 /*
698 ** Return a list of all triggers on table pTab if there exists at least
699 ** one trigger that must be fired when an operation of type 'op' is
700 ** performed on the table, and, if that operation is an UPDATE, if at
701 ** least one of the columns in pChanges is being modified.
702 */
703 Trigger *sqlite3TriggersExist(
704   Parse *pParse,          /* Parse context */
705   Table *pTab,            /* The table the contains the triggers */
706   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
707   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
708   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
709 ){
710   int mask = 0;
711   Trigger *pList = 0;
712   Trigger *p;
713 
714   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
715     pList = sqlite3TriggerList(pParse, pTab);
716   }
717   assert( pList==0 || IsVirtual(pTab)==0 );
718   for(p=pList; p; p=p->pNext){
719     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
720       mask |= p->tr_tm;
721     }
722   }
723   if( pMask ){
724     *pMask = mask;
725   }
726   return (mask ? pList : 0);
727 }
728 
729 /*
730 ** Convert the pStep->zTarget string into a SrcList and return a pointer
731 ** to that SrcList.
732 **
733 ** This routine adds a specific database name, if needed, to the target when
734 ** forming the SrcList.  This prevents a trigger in one database from
735 ** referring to a target in another database.  An exception is when the
736 ** trigger is in TEMP in which case it can refer to any other database it
737 ** wants.
738 */
739 static SrcList *targetSrcList(
740   Parse *pParse,       /* The parsing context */
741   TriggerStep *pStep   /* The trigger containing the target token */
742 ){
743   sqlite3 *db = pParse->db;
744   int iDb;             /* Index of the database to use */
745   SrcList *pSrc;       /* SrcList to be returned */
746 
747   pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
748   if( pSrc ){
749     assert( pSrc->nSrc>0 );
750     pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
751     iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
752     if( iDb==0 || iDb>=2 ){
753       const char *zDb;
754       assert( iDb<db->nDb );
755       zDb = db->aDb[iDb].zDbSName;
756       pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
757     }
758   }
759   return pSrc;
760 }
761 
762 /*
763 ** Generate VDBE code for the statements inside the body of a single
764 ** trigger.
765 */
766 static int codeTriggerProgram(
767   Parse *pParse,            /* The parser context */
768   TriggerStep *pStepList,   /* List of statements inside the trigger body */
769   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
770 ){
771   TriggerStep *pStep;
772   Vdbe *v = pParse->pVdbe;
773   sqlite3 *db = pParse->db;
774 
775   assert( pParse->pTriggerTab && pParse->pToplevel );
776   assert( pStepList );
777   assert( v!=0 );
778   for(pStep=pStepList; pStep; pStep=pStep->pNext){
779     /* Figure out the ON CONFLICT policy that will be used for this step
780     ** of the trigger program. If the statement that caused this trigger
781     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
782     ** the ON CONFLICT policy that was specified as part of the trigger
783     ** step statement. Example:
784     **
785     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
786     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
787     **   END;
788     **
789     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
790     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
791     */
792     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
793     assert( pParse->okConstFactor==0 );
794 
795 #ifndef SQLITE_OMIT_TRACE
796     if( pStep->zSpan ){
797       sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
798                         sqlite3MPrintf(db, "-- %s", pStep->zSpan),
799                         P4_DYNAMIC);
800     }
801 #endif
802 
803     switch( pStep->op ){
804       case TK_UPDATE: {
805         sqlite3Update(pParse,
806           targetSrcList(pParse, pStep),
807           sqlite3ExprListDup(db, pStep->pExprList, 0),
808           sqlite3ExprDup(db, pStep->pWhere, 0),
809           pParse->eOrconf, 0, 0, 0
810         );
811         break;
812       }
813       case TK_INSERT: {
814         sqlite3Insert(pParse,
815           targetSrcList(pParse, pStep),
816           sqlite3SelectDup(db, pStep->pSelect, 0),
817           sqlite3IdListDup(db, pStep->pIdList),
818           pParse->eOrconf,
819           sqlite3UpsertDup(db, pStep->pUpsert)
820         );
821         break;
822       }
823       case TK_DELETE: {
824         sqlite3DeleteFrom(pParse,
825           targetSrcList(pParse, pStep),
826           sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
827         );
828         break;
829       }
830       default: assert( pStep->op==TK_SELECT ); {
831         SelectDest sDest;
832         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
833         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
834         sqlite3Select(pParse, pSelect, &sDest);
835         sqlite3SelectDelete(db, pSelect);
836         break;
837       }
838     }
839     if( pStep->op!=TK_SELECT ){
840       sqlite3VdbeAddOp0(v, OP_ResetCount);
841     }
842   }
843 
844   return 0;
845 }
846 
847 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
848 /*
849 ** This function is used to add VdbeComment() annotations to a VDBE
850 ** program. It is not used in production code, only for debugging.
851 */
852 static const char *onErrorText(int onError){
853   switch( onError ){
854     case OE_Abort:    return "abort";
855     case OE_Rollback: return "rollback";
856     case OE_Fail:     return "fail";
857     case OE_Replace:  return "replace";
858     case OE_Ignore:   return "ignore";
859     case OE_Default:  return "default";
860   }
861   return "n/a";
862 }
863 #endif
864 
865 /*
866 ** Parse context structure pFrom has just been used to create a sub-vdbe
867 ** (trigger program). If an error has occurred, transfer error information
868 ** from pFrom to pTo.
869 */
870 static void transferParseError(Parse *pTo, Parse *pFrom){
871   assert( pFrom->zErrMsg==0 || pFrom->nErr );
872   assert( pTo->zErrMsg==0 || pTo->nErr );
873   if( pTo->nErr==0 ){
874     pTo->zErrMsg = pFrom->zErrMsg;
875     pTo->nErr = pFrom->nErr;
876     pTo->rc = pFrom->rc;
877   }else{
878     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
879   }
880 }
881 
882 /*
883 ** Create and populate a new TriggerPrg object with a sub-program
884 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
885 */
886 static TriggerPrg *codeRowTrigger(
887   Parse *pParse,       /* Current parse context */
888   Trigger *pTrigger,   /* Trigger to code */
889   Table *pTab,         /* The table pTrigger is attached to */
890   int orconf           /* ON CONFLICT policy to code trigger program with */
891 ){
892   Parse *pTop = sqlite3ParseToplevel(pParse);
893   sqlite3 *db = pParse->db;   /* Database handle */
894   TriggerPrg *pPrg;           /* Value to return */
895   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
896   Vdbe *v;                    /* Temporary VM */
897   NameContext sNC;            /* Name context for sub-vdbe */
898   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
899   Parse *pSubParse;           /* Parse context for sub-vdbe */
900   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
901 
902   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
903   assert( pTop->pVdbe );
904 
905   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
906   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
907   ** list of the top-level Parse object sooner rather than later.  */
908   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
909   if( !pPrg ) return 0;
910   pPrg->pNext = pTop->pTriggerPrg;
911   pTop->pTriggerPrg = pPrg;
912   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
913   if( !pProgram ) return 0;
914   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
915   pPrg->pTrigger = pTrigger;
916   pPrg->orconf = orconf;
917   pPrg->aColmask[0] = 0xffffffff;
918   pPrg->aColmask[1] = 0xffffffff;
919 
920   /* Allocate and populate a new Parse context to use for coding the
921   ** trigger sub-program.  */
922   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
923   if( !pSubParse ) return 0;
924   memset(&sNC, 0, sizeof(sNC));
925   sNC.pParse = pSubParse;
926   pSubParse->db = db;
927   pSubParse->pTriggerTab = pTab;
928   pSubParse->pToplevel = pTop;
929   pSubParse->zAuthContext = pTrigger->zName;
930   pSubParse->eTriggerOp = pTrigger->op;
931   pSubParse->nQueryLoop = pParse->nQueryLoop;
932   pSubParse->disableVtab = pParse->disableVtab;
933 
934   v = sqlite3GetVdbe(pSubParse);
935   if( v ){
936     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
937       pTrigger->zName, onErrorText(orconf),
938       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
939         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
940         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
941         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
942       pTab->zName
943     ));
944 #ifndef SQLITE_OMIT_TRACE
945     if( pTrigger->zName ){
946       sqlite3VdbeChangeP4(v, -1,
947         sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
948       );
949     }
950 #endif
951 
952     /* If one was specified, code the WHEN clause. If it evaluates to false
953     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
954     ** OP_Halt inserted at the end of the program.  */
955     if( pTrigger->pWhen ){
956       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
957       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
958        && db->mallocFailed==0
959       ){
960         iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
961         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
962       }
963       sqlite3ExprDelete(db, pWhen);
964     }
965 
966     /* Code the trigger program into the sub-vdbe. */
967     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
968 
969     /* Insert an OP_Halt at the end of the sub-program. */
970     if( iEndTrigger ){
971       sqlite3VdbeResolveLabel(v, iEndTrigger);
972     }
973     sqlite3VdbeAddOp0(v, OP_Halt);
974     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
975 
976     transferParseError(pParse, pSubParse);
977     if( db->mallocFailed==0 && pParse->nErr==0 ){
978       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
979     }
980     pProgram->nMem = pSubParse->nMem;
981     pProgram->nCsr = pSubParse->nTab;
982     pProgram->token = (void *)pTrigger;
983     pPrg->aColmask[0] = pSubParse->oldmask;
984     pPrg->aColmask[1] = pSubParse->newmask;
985     sqlite3VdbeDelete(v);
986   }
987 
988   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
989   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
990   sqlite3ParserReset(pSubParse);
991   sqlite3StackFree(db, pSubParse);
992 
993   return pPrg;
994 }
995 
996 /*
997 ** Return a pointer to a TriggerPrg object containing the sub-program for
998 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
999 ** TriggerPrg object exists, a new object is allocated and populated before
1000 ** being returned.
1001 */
1002 static TriggerPrg *getRowTrigger(
1003   Parse *pParse,       /* Current parse context */
1004   Trigger *pTrigger,   /* Trigger to code */
1005   Table *pTab,         /* The table trigger pTrigger is attached to */
1006   int orconf           /* ON CONFLICT algorithm. */
1007 ){
1008   Parse *pRoot = sqlite3ParseToplevel(pParse);
1009   TriggerPrg *pPrg;
1010 
1011   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
1012 
1013   /* It may be that this trigger has already been coded (or is in the
1014   ** process of being coded). If this is the case, then an entry with
1015   ** a matching TriggerPrg.pTrigger field will be present somewhere
1016   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
1017   for(pPrg=pRoot->pTriggerPrg;
1018       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
1019       pPrg=pPrg->pNext
1020   );
1021 
1022   /* If an existing TriggerPrg could not be located, create a new one. */
1023   if( !pPrg ){
1024     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
1025   }
1026 
1027   return pPrg;
1028 }
1029 
1030 /*
1031 ** Generate code for the trigger program associated with trigger p on
1032 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
1033 ** function are the same as those described in the header function for
1034 ** sqlite3CodeRowTrigger()
1035 */
1036 void sqlite3CodeRowTriggerDirect(
1037   Parse *pParse,       /* Parse context */
1038   Trigger *p,          /* Trigger to code */
1039   Table *pTab,         /* The table to code triggers from */
1040   int reg,             /* Reg array containing OLD.* and NEW.* values */
1041   int orconf,          /* ON CONFLICT policy */
1042   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
1043 ){
1044   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
1045   TriggerPrg *pPrg;
1046   pPrg = getRowTrigger(pParse, p, pTab, orconf);
1047   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
1048 
1049   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
1050   ** is a pointer to the sub-vdbe containing the trigger program.  */
1051   if( pPrg ){
1052     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
1053 
1054     sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
1055                       (const char *)pPrg->pProgram, P4_SUBPROGRAM);
1056     VdbeComment(
1057         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
1058 
1059     /* Set the P5 operand of the OP_Program instruction to non-zero if
1060     ** recursive invocation of this trigger program is disallowed. Recursive
1061     ** invocation is disallowed if (a) the sub-program is really a trigger,
1062     ** not a foreign key action, and (b) the flag to enable recursive triggers
1063     ** is clear.  */
1064     sqlite3VdbeChangeP5(v, (u8)bRecursive);
1065   }
1066 }
1067 
1068 /*
1069 ** This is called to code the required FOR EACH ROW triggers for an operation
1070 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
1071 ** is given by the op parameter. The tr_tm parameter determines whether the
1072 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
1073 ** parameter pChanges is passed the list of columns being modified.
1074 **
1075 ** If there are no triggers that fire at the specified time for the specified
1076 ** operation on pTab, this function is a no-op.
1077 **
1078 ** The reg argument is the address of the first in an array of registers
1079 ** that contain the values substituted for the new.* and old.* references
1080 ** in the trigger program. If N is the number of columns in table pTab
1081 ** (a copy of pTab->nCol), then registers are populated as follows:
1082 **
1083 **   Register       Contains
1084 **   ------------------------------------------------------
1085 **   reg+0          OLD.rowid
1086 **   reg+1          OLD.* value of left-most column of pTab
1087 **   ...            ...
1088 **   reg+N          OLD.* value of right-most column of pTab
1089 **   reg+N+1        NEW.rowid
1090 **   reg+N+2        OLD.* value of left-most column of pTab
1091 **   ...            ...
1092 **   reg+N+N+1      NEW.* value of right-most column of pTab
1093 **
1094 ** For ON DELETE triggers, the registers containing the NEW.* values will
1095 ** never be accessed by the trigger program, so they are not allocated or
1096 ** populated by the caller (there is no data to populate them with anyway).
1097 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1098 ** are never accessed, and so are not allocated by the caller. So, for an
1099 ** ON INSERT trigger, the value passed to this function as parameter reg
1100 ** is not a readable register, although registers (reg+N) through
1101 ** (reg+N+N+1) are.
1102 **
1103 ** Parameter orconf is the default conflict resolution algorithm for the
1104 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1105 ** is the instruction that control should jump to if a trigger program
1106 ** raises an IGNORE exception.
1107 */
1108 void sqlite3CodeRowTrigger(
1109   Parse *pParse,       /* Parse context */
1110   Trigger *pTrigger,   /* List of triggers on table pTab */
1111   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1112   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1113   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1114   Table *pTab,         /* The table to code triggers from */
1115   int reg,             /* The first in an array of registers (see above) */
1116   int orconf,          /* ON CONFLICT policy */
1117   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
1118 ){
1119   Trigger *p;          /* Used to iterate through pTrigger list */
1120 
1121   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1122   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1123   assert( (op==TK_UPDATE)==(pChanges!=0) );
1124 
1125   for(p=pTrigger; p; p=p->pNext){
1126 
1127     /* Sanity checking:  The schema for the trigger and for the table are
1128     ** always defined.  The trigger must be in the same schema as the table
1129     ** or else it must be a TEMP trigger. */
1130     assert( p->pSchema!=0 );
1131     assert( p->pTabSchema!=0 );
1132     assert( p->pSchema==p->pTabSchema
1133          || p->pSchema==pParse->db->aDb[1].pSchema );
1134 
1135     /* Determine whether we should code this trigger */
1136     if( p->op==op
1137      && p->tr_tm==tr_tm
1138      && checkColumnOverlap(p->pColumns, pChanges)
1139     ){
1140       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1141     }
1142   }
1143 }
1144 
1145 /*
1146 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1147 ** This function returns a 32-bit bitmask indicating which columns of the
1148 ** old.* or new.* tables actually are used by triggers. This information
1149 ** may be used by the caller, for example, to avoid having to load the entire
1150 ** old.* record into memory when executing an UPDATE or DELETE command.
1151 **
1152 ** Bit 0 of the returned mask is set if the left-most column of the
1153 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1154 ** the second leftmost column value is required, and so on. If there
1155 ** are more than 32 columns in the table, and at least one of the columns
1156 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1157 **
1158 ** It is not possible to determine if the old.rowid or new.rowid column is
1159 ** accessed by triggers. The caller must always assume that it is.
1160 **
1161 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1162 ** applies to the old.* table. If 1, the new.* table.
1163 **
1164 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1165 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1166 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1167 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1168 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1169 */
1170 u32 sqlite3TriggerColmask(
1171   Parse *pParse,       /* Parse context */
1172   Trigger *pTrigger,   /* List of triggers on table pTab */
1173   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
1174   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
1175   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1176   Table *pTab,         /* The table to code triggers from */
1177   int orconf           /* Default ON CONFLICT policy for trigger steps */
1178 ){
1179   const int op = pChanges ? TK_UPDATE : TK_DELETE;
1180   u32 mask = 0;
1181   Trigger *p;
1182 
1183   assert( isNew==1 || isNew==0 );
1184   for(p=pTrigger; p; p=p->pNext){
1185     if( p->op==op && (tr_tm&p->tr_tm)
1186      && checkColumnOverlap(p->pColumns,pChanges)
1187     ){
1188       TriggerPrg *pPrg;
1189       pPrg = getRowTrigger(pParse, p, pTab, orconf);
1190       if( pPrg ){
1191         mask |= pPrg->aColmask[isNew];
1192       }
1193     }
1194   }
1195 
1196   return mask;
1197 }
1198 
1199 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
1200