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