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