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