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