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