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