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