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