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