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